* image.c (slurp_file, xbm_read_bitmap_data): Cast to the correct
[bpt/emacs.git] / src / image.c
CommitLineData
4ef0d4d0 1/* Functions for image support on window system.
0b5538bd
TTN
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4ef0d4d0
KS
4
5This file is part of GNU Emacs.
6
7GNU Emacs is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 2, or (at your option)
10any later version.
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Emacs; see the file COPYING. If not, write to
4fc5845f
LK
19the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20Boston, MA 02110-1301, USA. */
4ef0d4d0
KS
21
22#include <config.h>
4ef0d4d0
KS
23#include <stdio.h>
24#include <math.h>
be8c4ce4 25#include <ctype.h>
4ef0d4d0
KS
26
27#ifdef HAVE_UNISTD_H
28#include <unistd.h>
29#endif
30
31/* This makes the fields of a Display accessible, in Xlib header files. */
32
33#define XLIB_ILLEGAL_ACCESS
34
35#include "lisp.h"
36#include "frame.h"
37#include "window.h"
38#include "dispextern.h"
39#include "blockinput.h"
40#include "systime.h"
41#include <epaths.h>
42
43
44#ifdef HAVE_X_WINDOWS
45#include "xterm.h"
46#include <sys/types.h>
47#include <sys/stat.h>
48
49#define COLOR_TABLE_SUPPORT 1
50
51typedef struct x_bitmap_record Bitmap_Record;
4ef0d4d0
KS
52#define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
53#define NO_PIXMAP None
4ef0d4d0
KS
54
55#define RGB_PIXEL_COLOR unsigned long
56
9ecf6403
YM
57#define PIX_MASK_RETAIN 0
58#define PIX_MASK_DRAW 1
4ef0d4d0
KS
59#endif /* HAVE_X_WINDOWS */
60
61
62#ifdef HAVE_NTGUI
63#include "w32term.h"
64
65/* W32_TODO : Color tables on W32. */
66#undef COLOR_TABLE_SUPPORT
67
68typedef struct w32_bitmap_record Bitmap_Record;
4ef0d4d0
KS
69#define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
70#define NO_PIXMAP 0
4ef0d4d0
KS
71
72#define RGB_PIXEL_COLOR COLORREF
73
9ecf6403
YM
74#define PIX_MASK_RETAIN 0
75#define PIX_MASK_DRAW 1
4ef0d4d0
KS
76
77#define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
78#define x_defined_color w32_defined_color
79#define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
80#endif /* HAVE_NTGUI */
81
82
83#ifdef MAC_OS
84#include "macterm.h"
b15325b2 85#include <sys/stat.h>
4ef0d4d0
KS
86#ifndef MAC_OSX
87#include <alloca.h>
b15325b2 88#include <sys/param.h>
4ef0d4d0 89#endif
d45b2e9e 90#if TARGET_API_MAC_CARBON
4ef0d4d0
KS
91#ifdef MAC_OSX
92#include <QuickTime/QuickTime.h>
d45b2e9e
YM
93#else /* not MAC_OSX */
94#include <QuickTime.h>
95#endif /* not MAC_OSX */
96#else /* not TARGET_API_MAC_CARBON */
4ef0d4d0
KS
97#include <Windows.h>
98#include <Gestalt.h>
99#include <TextUtils.h>
b15325b2
ST
100#include <ImageCompression.h>
101#include <QuickTimeComponents.h>
d45b2e9e 102#endif /* not TARGET_API_MAC_CARBON */
4ef0d4d0
KS
103
104/* MAC_TODO : Color tables on Mac. */
105#undef COLOR_TABLE_SUPPORT
106
4ef0d4d0
KS
107#define ZPixmap 0 /* arbitrary */
108typedef struct mac_bitmap_record Bitmap_Record;
109
4ef0d4d0
KS
110#define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
111#define NO_PIXMAP 0
4ef0d4d0
KS
112
113#define RGB_PIXEL_COLOR unsigned long
114
9ecf6403
YM
115/* A black pixel in a mask bitmap/pixmap means ``draw a source
116 pixel''. A white pixel means ``retain the current pixel''. */
117#define PIX_MASK_DRAW RGB_TO_ULONG(0,0,0)
118#define PIX_MASK_RETAIN RGB_TO_ULONG(255,255,255)
119
4ef0d4d0
KS
120#define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
121#define x_defined_color mac_defined_color
122#define DefaultDepthOfScreen(screen) (one_mac_display_info.n_planes)
123#define XDrawLine(display, w, gc, x1, y1, x2, y2) \
124 mac_draw_line_to_pixmap(display, w, gc, x1, y1, x2, y2)
125
126#endif /* MAC_OS */
127
128
129/* Search path for bitmap files. */
130
131Lisp_Object Vx_bitmap_file_path;
132
133
134static void x_disable_image P_ ((struct frame *, struct image *));
135static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
136 Lisp_Object));
137
138static void init_color_table P_ ((void));
139static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
140#ifdef COLOR_TABLE_SUPPORT
141static void free_color_table P_ ((void));
142static unsigned long *colors_in_color_table P_ ((int *n));
143static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
144#endif
145
146/* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
147 id, which is just an int that this section returns. Bitmaps are
148 reference counted so they can be shared among frames.
149
150 Bitmap indices are guaranteed to be > 0, so a negative number can
151 be used to indicate no bitmap.
152
153 If you use x_create_bitmap_from_data, then you must keep track of
154 the bitmaps yourself. That is, creating a bitmap from the same
155 data more than once will not be caught. */
156
157#ifdef MAC_OS
158
159static XImagePtr
160XGetImage (display, pixmap, x, y, width, height, plane_mask, format)
161 Display *display; /* not used */
162 Pixmap pixmap;
163 int x, y; /* not used */
164 unsigned int width, height; /* not used */
165 unsigned long plane_mask; /* not used */
166 int format; /* not used */
167{
168#if GLYPH_DEBUG
169 xassert (x == 0 && y == 0);
170 {
171 Rect ri, rp;
172 SetRect (&ri, 0, 0, width, height);
173 xassert (EqualRect (&ri, GetPixBounds (GetGWorldPixMap (pixmap), &rp)));
174 }
175 xassert (! (pixelsLocked & GetPixelsState (GetGWorldPixMap (pixmap))));
176#endif
177
178 LockPixels (GetGWorldPixMap (pixmap));
179
180 return pixmap;
181}
182
183static void
184XPutPixel (ximage, x, y, pixel)
185 XImagePtr ximage;
186 int x, y;
187 unsigned long pixel;
188{
9ecf6403
YM
189 PixMapHandle pixmap = GetGWorldPixMap (ximage);
190 short depth = GetPixDepth (pixmap);
191
192 if (depth == 32)
193 {
194 char *base_addr = GetPixBaseAddr (pixmap);
195 short row_bytes = GetPixRowBytes (pixmap);
196
197 ((unsigned long *) (base_addr + y * row_bytes))[x] = pixel;
198 }
199 else if (depth == 1)
200 {
201 char *base_addr = GetPixBaseAddr (pixmap);
202 short row_bytes = GetPixRowBytes (pixmap);
203
204 if (pixel == PIX_MASK_DRAW)
205 base_addr[y * row_bytes + x / 8] |= (1 << 7) >> (x & 7);
206 else
207 base_addr[y * row_bytes + x / 8] &= ~((1 << 7) >> (x & 7));
208 }
209 else
210 {
211 CGrafPtr old_port;
212 GDHandle old_gdh;
213 RGBColor color;
214
215 GetGWorld (&old_port, &old_gdh);
216 SetGWorld (ximage, NULL);
4ef0d4d0 217
9ecf6403
YM
218 color.red = RED16_FROM_ULONG (pixel);
219 color.green = GREEN16_FROM_ULONG (pixel);
220 color.blue = BLUE16_FROM_ULONG (pixel);
4ef0d4d0 221
9ecf6403 222 SetCPixel (x, y, &color);
2a316a84 223
9ecf6403
YM
224 SetGWorld (old_port, old_gdh);
225 }
4ef0d4d0
KS
226}
227
228static unsigned long
229XGetPixel (ximage, x, y)
230 XImagePtr ximage;
231 int x, y;
232{
9ecf6403
YM
233 PixMapHandle pixmap = GetGWorldPixMap (ximage);
234 short depth = GetPixDepth (pixmap);
4ef0d4d0 235
9ecf6403
YM
236 if (depth == 32)
237 {
238 char *base_addr = GetPixBaseAddr (pixmap);
239 short row_bytes = GetPixRowBytes (pixmap);
240
241 return ((unsigned long *) (base_addr + y * row_bytes))[x];
242 }
243 else if (depth == 1)
244 {
245 char *base_addr = GetPixBaseAddr (pixmap);
246 short row_bytes = GetPixRowBytes (pixmap);
4ef0d4d0 247
9ecf6403
YM
248 if (base_addr[y * row_bytes + x / 8] & (1 << (~x & 7)))
249 return PIX_MASK_DRAW;
250 else
251 return PIX_MASK_RETAIN;
252 }
253 else
254 {
255 CGrafPtr old_port;
256 GDHandle old_gdh;
257 RGBColor color;
2a316a84 258
9ecf6403
YM
259 GetGWorld (&old_port, &old_gdh);
260 SetGWorld (ximage, NULL);
261
262 GetCPixel (x, y, &color);
263
264 SetGWorld (old_port, old_gdh);
265 return RGB_TO_ULONG (color.red >> 8, color.green >> 8, color.blue >> 8);
266 }
4ef0d4d0
KS
267}
268
269static void
270XDestroyImage (ximg)
271 XImagePtr ximg;
272{
273 UnlockPixels (GetGWorldPixMap (ximg));
274}
b0da69a7 275#endif /* MAC_OS */
4ef0d4d0
KS
276
277
278/* Functions to access the contents of a bitmap, given an id. */
279
280int
281x_bitmap_height (f, id)
282 FRAME_PTR f;
283 int id;
284{
285 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
286}
287
288int
289x_bitmap_width (f, id)
290 FRAME_PTR f;
291 int id;
292{
293 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
294}
295
296#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
297int
298x_bitmap_pixmap (f, id)
299 FRAME_PTR f;
300 int id;
301{
302 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
303}
304#endif
305
306#ifdef HAVE_X_WINDOWS
307int
308x_bitmap_mask (f, id)
309 FRAME_PTR f;
310 int id;
311{
312 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
313}
314#endif
315
316/* Allocate a new bitmap record. Returns index of new record. */
317
318static int
319x_allocate_bitmap_record (f)
320 FRAME_PTR f;
321{
322 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
323 int i;
324
325 if (dpyinfo->bitmaps == NULL)
326 {
327 dpyinfo->bitmaps_size = 10;
328 dpyinfo->bitmaps
329 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
330 dpyinfo->bitmaps_last = 1;
331 return 1;
332 }
333
334 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
335 return ++dpyinfo->bitmaps_last;
336
337 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
338 if (dpyinfo->bitmaps[i].refcount == 0)
339 return i + 1;
340
341 dpyinfo->bitmaps_size *= 2;
342 dpyinfo->bitmaps
343 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
344 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
345 return ++dpyinfo->bitmaps_last;
346}
347
348/* Add one reference to the reference count of the bitmap with id ID. */
349
350void
351x_reference_bitmap (f, id)
352 FRAME_PTR f;
353 int id;
354{
355 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
356}
357
358/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
359
360int
361x_create_bitmap_from_data (f, bits, width, height)
362 struct frame *f;
363 char *bits;
364 unsigned int width, height;
365{
366 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
367 int id;
368
369#ifdef HAVE_X_WINDOWS
370 Pixmap bitmap;
371 bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
372 bits, width, height);
373 if (! bitmap)
374 return -1;
375#endif /* HAVE_X_WINDOWS */
376
377#ifdef HAVE_NTGUI
378 Pixmap bitmap;
379 bitmap = CreateBitmap (width, height,
380 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
381 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
382 bits);
383 if (! bitmap)
384 return -1;
385#endif /* HAVE_NTGUI */
386
387#ifdef MAC_OS
388 /* MAC_TODO: for now fail if width is not mod 16 (toolbox requires it) */
389 if (width % 16 != 0)
390 return -1;
391#endif
392
393 id = x_allocate_bitmap_record (f);
394#ifdef MAC_OS
395 dpyinfo->bitmaps[id - 1].bitmap_data = (char *) xmalloc (height * width);
396 if (! dpyinfo->bitmaps[id - 1].bitmap_data)
397 return -1;
398 bcopy (bits, dpyinfo->bitmaps[id - 1].bitmap_data, height * width);
399#endif /* MAC_OS */
400
401 dpyinfo->bitmaps[id - 1].file = NULL;
402 dpyinfo->bitmaps[id - 1].height = height;
403 dpyinfo->bitmaps[id - 1].width = width;
404 dpyinfo->bitmaps[id - 1].refcount = 1;
405
406#ifdef HAVE_X_WINDOWS
407 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
408 dpyinfo->bitmaps[id - 1].have_mask = 0;
409 dpyinfo->bitmaps[id - 1].depth = 1;
410#endif /* HAVE_X_WINDOWS */
411
412#ifdef HAVE_NTGUI
413 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
414 dpyinfo->bitmaps[id - 1].hinst = NULL;
415 dpyinfo->bitmaps[id - 1].depth = 1;
416#endif /* HAVE_NTGUI */
417
418 return id;
419}
420
421/* Create bitmap from file FILE for frame F. */
422
423int
424x_create_bitmap_from_file (f, file)
425 struct frame *f;
426 Lisp_Object file;
427{
428#ifdef MAC_OS
429 return -1; /* MAC_TODO : bitmap support */
430#endif /* MAC_OS */
431
432#ifdef HAVE_NTGUI
433 return -1; /* W32_TODO : bitmap support */
434#endif /* HAVE_NTGUI */
435
436#ifdef HAVE_X_WINDOWS
437 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
438 unsigned int width, height;
439 Pixmap bitmap;
440 int xhot, yhot, result, id;
441 Lisp_Object found;
442 int fd;
443 char *filename;
444
445 /* Look for an existing bitmap with the same name. */
446 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
447 {
448 if (dpyinfo->bitmaps[id].refcount
449 && dpyinfo->bitmaps[id].file
450 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
451 {
452 ++dpyinfo->bitmaps[id].refcount;
453 return id + 1;
454 }
455 }
456
457 /* Search bitmap-file-path for the file, if appropriate. */
458 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
459 if (fd < 0)
460 return -1;
461 emacs_close (fd);
462
463 filename = (char *) SDATA (found);
464
465 result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
466 filename, &width, &height, &bitmap, &xhot, &yhot);
467 if (result != BitmapSuccess)
468 return -1;
469
470 id = x_allocate_bitmap_record (f);
471 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
472 dpyinfo->bitmaps[id - 1].have_mask = 0;
473 dpyinfo->bitmaps[id - 1].refcount = 1;
474 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
475 dpyinfo->bitmaps[id - 1].depth = 1;
476 dpyinfo->bitmaps[id - 1].height = height;
477 dpyinfo->bitmaps[id - 1].width = width;
478 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
479
480 return id;
481#endif /* HAVE_X_WINDOWS */
482}
483
484/* Free bitmap B. */
485
486static void
487Free_Bitmap_Record (dpyinfo, bm)
488 Display_Info *dpyinfo;
489 Bitmap_Record *bm;
490{
491#ifdef HAVE_X_WINDOWS
492 XFreePixmap (dpyinfo->display, bm->pixmap);
493 if (bm->have_mask)
494 XFreePixmap (dpyinfo->display, bm->mask);
495#endif /* HAVE_X_WINDOWS */
496
497#ifdef HAVE_NTGUI
498 DeleteObject (bm->pixmap);
499#endif /* HAVE_NTGUI */
500
501#ifdef MAC_OS
502 xfree (bm->bitmap_data); /* Added ++kfs */
503 bm->bitmap_data = NULL;
504#endif /* MAC_OS */
505
506 if (bm->file)
507 {
508 xfree (bm->file);
509 bm->file = NULL;
510 }
511}
512
513/* Remove reference to bitmap with id number ID. */
514
515void
516x_destroy_bitmap (f, id)
517 FRAME_PTR f;
518 int id;
519{
520 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
521
522 if (id > 0)
523 {
524 Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];
525
526 if (--bm->refcount == 0)
527 {
528 BLOCK_INPUT;
529 Free_Bitmap_Record (dpyinfo, bm);
530 UNBLOCK_INPUT;
531 }
532 }
533}
534
535/* Free all the bitmaps for the display specified by DPYINFO. */
536
537void
538x_destroy_all_bitmaps (dpyinfo)
539 Display_Info *dpyinfo;
540{
541 int i;
542 Bitmap_Record *bm = dpyinfo->bitmaps;
543
544 for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
545 if (bm->refcount > 0)
546 Free_Bitmap_Record (dpyinfo, bm);
547
548 dpyinfo->bitmaps_last = 0;
549}
550
551
552#ifdef HAVE_X_WINDOWS
553
554/* Useful functions defined in the section
555 `Image type independent image structures' below. */
556
557static unsigned long four_corners_best P_ ((XImagePtr ximg, unsigned long width,
558 unsigned long height));
559
560static int x_create_x_image_and_pixmap P_ ((struct frame *f, int width, int height,
561 int depth, XImagePtr *ximg,
562 Pixmap *pixmap));
563
564static void x_destroy_x_image P_ ((XImagePtr ximg));
565
566
567/* Create a mask of a bitmap. Note is this not a perfect mask.
568 It's nicer with some borders in this context */
569
570int
571x_create_bitmap_mask (f, id)
572 struct frame *f;
573 int id;
574{
575 Pixmap pixmap, mask;
576 XImagePtr ximg, mask_img;
577 unsigned long width, height;
578 int result;
579 unsigned long bg;
580 unsigned long x, y, xp, xm, yp, ym;
581 GC gc;
582
583 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
584
585 if (!(id > 0))
586 return -1;
587
588 pixmap = x_bitmap_pixmap (f, id);
589 width = x_bitmap_width (f, id);
590 height = x_bitmap_height (f, id);
591
592 BLOCK_INPUT;
593 ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
594 ~0, ZPixmap);
595
596 if (!ximg)
597 {
598 UNBLOCK_INPUT;
599 return -1;
600 }
601
602 result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);
603
604 UNBLOCK_INPUT;
605 if (!result)
606 {
607 XDestroyImage (ximg);
608 return -1;
609 }
610
611 bg = four_corners_best (ximg, width, height);
612
613 for (y = 0; y < ximg->height; ++y)
614 {
615 for (x = 0; x < ximg->width; ++x)
616 {
617 xp = x != ximg->width - 1 ? x + 1 : 0;
618 xm = x != 0 ? x - 1 : ximg->width - 1;
619 yp = y != ximg->height - 1 ? y + 1 : 0;
620 ym = y != 0 ? y - 1 : ximg->height - 1;
621 if (XGetPixel (ximg, x, y) == bg
622 && XGetPixel (ximg, x, yp) == bg
623 && XGetPixel (ximg, x, ym) == bg
624 && XGetPixel (ximg, xp, y) == bg
625 && XGetPixel (ximg, xp, yp) == bg
626 && XGetPixel (ximg, xp, ym) == bg
627 && XGetPixel (ximg, xm, y) == bg
628 && XGetPixel (ximg, xm, yp) == bg
629 && XGetPixel (ximg, xm, ym) == bg)
630 XPutPixel (mask_img, x, y, 0);
631 else
632 XPutPixel (mask_img, x, y, 1);
633 }
634 }
635
636 xassert (interrupt_input_blocked);
637 gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
638 XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
639 width, height);
640 XFreeGC (FRAME_X_DISPLAY (f), gc);
641
642 dpyinfo->bitmaps[id - 1].have_mask = 1;
643 dpyinfo->bitmaps[id - 1].mask = mask;
644
645 XDestroyImage (ximg);
646 x_destroy_x_image (mask_img);
647
648 return 0;
649}
650
651#endif /* HAVE_X_WINDOWS */
652
653
654/***********************************************************************
655 Image types
656 ***********************************************************************/
657
658/* Value is the number of elements of vector VECTOR. */
659
660#define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
661
662/* List of supported image types. Use define_image_type to add new
663 types. Use lookup_image_type to find a type for a given symbol. */
664
665static struct image_type *image_types;
666
0855eb52
JB
667/* A list of symbols, one for each supported image type. */
668
669Lisp_Object Vimage_types;
670
2a611c1a
JB
671/* An alist of image types and libraries that implement the type. */
672
673Lisp_Object Vimage_library_alist;
674
0855eb52
JB
675/* Cache for delayed-loading image types. */
676
677static Lisp_Object Vimage_type_cache;
678
4ef0d4d0
KS
679/* The symbol `xbm' which is used as the type symbol for XBM images. */
680
681Lisp_Object Qxbm;
682
683/* Keywords. */
684
685extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
686extern Lisp_Object QCdata, QCtype;
e1dfec15 687extern Lisp_Object Qcenter;
4ef0d4d0
KS
688Lisp_Object QCascent, QCmargin, QCrelief;
689Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
690Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
691
692/* Other symbols. */
693
694Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
4ef0d4d0
KS
695
696/* Time in seconds after which images should be removed from the cache
697 if not displayed. */
698
699Lisp_Object Vimage_cache_eviction_delay;
700
701/* Function prototypes. */
702
0855eb52 703static Lisp_Object define_image_type P_ ((struct image_type *type, int loaded));
4ef0d4d0
KS
704static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
705static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
706static void x_laplace P_ ((struct frame *, struct image *));
707static void x_emboss P_ ((struct frame *, struct image *));
708static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
709 Lisp_Object));
710
0855eb52
JB
711#define CACHE_IMAGE_TYPE(type, status) \
712 do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)
713
714#define ADD_IMAGE_TYPE(type) \
715 do { Vimage_types = Fcons (type, Vimage_types); } while (0)
4ef0d4d0
KS
716
717/* Define a new image type from TYPE. This adds a copy of TYPE to
0855eb52 718 image_types and caches the loading status of TYPE. */
4ef0d4d0 719
0855eb52
JB
720static Lisp_Object
721define_image_type (type, loaded)
4ef0d4d0 722 struct image_type *type;
0855eb52 723 int loaded;
4ef0d4d0 724{
0855eb52
JB
725 Lisp_Object success;
726
727 if (!loaded)
728 success = Qnil;
729 else
730 {
731 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
732 The initialized data segment is read-only. */
733 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
734 bcopy (type, p, sizeof *p);
735 p->next = image_types;
736 image_types = p;
737 success = Qt;
738 }
739
adac86db 740 CACHE_IMAGE_TYPE (*type->type, success);
0855eb52 741 return success;
4ef0d4d0
KS
742}
743
744
745/* Look up image type SYMBOL, and return a pointer to its image_type
746 structure. Value is null if SYMBOL is not a known image type. */
747
748static INLINE struct image_type *
749lookup_image_type (symbol)
750 Lisp_Object symbol;
751{
752 struct image_type *type;
753
803aac3e 754 /* We must initialize the image-type if it hasn't been already. */
2a611c1a 755 if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
803aac3e
MB
756 return 0; /* unimplemented */
757
4ef0d4d0
KS
758 for (type = image_types; type; type = type->next)
759 if (EQ (symbol, *type->type))
760 break;
761
762 return type;
763}
764
765
766/* Value is non-zero if OBJECT is a valid Lisp image specification. A
767 valid image specification is a list whose car is the symbol
768 `image', and whose rest is a property list. The property list must
769 contain a value for key `:type'. That value must be the name of a
770 supported image type. The rest of the property list depends on the
771 image type. */
772
773int
774valid_image_p (object)
775 Lisp_Object object;
776{
777 int valid_p = 0;
778
779 if (IMAGEP (object))
780 {
781 Lisp_Object tem;
782
783 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
784 if (EQ (XCAR (tem), QCtype))
785 {
786 tem = XCDR (tem);
787 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
788 {
789 struct image_type *type;
790 type = lookup_image_type (XCAR (tem));
791 if (type)
792 valid_p = type->valid_p (object);
793 }
794
795 break;
796 }
797 }
798
799 return valid_p;
800}
801
802
803/* Log error message with format string FORMAT and argument ARG.
804 Signaling an error, e.g. when an image cannot be loaded, is not a
805 good idea because this would interrupt redisplay, and the error
806 message display would lead to another redisplay. This function
807 therefore simply displays a message. */
808
809static void
810image_error (format, arg1, arg2)
811 char *format;
812 Lisp_Object arg1, arg2;
813{
814 add_to_log (format, arg1, arg2);
815}
816
817
818\f
819/***********************************************************************
820 Image specifications
821 ***********************************************************************/
822
823enum image_value_type
824{
825 IMAGE_DONT_CHECK_VALUE_TYPE,
826 IMAGE_STRING_VALUE,
827 IMAGE_STRING_OR_NIL_VALUE,
828 IMAGE_SYMBOL_VALUE,
829 IMAGE_POSITIVE_INTEGER_VALUE,
830 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
831 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
832 IMAGE_ASCENT_VALUE,
833 IMAGE_INTEGER_VALUE,
834 IMAGE_FUNCTION_VALUE,
835 IMAGE_NUMBER_VALUE,
836 IMAGE_BOOL_VALUE
837};
838
839/* Structure used when parsing image specifications. */
840
841struct image_keyword
842{
843 /* Name of keyword. */
844 char *name;
845
846 /* The type of value allowed. */
847 enum image_value_type type;
848
849 /* Non-zero means key must be present. */
850 int mandatory_p;
851
852 /* Used to recognize duplicate keywords in a property list. */
853 int count;
854
855 /* The value that was found. */
856 Lisp_Object value;
857};
858
859
860static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
861 int, Lisp_Object));
862static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
863
864
865/* Parse image spec SPEC according to KEYWORDS. A valid image spec
866 has the format (image KEYWORD VALUE ...). One of the keyword/
867 value pairs must be `:type TYPE'. KEYWORDS is a vector of
868 image_keywords structures of size NKEYWORDS describing other
869 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
870
871static int
872parse_image_spec (spec, keywords, nkeywords, type)
873 Lisp_Object spec;
874 struct image_keyword *keywords;
875 int nkeywords;
876 Lisp_Object type;
877{
878 int i;
879 Lisp_Object plist;
880
881 if (!IMAGEP (spec))
882 return 0;
883
884 plist = XCDR (spec);
885 while (CONSP (plist))
886 {
887 Lisp_Object key, value;
888
889 /* First element of a pair must be a symbol. */
890 key = XCAR (plist);
891 plist = XCDR (plist);
892 if (!SYMBOLP (key))
893 return 0;
894
895 /* There must follow a value. */
896 if (!CONSP (plist))
897 return 0;
898 value = XCAR (plist);
899 plist = XCDR (plist);
900
901 /* Find key in KEYWORDS. Error if not found. */
902 for (i = 0; i < nkeywords; ++i)
903 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
904 break;
905
906 if (i == nkeywords)
907 continue;
908
909 /* Record that we recognized the keyword. If a keywords
910 was found more than once, it's an error. */
911 keywords[i].value = value;
912 ++keywords[i].count;
913
914 if (keywords[i].count > 1)
915 return 0;
916
917 /* Check type of value against allowed type. */
918 switch (keywords[i].type)
919 {
920 case IMAGE_STRING_VALUE:
921 if (!STRINGP (value))
922 return 0;
923 break;
924
925 case IMAGE_STRING_OR_NIL_VALUE:
926 if (!STRINGP (value) && !NILP (value))
927 return 0;
928 break;
929
930 case IMAGE_SYMBOL_VALUE:
931 if (!SYMBOLP (value))
932 return 0;
933 break;
934
935 case IMAGE_POSITIVE_INTEGER_VALUE:
936 if (!INTEGERP (value) || XINT (value) <= 0)
937 return 0;
938 break;
939
940 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
941 if (INTEGERP (value) && XINT (value) >= 0)
942 break;
943 if (CONSP (value)
944 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
945 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
946 break;
947 return 0;
948
949 case IMAGE_ASCENT_VALUE:
950 if (SYMBOLP (value) && EQ (value, Qcenter))
951 break;
952 else if (INTEGERP (value)
953 && XINT (value) >= 0
954 && XINT (value) <= 100)
955 break;
956 return 0;
957
958 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
959 if (!INTEGERP (value) || XINT (value) < 0)
960 return 0;
961 break;
962
963 case IMAGE_DONT_CHECK_VALUE_TYPE:
964 break;
965
966 case IMAGE_FUNCTION_VALUE:
967 value = indirect_function (value);
968 if (SUBRP (value)
969 || COMPILEDP (value)
970 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
971 break;
972 return 0;
973
974 case IMAGE_NUMBER_VALUE:
975 if (!INTEGERP (value) && !FLOATP (value))
976 return 0;
977 break;
978
979 case IMAGE_INTEGER_VALUE:
980 if (!INTEGERP (value))
981 return 0;
982 break;
983
984 case IMAGE_BOOL_VALUE:
985 if (!NILP (value) && !EQ (value, Qt))
986 return 0;
987 break;
988
989 default:
990 abort ();
991 break;
992 }
993
994 if (EQ (key, QCtype) && !EQ (type, value))
995 return 0;
996 }
997
998 /* Check that all mandatory fields are present. */
999 for (i = 0; i < nkeywords; ++i)
1000 if (keywords[i].mandatory_p && keywords[i].count == 0)
1001 return 0;
1002
1003 return NILP (plist);
1004}
1005
1006
1007/* Return the value of KEY in image specification SPEC. Value is nil
1008 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
1009 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
1010
1011static Lisp_Object
1012image_spec_value (spec, key, found)
1013 Lisp_Object spec, key;
1014 int *found;
1015{
1016 Lisp_Object tail;
1017
1018 xassert (valid_image_p (spec));
1019
1020 for (tail = XCDR (spec);
1021 CONSP (tail) && CONSP (XCDR (tail));
1022 tail = XCDR (XCDR (tail)))
1023 {
1024 if (EQ (XCAR (tail), key))
1025 {
1026 if (found)
1027 *found = 1;
1028 return XCAR (XCDR (tail));
1029 }
1030 }
1031
1032 if (found)
1033 *found = 0;
1034 return Qnil;
1035}
1036
1037
1038DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
1039 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
1040PIXELS non-nil means return the size in pixels, otherwise return the
1041size in canonical character units.
1042FRAME is the frame on which the image will be displayed. FRAME nil
1043or omitted means use the selected frame. */)
1044 (spec, pixels, frame)
1045 Lisp_Object spec, pixels, frame;
1046{
1047 Lisp_Object size;
1048
1049 size = Qnil;
1050 if (valid_image_p (spec))
1051 {
1052 struct frame *f = check_x_frame (frame);
1053 int id = lookup_image (f, spec);
1054 struct image *img = IMAGE_FROM_ID (f, id);
1055 int width = img->width + 2 * img->hmargin;
1056 int height = img->height + 2 * img->vmargin;
1057
1058 if (NILP (pixels))
1059 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
1060 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
1061 else
1062 size = Fcons (make_number (width), make_number (height));
1063 }
1064 else
1065 error ("Invalid image specification");
1066
1067 return size;
1068}
1069
1070
1071DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
1072 doc: /* Return t if image SPEC has a mask bitmap.
1073FRAME is the frame on which the image will be displayed. FRAME nil
1074or omitted means use the selected frame. */)
1075 (spec, frame)
1076 Lisp_Object spec, frame;
1077{
1078 Lisp_Object mask;
1079
1080 mask = Qnil;
1081 if (valid_image_p (spec))
1082 {
1083 struct frame *f = check_x_frame (frame);
1084 int id = lookup_image (f, spec);
1085 struct image *img = IMAGE_FROM_ID (f, id);
1086 if (img->mask)
1087 mask = Qt;
1088 }
1089 else
1090 error ("Invalid image specification");
1091
1092 return mask;
1093}
1094
1095\f
1096/***********************************************************************
1097 Image type independent image structures
1098 ***********************************************************************/
1099
1100static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
1101static void free_image P_ ((struct frame *f, struct image *img));
1102
1103
1104/* Allocate and return a new image structure for image specification
1105 SPEC. SPEC has a hash value of HASH. */
1106
1107static struct image *
1108make_image (spec, hash)
1109 Lisp_Object spec;
1110 unsigned hash;
1111{
1112 struct image *img = (struct image *) xmalloc (sizeof *img);
1113
1114 xassert (valid_image_p (spec));
1115 bzero (img, sizeof *img);
1116 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1117 xassert (img->type != NULL);
1118 img->spec = spec;
1119 img->data.lisp_val = Qnil;
1120 img->ascent = DEFAULT_IMAGE_ASCENT;
1121 img->hash = hash;
1122 return img;
1123}
1124
1125
1126/* Free image IMG which was used on frame F, including its resources. */
1127
1128static void
1129free_image (f, img)
1130 struct frame *f;
1131 struct image *img;
1132{
1133 if (img)
1134 {
1135 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1136
1137 /* Remove IMG from the hash table of its cache. */
1138 if (img->prev)
1139 img->prev->next = img->next;
1140 else
1141 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
1142
1143 if (img->next)
1144 img->next->prev = img->prev;
1145
1146 c->images[img->id] = NULL;
1147
1148 /* Free resources, then free IMG. */
1149 img->type->free (f, img);
1150 xfree (img);
1151 }
1152}
1153
1154
1155/* Prepare image IMG for display on frame F. Must be called before
1156 drawing an image. */
1157
1158void
1159prepare_image_for_display (f, img)
1160 struct frame *f;
1161 struct image *img;
1162{
1163 EMACS_TIME t;
1164
1165 /* We're about to display IMG, so set its timestamp to `now'. */
1166 EMACS_GET_TIME (t);
1167 img->timestamp = EMACS_SECS (t);
1168
1169 /* If IMG doesn't have a pixmap yet, load it now, using the image
1170 type dependent loader function. */
1171 if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
1172 img->load_failed_p = img->type->load (f, img) == 0;
1173}
1174
1175
1176/* Value is the number of pixels for the ascent of image IMG when
1177 drawn in face FACE. */
1178
1179int
1938bc36 1180image_ascent (img, face, slice)
4ef0d4d0
KS
1181 struct image *img;
1182 struct face *face;
1938bc36 1183 struct glyph_slice *slice;
4ef0d4d0 1184{
1938bc36 1185 int height;
4ef0d4d0
KS
1186 int ascent;
1187
1938bc36
KS
1188 if (slice->height == img->height)
1189 height = img->height + img->vmargin;
1190 else if (slice->y == 0)
1191 height = slice->height + img->vmargin;
1192 else
1193 height = slice->height;
1194
4ef0d4d0
KS
1195 if (img->ascent == CENTERED_IMAGE_ASCENT)
1196 {
1197 if (face->font)
1198 {
1199#ifdef HAVE_NTGUI
1200 /* W32 specific version. Why?. ++kfs */
1201 ascent = height / 2 - (FONT_DESCENT(face->font)
1202 - FONT_BASE(face->font)) / 2;
1203#else
1204 /* This expression is arranged so that if the image can't be
1205 exactly centered, it will be moved slightly up. This is
1206 because a typical font is `top-heavy' (due to the presence
1207 uppercase letters), so the image placement should err towards
1208 being top-heavy too. It also just generally looks better. */
1209 ascent = (height + face->font->ascent - face->font->descent + 1) / 2;
1210#endif /* HAVE_NTGUI */
1211 }
1212 else
1213 ascent = height / 2;
1214 }
1215 else
1216 ascent = (int) (height * img->ascent / 100.0);
1217
1218 return ascent;
1219}
1220
1221\f
1222/* Image background colors. */
1223
1224/* Find the "best" corner color of a bitmap.
1225 On W32, XIMG is assumed to a device context with the bitmap selected. */
1226
1227static RGB_PIXEL_COLOR
1228four_corners_best (ximg, width, height)
1229 XImagePtr_or_DC ximg;
1230 unsigned long width, height;
1231{
1232 RGB_PIXEL_COLOR corners[4], best;
1233 int i, best_count;
1234
1235 /* Get the colors at the corners of ximg. */
1236 corners[0] = GET_PIXEL (ximg, 0, 0);
1237 corners[1] = GET_PIXEL (ximg, width - 1, 0);
1238 corners[2] = GET_PIXEL (ximg, width - 1, height - 1);
1239 corners[3] = GET_PIXEL (ximg, 0, height - 1);
1240
1241 /* Choose the most frequently found color as background. */
1242 for (i = best_count = 0; i < 4; ++i)
1243 {
1244 int j, n;
1245
1246 for (j = n = 0; j < 4; ++j)
1247 if (corners[i] == corners[j])
1248 ++n;
1249
1250 if (n > best_count)
1251 best = corners[i], best_count = n;
1252 }
1253
1254 return best;
1255}
1256
1257/* Portability macros */
1258
1259#ifdef HAVE_NTGUI
1260
1261#define Destroy_Image(img_dc, prev) \
1262 do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)
1263
1264#define Free_Pixmap(display, pixmap) \
1265 DeleteObject (pixmap)
1266
1267#else
1268
1269#define Destroy_Image(ximg, dummy) \
1270 XDestroyImage (ximg)
1271
1272#define Free_Pixmap(display, pixmap) \
1273 XFreePixmap (display, pixmap)
1274
1275#endif /* HAVE_NTGUI */
1276
1277
1278/* Return the `background' field of IMG. If IMG doesn't have one yet,
1279 it is guessed heuristically. If non-zero, XIMG is an existing
1280 XImage object (or device context with the image selected on W32) to
1f026899 1281 use for the heuristic. */
4ef0d4d0
KS
1282
1283RGB_PIXEL_COLOR
1284image_background (img, f, ximg)
1285 struct image *img;
1286 struct frame *f;
1287 XImagePtr_or_DC ximg;
1288{
1289 if (! img->background_valid)
1290 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1291 {
1292 int free_ximg = !ximg;
1293#ifdef HAVE_NTGUI
1294 HGDIOBJ prev;
1295#endif /* HAVE_NTGUI */
1296
1297 if (free_ximg)
1298 {
1299#ifndef HAVE_NTGUI
1300 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
1301 0, 0, img->width, img->height, ~0, ZPixmap);
1302#else
1303 HDC frame_dc = get_frame_dc (f);
1304 ximg = CreateCompatibleDC (frame_dc);
1305 release_frame_dc (f, frame_dc);
1306 prev = SelectObject (ximg, img->pixmap);
1307#endif /* !HAVE_NTGUI */
1308 }
1309
1310 img->background = four_corners_best (ximg, img->width, img->height);
1311
1312 if (free_ximg)
1313 Destroy_Image (ximg, prev);
1f026899 1314
4ef0d4d0
KS
1315 img->background_valid = 1;
1316 }
1317
1318 return img->background;
1319}
1320
1321/* Return the `background_transparent' field of IMG. If IMG doesn't
1322 have one yet, it is guessed heuristically. If non-zero, MASK is an
1323 existing XImage object to use for the heuristic. */
1324
1325int
1326image_background_transparent (img, f, mask)
1327 struct image *img;
1328 struct frame *f;
1329 XImagePtr_or_DC mask;
1330{
1331 if (! img->background_transparent_valid)
1332 /* IMG doesn't have a background yet, try to guess a reasonable value. */
1333 {
1334 if (img->mask)
1335 {
1336 int free_mask = !mask;
1337#ifdef HAVE_NTGUI
1338 HGDIOBJ prev;
1339#endif /* HAVE_NTGUI */
1340
1341 if (free_mask)
1342 {
1343#ifndef HAVE_NTGUI
1344 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
1345 0, 0, img->width, img->height, ~0, ZPixmap);
1346#else
1347 HDC frame_dc = get_frame_dc (f);
1348 mask = CreateCompatibleDC (frame_dc);
1349 release_frame_dc (f, frame_dc);
1350 prev = SelectObject (mask, img->mask);
1351#endif /* HAVE_NTGUI */
1352 }
1353
1354 img->background_transparent
9ecf6403 1355 = (four_corners_best (mask, img->width, img->height) == PIX_MASK_RETAIN);
4ef0d4d0
KS
1356
1357 if (free_mask)
1358 Destroy_Image (mask, prev);
1359 }
1360 else
1361 img->background_transparent = 0;
1362
1363 img->background_transparent_valid = 1;
1364 }
1365
1366 return img->background_transparent;
1367}
1368
1369\f
1370/***********************************************************************
1371 Helper functions for X image types
1372 ***********************************************************************/
1373
1374static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
1375 int, int));
1376static void x_clear_image P_ ((struct frame *f, struct image *img));
1377static unsigned long x_alloc_image_color P_ ((struct frame *f,
1378 struct image *img,
1379 Lisp_Object color_name,
1380 unsigned long dflt));
1381
1382
1383/* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
1384 free the pixmap if any. MASK_P non-zero means clear the mask
1385 pixmap if any. COLORS_P non-zero means free colors allocated for
1386 the image, if any. */
1387
1388static void
1389x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
1390 struct frame *f;
1391 struct image *img;
1392 int pixmap_p, mask_p, colors_p;
1393{
1394 if (pixmap_p && img->pixmap)
1395 {
1396 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
1397 img->pixmap = NO_PIXMAP;
1398 img->background_valid = 0;
1399 }
1400
1401 if (mask_p && img->mask)
1402 {
1403 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1404 img->mask = NO_PIXMAP;
1405 img->background_transparent_valid = 0;
1406 }
1407
1408 if (colors_p && img->ncolors)
1409 {
1410 /* MAC_TODO: color table support. */
1411 /* W32_TODO: color table support. */
1412#ifdef HAVE_X_WINDOWS
1413 x_free_colors (f, img->colors, img->ncolors);
1414#endif /* HAVE_X_WINDOWS */
1415 xfree (img->colors);
1416 img->colors = NULL;
1417 img->ncolors = 0;
1418 }
1419}
1420
1421/* Free X resources of image IMG which is used on frame F. */
1422
1423static void
1424x_clear_image (f, img)
1425 struct frame *f;
1426 struct image *img;
1427{
1428 BLOCK_INPUT;
1429 x_clear_image_1 (f, img, 1, 1, 1);
1430 UNBLOCK_INPUT;
1431}
1432
1433
1434/* Allocate color COLOR_NAME for image IMG on frame F. If color
1435 cannot be allocated, use DFLT. Add a newly allocated color to
1436 IMG->colors, so that it can be freed again. Value is the pixel
1437 color. */
1438
1439static unsigned long
1440x_alloc_image_color (f, img, color_name, dflt)
1441 struct frame *f;
1442 struct image *img;
1443 Lisp_Object color_name;
1444 unsigned long dflt;
1445{
1446 XColor color;
1447 unsigned long result;
1448
1449 xassert (STRINGP (color_name));
1450
1451 if (x_defined_color (f, SDATA (color_name), &color, 1))
1452 {
1453 /* This isn't called frequently so we get away with simply
1454 reallocating the color vector to the needed size, here. */
1455 ++img->ncolors;
1456 img->colors =
1457 (unsigned long *) xrealloc (img->colors,
1458 img->ncolors * sizeof *img->colors);
1459 img->colors[img->ncolors - 1] = color.pixel;
1460 result = color.pixel;
1461 }
1462 else
1463 result = dflt;
1464
1465 return result;
1466}
1467
1468
1469\f
1470/***********************************************************************
1471 Image Cache
1472 ***********************************************************************/
1473
1474static void cache_image P_ ((struct frame *f, struct image *img));
1475static void postprocess_image P_ ((struct frame *, struct image *));
1476
1477/* Return a new, initialized image cache that is allocated from the
1478 heap. Call free_image_cache to free an image cache. */
1479
1480struct image_cache *
1481make_image_cache ()
1482{
1483 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
1484 int size;
1485
1486 bzero (c, sizeof *c);
1487 c->size = 50;
1488 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
1489 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1490 c->buckets = (struct image **) xmalloc (size);
1491 bzero (c->buckets, size);
1492 return c;
1493}
1494
1495
1496/* Free image cache of frame F. Be aware that X frames share images
1497 caches. */
1498
1499void
1500free_image_cache (f)
1501 struct frame *f;
1502{
1503 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1504 if (c)
1505 {
1506 int i;
1507
1508 /* Cache should not be referenced by any frame when freed. */
1509 xassert (c->refcount == 0);
1510
1511 for (i = 0; i < c->used; ++i)
1512 free_image (f, c->images[i]);
1513 xfree (c->images);
1514 xfree (c->buckets);
1515 xfree (c);
1516 FRAME_X_IMAGE_CACHE (f) = NULL;
1517 }
1518}
1519
1520
1521/* Clear image cache of frame F. FORCE_P non-zero means free all
1522 images. FORCE_P zero means clear only images that haven't been
1523 displayed for some time. Should be called from time to time to
1524 reduce the number of loaded images. If image-eviction-seconds is
1525 non-nil, this frees images in the cache which weren't displayed for
1526 at least that many seconds. */
1527
1528void
1529clear_image_cache (f, force_p)
1530 struct frame *f;
1531 int force_p;
1532{
1533 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1534
1535 if (c && INTEGERP (Vimage_cache_eviction_delay))
1536 {
1537 EMACS_TIME t;
1538 unsigned long old;
1539 int i, nfreed;
1540
1541 EMACS_GET_TIME (t);
1542 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
1543
1544 /* Block input so that we won't be interrupted by a SIGIO
1545 while being in an inconsistent state. */
1546 BLOCK_INPUT;
1547
1548 for (i = nfreed = 0; i < c->used; ++i)
1549 {
1550 struct image *img = c->images[i];
1551 if (img != NULL
1552 && (force_p || img->timestamp < old))
1553 {
1554 free_image (f, img);
1555 ++nfreed;
1556 }
1557 }
1558
1559 /* We may be clearing the image cache because, for example,
1560 Emacs was iconified for a longer period of time. In that
1561 case, current matrices may still contain references to
1562 images freed above. So, clear these matrices. */
1563 if (nfreed)
1564 {
1565 Lisp_Object tail, frame;
1566
1567 FOR_EACH_FRAME (tail, frame)
1568 {
1569 struct frame *f = XFRAME (frame);
1570 if (FRAME_WINDOW_P (f)
1571 && FRAME_X_IMAGE_CACHE (f) == c)
1572 clear_current_matrices (f);
1573 }
1574
1575 ++windows_or_buffers_changed;
1576 }
1577
1578 UNBLOCK_INPUT;
1579 }
1580}
1581
1582
1583DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
1584 0, 1, 0,
1585 doc: /* Clear the image cache of FRAME.
1586FRAME nil or omitted means use the selected frame.
1587FRAME t means clear the image caches of all frames. */)
1588 (frame)
1589 Lisp_Object frame;
1590{
1591 if (EQ (frame, Qt))
1592 {
1593 Lisp_Object tail;
1594
1595 FOR_EACH_FRAME (tail, frame)
1596 if (FRAME_WINDOW_P (XFRAME (frame)))
1597 clear_image_cache (XFRAME (frame), 1);
1598 }
1599 else
1600 clear_image_cache (check_x_frame (frame), 1);
1601
1602 return Qnil;
1603}
1604
1605
1606/* Compute masks and transform image IMG on frame F, as specified
1607 by the image's specification, */
1608
1609static void
1610postprocess_image (f, img)
1611 struct frame *f;
1612 struct image *img;
1613{
1614 /* Manipulation of the image's mask. */
1615 if (img->pixmap)
1616 {
1617 Lisp_Object conversion, spec;
1618 Lisp_Object mask;
1619
1620 spec = img->spec;
1621
1622 /* `:heuristic-mask t'
1623 `:mask heuristic'
1624 means build a mask heuristically.
1625 `:heuristic-mask (R G B)'
1626 `:mask (heuristic (R G B))'
1627 means build a mask from color (R G B) in the
1628 image.
1629 `:mask nil'
1630 means remove a mask, if any. */
1631
1632 mask = image_spec_value (spec, QCheuristic_mask, NULL);
1633 if (!NILP (mask))
1634 x_build_heuristic_mask (f, img, mask);
1635 else
1636 {
1637 int found_p;
1638
1639 mask = image_spec_value (spec, QCmask, &found_p);
1640
1641 if (EQ (mask, Qheuristic))
1642 x_build_heuristic_mask (f, img, Qt);
1643 else if (CONSP (mask)
1644 && EQ (XCAR (mask), Qheuristic))
1645 {
1646 if (CONSP (XCDR (mask)))
1647 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
1648 else
1649 x_build_heuristic_mask (f, img, XCDR (mask));
1650 }
1651 else if (NILP (mask) && found_p && img->mask)
1652 {
1653 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
1654 img->mask = NO_PIXMAP;
1655 }
1656 }
1657
1658
1659 /* Should we apply an image transformation algorithm? */
1660 conversion = image_spec_value (spec, QCconversion, NULL);
1661 if (EQ (conversion, Qdisabled))
1662 x_disable_image (f, img);
1663 else if (EQ (conversion, Qlaplace))
1664 x_laplace (f, img);
1665 else if (EQ (conversion, Qemboss))
1666 x_emboss (f, img);
1667 else if (CONSP (conversion)
1668 && EQ (XCAR (conversion), Qedge_detection))
1669 {
1670 Lisp_Object tem;
1671 tem = XCDR (conversion);
1672 if (CONSP (tem))
1673 x_edge_detection (f, img,
1674 Fplist_get (tem, QCmatrix),
1675 Fplist_get (tem, QCcolor_adjustment));
1676 }
1677 }
1678}
1679
1680
1681/* Return the id of image with Lisp specification SPEC on frame F.
1682 SPEC must be a valid Lisp image specification (see valid_image_p). */
1683
1684int
1685lookup_image (f, spec)
1686 struct frame *f;
1687 Lisp_Object spec;
1688{
1689 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1690 struct image *img;
1691 int i;
1692 unsigned hash;
1693 struct gcpro gcpro1;
1694 EMACS_TIME now;
1695
1696 /* F must be a window-system frame, and SPEC must be a valid image
1697 specification. */
1698 xassert (FRAME_WINDOW_P (f));
1699 xassert (valid_image_p (spec));
1700
1701 GCPRO1 (spec);
1702
1703 /* Look up SPEC in the hash table of the image cache. */
1704 hash = sxhash (spec, 0);
1705 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
1706
1707 for (img = c->buckets[i]; img; img = img->next)
1708 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
1709 break;
1710
1711 /* If not found, create a new image and cache it. */
1712 if (img == NULL)
1713 {
1714 extern Lisp_Object Qpostscript;
1715
1716 BLOCK_INPUT;
1717 img = make_image (spec, hash);
1718 cache_image (f, img);
1719 img->load_failed_p = img->type->load (f, img) == 0;
1720
1721 /* If we can't load the image, and we don't have a width and
1722 height, use some arbitrary width and height so that we can
1723 draw a rectangle for it. */
1724 if (img->load_failed_p)
1725 {
1726 Lisp_Object value;
1727
1728 value = image_spec_value (spec, QCwidth, NULL);
1729 img->width = (INTEGERP (value)
1730 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
1731 value = image_spec_value (spec, QCheight, NULL);
1732 img->height = (INTEGERP (value)
1733 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
1734 }
1735 else
1736 {
1737 /* Handle image type independent image attributes
1738 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
1739 `:background COLOR'. */
1740 Lisp_Object ascent, margin, relief, bg;
1741
1742 ascent = image_spec_value (spec, QCascent, NULL);
1743 if (INTEGERP (ascent))
1744 img->ascent = XFASTINT (ascent);
1745 else if (EQ (ascent, Qcenter))
1746 img->ascent = CENTERED_IMAGE_ASCENT;
1747
1748 margin = image_spec_value (spec, QCmargin, NULL);
1749 if (INTEGERP (margin) && XINT (margin) >= 0)
1750 img->vmargin = img->hmargin = XFASTINT (margin);
1751 else if (CONSP (margin) && INTEGERP (XCAR (margin))
1752 && INTEGERP (XCDR (margin)))
1753 {
1754 if (XINT (XCAR (margin)) > 0)
1755 img->hmargin = XFASTINT (XCAR (margin));
1756 if (XINT (XCDR (margin)) > 0)
1757 img->vmargin = XFASTINT (XCDR (margin));
1758 }
1759
1760 relief = image_spec_value (spec, QCrelief, NULL);
1761 if (INTEGERP (relief))
1762 {
1763 img->relief = XINT (relief);
1764 img->hmargin += abs (img->relief);
1765 img->vmargin += abs (img->relief);
1766 }
1767
1768 if (! img->background_valid)
1769 {
1770 bg = image_spec_value (img->spec, QCbackground, NULL);
1771 if (!NILP (bg))
1772 {
1773 img->background
1774 = x_alloc_image_color (f, img, bg,
1775 FRAME_BACKGROUND_PIXEL (f));
1776 img->background_valid = 1;
1777 }
1778 }
1779
1780 /* Do image transformations and compute masks, unless we
1781 don't have the image yet. */
1782 if (!EQ (*img->type->type, Qpostscript))
1783 postprocess_image (f, img);
1784 }
1785
1786 UNBLOCK_INPUT;
1787 }
1788
1789 /* We're using IMG, so set its timestamp to `now'. */
1790 EMACS_GET_TIME (now);
1791 img->timestamp = EMACS_SECS (now);
1792
1793 UNGCPRO;
1794
1795 /* Value is the image id. */
1796 return img->id;
1797}
1798
1799
1800/* Cache image IMG in the image cache of frame F. */
1801
1802static void
1803cache_image (f, img)
1804 struct frame *f;
1805 struct image *img;
1806{
1807 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1808 int i;
1809
1810 /* Find a free slot in c->images. */
1811 for (i = 0; i < c->used; ++i)
1812 if (c->images[i] == NULL)
1813 break;
1814
1815 /* If no free slot found, maybe enlarge c->images. */
1816 if (i == c->used && c->used == c->size)
1817 {
1818 c->size *= 2;
1819 c->images = (struct image **) xrealloc (c->images,
1820 c->size * sizeof *c->images);
1821 }
1822
1823 /* Add IMG to c->images, and assign IMG an id. */
1824 c->images[i] = img;
1825 img->id = i;
1826 if (i == c->used)
1827 ++c->used;
1828
1829 /* Add IMG to the cache's hash table. */
1830 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
1831 img->next = c->buckets[i];
1832 if (img->next)
1833 img->next->prev = img;
1834 img->prev = NULL;
1835 c->buckets[i] = img;
1836}
1837
1838
1839/* Call FN on every image in the image cache of frame F. Used to mark
1840 Lisp Objects in the image cache. */
1841
1842void
1843forall_images_in_image_cache (f, fn)
1844 struct frame *f;
1845 void (*fn) P_ ((struct image *img));
1846{
1847 if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f))
1848 {
1849 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
1850 if (c)
1851 {
1852 int i;
1853 for (i = 0; i < c->used; ++i)
1854 if (c->images[i])
1855 fn (c->images[i]);
1856 }
1857 }
1858}
1859
1860
1861\f
1862/***********************************************************************
1863 X / MAC / W32 support code
1864 ***********************************************************************/
1865
1866#ifdef HAVE_NTGUI
1867
1868/* Macro for defining functions that will be loaded from image DLLs. */
09e8eb5b 1869#define DEF_IMGLIB_FN(func) int (FAR CDECL *fn_##func)()
4ef0d4d0
KS
1870
1871/* Macro for loading those image functions from the library. */
1872#define LOAD_IMGLIB_FN(lib,func) { \
1873 fn_##func = (void *) GetProcAddress (lib, #func); \
1874 if (!fn_##func) return 0; \
1875 }
1876
0855eb52
JB
1877/* Load a DLL implementing an image type.
1878 The `image-library-alist' variable associates a symbol,
1879 identifying an image type, to a list of possible filenames.
1880 The function returns NULL if no library could be loaded for
1881 the given image type, or if the library was previously loaded;
1882 else the handle of the DLL. */
1883static HMODULE
1884w32_delayed_load (Lisp_Object libraries, Lisp_Object type)
1885{
1886 HMODULE library = NULL;
1887
1888 if (CONSP (libraries) && NILP (Fassq (type, Vimage_type_cache)))
1889 {
1890 Lisp_Object dlls = Fassq (type, libraries);
1891
1892 if (CONSP (dlls))
1893 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
1894 {
1895 CHECK_STRING_CAR (dlls);
1896 if (library = LoadLibrary (SDATA (XCAR (dlls))))
1897 break;
1898 }
1899 }
1900
1901 return library;
1902}
1903
4ef0d4d0
KS
1904#endif /* HAVE_NTGUI */
1905
1906static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
1907 XImagePtr *, Pixmap *));
1908static void x_destroy_x_image P_ ((XImagePtr));
1909static void x_put_x_image P_ ((struct frame *, XImagePtr, Pixmap, int, int));
1910
1911
1912/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
1913 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
1914 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
1915 via xmalloc. Print error messages via image_error if an error
1916 occurs. Value is non-zero if successful.
1917
1918 On W32, a DEPTH of zero signifies a 24 bit image, otherwise DEPTH
1919 should indicate the bit depth of the image. */
1920
1921static int
1922x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
1923 struct frame *f;
1924 int width, height, depth;
1925 XImagePtr *ximg;
1926 Pixmap *pixmap;
1927{
1928#ifdef HAVE_X_WINDOWS
1929 Display *display = FRAME_X_DISPLAY (f);
1930 Window window = FRAME_X_WINDOW (f);
1931 Screen *screen = FRAME_X_SCREEN (f);
1932
1933 xassert (interrupt_input_blocked);
1934
1935 if (depth <= 0)
1936 depth = DefaultDepthOfScreen (screen);
1937 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
1938 depth, ZPixmap, 0, NULL, width, height,
1939 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
1940 if (*ximg == NULL)
1941 {
1942 image_error ("Unable to allocate X image", Qnil, Qnil);
1943 return 0;
1944 }
1945
1946 /* Allocate image raster. */
1947 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
1948
1949 /* Allocate a pixmap of the same size. */
1950 *pixmap = XCreatePixmap (display, window, width, height, depth);
1951 if (*pixmap == NO_PIXMAP)
1952 {
1953 x_destroy_x_image (*ximg);
1954 *ximg = NULL;
1955 image_error ("Unable to create X pixmap", Qnil, Qnil);
1956 return 0;
1957 }
1958
1959 return 1;
1960#endif /* HAVE_X_WINDOWS */
1961
1962#ifdef HAVE_NTGUI
1963
1964 BITMAPINFOHEADER *header;
1965 HDC hdc;
1966 int scanline_width_bits;
1967 int remainder;
1968 int palette_colors = 0;
1969
1970 if (depth == 0)
1971 depth = 24;
1972
1973 if (depth != 1 && depth != 4 && depth != 8
1974 && depth != 16 && depth != 24 && depth != 32)
1975 {
1976 image_error ("Invalid image bit depth specified", Qnil, Qnil);
1977 return 0;
1978 }
1979
1980 scanline_width_bits = width * depth;
1981 remainder = scanline_width_bits % 32;
1982
1983 if (remainder)
1984 scanline_width_bits += 32 - remainder;
1985
1986 /* Bitmaps with a depth less than 16 need a palette. */
1987 /* BITMAPINFO structure already contains the first RGBQUAD. */
1988 if (depth < 16)
1989 palette_colors = 1 << depth - 1;
1990
1991 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
1992 if (*ximg == NULL)
1993 {
1994 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
1995 return 0;
1996 }
1997
1998 header = &((*ximg)->info.bmiHeader);
1999 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
2000 header->biSize = sizeof (*header);
2001 header->biWidth = width;
2002 header->biHeight = -height; /* negative indicates a top-down bitmap. */
2003 header->biPlanes = 1;
2004 header->biBitCount = depth;
2005 header->biCompression = BI_RGB;
2006 header->biClrUsed = palette_colors;
2007
2008 /* TODO: fill in palette. */
2009 if (depth == 1)
2010 {
2011 (*ximg)->info.bmiColors[0].rgbBlue = 0;
2012 (*ximg)->info.bmiColors[0].rgbGreen = 0;
2013 (*ximg)->info.bmiColors[0].rgbRed = 0;
2014 (*ximg)->info.bmiColors[0].rgbReserved = 0;
2015 (*ximg)->info.bmiColors[1].rgbBlue = 255;
2016 (*ximg)->info.bmiColors[1].rgbGreen = 255;
2017 (*ximg)->info.bmiColors[1].rgbRed = 255;
2018 (*ximg)->info.bmiColors[1].rgbReserved = 0;
2019 }
2020
2021 hdc = get_frame_dc (f);
2022
2023 /* Create a DIBSection and raster array for the bitmap,
2024 and store its handle in *pixmap. */
2025 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
2026 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
2e09fef1
EZ
2027 /* casting avoids a GCC warning */
2028 (void **)&((*ximg)->data), NULL, 0);
4ef0d4d0
KS
2029
2030 /* Realize display palette and garbage all frames. */
2031 release_frame_dc (f, hdc);
2032
2033 if (*pixmap == NULL)
2034 {
2035 DWORD err = GetLastError();
2036 Lisp_Object errcode;
2037 /* All system errors are < 10000, so the following is safe. */
2038 XSETINT (errcode, (int) err);
2039 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2040 x_destroy_x_image (*ximg);
2041 return 0;
2042 }
2043
2044 return 1;
2045
2046#endif /* HAVE_NTGUI */
2047
2048#ifdef MAC_OS
2049 Display *display = FRAME_X_DISPLAY (f);
2050 Window window = FRAME_X_WINDOW (f);
2051
2052 xassert (interrupt_input_blocked);
2053
2054 /* Allocate a pixmap of the same size. */
2055 *pixmap = XCreatePixmap (display, window, width, height, depth);
2056 if (*pixmap == NO_PIXMAP)
2057 {
4ef0d4d0
KS
2058 *ximg = NULL;
2059 image_error ("Unable to create X pixmap", Qnil, Qnil);
2060 return 0;
2061 }
2062
2063 LockPixels (GetGWorldPixMap (*pixmap));
2064 *ximg = *pixmap;
2065 return 1;
2066
2067#endif /* MAC_OS */
2068}
2069
2070
2071/* Destroy XImage XIMG. Free XIMG->data. */
2072
2073static void
2074x_destroy_x_image (ximg)
2075 XImagePtr ximg;
2076{
2077 xassert (interrupt_input_blocked);
2078 if (ximg)
2079 {
2080#ifdef HAVE_X_WINDOWS
2081 xfree (ximg->data);
2082 ximg->data = NULL;
2083 XDestroyImage (ximg);
2084#endif /* HAVE_X_WINDOWS */
2085#ifdef HAVE_NTGUI
2086 /* Data will be freed by DestroyObject. */
2087 ximg->data = NULL;
2088 xfree (ximg);
2089#endif /* HAVE_NTGUI */
2090#ifdef MAC_OS
2091 XDestroyImage (ximg);
2092#endif /* MAC_OS */
2093 }
2094}
2095
2096
2097/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
2098 are width and height of both the image and pixmap. */
2099
2100static void
2101x_put_x_image (f, ximg, pixmap, width, height)
2102 struct frame *f;
2103 XImagePtr ximg;
2104 Pixmap pixmap;
2105 int width, height;
2106{
2107#ifdef HAVE_X_WINDOWS
2108 GC gc;
2109
2110 xassert (interrupt_input_blocked);
2111 gc = XCreateGC (FRAME_X_DISPLAY (f), pixmap, 0, NULL);
2112 XPutImage (FRAME_X_DISPLAY (f), pixmap, gc, ximg, 0, 0, 0, 0, width, height);
2113 XFreeGC (FRAME_X_DISPLAY (f), gc);
2114#endif /* HAVE_X_WINDOWS */
2115
2116#ifdef HAVE_NTGUI
2117#if 0 /* I don't think this is necessary looking at where it is used. */
2118 HDC hdc = get_frame_dc (f);
2119 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
2120 release_frame_dc (f, hdc);
2121#endif
2122#endif /* HAVE_NTGUI */
2123
2124#ifdef MAC_OS
2125 xassert (ximg == pixmap);
2126#endif /* MAC_OS */
2127}
2128
2129\f
2130/***********************************************************************
2131 File Handling
2132 ***********************************************************************/
2133
4ef0d4d0
KS
2134static unsigned char *slurp_file P_ ((char *, int *));
2135
2136
2137/* Find image file FILE. Look in data-directory, then
2138 x-bitmap-file-path. Value is the full name of the file found, or
2139 nil if not found. */
2140
c640aa9b 2141Lisp_Object
4ef0d4d0
KS
2142x_find_image_file (file)
2143 Lisp_Object file;
2144{
2145 Lisp_Object file_found, search_path;
2146 struct gcpro gcpro1, gcpro2;
2147 int fd;
2148
2149 file_found = Qnil;
2150 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
2151 GCPRO2 (file_found, search_path);
2152
2153 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
2154 fd = openp (search_path, file, Qnil, &file_found, Qnil);
2155
2156 if (fd == -1)
2157 file_found = Qnil;
2158 else
2159 close (fd);
2160
2161 UNGCPRO;
2162 return file_found;
2163}
2164
2165
2166/* Read FILE into memory. Value is a pointer to a buffer allocated
2167 with xmalloc holding FILE's contents. Value is null if an error
2168 occurred. *SIZE is set to the size of the file. */
2169
2170static unsigned char *
2171slurp_file (file, size)
2172 char *file;
2173 int *size;
2174{
2175 FILE *fp = NULL;
2176 unsigned char *buf = NULL;
2177 struct stat st;
2178
2179 if (stat (file, &st) == 0
2180 && (fp = fopen (file, "rb")) != NULL
fa8459a3 2181 && (buf = (unsigned char *) xmalloc (st.st_size),
4ef0d4d0
KS
2182 fread (buf, 1, st.st_size, fp) == st.st_size))
2183 {
2184 *size = st.st_size;
2185 fclose (fp);
2186 }
2187 else
2188 {
2189 if (fp)
2190 fclose (fp);
2191 if (buf)
2192 {
2193 xfree (buf);
2194 buf = NULL;
2195 }
2196 }
2197
2198 return buf;
2199}
2200
2201
2202\f
2203#ifdef MAC_OS
2204
2205/***********************************************************************
2206 MAC Image Load Functions
2207 ***********************************************************************/
2208
2209static int image_load_quicktime P_ ((struct frame *, struct image *img,
2210 OSType));
2211#ifdef MAC_OSX
2212static int image_load_quartz2d P_ ((struct frame *, struct image *img, int));
2213#endif
2214
2215static OSErr
2216find_image_fsspec (specified_file, file, fss)
2217 Lisp_Object specified_file, *file;
2218 FSSpec *fss;
2219{
9ecf6403 2220#if MAC_OSX
4ef0d4d0 2221 FSRef fsr;
4ef0d4d0
KS
2222#endif
2223 OSErr err;
2224
2225 *file = x_find_image_file (specified_file);
2226 if (!STRINGP (*file))
2227 return fnfErr; /* file or directory not found;
2228 incomplete pathname */
2229 /* Try to open the image file. */
9ecf6403 2230#if MAC_OSX
4ef0d4d0
KS
2231 err = FSPathMakeRef (SDATA (*file), &fsr, NULL);
2232 if (err == noErr)
2233 err = FSGetCatalogInfo (&fsr, kFSCatInfoNone, NULL, NULL, fss, NULL);
2234#else
9ecf6403 2235 err = posix_pathname_to_fsspec (SDATA (*file), fss);
4ef0d4d0
KS
2236#endif
2237 return err;
2238}
2239
2240static int
2241image_load_qt_1 (f, img, type, fss, dh)
2242 struct frame *f;
2243 struct image *img;
2244 OSType type;
2245 FSSpec *fss;
2246 Handle dh;
2247{
2248 OSErr err;
2249 GraphicsImportComponent gi;
2250 Rect rect;
2251 int width, height;
2252 short draw_all_pixels;
2253 Lisp_Object specified_bg;
2254 XColor color;
2255 XImagePtr ximg;
2256 RGBColor bg_color;
2257
2258 err = OpenADefaultComponent (GraphicsImporterComponentType,
2259 type, &gi);
2260 if (err != noErr)
2261 {
2262 image_error ("Cannot get importer component for `%s'", img->spec, Qnil);
2263 return 0;
2264 }
2265 if (dh == NULL)
2266 {
2267 /* read from file system spec */
2268 err = GraphicsImportSetDataFile (gi, fss);
2269 if (err != noErr)
2270 {
2271 image_error ("Cannot set fsspec to graphics importer for '%s'",
2272 img->spec, Qnil);
2273 goto error;
2274 }
2275 }
2276 else
2277 {
2278 /* read from data handle */
2279 err = GraphicsImportSetDataHandle (gi, dh);
2280 if (err != noErr)
2281 {
2282 image_error ("Cannot set data handle to graphics importer for `%s'",
2283 img->spec, Qnil);
2284 goto error;
2285 }
2286 }
2287 err = GraphicsImportGetNaturalBounds (gi, &rect);
2288 if (err != noErr)
2289 {
2290 image_error ("Error reading `%s'", img->spec, Qnil);
2291 goto error;
2292 }
2293 width = img->width = rect.right - rect.left;
2294 height = img->height = rect.bottom - rect.top;
2295 err = GraphicsImportDoesDrawAllPixels (gi, &draw_all_pixels);
2296#if 0
2297 /* Don't check the error code here. It may have an undocumented
2298 value -32766. */
2299 if (err != noErr)
2300 {
2301 image_error ("Error reading `%s'", img->spec, Qnil);
2302 goto error;
2303 }
2304#endif
2305 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2306 {
2307 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2308 if (!STRINGP (specified_bg) ||
2309 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2310 {
2311 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2312 color.red = RED16_FROM_ULONG (color.pixel);
2313 color.green = GREEN16_FROM_ULONG (color.pixel);
2314 color.blue = BLUE16_FROM_ULONG (color.pixel);
2315 }
2316 }
2317
2318 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2319 goto error;
2320 if (draw_all_pixels != graphicsImporterDrawsAllPixels)
2321 {
2a316a84
ST
2322 CGrafPtr old_port;
2323 GDHandle old_gdh;
2324
2325 GetGWorld (&old_port, &old_gdh);
4ef0d4d0
KS
2326 SetGWorld (ximg, NULL);
2327 bg_color.red = color.red;
2328 bg_color.green = color.green;
2329 bg_color.blue = color.blue;
2330 RGBBackColor (&bg_color);
2331#if TARGET_API_MAC_CARBON
2332 GetPortBounds (ximg, &rect);
2333 EraseRect (&rect);
2334#else
2335 EraseRect (&(ximg->portRect));
2336#endif
2a316a84 2337 SetGWorld (old_port, old_gdh);
4ef0d4d0
KS
2338 }
2339 GraphicsImportSetGWorld (gi, ximg, NULL);
2340 GraphicsImportDraw (gi);
2341 CloseComponent (gi);
2342
2343 /* Maybe fill in the background field while we have ximg handy. */
2344 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2345 IMAGE_BACKGROUND (img, f, ximg);
2346
2347 /* Put the image into the pixmap. */
2348 x_put_x_image (f, ximg, img->pixmap, width, height);
2349 x_destroy_x_image (ximg);
2350 return 1;
2351
2352 error:
2353 CloseComponent (gi);
2354 return 0;
2355}
2356
2357
2358/* Load an image using the QuickTime Graphics Importer.
2359 Note: The alpha channel does not work for PNG images. */
2360static int
2361image_load_quicktime (f, img, type)
2362 struct frame *f;
2363 struct image *img;
2364 OSType type;
2365{
2366 Lisp_Object specified_file;
2367 Lisp_Object specified_data;
2368 OSErr err;
2369
2370 specified_file = image_spec_value (img->spec, QCfile, NULL);
2371 specified_data = image_spec_value (img->spec, QCdata, NULL);
2372
2373 if (NILP (specified_data))
2374 {
2375 /* Read from a file */
2376 Lisp_Object file;
2377 FSSpec fss;
2378
2379 err = find_image_fsspec (specified_file, &file, &fss);
2380 if (err != noErr)
2381 {
2382 if (err == fnfErr)
2383 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2384 else
2385 image_error ("Cannot open `%s'", file, Qnil);
2386 return 0;
2387 }
2388 return image_load_qt_1 (f, img, type, &fss, NULL);
2389 }
2390 else
2391 {
2392 /* Memory source! */
2393 int success_p;
2394 Handle dh;
2395
2396 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
2397 if (err != noErr)
2398 {
2399 image_error ("Cannot allocate data handle for `%s'",
2400 img->spec, Qnil);
2401 return 0;
2402 }
2403 success_p = image_load_qt_1 (f, img, type, NULL, dh);
2404 DisposeHandle (dh);
2405 return success_p;
2406 }
2407}
2408
2409
2410#ifdef MAC_OSX
2411/* Load a PNG/JPEG image using Quartz 2D decoding routines.
2412 CGImageCreateWithPNGDataProvider is provided after Mac OS X 10.2.
2413 So don't use this function directly but determine at runtime
2414 whether it exists. */
2415typedef CGImageRef (*CGImageCreateWithPNGDataProviderProcType)
2416 (CGDataProviderRef, const float [], bool, CGColorRenderingIntent);
2417static CGImageCreateWithPNGDataProviderProcType MyCGImageCreateWithPNGDataProvider;
2418
2419
2420static void
2421init_image_func_pointer ()
2422{
2423 if (NSIsSymbolNameDefined ("_CGImageCreateWithPNGDataProvider"))
2424 {
2425 MyCGImageCreateWithPNGDataProvider
2426 = (CGImageCreateWithPNGDataProviderProcType)
2427 NSAddressOfSymbol (NSLookupAndBindSymbol
2428 ("_CGImageCreateWithPNGDataProvider"));
2429 }
2430 else
2431 MyCGImageCreateWithPNGDataProvider = NULL;
2432}
2433
2434
2435static int
2436image_load_quartz2d (f, img, png_p)
2437 struct frame *f;
2438 struct image *img;
2439 int png_p;
2440{
2441 Lisp_Object file, specified_file;
2442 Lisp_Object specified_data, specified_bg;
2443 struct gcpro gcpro1;
2444 CGDataProviderRef source;
2445 CGImageRef image;
2446 int width, height;
2447 XColor color;
2448 XImagePtr ximg = NULL;
2449 CGContextRef context;
2450 CGRect rectangle;
2451
2452 /* Open the file. */
2453 specified_file = image_spec_value (img->spec, QCfile, NULL);
2454 specified_data = image_spec_value (img->spec, QCdata, NULL);
2455
2456 file = Qnil;
2457 GCPRO1 (file);
2458
2459 if (NILP (specified_data))
2460 {
2461 CFStringRef path;
2462 CFURLRef url;
2463
2464 file = x_find_image_file (specified_file);
2465 if (!STRINGP (file))
2466 {
2467 image_error ("Cannot find image file `%s'", specified_file, Qnil);
2468 UNGCPRO;
2469 return 0;
2470 }
a5e700ca 2471 path = cfstring_create_with_string (file);
4ef0d4d0
KS
2472 url = CFURLCreateWithFileSystemPath (NULL, path,
2473 kCFURLPOSIXPathStyle, 0);
2474 CFRelease (path);
2475 source = CGDataProviderCreateWithURL (url);
2476 CFRelease (url);
2477 }
2478 else
2479 source = CGDataProviderCreateWithData (NULL, SDATA (specified_data),
2480 SBYTES (specified_data), NULL);
2481
2482 if (png_p)
2483 image = (*MyCGImageCreateWithPNGDataProvider) (source, NULL, FALSE,
2484 kCGRenderingIntentDefault);
2485 else
2486 image = CGImageCreateWithJPEGDataProvider (source, NULL, FALSE,
2487 kCGRenderingIntentDefault);
2488
2489 CGDataProviderRelease (source);
2490 if (image == NULL)
2491 {
2492 UNGCPRO;
2493 image_error ("Error reading image `%s'", img->spec, Qnil);
2494 return 0;
2495 }
2496
2497 if (png_p)
2498 {
2499 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
2500 if (!STRINGP (specified_bg) ||
2501 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
2502 {
2503 color.pixel = FRAME_BACKGROUND_PIXEL (f);
2504 color.red = RED16_FROM_ULONG (color.pixel);
2505 color.green = GREEN16_FROM_ULONG (color.pixel);
2506 color.blue = BLUE16_FROM_ULONG (color.pixel);
2507 }
2508 }
2509 width = img->width = CGImageGetWidth (image);
2510 height = img->height = CGImageGetHeight (image);
2511 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
2512 {
2513 CGImageRelease (image);
2514 UNGCPRO;
2515 return 0;
2516 }
2517 rectangle = CGRectMake (0, 0, width, height);
2518 QDBeginCGContext (ximg, &context);
2519 if (png_p)
2520 {
2521 CGContextSetRGBFillColor (context, color.red / 65535.0,
2522 color.green / 65535.0,
2523 color.blue / 65535.0, 1.0);
2524 CGContextFillRect (context, rectangle);
2525 }
2526 CGContextDrawImage (context, rectangle, image);
2527 QDEndCGContext (ximg, &context);
2528 CGImageRelease (image);
2529
2530 /* Maybe fill in the background field while we have ximg handy. */
2531 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2532 IMAGE_BACKGROUND (img, f, ximg);
2533
2534 /* Put the image into the pixmap. */
2535 x_put_x_image (f, ximg, img->pixmap, width, height);
2536 x_destroy_x_image (ximg);
2537 UNGCPRO;
2538 return 1;
2539}
2540#endif
2541
2542#endif /* MAC_OS */
2543
2544\f
2545/***********************************************************************
2546 XBM images
2547 ***********************************************************************/
2548
2549static int xbm_scan P_ ((unsigned char **, unsigned char *, char *, int *));
2550static int xbm_load P_ ((struct frame *f, struct image *img));
2551static int xbm_load_image P_ ((struct frame *f, struct image *img,
2552 unsigned char *, unsigned char *));
2553static int xbm_image_p P_ ((Lisp_Object object));
2554static int xbm_read_bitmap_data P_ ((unsigned char *, unsigned char *,
2555 int *, int *, unsigned char **));
2556static int xbm_file_p P_ ((Lisp_Object));
2557
2558
2559/* Indices of image specification fields in xbm_format, below. */
2560
2561enum xbm_keyword_index
2562{
2563 XBM_TYPE,
2564 XBM_FILE,
2565 XBM_WIDTH,
2566 XBM_HEIGHT,
2567 XBM_DATA,
2568 XBM_FOREGROUND,
2569 XBM_BACKGROUND,
2570 XBM_ASCENT,
2571 XBM_MARGIN,
2572 XBM_RELIEF,
2573 XBM_ALGORITHM,
2574 XBM_HEURISTIC_MASK,
2575 XBM_MASK,
2576 XBM_LAST
2577};
2578
2579/* Vector of image_keyword structures describing the format
2580 of valid XBM image specifications. */
2581
2582static struct image_keyword xbm_format[XBM_LAST] =
2583{
2584 {":type", IMAGE_SYMBOL_VALUE, 1},
2585 {":file", IMAGE_STRING_VALUE, 0},
2586 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2587 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
2588 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2589 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
2590 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
2591 {":ascent", IMAGE_ASCENT_VALUE, 0},
2592 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
2593 {":relief", IMAGE_INTEGER_VALUE, 0},
2594 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2595 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
2596 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
2597};
2598
2599/* Structure describing the image type XBM. */
2600
2601static struct image_type xbm_type =
2602{
2603 &Qxbm,
2604 xbm_image_p,
2605 xbm_load,
2606 x_clear_image,
2607 NULL
2608};
2609
2610/* Tokens returned from xbm_scan. */
2611
2612enum xbm_token
2613{
2614 XBM_TK_IDENT = 256,
2615 XBM_TK_NUMBER
2616};
2617
2618
2619/* Return non-zero if OBJECT is a valid XBM-type image specification.
2620 A valid specification is a list starting with the symbol `image'
2621 The rest of the list is a property list which must contain an
2622 entry `:type xbm..
2623
2624 If the specification specifies a file to load, it must contain
2625 an entry `:file FILENAME' where FILENAME is a string.
2626
2627 If the specification is for a bitmap loaded from memory it must
2628 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
2629 WIDTH and HEIGHT are integers > 0. DATA may be:
2630
2631 1. a string large enough to hold the bitmap data, i.e. it must
2632 have a size >= (WIDTH + 7) / 8 * HEIGHT
2633
2634 2. a bool-vector of size >= WIDTH * HEIGHT
2635
2636 3. a vector of strings or bool-vectors, one for each line of the
2637 bitmap.
2638
2639 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
2640 may not be specified in this case because they are defined in the
2641 XBM file.
2642
2643 Both the file and data forms may contain the additional entries
2644 `:background COLOR' and `:foreground COLOR'. If not present,
2645 foreground and background of the frame on which the image is
2646 displayed is used. */
2647
2648static int
2649xbm_image_p (object)
2650 Lisp_Object object;
2651{
2652 struct image_keyword kw[XBM_LAST];
2653
2654 bcopy (xbm_format, kw, sizeof kw);
2655 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
2656 return 0;
2657
2658 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
2659
2660 if (kw[XBM_FILE].count)
2661 {
2662 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
2663 return 0;
2664 }
2665 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
2666 {
2667 /* In-memory XBM file. */
2668 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
2669 return 0;
2670 }
2671 else
2672 {
2673 Lisp_Object data;
2674 int width, height;
2675
2676 /* Entries for `:width', `:height' and `:data' must be present. */
2677 if (!kw[XBM_WIDTH].count
2678 || !kw[XBM_HEIGHT].count
2679 || !kw[XBM_DATA].count)
2680 return 0;
2681
2682 data = kw[XBM_DATA].value;
2683 width = XFASTINT (kw[XBM_WIDTH].value);
2684 height = XFASTINT (kw[XBM_HEIGHT].value);
2685
2686 /* Check type of data, and width and height against contents of
2687 data. */
2688 if (VECTORP (data))
2689 {
2690 int i;
2691
2692 /* Number of elements of the vector must be >= height. */
2693 if (XVECTOR (data)->size < height)
2694 return 0;
2695
2696 /* Each string or bool-vector in data must be large enough
2697 for one line of the image. */
2698 for (i = 0; i < height; ++i)
2699 {
2700 Lisp_Object elt = XVECTOR (data)->contents[i];
2701
2702 if (STRINGP (elt))
2703 {
2704 if (SCHARS (elt)
2705 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
2706 return 0;
2707 }
2708 else if (BOOL_VECTOR_P (elt))
2709 {
2710 if (XBOOL_VECTOR (elt)->size < width)
2711 return 0;
2712 }
2713 else
2714 return 0;
2715 }
2716 }
2717 else if (STRINGP (data))
2718 {
2719 if (SCHARS (data)
2720 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
2721 return 0;
2722 }
2723 else if (BOOL_VECTOR_P (data))
2724 {
2725 if (XBOOL_VECTOR (data)->size < width * height)
2726 return 0;
2727 }
2728 else
2729 return 0;
2730 }
2731
2732 return 1;
2733}
2734
2735
2736/* Scan a bitmap file. FP is the stream to read from. Value is
2737 either an enumerator from enum xbm_token, or a character for a
2738 single-character token, or 0 at end of file. If scanning an
2739 identifier, store the lexeme of the identifier in SVAL. If
2740 scanning a number, store its value in *IVAL. */
2741
2742static int
2743xbm_scan (s, end, sval, ival)
2744 unsigned char **s, *end;
2745 char *sval;
2746 int *ival;
2747{
2748 unsigned int c;
2749
2750 loop:
2751
2752 /* Skip white space. */
2753 while (*s < end && (c = *(*s)++, isspace (c)))
2754 ;
2755
2756 if (*s >= end)
2757 c = 0;
2758 else if (isdigit (c))
2759 {
2760 int value = 0, digit;
2761
2762 if (c == '0' && *s < end)
2763 {
2764 c = *(*s)++;
2765 if (c == 'x' || c == 'X')
2766 {
2767 while (*s < end)
2768 {
2769 c = *(*s)++;
2770 if (isdigit (c))
2771 digit = c - '0';
2772 else if (c >= 'a' && c <= 'f')
2773 digit = c - 'a' + 10;
2774 else if (c >= 'A' && c <= 'F')
2775 digit = c - 'A' + 10;
2776 else
2777 break;
2778 value = 16 * value + digit;
2779 }
2780 }
2781 else if (isdigit (c))
2782 {
2783 value = c - '0';
2784 while (*s < end
2785 && (c = *(*s)++, isdigit (c)))
2786 value = 8 * value + c - '0';
2787 }
2788 }
2789 else
2790 {
2791 value = c - '0';
2792 while (*s < end
2793 && (c = *(*s)++, isdigit (c)))
2794 value = 10 * value + c - '0';
2795 }
2796
2797 if (*s < end)
2798 *s = *s - 1;
2799 *ival = value;
2800 c = XBM_TK_NUMBER;
2801 }
2802 else if (isalpha (c) || c == '_')
2803 {
2804 *sval++ = c;
2805 while (*s < end
2806 && (c = *(*s)++, (isalnum (c) || c == '_')))
2807 *sval++ = c;
2808 *sval = 0;
2809 if (*s < end)
2810 *s = *s - 1;
2811 c = XBM_TK_IDENT;
2812 }
2813 else if (c == '/' && **s == '*')
2814 {
2815 /* C-style comment. */
2816 ++*s;
2817 while (**s && (**s != '*' || *(*s + 1) != '/'))
2818 ++*s;
2819 if (**s)
2820 {
2821 *s += 2;
2822 goto loop;
2823 }
2824 }
2825
2826 return c;
2827}
2828
2829#ifdef HAVE_NTGUI
2830
2831/* Create a Windows bitmap from X bitmap data. */
2832static HBITMAP
2833w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
2834{
2835 static unsigned char swap_nibble[16]
2836 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
2837 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
2838 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
2839 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
2840 int i, j, w1, w2;
2841 unsigned char *bits, *p;
2842 HBITMAP bmp;
2843
2844 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
2845 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
2846 bits = (unsigned char *) alloca (height * w2);
2847 bzero (bits, height * w2);
2848 for (i = 0; i < height; i++)
2849 {
2850 p = bits + i*w2;
2851 for (j = 0; j < w1; j++)
2852 {
2853 /* Bitswap XBM bytes to match how Windows does things. */
2854 unsigned char c = *data++;
2855 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
2856 | (swap_nibble[(c>>4) & 0xf]));
2857 }
2858 }
2859 bmp = CreateBitmap (width, height, 1, 1, (char *) bits);
2860
2861 return bmp;
2862}
2863
2864static void convert_mono_to_color_image (f, img, foreground, background)
2865 struct frame *f;
2866 struct image *img;
2867 COLORREF foreground, background;
2868{
2869 HDC hdc, old_img_dc, new_img_dc;
2870 HGDIOBJ old_prev, new_prev;
2871 HBITMAP new_pixmap;
2872
2873 hdc = get_frame_dc (f);
2874 old_img_dc = CreateCompatibleDC (hdc);
2875 new_img_dc = CreateCompatibleDC (hdc);
2876 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
2877 release_frame_dc (f, hdc);
2878 old_prev = SelectObject (old_img_dc, img->pixmap);
2879 new_prev = SelectObject (new_img_dc, new_pixmap);
2880 SetTextColor (new_img_dc, foreground);
2881 SetBkColor (new_img_dc, background);
2882
2883 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
2884 0, 0, SRCCOPY);
2885
2886 SelectObject (old_img_dc, old_prev);
2887 SelectObject (new_img_dc, new_prev);
2888 DeleteDC (old_img_dc);
2889 DeleteDC (new_img_dc);
2890 DeleteObject (img->pixmap);
2891 if (new_pixmap == 0)
2892 fprintf (stderr, "Failed to convert image to color.\n");
2893 else
2894 img->pixmap = new_pixmap;
2895}
2896
2897#define XBM_BIT_SHUFFLE(b) (~(b))
2898
2899#else
2900
2901#define XBM_BIT_SHUFFLE(b) (b)
2902
2903#endif /* HAVE_NTGUI */
2904
2905
2906static void
2907Create_Pixmap_From_Bitmap_Data(f, img, data, fg, bg, non_default_colors)
2908 struct frame *f;
2909 struct image *img;
2910 char *data;
2911 RGB_PIXEL_COLOR fg, bg;
2912 int non_default_colors;
2913{
2914#ifdef HAVE_NTGUI
2915 img->pixmap
2916 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
2917
2918 /* If colors were specified, transfer the bitmap to a color one. */
2919 if (non_default_colors)
2920 convert_mono_to_color_image (f, img, fg, bg);
2921#else
2922 img->pixmap
2923 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
2924 FRAME_X_WINDOW (f),
2925 data,
2926 img->width, img->height,
2927 fg, bg,
2928 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
2929#endif /* HAVE_NTGUI */
2930}
2931
2932
2933
2934/* Replacement for XReadBitmapFileData which isn't available under old
2935 X versions. CONTENTS is a pointer to a buffer to parse; END is the
2936 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
2937 the image. Return in *DATA the bitmap data allocated with xmalloc.
2938 Value is non-zero if successful. DATA null means just test if
2939 CONTENTS looks like an in-memory XBM file. */
2940
2941static int
2942xbm_read_bitmap_data (contents, end, width, height, data)
2943 unsigned char *contents, *end;
2944 int *width, *height;
2945 unsigned char **data;
2946{
2947 unsigned char *s = contents;
2948 char buffer[BUFSIZ];
2949 int padding_p = 0;
2950 int v10 = 0;
2951 int bytes_per_line, i, nbytes;
2952 unsigned char *p;
2953 int value;
2954 int LA1;
2955
2956#define match() \
2957 LA1 = xbm_scan (&s, end, buffer, &value)
2958
2959#define expect(TOKEN) \
2960 if (LA1 != (TOKEN)) \
2961 goto failure; \
2962 else \
2963 match ()
2964
2965#define expect_ident(IDENT) \
2966 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
2967 match (); \
2968 else \
2969 goto failure
2970
2971 *width = *height = -1;
2972 if (data)
2973 *data = NULL;
2974 LA1 = xbm_scan (&s, end, buffer, &value);
2975
2976 /* Parse defines for width, height and hot-spots. */
2977 while (LA1 == '#')
2978 {
2979 match ();
2980 expect_ident ("define");
2981 expect (XBM_TK_IDENT);
2982
2983 if (LA1 == XBM_TK_NUMBER);
2984 {
2985 char *p = strrchr (buffer, '_');
2986 p = p ? p + 1 : buffer;
2987 if (strcmp (p, "width") == 0)
2988 *width = value;
2989 else if (strcmp (p, "height") == 0)
2990 *height = value;
2991 }
2992 expect (XBM_TK_NUMBER);
2993 }
2994
2995 if (*width < 0 || *height < 0)
2996 goto failure;
2997 else if (data == NULL)
2998 goto success;
2999
3000 /* Parse bits. Must start with `static'. */
3001 expect_ident ("static");
3002 if (LA1 == XBM_TK_IDENT)
3003 {
3004 if (strcmp (buffer, "unsigned") == 0)
3005 {
3006 match ();
3007 expect_ident ("char");
3008 }
3009 else if (strcmp (buffer, "short") == 0)
3010 {
3011 match ();
3012 v10 = 1;
3013 if (*width % 16 && *width % 16 < 9)
3014 padding_p = 1;
3015 }
3016 else if (strcmp (buffer, "char") == 0)
3017 match ();
3018 else
3019 goto failure;
3020 }
3021 else
3022 goto failure;
3023
3024 expect (XBM_TK_IDENT);
3025 expect ('[');
3026 expect (']');
3027 expect ('=');
3028 expect ('{');
3029
3030 bytes_per_line = (*width + 7) / 8 + padding_p;
3031 nbytes = bytes_per_line * *height;
fa8459a3 3032 p = *data = (unsigned char *) xmalloc (nbytes);
4ef0d4d0
KS
3033
3034 if (v10)
3035 {
3036 for (i = 0; i < nbytes; i += 2)
3037 {
3038 int val = value;
3039 expect (XBM_TK_NUMBER);
3040
3041 *p++ = XBM_BIT_SHUFFLE (val);
3042 if (!padding_p || ((i + 2) % bytes_per_line))
3043 *p++ = XBM_BIT_SHUFFLE (value >> 8);
3044
3045 if (LA1 == ',' || LA1 == '}')
3046 match ();
3047 else
3048 goto failure;
3049 }
3050 }
3051 else
3052 {
3053 for (i = 0; i < nbytes; ++i)
3054 {
3055 int val = value;
3056 expect (XBM_TK_NUMBER);
3057
3058 *p++ = XBM_BIT_SHUFFLE (val);
3059
3060 if (LA1 == ',' || LA1 == '}')
3061 match ();
3062 else
3063 goto failure;
3064 }
3065 }
3066
3067 success:
3068 return 1;
3069
3070 failure:
3071
3072 if (data && *data)
3073 {
3074 xfree (*data);
3075 *data = NULL;
3076 }
3077 return 0;
3078
3079#undef match
3080#undef expect
3081#undef expect_ident
3082}
3083
3084
3085/* Load XBM image IMG which will be displayed on frame F from buffer
3086 CONTENTS. END is the end of the buffer. Value is non-zero if
3087 successful. */
3088
3089static int
3090xbm_load_image (f, img, contents, end)
3091 struct frame *f;
3092 struct image *img;
3093 unsigned char *contents, *end;
3094{
3095 int rc;
3096 unsigned char *data;
3097 int success_p = 0;
3098
3099 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
3100 if (rc)
3101 {
3102 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3103 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3104 int non_default_colors = 0;
3105 Lisp_Object value;
3106
3107 xassert (img->width > 0 && img->height > 0);
3108
3109 /* Get foreground and background colors, maybe allocate colors. */
3110 value = image_spec_value (img->spec, QCforeground, NULL);
3111 if (!NILP (value))
3112 {
3113 foreground = x_alloc_image_color (f, img, value, foreground);
3114 non_default_colors = 1;
3115 }
3116 value = image_spec_value (img->spec, QCbackground, NULL);
3117 if (!NILP (value))
3118 {
3119 background = x_alloc_image_color (f, img, value, background);
3120 img->background = background;
3121 img->background_valid = 1;
3122 non_default_colors = 1;
3123 }
3124
1f026899 3125 Create_Pixmap_From_Bitmap_Data (f, img, data,
4ef0d4d0
KS
3126 foreground, background,
3127 non_default_colors);
3128 xfree (data);
3129
3130 if (img->pixmap == NO_PIXMAP)
3131 {
3132 x_clear_image (f, img);
3133 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
3134 }
3135 else
3136 success_p = 1;
3137 }
3138 else
3139 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3140
3141 return success_p;
3142}
3143
3144
3145/* Value is non-zero if DATA looks like an in-memory XBM file. */
3146
3147static int
3148xbm_file_p (data)
3149 Lisp_Object data;
3150{
3151 int w, h;
3152 return (STRINGP (data)
3153 && xbm_read_bitmap_data (SDATA (data),
3154 (SDATA (data)
3155 + SBYTES (data)),
3156 &w, &h, NULL));
3157}
3158
3159
3160/* Fill image IMG which is used on frame F with pixmap data. Value is
3161 non-zero if successful. */
3162
3163static int
3164xbm_load (f, img)
3165 struct frame *f;
3166 struct image *img;
3167{
3168 int success_p = 0;
3169 Lisp_Object file_name;
3170
3171 xassert (xbm_image_p (img->spec));
3172
3173 /* If IMG->spec specifies a file name, create a non-file spec from it. */
3174 file_name = image_spec_value (img->spec, QCfile, NULL);
3175 if (STRINGP (file_name))
3176 {
3177 Lisp_Object file;
3178 unsigned char *contents;
3179 int size;
3180 struct gcpro gcpro1;
3181
3182 file = x_find_image_file (file_name);
3183 GCPRO1 (file);
3184 if (!STRINGP (file))
3185 {
3186 image_error ("Cannot find image file `%s'", file_name, Qnil);
3187 UNGCPRO;
3188 return 0;
3189 }
3190
3191 contents = slurp_file (SDATA (file), &size);
3192 if (contents == NULL)
3193 {
3194 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
3195 UNGCPRO;
3196 return 0;
3197 }
3198
3199 success_p = xbm_load_image (f, img, contents, contents + size);
3200 UNGCPRO;
3201 }
3202 else
3203 {
3204 struct image_keyword fmt[XBM_LAST];
3205 Lisp_Object data;
3206 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
3207 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
3208 int non_default_colors = 0;
3209 char *bits;
3210 int parsed_p;
3211 int in_memory_file_p = 0;
3212
3213 /* See if data looks like an in-memory XBM file. */
3214 data = image_spec_value (img->spec, QCdata, NULL);
3215 in_memory_file_p = xbm_file_p (data);
3216
3217 /* Parse the image specification. */
3218 bcopy (xbm_format, fmt, sizeof fmt);
3219 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
3220 xassert (parsed_p);
3221
3222 /* Get specified width, and height. */
3223 if (!in_memory_file_p)
3224 {
3225 img->width = XFASTINT (fmt[XBM_WIDTH].value);
3226 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
3227 xassert (img->width > 0 && img->height > 0);
3228 }
3229
3230 /* Get foreground and background colors, maybe allocate colors. */
3231 if (fmt[XBM_FOREGROUND].count
3232 && STRINGP (fmt[XBM_FOREGROUND].value))
3233 {
3234 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
3235 foreground);
3236 non_default_colors = 1;
3237 }
3238
3239 if (fmt[XBM_BACKGROUND].count
3240 && STRINGP (fmt[XBM_BACKGROUND].value))
3241 {
3242 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
3243 background);
3244 non_default_colors = 1;
3245 }
3246
3247 if (in_memory_file_p)
3248 success_p = xbm_load_image (f, img, SDATA (data),
3249 (SDATA (data)
3250 + SBYTES (data)));
3251 else
3252 {
3253 if (VECTORP (data))
3254 {
3255 int i;
3256 char *p;
3257 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
3258
3259 p = bits = (char *) alloca (nbytes * img->height);
3260 for (i = 0; i < img->height; ++i, p += nbytes)
3261 {
3262 Lisp_Object line = XVECTOR (data)->contents[i];
3263 if (STRINGP (line))
3264 bcopy (SDATA (line), p, nbytes);
3265 else
3266 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
3267 }
3268 }
3269 else if (STRINGP (data))
3270 bits = SDATA (data);
3271 else
3272 bits = XBOOL_VECTOR (data)->data;
3273
3274 /* Create the pixmap. */
3275
3276 Create_Pixmap_From_Bitmap_Data (f, img, bits,
3277 foreground, background,
3278 non_default_colors);
3279 if (img->pixmap)
3280 success_p = 1;
3281 else
3282 {
3283 image_error ("Unable to create pixmap for XBM image `%s'",
3284 img->spec, Qnil);
3285 x_clear_image (f, img);
3286 }
3287 }
3288 }
3289
3290 return success_p;
3291}
3292
3293
3294\f
3295/***********************************************************************
3296 XPM images
3297 ***********************************************************************/
3298
ea1aaa6f 3299#if defined (HAVE_XPM) || defined (MAC_OS)
4ef0d4d0
KS
3300
3301static int xpm_image_p P_ ((Lisp_Object object));
3302static int xpm_load P_ ((struct frame *f, struct image *img));
3303static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
3304
ea1aaa6f
ST
3305#endif /* HAVE_XPM || MAC_OS */
3306
3307#ifdef HAVE_XPM
4ef0d4d0
KS
3308#ifdef HAVE_NTGUI
3309/* Indicate to xpm.h that we don't have Xlib. */
3310#define FOR_MSW
3311/* simx.h in xpm defines XColor and XImage differently than Emacs. */
279d3293 3312/* It also defines Display the same way as Emacs, but gcc 3.3 still barfs. */
4ef0d4d0
KS
3313#define XColor xpm_XColor
3314#define XImage xpm_XImage
279d3293 3315#define Display xpm_Display
4ef0d4d0
KS
3316#define PIXEL_ALREADY_TYPEDEFED
3317#include "X11/xpm.h"
3318#undef FOR_MSW
3319#undef XColor
3320#undef XImage
279d3293 3321#undef Display
4ef0d4d0
KS
3322#undef PIXEL_ALREADY_TYPEDEFED
3323#else
3324#include "X11/xpm.h"
3325#endif /* HAVE_NTGUI */
ea1aaa6f 3326#endif /* HAVE_XPM */
4ef0d4d0 3327
ea1aaa6f 3328#if defined (HAVE_XPM) || defined (MAC_OS)
4ef0d4d0
KS
3329/* The symbol `xpm' identifying XPM-format images. */
3330
3331Lisp_Object Qxpm;
3332
3333/* Indices of image specification fields in xpm_format, below. */
3334
3335enum xpm_keyword_index
3336{
3337 XPM_TYPE,
3338 XPM_FILE,
3339 XPM_DATA,
3340 XPM_ASCENT,
3341 XPM_MARGIN,
3342 XPM_RELIEF,
3343 XPM_ALGORITHM,
3344 XPM_HEURISTIC_MASK,
3345 XPM_MASK,
3346 XPM_COLOR_SYMBOLS,
3347 XPM_BACKGROUND,
3348 XPM_LAST
3349};
3350
3351/* Vector of image_keyword structures describing the format
3352 of valid XPM image specifications. */
3353
3354static struct image_keyword xpm_format[XPM_LAST] =
3355{
3356 {":type", IMAGE_SYMBOL_VALUE, 1},
3357 {":file", IMAGE_STRING_VALUE, 0},
3358 {":data", IMAGE_STRING_VALUE, 0},
3359 {":ascent", IMAGE_ASCENT_VALUE, 0},
3360 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
3361 {":relief", IMAGE_INTEGER_VALUE, 0},
3362 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3363 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3364 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3365 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3366 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
3367};
3368
3369/* Structure describing the image type XPM. */
3370
3371static struct image_type xpm_type =
3372{
3373 &Qxpm,
3374 xpm_image_p,
3375 xpm_load,
3376 x_clear_image,
3377 NULL
3378};
3379
3380#ifdef HAVE_X_WINDOWS
3381
3382/* Define ALLOC_XPM_COLORS if we can use Emacs' own color allocation
3383 functions for allocating image colors. Our own functions handle
3384 color allocation failures more gracefully than the ones on the XPM
3385 lib. */
3386
3387#if defined XpmAllocColor && defined XpmFreeColors && defined XpmColorClosure
3388#define ALLOC_XPM_COLORS
3389#endif
3390#endif /* HAVE_X_WINDOWS */
3391
3392#ifdef ALLOC_XPM_COLORS
3393
3394static void xpm_init_color_cache P_ ((struct frame *, XpmAttributes *));
3395static void xpm_free_color_cache P_ ((void));
3396static int xpm_lookup_color P_ ((struct frame *, char *, XColor *));
3397static int xpm_color_bucket P_ ((char *));
3398static struct xpm_cached_color *xpm_cache_color P_ ((struct frame *, char *,
3399 XColor *, int));
3400
3401/* An entry in a hash table used to cache color definitions of named
3402 colors. This cache is necessary to speed up XPM image loading in
3403 case we do color allocations ourselves. Without it, we would need
3404 a call to XParseColor per pixel in the image. */
3405
3406struct xpm_cached_color
3407{
3408 /* Next in collision chain. */
3409 struct xpm_cached_color *next;
3410
3411 /* Color definition (RGB and pixel color). */
3412 XColor color;
3413
3414 /* Color name. */
3415 char name[1];
3416};
3417
3418/* The hash table used for the color cache, and its bucket vector
3419 size. */
3420
3421#define XPM_COLOR_CACHE_BUCKETS 1001
3422struct xpm_cached_color **xpm_color_cache;
3423
3424/* Initialize the color cache. */
3425
3426static void
3427xpm_init_color_cache (f, attrs)
3428 struct frame *f;
3429 XpmAttributes *attrs;
3430{
3431 size_t nbytes = XPM_COLOR_CACHE_BUCKETS * sizeof *xpm_color_cache;
3432 xpm_color_cache = (struct xpm_cached_color **) xmalloc (nbytes);
3433 memset (xpm_color_cache, 0, nbytes);
3434 init_color_table ();
3435
3436 if (attrs->valuemask & XpmColorSymbols)
3437 {
3438 int i;
3439 XColor color;
3440
3441 for (i = 0; i < attrs->numsymbols; ++i)
3442 if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3443 attrs->colorsymbols[i].value, &color))
3444 {
3445 color.pixel = lookup_rgb_color (f, color.red, color.green,
3446 color.blue);
3447 xpm_cache_color (f, attrs->colorsymbols[i].name, &color, -1);
3448 }
3449 }
3450}
3451
3452/* Free the color cache. */
3453
3454static void
3455xpm_free_color_cache ()
3456{
3457 struct xpm_cached_color *p, *next;
3458 int i;
3459
3460 for (i = 0; i < XPM_COLOR_CACHE_BUCKETS; ++i)
3461 for (p = xpm_color_cache[i]; p; p = next)
3462 {
3463 next = p->next;
3464 xfree (p);
3465 }
3466
3467 xfree (xpm_color_cache);
3468 xpm_color_cache = NULL;
3469 free_color_table ();
3470}
3471
3472/* Return the bucket index for color named COLOR_NAME in the color
3473 cache. */
3474
3475static int
3476xpm_color_bucket (color_name)
3477 char *color_name;
3478{
3479 unsigned h = 0;
3480 char *s;
3481
3482 for (s = color_name; *s; ++s)
3483 h = (h << 2) ^ *s;
3484 return h %= XPM_COLOR_CACHE_BUCKETS;
3485}
3486
3487
3488/* On frame F, cache values COLOR for color with name COLOR_NAME.
3489 BUCKET, if >= 0, is a precomputed bucket index. Value is the cache
3490 entry added. */
3491
3492static struct xpm_cached_color *
3493xpm_cache_color (f, color_name, color, bucket)
3494 struct frame *f;
3495 char *color_name;
3496 XColor *color;
3497 int bucket;
3498{
3499 size_t nbytes;
3500 struct xpm_cached_color *p;
3501
3502 if (bucket < 0)
3503 bucket = xpm_color_bucket (color_name);
3504
3505 nbytes = sizeof *p + strlen (color_name);
3506 p = (struct xpm_cached_color *) xmalloc (nbytes);
3507 strcpy (p->name, color_name);
3508 p->color = *color;
3509 p->next = xpm_color_cache[bucket];
3510 xpm_color_cache[bucket] = p;
3511 return p;
3512}
3513
3514/* Look up color COLOR_NAME for frame F in the color cache. If found,
3515 return the cached definition in *COLOR. Otherwise, make a new
3516 entry in the cache and allocate the color. Value is zero if color
3517 allocation failed. */
3518
3519static int
3520xpm_lookup_color (f, color_name, color)
3521 struct frame *f;
3522 char *color_name;
3523 XColor *color;
3524{
3525 struct xpm_cached_color *p;
3526 int h = xpm_color_bucket (color_name);
3527
3528 for (p = xpm_color_cache[h]; p; p = p->next)
3529 if (strcmp (p->name, color_name) == 0)
3530 break;
3531
3532 if (p != NULL)
3533 *color = p->color;
3534 else if (XParseColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
3535 color_name, color))
3536 {
3537 color->pixel = lookup_rgb_color (f, color->red, color->green,
3538 color->blue);
3539 p = xpm_cache_color (f, color_name, color, h);
3540 }
3541 /* You get `opaque' at least from ImageMagick converting pbm to xpm
3542 with transparency, and it's useful. */
3543 else if (strcmp ("opaque", color_name) == 0)
3544 {
3545 bzero (color, sizeof (XColor)); /* Is this necessary/correct? */
3546 color->pixel = FRAME_FOREGROUND_PIXEL (f);
3547 p = xpm_cache_color (f, color_name, color, h);
3548 }
3549
3550 return p != NULL;
3551}
3552
3553
3554/* Callback for allocating color COLOR_NAME. Called from the XPM lib.
3555 CLOSURE is a pointer to the frame on which we allocate the
3556 color. Return in *COLOR the allocated color. Value is non-zero
3557 if successful. */
3558
3559static int
3560xpm_alloc_color (dpy, cmap, color_name, color, closure)
3561 Display *dpy;
3562 Colormap cmap;
3563 char *color_name;
3564 XColor *color;
3565 void *closure;
3566{
3567 return xpm_lookup_color ((struct frame *) closure, color_name, color);
3568}
3569
3570
3571/* Callback for freeing NPIXELS colors contained in PIXELS. CLOSURE
3572 is a pointer to the frame on which we allocate the color. Value is
3573 non-zero if successful. */
3574
3575static int
3576xpm_free_colors (dpy, cmap, pixels, npixels, closure)
3577 Display *dpy;
3578 Colormap cmap;
3579 Pixel *pixels;
3580 int npixels;
3581 void *closure;
3582{
3583 return 1;
3584}
3585
3586#endif /* ALLOC_XPM_COLORS */
3587
3588
3589#ifdef HAVE_NTGUI
3590
3591/* XPM library details. */
3592
3593DEF_IMGLIB_FN (XpmFreeAttributes);
3594DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
3595DEF_IMGLIB_FN (XpmReadFileToImage);
3596DEF_IMGLIB_FN (XImageFree);
3597
4ef0d4d0 3598static int
0855eb52 3599init_xpm_functions (Lisp_Object libraries)
4ef0d4d0
KS
3600{
3601 HMODULE library;
3602
0855eb52 3603 if (!(library = w32_delayed_load (libraries, Qxpm)))
4ef0d4d0
KS
3604 return 0;
3605
3606 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
3607 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
3608 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
3609 LOAD_IMGLIB_FN (library, XImageFree);
3610 return 1;
3611}
3612
3613#endif /* HAVE_NTGUI */
3614
3615
3616/* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
3617 for XPM images. Such a list must consist of conses whose car and
3618 cdr are strings. */
3619
3620static int
3621xpm_valid_color_symbols_p (color_symbols)
3622 Lisp_Object color_symbols;
3623{
3624 while (CONSP (color_symbols))
3625 {
3626 Lisp_Object sym = XCAR (color_symbols);
3627 if (!CONSP (sym)
3628 || !STRINGP (XCAR (sym))
3629 || !STRINGP (XCDR (sym)))
3630 break;
3631 color_symbols = XCDR (color_symbols);
3632 }
3633
3634 return NILP (color_symbols);
3635}
3636
3637
3638/* Value is non-zero if OBJECT is a valid XPM image specification. */
3639
3640static int
3641xpm_image_p (object)
3642 Lisp_Object object;
3643{
3644 struct image_keyword fmt[XPM_LAST];
3645 bcopy (xpm_format, fmt, sizeof fmt);
3646 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
3647 /* Either `:file' or `:data' must be present. */
3648 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
3649 /* Either no `:color-symbols' or it's a list of conses
3650 whose car and cdr are strings. */
3651 && (fmt[XPM_COLOR_SYMBOLS].count == 0
3652 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
3653}
3654
ea1aaa6f 3655#endif /* HAVE_XPM || MAC_OS */
4ef0d4d0
KS
3656
3657/* Load image IMG which will be displayed on frame F. Value is
3658 non-zero if successful. */
3659
ea1aaa6f
ST
3660#ifdef HAVE_XPM
3661
4ef0d4d0
KS
3662static int
3663xpm_load (f, img)
3664 struct frame *f;
3665 struct image *img;
3666{
3667 int rc;
3668 XpmAttributes attrs;
3669 Lisp_Object specified_file, color_symbols;
3670#ifdef HAVE_NTGUI
3671 HDC hdc;
3672 xpm_XImage * xpm_image = NULL, * xpm_mask = NULL;
3673#endif /* HAVE_NTGUI */
3674
3675 /* Configure the XPM lib. Use the visual of frame F. Allocate
3676 close colors. Return colors allocated. */
3677 bzero (&attrs, sizeof attrs);
3678
3679#ifndef HAVE_NTGUI
3680 attrs.visual = FRAME_X_VISUAL (f);
3681 attrs.colormap = FRAME_X_COLORMAP (f);
3682 attrs.valuemask |= XpmVisual;
3683 attrs.valuemask |= XpmColormap;
3684#endif /* HAVE_NTGUI */
3685
3686#ifdef ALLOC_XPM_COLORS
3687 /* Allocate colors with our own functions which handle
3688 failing color allocation more gracefully. */
3689 attrs.color_closure = f;
3690 attrs.alloc_color = xpm_alloc_color;
3691 attrs.free_colors = xpm_free_colors;
3692 attrs.valuemask |= XpmAllocColor | XpmFreeColors | XpmColorClosure;
3693#else /* not ALLOC_XPM_COLORS */
3694 /* Let the XPM lib allocate colors. */
3695 attrs.valuemask |= XpmReturnAllocPixels;
3696#ifdef XpmAllocCloseColors
3697 attrs.alloc_close_colors = 1;
3698 attrs.valuemask |= XpmAllocCloseColors;
3699#else /* not XpmAllocCloseColors */
3700 attrs.closeness = 600;
3701 attrs.valuemask |= XpmCloseness;
3702#endif /* not XpmAllocCloseColors */
3703#endif /* ALLOC_XPM_COLORS */
3704
3705 /* If image specification contains symbolic color definitions, add
3706 these to `attrs'. */
3707 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
3708 if (CONSP (color_symbols))
3709 {
3710 Lisp_Object tail;
3711 XpmColorSymbol *xpm_syms;
3712 int i, size;
3713
3714 attrs.valuemask |= XpmColorSymbols;
3715
3716 /* Count number of symbols. */
3717 attrs.numsymbols = 0;
3718 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
3719 ++attrs.numsymbols;
3720
3721 /* Allocate an XpmColorSymbol array. */
3722 size = attrs.numsymbols * sizeof *xpm_syms;
3723 xpm_syms = (XpmColorSymbol *) alloca (size);
3724 bzero (xpm_syms, size);
3725 attrs.colorsymbols = xpm_syms;
3726
3727 /* Fill the color symbol array. */
3728 for (tail = color_symbols, i = 0;
3729 CONSP (tail);
3730 ++i, tail = XCDR (tail))
3731 {
3732 Lisp_Object name = XCAR (XCAR (tail));
3733 Lisp_Object color = XCDR (XCAR (tail));
3734 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
3735 strcpy (xpm_syms[i].name, SDATA (name));
3736 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
3737 strcpy (xpm_syms[i].value, SDATA (color));
3738 }
3739 }
3740
3741 /* Create a pixmap for the image, either from a file, or from a
3742 string buffer containing data in the same format as an XPM file. */
3743#ifdef ALLOC_XPM_COLORS
3744 xpm_init_color_cache (f, &attrs);
3745#endif
3746
3747 specified_file = image_spec_value (img->spec, QCfile, NULL);
3748
3749#ifdef HAVE_NTGUI
3750 {
3751 HDC frame_dc = get_frame_dc (f);
3752 hdc = CreateCompatibleDC (frame_dc);
3753 release_frame_dc (f, frame_dc);
3754 }
3755#endif /* HAVE_NTGUI */
3756
3757 if (STRINGP (specified_file))
3758 {
3759 Lisp_Object file = x_find_image_file (specified_file);
3760 if (!STRINGP (file))
3761 {
3762 image_error ("Cannot find image file `%s'", specified_file, Qnil);
3763 return 0;
3764 }
3765
3766#ifdef HAVE_NTGUI
3767 /* XpmReadFileToPixmap is not available in the Windows port of
3768 libxpm. But XpmReadFileToImage almost does what we want. */
3769 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
3770 &xpm_image, &xpm_mask,
3771 &attrs);
3772#else
3773 rc = XpmReadFileToPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3774 SDATA (file), &img->pixmap, &img->mask,
3775 &attrs);
3776#endif /* HAVE_NTGUI */
3777 }
3778 else
3779 {
3780 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
3781#ifdef HAVE_NTGUI
3782 /* XpmCreatePixmapFromBuffer is not available in the Windows port
3783 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
3784 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
3785 &xpm_image, &xpm_mask,
3786 &attrs);
3787#else
3788 rc = XpmCreatePixmapFromBuffer (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3789 SDATA (buffer),
3790 &img->pixmap, &img->mask,
3791 &attrs);
3792#endif /* HAVE_NTGUI */
3793 }
3794
3795 if (rc == XpmSuccess)
3796 {
3797#if defined (COLOR_TABLE_SUPPORT) && defined (ALLOC_XPM_COLORS)
3798 img->colors = colors_in_color_table (&img->ncolors);
3799#else /* not ALLOC_XPM_COLORS */
3800 int i;
3801
3802#ifdef HAVE_NTGUI
3803 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
3804 plus some duplicate attributes. */
3805 if (xpm_image && xpm_image->bitmap)
3806 {
3807 img->pixmap = xpm_image->bitmap;
3808 /* XImageFree in libXpm frees XImage struct without destroying
3809 the bitmap, which is what we want. */
3810 fn_XImageFree (xpm_image);
3811 }
3812 if (xpm_mask && xpm_mask->bitmap)
3813 {
3814 /* The mask appears to be inverted compared with what we expect.
3815 TODO: invert our expectations. See other places where we
3816 have to invert bits because our idea of masks is backwards. */
3817 HGDIOBJ old_obj;
3818 old_obj = SelectObject (hdc, xpm_mask->bitmap);
3819
3820 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
3821 SelectObject (hdc, old_obj);
3822
3823 img->mask = xpm_mask->bitmap;
3824 fn_XImageFree (xpm_mask);
3825 DeleteDC (hdc);
3826 }
3827
3828 DeleteDC (hdc);
3829#endif /* HAVE_NTGUI */
3830
3831 /* Remember allocated colors. */
3832 img->ncolors = attrs.nalloc_pixels;
3833 img->colors = (unsigned long *) xmalloc (img->ncolors
3834 * sizeof *img->colors);
3835 for (i = 0; i < attrs.nalloc_pixels; ++i)
3836 {
3837 img->colors[i] = attrs.alloc_pixels[i];
3838#ifdef DEBUG_X_COLORS
3839 register_color (img->colors[i]);
3840#endif
3841 }
3842#endif /* not ALLOC_XPM_COLORS */
3843
3844 img->width = attrs.width;
3845 img->height = attrs.height;
3846 xassert (img->width > 0 && img->height > 0);
3847
3848 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
3849#ifdef HAVE_NTGUI
3850 fn_XpmFreeAttributes (&attrs);
3851#else
3852 XpmFreeAttributes (&attrs);
3853#endif /* HAVE_NTGUI */
3854 }
3855 else
3856 {
3857#ifdef HAVE_NTGUI
3858 DeleteDC (hdc);
3859#endif /* HAVE_NTGUI */
3860
3861 switch (rc)
3862 {
3863 case XpmOpenFailed:
3864 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
3865 break;
3866
3867 case XpmFileInvalid:
3868 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
3869 break;
3870
3871 case XpmNoMemory:
3872 image_error ("Out of memory (%s)", img->spec, Qnil);
3873 break;
3874
3875 case XpmColorFailed:
3876 image_error ("Color allocation error (%s)", img->spec, Qnil);
3877 break;
3878
3879 default:
3880 image_error ("Unknown error (%s)", img->spec, Qnil);
3881 break;
3882 }
3883 }
3884
3885#ifdef ALLOC_XPM_COLORS
3886 xpm_free_color_cache ();
3887#endif
3888 return rc == XpmSuccess;
3889}
3890
3891#endif /* HAVE_XPM */
3892
ea1aaa6f
ST
3893#ifdef MAC_OS
3894
3895/* XPM support functions for Mac OS where libxpm is not available.
3896 Only XPM version 3 (without any extensions) is supported. */
3897
3898static int xpm_scan P_ ((unsigned char **, unsigned char *,
9ecf6403 3899 unsigned char **, int *));
ea1aaa6f
ST
3900static Lisp_Object xpm_make_color_table_v
3901 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3902 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3903static void xpm_put_color_table_v P_ ((Lisp_Object, unsigned char *,
9ecf6403 3904 int, Lisp_Object));
ea1aaa6f 3905static Lisp_Object xpm_get_color_table_v P_ ((Lisp_Object,
9ecf6403 3906 unsigned char *, int));
ea1aaa6f
ST
3907static Lisp_Object xpm_make_color_table_h
3908 P_ ((void (**) (Lisp_Object, unsigned char *, int, Lisp_Object),
3909 Lisp_Object (**) (Lisp_Object, unsigned char *, int)));
3910static void xpm_put_color_table_h P_ ((Lisp_Object, unsigned char *,
9ecf6403 3911 int, Lisp_Object));
ea1aaa6f 3912static Lisp_Object xpm_get_color_table_h P_ ((Lisp_Object,
9ecf6403 3913 unsigned char *, int));
ea1aaa6f
ST
3914static int xpm_str_to_color_key P_ ((char *));
3915static int xpm_load_image P_ ((struct frame *, struct image *,
9ecf6403 3916 unsigned char *, unsigned char *));
ea1aaa6f
ST
3917
3918/* Tokens returned from xpm_scan. */
3919
3920enum xpm_token
3921{
3922 XPM_TK_IDENT = 256,
3923 XPM_TK_STRING,
3924 XPM_TK_EOF
3925};
3926
3927/* Scan an XPM data and return a character (< 256) or a token defined
3928 by enum xpm_token above. *S and END are the start (inclusive) and
3929 the end (exclusive) addresses of the data, respectively. Advance
3930 *S while scanning. If token is either XPM_TK_IDENT or
3931 XPM_TK_STRING, *BEG and *LEN are set to the start address and the
3932 length of the corresponding token, respectively. */
3933
3934static int
3935xpm_scan (s, end, beg, len)
3936 unsigned char **s, *end, **beg;
3937 int *len;
3938{
3939 int c;
3940
3941 while (*s < end)
3942 {
3943 /* Skip white-space. */
3944 while (*s < end && (c = *(*s)++, isspace (c)))
9ecf6403 3945 ;
ea1aaa6f
ST
3946
3947 /* gnus-pointer.xpm uses '-' in its identifier.
9ecf6403 3948 sb-dir-plus.xpm uses '+' in its identifier. */
ea1aaa6f 3949 if (isalpha (c) || c == '_' || c == '-' || c == '+')
9ecf6403
YM
3950 {
3951 *beg = *s - 1;
3952 while (*s < end &&
3953 (c = **s, isalnum (c) || c == '_' || c == '-' || c == '+'))
3954 ++*s;
3955 *len = *s - *beg;
3956 return XPM_TK_IDENT;
3957 }
ea1aaa6f 3958 else if (c == '"')
9ecf6403
YM
3959 {
3960 *beg = *s;
3961 while (*s < end && **s != '"')
3962 ++*s;
3963 *len = *s - *beg;
3964 if (*s < end)
3965 ++*s;
3966 return XPM_TK_STRING;
3967 }
ea1aaa6f 3968 else if (c == '/')
9ecf6403
YM
3969 {
3970 if (*s < end && **s == '*')
3971 {
3972 /* C-style comment. */
3973 ++*s;
3974 do
3975 {
3976 while (*s < end && *(*s)++ != '*')
3977 ;
3978 }
3979 while (*s < end && **s != '/');
3980 if (*s < end)
3981 ++*s;
3982 }
3983 else
3984 return c;
3985 }
ea1aaa6f 3986 else
9ecf6403 3987 return c;
ea1aaa6f
ST
3988 }
3989
3990 return XPM_TK_EOF;
3991}
3992
3993/* Functions for color table lookup in XPM data. A Key is a string
3994 specifying the color of each pixel in XPM data. A value is either
3995 an integer that specifies a pixel color, Qt that specifies
3996 transparency, or Qnil for the unspecified color. If the length of
3997 the key string is one, a vector is used as a table. Otherwise, a
3998 hash table is used. */
3999
4000static Lisp_Object
4001xpm_make_color_table_v (put_func, get_func)
4002 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4003 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4004{
4005 *put_func = xpm_put_color_table_v;
4006 *get_func = xpm_get_color_table_v;
4007 return Fmake_vector (make_number (256), Qnil);
4008}
4009
4010static void
4011xpm_put_color_table_v (color_table, chars_start, chars_len, color)
4012 Lisp_Object color_table;
4013 unsigned char *chars_start;
4014 int chars_len;
4015 Lisp_Object color;
4016{
4017 XVECTOR (color_table)->contents[*chars_start] = color;
4018}
4019
4020static Lisp_Object
4021xpm_get_color_table_v (color_table, chars_start, chars_len)
4022 Lisp_Object color_table;
4023 unsigned char *chars_start;
4024 int chars_len;
4025{
4026 return XVECTOR (color_table)->contents[*chars_start];
4027}
4028
4029static Lisp_Object
4030xpm_make_color_table_h (put_func, get_func)
4031 void (**put_func) (Lisp_Object, unsigned char *, int, Lisp_Object);
4032 Lisp_Object (**get_func) (Lisp_Object, unsigned char *, int);
4033{
4034 *put_func = xpm_put_color_table_h;
4035 *get_func = xpm_get_color_table_h;
4036 return make_hash_table (Qequal, make_number (DEFAULT_HASH_SIZE),
9ecf6403
YM
4037 make_float (DEFAULT_REHASH_SIZE),
4038 make_float (DEFAULT_REHASH_THRESHOLD),
4039 Qnil, Qnil, Qnil);
ea1aaa6f
ST
4040}
4041
4042static void
4043xpm_put_color_table_h (color_table, chars_start, chars_len, color)
4044 Lisp_Object color_table;
4045 unsigned char *chars_start;
4046 int chars_len;
4047 Lisp_Object color;
4048{
4049 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4050 unsigned hash_code;
4051 Lisp_Object chars = make_unibyte_string (chars_start, chars_len);
4052
4053 hash_lookup (table, chars, &hash_code);
4054 hash_put (table, chars, color, hash_code);
4055}
4056
4057static Lisp_Object
4058xpm_get_color_table_h (color_table, chars_start, chars_len)
4059 Lisp_Object color_table;
4060 unsigned char *chars_start;
4061 int chars_len;
4062{
4063 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
4064 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len),
9ecf6403 4065 NULL);
ea1aaa6f
ST
4066
4067 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
4068}
4069
4070enum xpm_color_key {
4071 XPM_COLOR_KEY_S,
4072 XPM_COLOR_KEY_M,
4073 XPM_COLOR_KEY_G4,
4074 XPM_COLOR_KEY_G,
4075 XPM_COLOR_KEY_C
4076};
4077
4078static char xpm_color_key_strings[][4] = {"s", "m", "g4", "g", "c"};
4079
4080static int
4081xpm_str_to_color_key (s)
4082 char *s;
4083{
4084 int i;
4085
4086 for (i = 0;
4087 i < sizeof xpm_color_key_strings / sizeof xpm_color_key_strings[0];
4088 i++)
4089 if (strcmp (xpm_color_key_strings[i], s) == 0)
4090 return i;
4091 return -1;
4092}
4093
4094static int
4095xpm_load_image (f, img, contents, end)
4096 struct frame *f;
4097 struct image *img;
4098 unsigned char *contents, *end;
4099{
4100 unsigned char *s = contents, *beg, *str;
4101 unsigned char buffer[BUFSIZ];
4102 int width, height, x, y;
4103 int num_colors, chars_per_pixel;
4104 int len, LA1;
4105 void (*put_color_table) (Lisp_Object, unsigned char *, int, Lisp_Object);
4106 Lisp_Object (*get_color_table) (Lisp_Object, unsigned char *, int);
4107 Lisp_Object frame, color_symbols, color_table;
4108 int best_key, have_mask = 0;
4109 XImagePtr ximg = NULL, mask_img = NULL;
4110
4111#define match() \
4112 LA1 = xpm_scan (&s, end, &beg, &len)
4113
9ecf6403
YM
4114#define expect(TOKEN) \
4115 if (LA1 != (TOKEN)) \
4116 goto failure; \
4117 else \
ea1aaa6f
ST
4118 match ()
4119
9ecf6403 4120#define expect_ident(IDENT) \
ea1aaa6f 4121 if (LA1 == XPM_TK_IDENT \
9ecf6403
YM
4122 && strlen ((IDENT)) == len && memcmp ((IDENT), beg, len) == 0) \
4123 match (); \
4124 else \
ea1aaa6f
ST
4125 goto failure
4126
4127 if (!(end - s >= 9 && memcmp (s, "/* XPM */", 9) == 0))
4128 goto failure;
4129 s += 9;
4130 match();
4131 expect_ident ("static");
4132 expect_ident ("char");
4133 expect ('*');
4134 expect (XPM_TK_IDENT);
4135 expect ('[');
4136 expect (']');
4137 expect ('=');
4138 expect ('{');
4139 expect (XPM_TK_STRING);
4140 if (len >= BUFSIZ)
4141 goto failure;
4142 memcpy (buffer, beg, len);
4143 buffer[len] = '\0';
4144 if (sscanf (buffer, "%d %d %d %d", &width, &height,
9ecf6403 4145 &num_colors, &chars_per_pixel) != 4
ea1aaa6f
ST
4146 || width <= 0 || height <= 0
4147 || num_colors <= 0 || chars_per_pixel <= 0)
4148 goto failure;
4149 expect (',');
4150
4151 XSETFRAME (frame, f);
4152 if (!NILP (Fxw_display_color_p (frame)))
4153 best_key = XPM_COLOR_KEY_C;
4154 else if (!NILP (Fx_display_grayscale_p (frame)))
4155 best_key = (XFASTINT (Fx_display_planes (frame)) > 2
9ecf6403 4156 ? XPM_COLOR_KEY_G : XPM_COLOR_KEY_G4);
ea1aaa6f
ST
4157 else
4158 best_key = XPM_COLOR_KEY_M;
4159
4160 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
4161 if (chars_per_pixel == 1)
4162 color_table = xpm_make_color_table_v (&put_color_table,
9ecf6403 4163 &get_color_table);
ea1aaa6f
ST
4164 else
4165 color_table = xpm_make_color_table_h (&put_color_table,
9ecf6403 4166 &get_color_table);
ea1aaa6f
ST
4167
4168 while (num_colors-- > 0)
4169 {
4170 unsigned char *color, *max_color;
4171 int key, next_key, max_key = 0;
4172 Lisp_Object symbol_color = Qnil, color_val;
4173 XColor cdef;
4174
4175 expect (XPM_TK_STRING);
4176 if (len <= chars_per_pixel || len >= BUFSIZ + chars_per_pixel)
9ecf6403 4177 goto failure;
ea1aaa6f
ST
4178 memcpy (buffer, beg + chars_per_pixel, len - chars_per_pixel);
4179 buffer[len - chars_per_pixel] = '\0';
4180
4181 str = strtok (buffer, " \t");
4182 if (str == NULL)
9ecf6403 4183 goto failure;
ea1aaa6f
ST
4184 key = xpm_str_to_color_key (str);
4185 if (key < 0)
9ecf6403 4186 goto failure;
ea1aaa6f 4187 do
9ecf6403
YM
4188 {
4189 color = strtok (NULL, " \t");
4190 if (color == NULL)
4191 goto failure;
ea1aaa6f 4192
9ecf6403
YM
4193 while (str = strtok (NULL, " \t"))
4194 {
4195 next_key = xpm_str_to_color_key (str);
4196 if (next_key >= 0)
4197 break;
4198 color[strlen (color)] = ' ';
4199 }
ea1aaa6f 4200
9ecf6403
YM
4201 if (key == XPM_COLOR_KEY_S)
4202 {
4203 if (NILP (symbol_color))
4204 symbol_color = build_string (color);
4205 }
4206 else if (max_key < key && key <= best_key)
4207 {
4208 max_key = key;
4209 max_color = color;
4210 }
4211 key = next_key;
4212 }
ea1aaa6f
ST
4213 while (str);
4214
4215 color_val = Qnil;
4216 if (!NILP (color_symbols) && !NILP (symbol_color))
9ecf6403
YM
4217 {
4218 Lisp_Object specified_color = Fassoc (symbol_color, color_symbols);
4219
4220 if (CONSP (specified_color) && STRINGP (XCDR (specified_color)))
4221 if (xstricmp (SDATA (XCDR (specified_color)), "None") == 0)
4222 color_val = Qt;
4223 else if (x_defined_color (f, SDATA (XCDR (specified_color)),
4224 &cdef, 0))
4225 color_val = make_number (cdef.pixel);
4226 }
ea1aaa6f 4227 if (NILP (color_val) && max_key > 0)
9ecf6403
YM
4228 if (xstricmp (max_color, "None") == 0)
4229 color_val = Qt;
4230 else if (x_defined_color (f, max_color, &cdef, 0))
4231 color_val = make_number (cdef.pixel);
ea1aaa6f 4232 if (!NILP (color_val))
9ecf6403 4233 (*put_color_table) (color_table, beg, chars_per_pixel, color_val);
ea1aaa6f
ST
4234
4235 expect (',');
4236 }
4237
4238 if (!x_create_x_image_and_pixmap (f, width, height, 0,
9ecf6403 4239 &ximg, &img->pixmap)
ea1aaa6f 4240 || !x_create_x_image_and_pixmap (f, width, height, 1,
9ecf6403 4241 &mask_img, &img->mask))
ea1aaa6f
ST
4242 {
4243 image_error ("Out of memory (%s)", img->spec, Qnil);
4244 goto error;
4245 }
4246
4247 for (y = 0; y < height; y++)
4248 {
4249 expect (XPM_TK_STRING);
4250 str = beg;
4251 if (len < width * chars_per_pixel)
9ecf6403 4252 goto failure;
ea1aaa6f 4253 for (x = 0; x < width; x++, str += chars_per_pixel)
9ecf6403
YM
4254 {
4255 Lisp_Object color_val =
4256 (*get_color_table) (color_table, str, chars_per_pixel);
4257
4258 XPutPixel (ximg, x, y,
4259 (INTEGERP (color_val) ? XINT (color_val)
4260 : FRAME_FOREGROUND_PIXEL (f)));
4261 XPutPixel (mask_img, x, y,
4262 (!EQ (color_val, Qt) ? PIX_MASK_DRAW
4263 : (have_mask = 1, PIX_MASK_RETAIN)));
4264 }
ea1aaa6f 4265 if (y + 1 < height)
9ecf6403 4266 expect (',');
ea1aaa6f
ST
4267 }
4268
4269 img->width = width;
4270 img->height = height;
4271
4272 x_put_x_image (f, ximg, img->pixmap, width, height);
4273 x_destroy_x_image (ximg);
4274 if (have_mask)
4275 {
9ecf6403
YM
4276 /* Fill in the background_transparent field while we have the
4277 mask handy. */
4278 image_background_transparent (img, f, mask_img);
4279
ea1aaa6f
ST
4280 x_put_x_image (f, mask_img, img->mask, width, height);
4281 x_destroy_x_image (mask_img);
4282 }
4283 else
4284 {
4285 x_destroy_x_image (mask_img);
4286 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
4287 img->mask = NO_PIXMAP;
4288 }
4289
4290 return 1;
4291
4292 failure:
4293 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
4294 error:
4295 x_destroy_x_image (ximg);
4296 x_destroy_x_image (mask_img);
4297 x_clear_image (f, img);
4298 return 0;
4299
4300#undef match
4301#undef expect
4302#undef expect_ident
4303}
4304
4305static int
4306xpm_load (f, img)
4307 struct frame *f;
4308 struct image *img;
4309{
4310 int success_p = 0;
4311 Lisp_Object file_name;
4312
4313 /* If IMG->spec specifies a file name, create a non-file spec from it. */
4314 file_name = image_spec_value (img->spec, QCfile, NULL);
4315 if (STRINGP (file_name))
4316 {
4317 Lisp_Object file;
4318 unsigned char *contents;
4319 int size;
4320 struct gcpro gcpro1;
4321
4322 file = x_find_image_file (file_name);
4323 GCPRO1 (file);
4324 if (!STRINGP (file))
9ecf6403
YM
4325 {
4326 image_error ("Cannot find image file `%s'", file_name, Qnil);
4327 UNGCPRO;
4328 return 0;
4329 }
ea1aaa6f
ST
4330
4331 contents = slurp_file (SDATA (file), &size);
4332 if (contents == NULL)
9ecf6403
YM
4333 {
4334 image_error ("Error loading XPM image `%s'", img->spec, Qnil);
4335 UNGCPRO;
4336 return 0;
4337 }
ea1aaa6f
ST
4338
4339 success_p = xpm_load_image (f, img, contents, contents + size);
4340 xfree (contents);
4341 UNGCPRO;
4342 }
4343 else
4344 {
4345 Lisp_Object data;
4346
4347 data = image_spec_value (img->spec, QCdata, NULL);
4348 success_p = xpm_load_image (f, img, SDATA (data),
9ecf6403 4349 SDATA (data) + SBYTES (data));
ea1aaa6f
ST
4350 }
4351
4352 return success_p;
4353}
4354
4355#endif /* MAC_OS */
b0da69a7 4356
ea1aaa6f 4357
4ef0d4d0
KS
4358\f
4359/***********************************************************************
4360 Color table
4361 ***********************************************************************/
4362
4363#ifdef COLOR_TABLE_SUPPORT
4364
4365/* An entry in the color table mapping an RGB color to a pixel color. */
4366
4367struct ct_color
4368{
4369 int r, g, b;
4370 unsigned long pixel;
4371
4372 /* Next in color table collision list. */
4373 struct ct_color *next;
4374};
4375
4376/* The bucket vector size to use. Must be prime. */
4377
4378#define CT_SIZE 101
4379
4380/* Value is a hash of the RGB color given by R, G, and B. */
4381
4382#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
4383
4384/* The color hash table. */
4385
4386struct ct_color **ct_table;
4387
4388/* Number of entries in the color table. */
4389
4390int ct_colors_allocated;
4391
4392/* Initialize the color table. */
4393
4394static void
4395init_color_table ()
4396{
4397 int size = CT_SIZE * sizeof (*ct_table);
4398 ct_table = (struct ct_color **) xmalloc (size);
4399 bzero (ct_table, size);
4400 ct_colors_allocated = 0;
4401}
4402
4403
4404/* Free memory associated with the color table. */
4405
4406static void
4407free_color_table ()
4408{
4409 int i;
4410 struct ct_color *p, *next;
4411
4412 for (i = 0; i < CT_SIZE; ++i)
4413 for (p = ct_table[i]; p; p = next)
4414 {
4415 next = p->next;
4416 xfree (p);
4417 }
4418
4419 xfree (ct_table);
4420 ct_table = NULL;
4421}
4422
4423
4424/* Value is a pixel color for RGB color R, G, B on frame F. If an
4425 entry for that color already is in the color table, return the
4426 pixel color of that entry. Otherwise, allocate a new color for R,
4427 G, B, and make an entry in the color table. */
4428
4429static unsigned long
4430lookup_rgb_color (f, r, g, b)
4431 struct frame *f;
4432 int r, g, b;
4433{
4434 unsigned hash = CT_HASH_RGB (r, g, b);
4435 int i = hash % CT_SIZE;
4436 struct ct_color *p;
4437 Display_Info *dpyinfo;
4438
4439 /* Handle TrueColor visuals specially, which improves performance by
4440 two orders of magnitude. Freeing colors on TrueColor visuals is
4441 a nop, and pixel colors specify RGB values directly. See also
4442 the Xlib spec, chapter 3.1. */
4443 dpyinfo = FRAME_X_DISPLAY_INFO (f);
4444 if (dpyinfo->red_bits > 0)
4445 {
4446 unsigned long pr, pg, pb;
4447
4448 /* Apply gamma-correction like normal color allocation does. */
4449 if (f->gamma)
4450 {
4451 XColor color;
4452 color.red = r, color.green = g, color.blue = b;
4453 gamma_correct (f, &color);
4454 r = color.red, g = color.green, b = color.blue;
4455 }
4456
4457 /* Scale down RGB values to the visual's bits per RGB, and shift
4458 them to the right position in the pixel color. Note that the
4459 original RGB values are 16-bit values, as usual in X. */
4460 pr = (r >> (16 - dpyinfo->red_bits)) << dpyinfo->red_offset;
4461 pg = (g >> (16 - dpyinfo->green_bits)) << dpyinfo->green_offset;
4462 pb = (b >> (16 - dpyinfo->blue_bits)) << dpyinfo->blue_offset;
4463
4464 /* Assemble the pixel color. */
4465 return pr | pg | pb;
4466 }
1f026899 4467
4ef0d4d0
KS
4468 for (p = ct_table[i]; p; p = p->next)
4469 if (p->r == r && p->g == g && p->b == b)
4470 break;
4471
4472 if (p == NULL)
4473 {
4474
4475#ifdef HAVE_X_WINDOWS
4476 XColor color;
4477 Colormap cmap;
4478 int rc;
4479
4480 color.red = r;
4481 color.green = g;
4482 color.blue = b;
4483
4484 cmap = FRAME_X_COLORMAP (f);
4485 rc = x_alloc_nearest_color (f, cmap, &color);
4486 if (rc)
4487 {
4488 ++ct_colors_allocated;
4489 p = (struct ct_color *) xmalloc (sizeof *p);
4490 p->r = r;
4491 p->g = g;
4492 p->b = b;
4493 p->pixel = color.pixel;
4494 p->next = ct_table[i];
4495 ct_table[i] = p;
4496 }
4497 else
4498 return FRAME_FOREGROUND_PIXEL (f);
4499
4500#else
4501 COLORREF color;
4502#ifdef HAVE_NTGUI
4503 color = PALETTERGB (r, g, b);
4504#else
4505 color = RGB_TO_ULONG (r, g, b);
4506#endif /* HAVE_NTGUI */
4507 ++ct_colors_allocated;
4508 p = (struct ct_color *) xmalloc (sizeof *p);
4509 p->r = r;
4510 p->g = g;
4511 p->b = b;
4512 p->pixel = color;
4513 p->next = ct_table[i];
4514 ct_table[i] = p;
4515#endif /* HAVE_X_WINDOWS */
4516
4517 }
4518
4519 return p->pixel;
4520}
4521
4522
4523/* Look up pixel color PIXEL which is used on frame F in the color
4524 table. If not already present, allocate it. Value is PIXEL. */
4525
4526static unsigned long
4527lookup_pixel_color (f, pixel)
4528 struct frame *f;
4529 unsigned long pixel;
4530{
4531 int i = pixel % CT_SIZE;
4532 struct ct_color *p;
4533
4534 for (p = ct_table[i]; p; p = p->next)
4535 if (p->pixel == pixel)
4536 break;
4537
4538 if (p == NULL)
4539 {
4540 XColor color;
4541 Colormap cmap;
4542 int rc;
4543
4544#ifdef HAVE_X_WINDOWS
4545 cmap = FRAME_X_COLORMAP (f);
4546 color.pixel = pixel;
4547 x_query_color (f, &color);
4548 rc = x_alloc_nearest_color (f, cmap, &color);
4549#else
4550 BLOCK_INPUT;
4551 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
4552 color.pixel = pixel;
4553 XQueryColor (NULL, cmap, &color);
4554 rc = x_alloc_nearest_color (f, cmap, &color);
4555 UNBLOCK_INPUT;
4556#endif /* HAVE_X_WINDOWS */
4557
4558 if (rc)
4559 {
4560 ++ct_colors_allocated;
4561
4562 p = (struct ct_color *) xmalloc (sizeof *p);
4563 p->r = color.red;
4564 p->g = color.green;
4565 p->b = color.blue;
4566 p->pixel = pixel;
4567 p->next = ct_table[i];
4568 ct_table[i] = p;
4569 }
4570 else
4571 return FRAME_FOREGROUND_PIXEL (f);
4572 }
4573 return p->pixel;
4574}
4575
4576
4577/* Value is a vector of all pixel colors contained in the color table,
4578 allocated via xmalloc. Set *N to the number of colors. */
4579
4580static unsigned long *
4581colors_in_color_table (n)
4582 int *n;
4583{
4584 int i, j;
4585 struct ct_color *p;
4586 unsigned long *colors;
4587
4588 if (ct_colors_allocated == 0)
4589 {
4590 *n = 0;
4591 colors = NULL;
4592 }
4593 else
4594 {
4595 colors = (unsigned long *) xmalloc (ct_colors_allocated
4596 * sizeof *colors);
4597 *n = ct_colors_allocated;
4598
4599 for (i = j = 0; i < CT_SIZE; ++i)
4600 for (p = ct_table[i]; p; p = p->next)
4601 colors[j++] = p->pixel;
4602 }
4603
4604 return colors;
4605}
4606
4607#else /* COLOR_TABLE_SUPPORT */
4608
4609static unsigned long
4610lookup_rgb_color (f, r, g, b)
4611 struct frame *f;
4612 int r, g, b;
4613{
4614 unsigned long pixel;
4615
4616#ifdef MAC_OS
4617 pixel = RGB_TO_ULONG (r >> 8, g >> 8, b >> 8);
4618 gamma_correct (f, &pixel);
4619#endif /* MAC_OS */
4620
4621#ifdef HAVE_NTGUI
4622 pixel = PALETTERGB (r >> 8, g >> 8, b >> 8);
4623#endif /* HAVE_NTGUI */
4624
4625 return pixel;
4626}
4627
4628static void
4629init_color_table ()
4630{
4631}
4632#endif /* COLOR_TABLE_SUPPORT */
4633
4634\f
4635/***********************************************************************
4636 Algorithms
4637 ***********************************************************************/
4638
4639static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
4640static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
4641static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
4642
4643#ifdef HAVE_NTGUI
4644static void XPutPixel (XImagePtr , int, int, COLORREF);
4645#endif /* HAVE_NTGUI */
4646
4647/* Non-zero means draw a cross on images having `:conversion
4648 disabled'. */
4649
4650int cross_disabled_images;
4651
4652/* Edge detection matrices for different edge-detection
4653 strategies. */
4654
4655static int emboss_matrix[9] = {
4656 /* x - 1 x x + 1 */
4657 2, -1, 0, /* y - 1 */
4658 -1, 0, 1, /* y */
4659 0, 1, -2 /* y + 1 */
4660};
4661
4662static int laplace_matrix[9] = {
4663 /* x - 1 x x + 1 */
4664 1, 0, 0, /* y - 1 */
4665 0, 0, 0, /* y */
4666 0, 0, -1 /* y + 1 */
4667};
4668
4669/* Value is the intensity of the color whose red/green/blue values
4670 are R, G, and B. */
4671
4672#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
4673
4674
4675/* On frame F, return an array of XColor structures describing image
4676 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
4677 non-zero means also fill the red/green/blue members of the XColor
4678 structures. Value is a pointer to the array of XColors structures,
4679 allocated with xmalloc; it must be freed by the caller. */
4680
4681static XColor *
4682x_to_xcolors (f, img, rgb_p)
4683 struct frame *f;
4684 struct image *img;
4685 int rgb_p;
4686{
4687 int x, y;
4688 XColor *colors, *p;
4689 XImagePtr_or_DC ximg;
4690#ifdef HAVE_NTGUI
4691 HDC hdc;
4692 HGDIOBJ prev;
4693#endif /* HAVE_NTGUI */
4694
4695 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
4696
4697#ifndef HAVE_NTGUI
4698 /* Get the X image IMG->pixmap. */
4699 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
4700 0, 0, img->width, img->height, ~0, ZPixmap);
4701#else
4702 /* Load the image into a memory device context. */
4703 hdc = get_frame_dc (f);
4704 ximg = CreateCompatibleDC (hdc);
4705 release_frame_dc (f, hdc);
4706 prev = SelectObject (ximg, img->pixmap);
4707#endif /* HAVE_NTGUI */
4708
4709 /* Fill the `pixel' members of the XColor array. I wished there
4710 were an easy and portable way to circumvent XGetPixel. */
4711 p = colors;
4712 for (y = 0; y < img->height; ++y)
4713 {
4714 XColor *row = p;
4715
4716#ifdef HAVE_X_WINDOWS
4717 for (x = 0; x < img->width; ++x, ++p)
4718 p->pixel = XGetPixel (ximg, x, y);
4719 if (rgb_p)
4720 x_query_colors (f, row, img->width);
4721
4722#else
4723
4724 for (x = 0; x < img->width; ++x, ++p)
4725 {
4726 /* W32_TODO: palette support needed here? */
4727 p->pixel = GET_PIXEL (ximg, x, y);
4728 if (rgb_p)
4729 {
4730#ifdef MAC_OS
4731 p->red = RED16_FROM_ULONG (p->pixel);
4732 p->green = GREEN16_FROM_ULONG (p->pixel);
4733 p->blue = BLUE16_FROM_ULONG (p->pixel);
4734#endif /* MAC_OS */
4735#ifdef HAVE_NTGUI
4736 p->red = 256 * GetRValue (p->pixel);
4737 p->green = 256 * GetGValue (p->pixel);
4738 p->blue = 256 * GetBValue (p->pixel);
4739#endif /* HAVE_NTGUI */
4740 }
4741 }
4742#endif /* HAVE_X_WINDOWS */
4743 }
4744
4745 Destroy_Image (ximg, prev);
4746
4747 return colors;
4748}
4749
4750#ifdef HAVE_NTGUI
4751
4752/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
4753 created with CreateDIBSection, with the pointer to the bit values
4754 stored in ximg->data. */
4755
4756static void XPutPixel (ximg, x, y, color)
4757 XImagePtr ximg;
4758 int x, y;
4759 COLORREF color;
4760{
4761 int width = ximg->info.bmiHeader.biWidth;
4762 int height = ximg->info.bmiHeader.biHeight;
4763 unsigned char * pixel;
4764
4765 /* True color images. */
4766 if (ximg->info.bmiHeader.biBitCount == 24)
4767 {
4768 int rowbytes = width * 3;
4769 /* Ensure scanlines are aligned on 4 byte boundaries. */
4770 if (rowbytes % 4)
4771 rowbytes += 4 - (rowbytes % 4);
4772
4773 pixel = ximg->data + y * rowbytes + x * 3;
4774 /* Windows bitmaps are in BGR order. */
4775 *pixel = GetBValue (color);
4776 *(pixel + 1) = GetGValue (color);
4777 *(pixel + 2) = GetRValue (color);
4778 }
4779 /* Monochrome images. */
4780 else if (ximg->info.bmiHeader.biBitCount == 1)
4781 {
4782 int rowbytes = width / 8;
4783 /* Ensure scanlines are aligned on 4 byte boundaries. */
4784 if (rowbytes % 4)
4785 rowbytes += 4 - (rowbytes % 4);
4786 pixel = ximg->data + y * rowbytes + x / 8;
4787 /* Filter out palette info. */
4788 if (color & 0x00ffffff)
4789 *pixel = *pixel | (1 << x % 8);
4790 else
4791 *pixel = *pixel & ~(1 << x % 8);
4792 }
4793 else
4794 image_error ("XPutPixel: palette image not supported", Qnil, Qnil);
4795}
4796
4797#endif /* HAVE_NTGUI */
4798
4799/* Create IMG->pixmap from an array COLORS of XColor structures, whose
4800 RGB members are set. F is the frame on which this all happens.
4801 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
4802
4803static void
4804x_from_xcolors (f, img, colors)
4805 struct frame *f;
4806 struct image *img;
4807 XColor *colors;
4808{
4809 int x, y;
4810 XImagePtr oimg;
4811 Pixmap pixmap;
4812 XColor *p;
4813
4814 init_color_table ();
4815
4816 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
4817 &oimg, &pixmap);
4818 p = colors;
4819 for (y = 0; y < img->height; ++y)
4820 for (x = 0; x < img->width; ++x, ++p)
4821 {
4822 unsigned long pixel;
4823 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
4824 XPutPixel (oimg, x, y, pixel);
4825 }
4826
4827 xfree (colors);
4828 x_clear_image_1 (f, img, 1, 0, 1);
4829
4830 x_put_x_image (f, oimg, pixmap, img->width, img->height);
4831 x_destroy_x_image (oimg);
4832 img->pixmap = pixmap;
4833#ifdef COLOR_TABLE_SUPPORT
4834 img->colors = colors_in_color_table (&img->ncolors);
4835 free_color_table ();
4836#endif /* COLOR_TABLE_SUPPORT */
4837}
4838
4839
4840/* On frame F, perform edge-detection on image IMG.
4841
4842 MATRIX is a nine-element array specifying the transformation
4843 matrix. See emboss_matrix for an example.
4844
4845 COLOR_ADJUST is a color adjustment added to each pixel of the
4846 outgoing image. */
4847
4848static void
4849x_detect_edges (f, img, matrix, color_adjust)
4850 struct frame *f;
4851 struct image *img;
4852 int matrix[9], color_adjust;
4853{
4854 XColor *colors = x_to_xcolors (f, img, 1);
4855 XColor *new, *p;
4856 int x, y, i, sum;
4857
4858 for (i = sum = 0; i < 9; ++i)
4859 sum += abs (matrix[i]);
4860
4861#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4862
4863 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
4864
4865 for (y = 0; y < img->height; ++y)
4866 {
4867 p = COLOR (new, 0, y);
4868 p->red = p->green = p->blue = 0xffff/2;
4869 p = COLOR (new, img->width - 1, y);
4870 p->red = p->green = p->blue = 0xffff/2;
4871 }
4872
4873 for (x = 1; x < img->width - 1; ++x)
4874 {
4875 p = COLOR (new, x, 0);
4876 p->red = p->green = p->blue = 0xffff/2;
4877 p = COLOR (new, x, img->height - 1);
4878 p->red = p->green = p->blue = 0xffff/2;
4879 }
4880
4881 for (y = 1; y < img->height - 1; ++y)
4882 {
4883 p = COLOR (new, 1, y);
4884
4885 for (x = 1; x < img->width - 1; ++x, ++p)
4886 {
4887 int r, g, b, y1, x1;
4888
4889 r = g = b = i = 0;
4890 for (y1 = y - 1; y1 < y + 2; ++y1)
4891 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
4892 if (matrix[i])
4893 {
4894 XColor *t = COLOR (colors, x1, y1);
4895 r += matrix[i] * t->red;
4896 g += matrix[i] * t->green;
4897 b += matrix[i] * t->blue;
4898 }
4899
4900 r = (r / sum + color_adjust) & 0xffff;
4901 g = (g / sum + color_adjust) & 0xffff;
4902 b = (b / sum + color_adjust) & 0xffff;
4903 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
4904 }
4905 }
4906
4907 xfree (colors);
4908 x_from_xcolors (f, img, new);
4909
4910#undef COLOR
4911}
4912
4913
4914/* Perform the pre-defined `emboss' edge-detection on image IMG
4915 on frame F. */
4916
4917static void
4918x_emboss (f, img)
4919 struct frame *f;
4920 struct image *img;
4921{
4922 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
4923}
4924
4925
4926/* Transform image IMG which is used on frame F with a Laplace
4927 edge-detection algorithm. The result is an image that can be used
4928 to draw disabled buttons, for example. */
4929
4930static void
4931x_laplace (f, img)
4932 struct frame *f;
4933 struct image *img;
4934{
4935 x_detect_edges (f, img, laplace_matrix, 45000);
4936}
4937
4938
4939/* Perform edge-detection on image IMG on frame F, with specified
4940 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
4941
4942 MATRIX must be either
4943
4944 - a list of at least 9 numbers in row-major form
4945 - a vector of at least 9 numbers
4946
4947 COLOR_ADJUST nil means use a default; otherwise it must be a
4948 number. */
4949
4950static void
4951x_edge_detection (f, img, matrix, color_adjust)
4952 struct frame *f;
4953 struct image *img;
4954 Lisp_Object matrix, color_adjust;
4955{
4956 int i = 0;
4957 int trans[9];
4958
4959 if (CONSP (matrix))
4960 {
4961 for (i = 0;
4962 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
4963 ++i, matrix = XCDR (matrix))
4964 trans[i] = XFLOATINT (XCAR (matrix));
4965 }
4966 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
4967 {
4968 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
4969 trans[i] = XFLOATINT (AREF (matrix, i));
4970 }
4971
4972 if (NILP (color_adjust))
4973 color_adjust = make_number (0xffff / 2);
4974
4975 if (i == 9 && NUMBERP (color_adjust))
4976 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
4977}
4978
4979
4980/* Transform image IMG on frame F so that it looks disabled. */
4981
4982static void
4983x_disable_image (f, img)
4984 struct frame *f;
4985 struct image *img;
4986{
4987 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
4988#ifdef HAVE_NTGUI
4989 int n_planes = dpyinfo->n_planes * dpyinfo->n_cbits;
4990#else
4991 int n_planes = dpyinfo->n_planes;
4992#endif /* HAVE_NTGUI */
4993
4994 if (n_planes >= 2)
4995 {
4996 /* Color (or grayscale). Convert to gray, and equalize. Just
4997 drawing such images with a stipple can look very odd, so
4998 we're using this method instead. */
4999 XColor *colors = x_to_xcolors (f, img, 1);
5000 XColor *p, *end;
5001 const int h = 15000;
5002 const int l = 30000;
5003
5004 for (p = colors, end = colors + img->width * img->height;
5005 p < end;
5006 ++p)
5007 {
5008 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
5009 int i2 = (0xffff - h - l) * i / 0xffff + l;
5010 p->red = p->green = p->blue = i2;
5011 }
5012
5013 x_from_xcolors (f, img, colors);
5014 }
5015
5016 /* Draw a cross over the disabled image, if we must or if we
5017 should. */
5018 if (n_planes < 2 || cross_disabled_images)
5019 {
5020#ifndef HAVE_NTGUI
5021 Display *dpy = FRAME_X_DISPLAY (f);
5022 GC gc;
5023
5024#ifdef MAC_OS
5025#define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, NULL, 0, NULL)
9ecf6403 5026#define MaskForeground(f) PIX_MASK_DRAW
4ef0d4d0
KS
5027#else
5028#define XCreateGC_pixmap(dpy, pixmap) XCreateGC (dpy, pixmap, 0, NULL)
5029#define MaskForeground(f) WHITE_PIX_DEFAULT (f)
5030#endif
5031
5032 gc = XCreateGC_pixmap (dpy, img->pixmap);
5033 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
5034 XDrawLine (dpy, img->pixmap, gc, 0, 0,
5035 img->width - 1, img->height - 1);
5036 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
5037 img->width - 1, 0);
5038 XFreeGC (dpy, gc);
5039
5040 if (img->mask)
5041 {
5042 gc = XCreateGC_pixmap (dpy, img->mask);
5043 XSetForeground (dpy, gc, MaskForeground (f));
5044 XDrawLine (dpy, img->mask, gc, 0, 0,
5045 img->width - 1, img->height - 1);
5046 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
5047 img->width - 1, 0);
5048 XFreeGC (dpy, gc);
5049 }
5050#else
5051 HDC hdc, bmpdc;
5052 HGDIOBJ prev;
5053
5054 hdc = get_frame_dc (f);
5055 bmpdc = CreateCompatibleDC (hdc);
5056 release_frame_dc (f, hdc);
5057
5058 prev = SelectObject (bmpdc, img->pixmap);
5059
5060 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
5061 MoveToEx (bmpdc, 0, 0, NULL);
5062 LineTo (bmpdc, img->width - 1, img->height - 1);
5063 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5064 LineTo (bmpdc, img->width - 1, 0);
5065
5066 if (img->mask)
5067 {
5068 SelectObject (bmpdc, img->mask);
5069 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
5070 MoveToEx (bmpdc, 0, 0, NULL);
5071 LineTo (bmpdc, img->width - 1, img->height - 1);
5072 MoveToEx (bmpdc, 0, img->height - 1, NULL);
5073 LineTo (bmpdc, img->width - 1, 0);
5074 }
5075 SelectObject (bmpdc, prev);
5076 DeleteDC (bmpdc);
5077#endif /* HAVE_NTGUI */
5078 }
5079}
5080
5081
5082/* Build a mask for image IMG which is used on frame F. FILE is the
5083 name of an image file, for error messages. HOW determines how to
5084 determine the background color of IMG. If it is a list '(R G B)',
5085 with R, G, and B being integers >= 0, take that as the color of the
5086 background. Otherwise, determine the background color of IMG
5087 heuristically. Value is non-zero if successful. */
5088
5089static int
5090x_build_heuristic_mask (f, img, how)
5091 struct frame *f;
5092 struct image *img;
5093 Lisp_Object how;
5094{
5095 XImagePtr_or_DC ximg;
5096#ifndef HAVE_NTGUI
5097 XImagePtr mask_img;
5098#else
5099 HDC frame_dc;
5100 HGDIOBJ prev;
5101 char *mask_img;
5102 int row_width;
5103#endif /* HAVE_NTGUI */
5104 int x, y, rc, use_img_background;
5105 unsigned long bg = 0;
5106
5107 if (img->mask)
5108 {
5109 Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
5110 img->mask = NO_PIXMAP;
5111 img->background_transparent_valid = 0;
5112 }
5113
5114#ifndef HAVE_NTGUI
5115 /* Create an image and pixmap serving as mask. */
5116 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
5117 &mask_img, &img->mask);
5118 if (!rc)
5119 return 0;
5120
5121 /* Get the X image of IMG->pixmap. */
5122 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap, 0, 0,
5123 img->width, img->height,
5124 ~0, ZPixmap);
5125#else
5126 /* Create the bit array serving as mask. */
5127 row_width = (img->width + 7) / 8;
5128 mask_img = xmalloc (row_width * img->height);
5129 bzero (mask_img, row_width * img->height);
5130
5131 /* Create a memory device context for IMG->pixmap. */
5132 frame_dc = get_frame_dc (f);
5133 ximg = CreateCompatibleDC (frame_dc);
5134 release_frame_dc (f, frame_dc);
5135 prev = SelectObject (ximg, img->pixmap);
5136#endif /* HAVE_NTGUI */
5137
5138 /* Determine the background color of ximg. If HOW is `(R G B)'
5139 take that as color. Otherwise, use the image's background color. */
5140 use_img_background = 1;
5141
5142 if (CONSP (how))
5143 {
5144 int rgb[3], i;
5145
5146 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
5147 {
5148 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
5149 how = XCDR (how);
5150 }
5151
5152 if (i == 3 && NILP (how))
5153 {
5154 char color_name[30];
5155 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
5156 bg = (
5157#ifdef HAVE_NTGUI
5158 0x00ffffff & /* Filter out palette info. */
5159#endif /* HAVE_NTGUI */
5160 x_alloc_image_color (f, img, build_string (color_name), 0));
5161 use_img_background = 0;
5162 }
5163 }
5164
5165 if (use_img_background)
5166 bg = four_corners_best (ximg, img->width, img->height);
5167
5168 /* Set all bits in mask_img to 1 whose color in ximg is different
5169 from the background color bg. */
5170#ifndef HAVE_NTGUI
5171 for (y = 0; y < img->height; ++y)
5172 for (x = 0; x < img->width; ++x)
5173 XPutPixel (mask_img, x, y, (XGetPixel (ximg, x, y) != bg
9ecf6403 5174 ? PIX_MASK_DRAW : PIX_MASK_RETAIN));
4ef0d4d0
KS
5175
5176 /* Fill in the background_transparent field while we have the mask handy. */
5177 image_background_transparent (img, f, mask_img);
5178
5179 /* Put mask_img into img->mask. */
5180 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
5181 x_destroy_x_image (mask_img);
5182
5183#else
5184 for (y = 0; y < img->height; ++y)
5185 for (x = 0; x < img->width; ++x)
5186 {
5187 COLORREF p = GetPixel (ximg, x, y);
5188 if (p != bg)
5189 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
5190 }
5191
5192 /* Create the mask image. */
5193 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
5194 mask_img);
5195 /* Fill in the background_transparent field while we have the mask handy. */
5196 SelectObject (ximg, img->mask);
5197 image_background_transparent (img, f, ximg);
5198
5199 /* Was: x_destroy_x_image ((XImagePtr )mask_img); which seems bogus ++kfs */
5200 xfree (mask_img);
5201#endif /* HAVE_NTGUI */
5202
5203 Destroy_Image (ximg, prev);
5204
5205 return 1;
5206}
5207
5208\f
5209/***********************************************************************
5210 PBM (mono, gray, color)
5211 ***********************************************************************/
5212
5213static int pbm_image_p P_ ((Lisp_Object object));
5214static int pbm_load P_ ((struct frame *f, struct image *img));
5215static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
5216
5217/* The symbol `pbm' identifying images of this type. */
5218
5219Lisp_Object Qpbm;
5220
5221/* Indices of image specification fields in gs_format, below. */
5222
5223enum pbm_keyword_index
5224{
5225 PBM_TYPE,
5226 PBM_FILE,
5227 PBM_DATA,
5228 PBM_ASCENT,
5229 PBM_MARGIN,
5230 PBM_RELIEF,
5231 PBM_ALGORITHM,
5232 PBM_HEURISTIC_MASK,
5233 PBM_MASK,
5234 PBM_FOREGROUND,
5235 PBM_BACKGROUND,
5236 PBM_LAST
5237};
5238
5239/* Vector of image_keyword structures describing the format
5240 of valid user-defined image specifications. */
5241
5242static struct image_keyword pbm_format[PBM_LAST] =
5243{
5244 {":type", IMAGE_SYMBOL_VALUE, 1},
5245 {":file", IMAGE_STRING_VALUE, 0},
5246 {":data", IMAGE_STRING_VALUE, 0},
5247 {":ascent", IMAGE_ASCENT_VALUE, 0},
5248 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5249 {":relief", IMAGE_INTEGER_VALUE, 0},
5250 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5251 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5252 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5253 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
5254 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5255};
5256
5257/* Structure describing the image type `pbm'. */
5258
5259static struct image_type pbm_type =
5260{
5261 &Qpbm,
5262 pbm_image_p,
5263 pbm_load,
5264 x_clear_image,
5265 NULL
5266};
5267
5268
5269/* Return non-zero if OBJECT is a valid PBM image specification. */
5270
5271static int
5272pbm_image_p (object)
5273 Lisp_Object object;
5274{
5275 struct image_keyword fmt[PBM_LAST];
5276
5277 bcopy (pbm_format, fmt, sizeof fmt);
5278
5279 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
5280 return 0;
5281
5282 /* Must specify either :data or :file. */
5283 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
5284}
5285
5286
5287/* Scan a decimal number from *S and return it. Advance *S while
5288 reading the number. END is the end of the string. Value is -1 at
5289 end of input. */
5290
5291static int
5292pbm_scan_number (s, end)
5293 unsigned char **s, *end;
5294{
5295 int c = 0, val = -1;
5296
5297 while (*s < end)
5298 {
5299 /* Skip white-space. */
5300 while (*s < end && (c = *(*s)++, isspace (c)))
5301 ;
5302
5303 if (c == '#')
5304 {
5305 /* Skip comment to end of line. */
5306 while (*s < end && (c = *(*s)++, c != '\n'))
5307 ;
5308 }
5309 else if (isdigit (c))
5310 {
5311 /* Read decimal number. */
5312 val = c - '0';
5313 while (*s < end && (c = *(*s)++, isdigit (c)))
5314 val = 10 * val + c - '0';
5315 break;
5316 }
5317 else
5318 break;
5319 }
5320
5321 return val;
5322}
5323
5324
5325#ifdef HAVE_NTGUI
5326#if 0 /* Unused. ++kfs */
5327
5328/* Read FILE into memory. Value is a pointer to a buffer allocated
5329 with xmalloc holding FILE's contents. Value is null if an error
5330 occurred. *SIZE is set to the size of the file. */
5331
5332static char *
5333pbm_read_file (file, size)
5334 Lisp_Object file;
5335 int *size;
5336{
5337 FILE *fp = NULL;
5338 char *buf = NULL;
5339 struct stat st;
5340
5341 if (stat (SDATA (file), &st) == 0
5342 && (fp = fopen (SDATA (file), "rb")) != NULL
5343 && (buf = (char *) xmalloc (st.st_size),
5344 fread (buf, 1, st.st_size, fp) == st.st_size))
5345 {
5346 *size = st.st_size;
5347 fclose (fp);
5348 }
5349 else
5350 {
5351 if (fp)
5352 fclose (fp);
5353 if (buf)
5354 {
5355 xfree (buf);
5356 buf = NULL;
5357 }
5358 }
5359
5360 return buf;
5361}
5362#endif
5363#endif /* HAVE_NTGUI */
5364
5365/* Load PBM image IMG for use on frame F. */
5366
5367static int
5368pbm_load (f, img)
5369 struct frame *f;
5370 struct image *img;
5371{
5372 int raw_p, x, y;
5373 int width, height, max_color_idx = 0;
5374 XImagePtr ximg;
5375 Lisp_Object file, specified_file;
5376 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
5377 struct gcpro gcpro1;
5378 unsigned char *contents = NULL;
5379 unsigned char *end, *p;
5380 int size;
5381
5382 specified_file = image_spec_value (img->spec, QCfile, NULL);
5383 file = Qnil;
5384 GCPRO1 (file);
5385
5386 if (STRINGP (specified_file))
5387 {
5388 file = x_find_image_file (specified_file);
5389 if (!STRINGP (file))
5390 {
5391 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5392 UNGCPRO;
5393 return 0;
5394 }
5395
5396 contents = slurp_file (SDATA (file), &size);
5397 if (contents == NULL)
5398 {
5399 image_error ("Error reading `%s'", file, Qnil);
5400 UNGCPRO;
5401 return 0;
5402 }
5403
5404 p = contents;
5405 end = contents + size;
5406 }
5407 else
5408 {
5409 Lisp_Object data;
5410 data = image_spec_value (img->spec, QCdata, NULL);
5411 p = SDATA (data);
5412 end = p + SBYTES (data);
5413 }
5414
5415 /* Check magic number. */
5416 if (end - p < 2 || *p++ != 'P')
5417 {
5418 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5419 error:
5420 xfree (contents);
5421 UNGCPRO;
5422 return 0;
5423 }
5424
5425 switch (*p++)
5426 {
5427 case '1':
5428 raw_p = 0, type = PBM_MONO;
5429 break;
5430
5431 case '2':
5432 raw_p = 0, type = PBM_GRAY;
5433 break;
5434
5435 case '3':
5436 raw_p = 0, type = PBM_COLOR;
5437 break;
5438
5439 case '4':
5440 raw_p = 1, type = PBM_MONO;
5441 break;
5442
5443 case '5':
5444 raw_p = 1, type = PBM_GRAY;
5445 break;
5446
5447 case '6':
5448 raw_p = 1, type = PBM_COLOR;
5449 break;
5450
5451 default:
5452 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
5453 goto error;
5454 }
5455
5456 /* Read width, height, maximum color-component. Characters
5457 starting with `#' up to the end of a line are ignored. */
5458 width = pbm_scan_number (&p, end);
5459 height = pbm_scan_number (&p, end);
5460
5461 if (type != PBM_MONO)
5462 {
5463 max_color_idx = pbm_scan_number (&p, end);
5464 if (raw_p && max_color_idx > 255)
5465 max_color_idx = 255;
5466 }
5467
5468 if (width < 0
5469 || height < 0
5470 || (type != PBM_MONO && max_color_idx < 0))
5471 goto error;
5472
5473 if (!x_create_x_image_and_pixmap (f, width, height, 0,
5474 &ximg, &img->pixmap))
5475 goto error;
5476
5477 /* Initialize the color hash table. */
5478 init_color_table ();
5479
5480 if (type == PBM_MONO)
5481 {
5482 int c = 0, g;
5483 struct image_keyword fmt[PBM_LAST];
5484 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
5485 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
5486
5487 /* Parse the image specification. */
5488 bcopy (pbm_format, fmt, sizeof fmt);
5489 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
5490
5491 /* Get foreground and background colors, maybe allocate colors. */
5492 if (fmt[PBM_FOREGROUND].count
5493 && STRINGP (fmt[PBM_FOREGROUND].value))
5494 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
5495 if (fmt[PBM_BACKGROUND].count
5496 && STRINGP (fmt[PBM_BACKGROUND].value))
5497 {
5498 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
5499 img->background = bg;
5500 img->background_valid = 1;
5501 }
5502
5503 for (y = 0; y < height; ++y)
5504 for (x = 0; x < width; ++x)
5505 {
5506 if (raw_p)
5507 {
5508 if ((x & 7) == 0)
5509 c = *p++;
5510 g = c & 0x80;
5511 c <<= 1;
5512 }
5513 else
5514 g = pbm_scan_number (&p, end);
5515
5516 XPutPixel (ximg, x, y, g ? fg : bg);
5517 }
5518 }
5519 else
5520 {
5521 for (y = 0; y < height; ++y)
5522 for (x = 0; x < width; ++x)
5523 {
5524 int r, g, b;
5525
5526 if (type == PBM_GRAY)
5527 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
5528 else if (raw_p)
5529 {
5530 r = *p++;
5531 g = *p++;
5532 b = *p++;
5533 }
5534 else
5535 {
5536 r = pbm_scan_number (&p, end);
5537 g = pbm_scan_number (&p, end);
5538 b = pbm_scan_number (&p, end);
5539 }
5540
5541 if (r < 0 || g < 0 || b < 0)
5542 {
5543 x_destroy_x_image (ximg);
5544 image_error ("Invalid pixel value in image `%s'",
5545 img->spec, Qnil);
5546 goto error;
5547 }
5548
5549 /* RGB values are now in the range 0..max_color_idx.
5550 Scale this to the range 0..0xffff supported by X. */
5551 r = (double) r * 65535 / max_color_idx;
5552 g = (double) g * 65535 / max_color_idx;
5553 b = (double) b * 65535 / max_color_idx;
5554 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
5555 }
5556 }
5557
5558#ifdef COLOR_TABLE_SUPPORT
5559 /* Store in IMG->colors the colors allocated for the image, and
5560 free the color table. */
5561 img->colors = colors_in_color_table (&img->ncolors);
5562 free_color_table ();
5563#endif /* COLOR_TABLE_SUPPORT */
5564
5565 img->width = width;
5566 img->height = height;
5567
5568 /* Maybe fill in the background field while we have ximg handy. */
5569
5570 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
5571 /* Casting avoids a GCC warning. */
5572 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
5573
5574 /* Put the image into a pixmap. */
5575 x_put_x_image (f, ximg, img->pixmap, width, height);
5576 x_destroy_x_image (ximg);
5577
5578 /* X and W32 versions did it here, MAC version above. ++kfs
1f026899 5579 img->width = width;
4ef0d4d0
KS
5580 img->height = height; */
5581
5582 UNGCPRO;
5583 xfree (contents);
5584 return 1;
5585}
5586
5587\f
5588/***********************************************************************
5589 PNG
5590 ***********************************************************************/
5591
5592#if defined (HAVE_PNG) || defined (MAC_OS)
5593
5594/* Function prototypes. */
5595
5596static int png_image_p P_ ((Lisp_Object object));
5597static int png_load P_ ((struct frame *f, struct image *img));
5598
5599/* The symbol `png' identifying images of this type. */
5600
5601Lisp_Object Qpng;
5602
5603/* Indices of image specification fields in png_format, below. */
5604
5605enum png_keyword_index
5606{
5607 PNG_TYPE,
5608 PNG_DATA,
5609 PNG_FILE,
5610 PNG_ASCENT,
5611 PNG_MARGIN,
5612 PNG_RELIEF,
5613 PNG_ALGORITHM,
5614 PNG_HEURISTIC_MASK,
5615 PNG_MASK,
5616 PNG_BACKGROUND,
5617 PNG_LAST
5618};
5619
5620/* Vector of image_keyword structures describing the format
5621 of valid user-defined image specifications. */
5622
5623static struct image_keyword png_format[PNG_LAST] =
5624{
5625 {":type", IMAGE_SYMBOL_VALUE, 1},
5626 {":data", IMAGE_STRING_VALUE, 0},
5627 {":file", IMAGE_STRING_VALUE, 0},
5628 {":ascent", IMAGE_ASCENT_VALUE, 0},
5629 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
5630 {":relief", IMAGE_INTEGER_VALUE, 0},
5631 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5632 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5633 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
5634 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
5635};
5636
5637/* Structure describing the image type `png'. */
5638
5639static struct image_type png_type =
5640{
5641 &Qpng,
5642 png_image_p,
5643 png_load,
5644 x_clear_image,
5645 NULL
5646};
5647
5648/* Return non-zero if OBJECT is a valid PNG image specification. */
5649
5650static int
5651png_image_p (object)
5652 Lisp_Object object;
5653{
5654 struct image_keyword fmt[PNG_LAST];
5655 bcopy (png_format, fmt, sizeof fmt);
5656
5657 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
5658 return 0;
5659
5660 /* Must specify either the :data or :file keyword. */
5661 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
5662}
5663
5664#endif /* HAVE_PNG || MAC_OS */
5665
5666
5667#ifdef HAVE_PNG
5668
5669#if defined HAVE_LIBPNG_PNG_H
5670# include <libpng/png.h>
5671#else
5672# include <png.h>
5673#endif
5674
5675#ifdef HAVE_NTGUI
5676/* PNG library details. */
5677
5678DEF_IMGLIB_FN (png_get_io_ptr);
5679DEF_IMGLIB_FN (png_check_sig);
5680DEF_IMGLIB_FN (png_create_read_struct);
5681DEF_IMGLIB_FN (png_create_info_struct);
5682DEF_IMGLIB_FN (png_destroy_read_struct);
5683DEF_IMGLIB_FN (png_set_read_fn);
4ef0d4d0
KS
5684DEF_IMGLIB_FN (png_set_sig_bytes);
5685DEF_IMGLIB_FN (png_read_info);
5686DEF_IMGLIB_FN (png_get_IHDR);
5687DEF_IMGLIB_FN (png_get_valid);
5688DEF_IMGLIB_FN (png_set_strip_16);
5689DEF_IMGLIB_FN (png_set_expand);
5690DEF_IMGLIB_FN (png_set_gray_to_rgb);
5691DEF_IMGLIB_FN (png_set_background);
5692DEF_IMGLIB_FN (png_get_bKGD);
5693DEF_IMGLIB_FN (png_read_update_info);
5694DEF_IMGLIB_FN (png_get_channels);
5695DEF_IMGLIB_FN (png_get_rowbytes);
5696DEF_IMGLIB_FN (png_read_image);
5697DEF_IMGLIB_FN (png_read_end);
5698DEF_IMGLIB_FN (png_error);
5699
5700static int
0855eb52 5701init_png_functions (Lisp_Object libraries)
4ef0d4d0
KS
5702{
5703 HMODULE library;
5704
4ef0d4d0 5705 /* Try loading libpng under probable names. */
0855eb52 5706 if (!(library = w32_delayed_load (libraries, Qpng)))
4ef0d4d0
KS
5707 return 0;
5708
5709 LOAD_IMGLIB_FN (library, png_get_io_ptr);
5710 LOAD_IMGLIB_FN (library, png_check_sig);
5711 LOAD_IMGLIB_FN (library, png_create_read_struct);
5712 LOAD_IMGLIB_FN (library, png_create_info_struct);
5713 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
5714 LOAD_IMGLIB_FN (library, png_set_read_fn);
4ef0d4d0
KS
5715 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
5716 LOAD_IMGLIB_FN (library, png_read_info);
5717 LOAD_IMGLIB_FN (library, png_get_IHDR);
5718 LOAD_IMGLIB_FN (library, png_get_valid);
5719 LOAD_IMGLIB_FN (library, png_set_strip_16);
5720 LOAD_IMGLIB_FN (library, png_set_expand);
5721 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
5722 LOAD_IMGLIB_FN (library, png_set_background);
5723 LOAD_IMGLIB_FN (library, png_get_bKGD);
5724 LOAD_IMGLIB_FN (library, png_read_update_info);
5725 LOAD_IMGLIB_FN (library, png_get_channels);
5726 LOAD_IMGLIB_FN (library, png_get_rowbytes);
5727 LOAD_IMGLIB_FN (library, png_read_image);
5728 LOAD_IMGLIB_FN (library, png_read_end);
5729 LOAD_IMGLIB_FN (library, png_error);
5730 return 1;
5731}
5732#else
5733
5734#define fn_png_get_io_ptr png_get_io_ptr
5735#define fn_png_check_sig png_check_sig
5736#define fn_png_create_read_struct png_create_read_struct
5737#define fn_png_create_info_struct png_create_info_struct
5738#define fn_png_destroy_read_struct png_destroy_read_struct
5739#define fn_png_set_read_fn png_set_read_fn
4ef0d4d0
KS
5740#define fn_png_set_sig_bytes png_set_sig_bytes
5741#define fn_png_read_info png_read_info
5742#define fn_png_get_IHDR png_get_IHDR
5743#define fn_png_get_valid png_get_valid
5744#define fn_png_set_strip_16 png_set_strip_16
5745#define fn_png_set_expand png_set_expand
5746#define fn_png_set_gray_to_rgb png_set_gray_to_rgb
5747#define fn_png_set_background png_set_background
5748#define fn_png_get_bKGD png_get_bKGD
5749#define fn_png_read_update_info png_read_update_info
5750#define fn_png_get_channels png_get_channels
5751#define fn_png_get_rowbytes png_get_rowbytes
5752#define fn_png_read_image png_read_image
5753#define fn_png_read_end png_read_end
5754#define fn_png_error png_error
5755
5756#endif /* HAVE_NTGUI */
5757
5758/* Error and warning handlers installed when the PNG library
5759 is initialized. */
5760
5761static void
5762my_png_error (png_ptr, msg)
5763 png_struct *png_ptr;
5764 char *msg;
5765{
5766 xassert (png_ptr != NULL);
5767 image_error ("PNG error: %s", build_string (msg), Qnil);
5768 longjmp (png_ptr->jmpbuf, 1);
5769}
5770
5771
5772static void
5773my_png_warning (png_ptr, msg)
5774 png_struct *png_ptr;
5775 char *msg;
5776{
5777 xassert (png_ptr != NULL);
5778 image_error ("PNG warning: %s", build_string (msg), Qnil);
5779}
5780
5781/* Memory source for PNG decoding. */
5782
5783struct png_memory_storage
5784{
5785 unsigned char *bytes; /* The data */
5786 size_t len; /* How big is it? */
5787 int index; /* Where are we? */
5788};
5789
5790
5791/* Function set as reader function when reading PNG image from memory.
5792 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5793 bytes from the input to DATA. */
5794
5795static void
5796png_read_from_memory (png_ptr, data, length)
5797 png_structp png_ptr;
5798 png_bytep data;
5799 png_size_t length;
5800{
5801 struct png_memory_storage *tbr
5802 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
5803
5804 if (length > tbr->len - tbr->index)
5805 fn_png_error (png_ptr, "Read error");
5806
5807 bcopy (tbr->bytes + tbr->index, data, length);
5808 tbr->index = tbr->index + length;
5809}
5810
b0da69a7 5811
9a22a004
JB
5812/* Function set as reader function when reading PNG image from a file.
5813 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
5814 bytes from the input to DATA. */
5815
5816static void
5817png_read_from_file (png_ptr, data, length)
5818 png_structp png_ptr;
5819 png_bytep data;
5820 png_size_t length;
5821{
5822 FILE *fp = (FILE *) fn_png_get_io_ptr (png_ptr);
5823
5824 if (fread (data, 1, length, fp) < length)
5825 fn_png_error (png_ptr, "Read error");
5826}
5827
5828
4ef0d4d0
KS
5829/* Load PNG image IMG for use on frame F. Value is non-zero if
5830 successful. */
5831
5832static int
5833png_load (f, img)
5834 struct frame *f;
5835 struct image *img;
5836{
5837 Lisp_Object file, specified_file;
5838 Lisp_Object specified_data;
5839 int x, y, i;
5840 XImagePtr ximg, mask_img = NULL;
5841 struct gcpro gcpro1;
5842 png_struct *png_ptr = NULL;
5843 png_info *info_ptr = NULL, *end_info = NULL;
5844 FILE *volatile fp = NULL;
5845 png_byte sig[8];
5846 png_byte * volatile pixels = NULL;
5847 png_byte ** volatile rows = NULL;
5848 png_uint_32 width, height;
5849 int bit_depth, color_type, interlace_type;
5850 png_byte channels;
5851 png_uint_32 row_bytes;
5852 int transparent_p;
5853 double screen_gamma;
5854 struct png_memory_storage tbr; /* Data to be read */
5855
5856 /* Find out what file to load. */
5857 specified_file = image_spec_value (img->spec, QCfile, NULL);
5858 specified_data = image_spec_value (img->spec, QCdata, NULL);
5859 file = Qnil;
5860 GCPRO1 (file);
5861
5862 if (NILP (specified_data))
5863 {
5864 file = x_find_image_file (specified_file);
5865 if (!STRINGP (file))
5866 {
5867 image_error ("Cannot find image file `%s'", specified_file, Qnil);
5868 UNGCPRO;
5869 return 0;
5870 }
5871
5872 /* Open the image file. */
5873 fp = fopen (SDATA (file), "rb");
5874 if (!fp)
5875 {
5876 image_error ("Cannot open image file `%s'", file, Qnil);
5877 UNGCPRO;
5878 fclose (fp);
5879 return 0;
5880 }
5881
5882 /* Check PNG signature. */
5883 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
5884 || !fn_png_check_sig (sig, sizeof sig))
5885 {
5886 image_error ("Not a PNG file: `%s'", file, Qnil);
5887 UNGCPRO;
5888 fclose (fp);
5889 return 0;
5890 }
5891 }
5892 else
5893 {
5894 /* Read from memory. */
5895 tbr.bytes = SDATA (specified_data);
5896 tbr.len = SBYTES (specified_data);
5897 tbr.index = 0;
5898
5899 /* Check PNG signature. */
5900 if (tbr.len < sizeof sig
5901 || !fn_png_check_sig (tbr.bytes, sizeof sig))
5902 {
5903 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
5904 UNGCPRO;
5905 return 0;
5906 }
5907
5908 /* Need to skip past the signature. */
5909 tbr.bytes += sizeof (sig);
5910 }
5911
2e09fef1
EZ
5912 /* Initialize read and info structs for PNG lib. Casting return
5913 value avoids a GCC warning on W32. */
5914 png_ptr = (png_structp)fn_png_create_read_struct (PNG_LIBPNG_VER_STRING,
5915 NULL, my_png_error,
5916 my_png_warning);
4ef0d4d0
KS
5917 if (!png_ptr)
5918 {
5919 if (fp) fclose (fp);
5920 UNGCPRO;
5921 return 0;
5922 }
5923
2e09fef1
EZ
5924 /* Casting return value avoids a GCC warning on W32. */
5925 info_ptr = (png_infop)fn_png_create_info_struct (png_ptr);
4ef0d4d0
KS
5926 if (!info_ptr)
5927 {
5928 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
5929 if (fp) fclose (fp);
5930 UNGCPRO;
5931 return 0;
5932 }
5933
2e09fef1
EZ
5934 /* Casting return value avoids a GCC warning on W32. */
5935 end_info = (png_infop)fn_png_create_info_struct (png_ptr);
4ef0d4d0
KS
5936 if (!end_info)
5937 {
5938 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
5939 if (fp) fclose (fp);
5940 UNGCPRO;
5941 return 0;
5942 }
5943
5944 /* Set error jump-back. We come back here when the PNG library
5945 detects an error. */
5946 if (setjmp (png_ptr->jmpbuf))
5947 {
5948 error:
5949 if (png_ptr)
5950 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
5951 xfree (pixels);
5952 xfree (rows);
5953 if (fp) fclose (fp);
5954 UNGCPRO;
5955 return 0;
5956 }
5957
5958 /* Read image info. */
5959 if (!NILP (specified_data))
5960 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
5961 else
9a22a004 5962 fn_png_set_read_fn (png_ptr, (void *) fp, png_read_from_file);
4ef0d4d0
KS
5963
5964 fn_png_set_sig_bytes (png_ptr, sizeof sig);
5965 fn_png_read_info (png_ptr, info_ptr);
5966 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
5967 &interlace_type, NULL, NULL);
5968
5969 /* If image contains simply transparency data, we prefer to
5970 construct a clipping mask. */
5971 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
5972 transparent_p = 1;
5973 else
5974 transparent_p = 0;
5975
5976 /* This function is easier to write if we only have to handle
5977 one data format: RGB or RGBA with 8 bits per channel. Let's
5978 transform other formats into that format. */
5979
5980 /* Strip more than 8 bits per channel. */
5981 if (bit_depth == 16)
5982 fn_png_set_strip_16 (png_ptr);
5983
5984 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
5985 if available. */
5986 fn_png_set_expand (png_ptr);
5987
5988 /* Convert grayscale images to RGB. */
5989 if (color_type == PNG_COLOR_TYPE_GRAY
5990 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
5991 fn_png_set_gray_to_rgb (png_ptr);
5992
5993 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
5994
5995#if 0 /* Avoid double gamma correction for PNG images. */
5996 { /* Tell the PNG lib to handle gamma correction for us. */
5997 int intent;
5998 double image_gamma;
5999#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
6000 if (png_get_sRGB (png_ptr, info_ptr, &intent))
6001 /* The libpng documentation says this is right in this case. */
6002 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6003 else
6004#endif
6005 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
6006 /* Image contains gamma information. */
6007 png_set_gamma (png_ptr, screen_gamma, image_gamma);
6008 else
6009 /* Use the standard default for the image gamma. */
6010 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6011 }
6012#endif /* if 0 */
6013
6014 /* Handle alpha channel by combining the image with a background
6015 color. Do this only if a real alpha channel is supplied. For
6016 simple transparency, we prefer a clipping mask. */
6017 if (!transparent_p)
6018 {
6019 png_color_16 *image_bg;
6020 Lisp_Object specified_bg
6021 = image_spec_value (img->spec, QCbackground, NULL);
6022
6023 if (STRINGP (specified_bg))
6024 /* The user specified `:background', use that. */
6025 {
6026 /* W32 version incorrectly used COLORREF here!! ++kfs */
6027 XColor color;
6028 if (x_defined_color (f, SDATA (specified_bg), &color, 0))
6029 {
6030 png_color_16 user_bg;
6031
6032 bzero (&user_bg, sizeof user_bg);
1f026899
KS
6033 user_bg.red = color.red >> 8;
6034 user_bg.green = color.green >> 8;
6035 user_bg.blue = color.blue >> 8;
4ef0d4d0
KS
6036
6037 fn_png_set_background (png_ptr, &user_bg,
6038 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6039 }
6040 }
6041 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
6042 /* Image contains a background color with which to
6043 combine the image. */
6044 fn_png_set_background (png_ptr, image_bg,
6045 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6046 else
6047 {
6048 /* Image does not contain a background color with which
6049 to combine the image data via an alpha channel. Use
6050 the frame's background instead. */
6051#ifdef HAVE_X_WINDOWS
6052 XColor color;
6053 png_color_16 frame_background;
6054
6055 color.pixel = FRAME_BACKGROUND_PIXEL (f);
6056 x_query_color (f, &color);
6057
6058 bzero (&frame_background, sizeof frame_background);
1f026899
KS
6059 frame_background.red = color.red >> 8;
6060 frame_background.green = color.green >> 8;
6061 frame_background.blue = color.blue >> 8;
4ef0d4d0
KS
6062#endif /* HAVE_X_WINDOWS */
6063
6064#ifdef HAVE_NTGUI
6065 COLORREF color;
6066 png_color_16 frame_background;
6067 color = FRAME_BACKGROUND_PIXEL (f);
6068#if 0 /* W32 TODO : Colormap support. */
6069 x_query_color (f, &color);
6070#endif
6071 bzero (&frame_background, sizeof frame_background);
1f026899
KS
6072 frame_background.red = GetRValue (color);
6073 frame_background.green = GetGValue (color);
6074 frame_background.blue = GetBValue (color);
4ef0d4d0
KS
6075#endif /* HAVE_NTGUI */
6076
6077#ifdef MAC_OS
6078 unsigned long color;
6079 png_color_16 frame_background;
6080 color = FRAME_BACKGROUND_PIXEL (f);
6081#if 0 /* MAC/W32 TODO : Colormap support. */
6082 x_query_color (f, &color);
6083#endif
6084 bzero (&frame_background, sizeof frame_background);
6085 frame_background.red = RED_FROM_ULONG (color);
6086 frame_background.green = GREEN_FROM_ULONG (color);
6087 frame_background.blue = BLUE_FROM_ULONG (color);
6088#endif /* MAC_OS */
6089
6090 fn_png_set_background (png_ptr, &frame_background,
6091 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6092 }
6093 }
6094
6095 /* Update info structure. */
6096 fn_png_read_update_info (png_ptr, info_ptr);
6097
6098 /* Get number of channels. Valid values are 1 for grayscale images
6099 and images with a palette, 2 for grayscale images with transparency
6100 information (alpha channel), 3 for RGB images, and 4 for RGB
6101 images with alpha channel, i.e. RGBA. If conversions above were
6102 sufficient we should only have 3 or 4 channels here. */
6103 channels = fn_png_get_channels (png_ptr, info_ptr);
6104 xassert (channels == 3 || channels == 4);
6105
6106 /* Number of bytes needed for one row of the image. */
6107 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6108
6109 /* Allocate memory for the image. */
6110 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
6111 rows = (png_byte **) xmalloc (height * sizeof *rows);
6112 for (i = 0; i < height; ++i)
6113 rows[i] = pixels + i * row_bytes;
6114
6115 /* Read the entire image. */
6116 fn_png_read_image (png_ptr, rows);
6117 fn_png_read_end (png_ptr, info_ptr);
6118 if (fp)
6119 {
6120 fclose (fp);
6121 fp = NULL;
6122 }
6123
6124 /* Create the X image and pixmap. */
6125 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
6126 &img->pixmap))
6127 goto error;
6128
6129 /* Create an image and pixmap serving as mask if the PNG image
6130 contains an alpha channel. */
6131 if (channels == 4
6132 && !transparent_p
6133 && !x_create_x_image_and_pixmap (f, width, height, 1,
6134 &mask_img, &img->mask))
6135 {
6136 x_destroy_x_image (ximg);
6137 Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
6138 img->pixmap = NO_PIXMAP;
6139 goto error;
6140 }
6141
6142 /* Fill the X image and mask from PNG data. */
6143 init_color_table ();
6144
6145 for (y = 0; y < height; ++y)
6146 {
6147 png_byte *p = rows[y];
6148
6149 for (x = 0; x < width; ++x)
6150 {
6151 unsigned r, g, b;
6152
6153 r = *p++ << 8;
6154 g = *p++ << 8;
6155 b = *p++ << 8;
6156 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
6157 /* An alpha channel, aka mask channel, associates variable
6158 transparency with an image. Where other image formats
6159 support binary transparency---fully transparent or fully
6160 opaque---PNG allows up to 254 levels of partial transparency.
6161 The PNG library implements partial transparency by combining
6162 the image with a specified background color.
6163
6164 I'm not sure how to handle this here nicely: because the
6165 background on which the image is displayed may change, for
6166 real alpha channel support, it would be necessary to create
6167 a new image for each possible background.
6168
6169 What I'm doing now is that a mask is created if we have
6170 boolean transparency information. Otherwise I'm using
6171 the frame's background color to combine the image with. */
6172
6173 if (channels == 4)
6174 {
6175 if (mask_img)
9ecf6403 6176 XPutPixel (mask_img, x, y, *p > 0 ? PIX_MASK_DRAW : PIX_MASK_RETAIN);
4ef0d4d0
KS
6177 ++p;
6178 }
6179 }
6180 }
6181
6182 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
6183 /* Set IMG's background color from the PNG image, unless the user
6184 overrode it. */
6185 {
6186 png_color_16 *bg;
6187 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
6188 {
6189 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
6190 img->background_valid = 1;
6191 }
6192 }
6193
6194#ifdef COLOR_TABLE_SUPPORT
6195 /* Remember colors allocated for this image. */
6196 img->colors = colors_in_color_table (&img->ncolors);
6197 free_color_table ();
6198#endif /* COLOR_TABLE_SUPPORT */
6199
6200 /* Clean up. */
6201 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6202 xfree (rows);
6203 xfree (pixels);
6204
6205 img->width = width;
6206 img->height = height;
6207
2e09fef1
EZ
6208 /* Maybe fill in the background field while we have ximg handy.
6209 Casting avoids a GCC warning. */
6210 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
6211
6212 /* Put the image into the pixmap, then free the X image and its buffer. */
6213 x_put_x_image (f, ximg, img->pixmap, width, height);
6214 x_destroy_x_image (ximg);
6215
6216 /* Same for the mask. */
6217 if (mask_img)
6218 {
2e09fef1
EZ
6219 /* Fill in the background_transparent field while we have the
6220 mask handy. Casting avoids a GCC warning. */
6221 image_background_transparent (img, f, (XImagePtr_or_DC)mask_img);
4ef0d4d0
KS
6222
6223 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
6224 x_destroy_x_image (mask_img);
6225 }
6226
6227 UNGCPRO;
6228 return 1;
6229}
6230
6231#else /* HAVE_PNG */
6232
6233#ifdef MAC_OS
6234static int
6235png_load (f, img)
6236 struct frame *f;
6237 struct image *img;
6238{
6239#ifdef MAC_OSX
6240 if (MyCGImageCreateWithPNGDataProvider)
6241 return image_load_quartz2d (f, img, 1);
6242 else
6243#endif
6244 return image_load_quicktime (f, img, kQTFileTypePNG);
6245}
6246#endif /* MAC_OS */
6247
6248#endif /* !HAVE_PNG */
6249
6250
6251\f
6252/***********************************************************************
6253 JPEG
6254 ***********************************************************************/
6255
6256#if defined (HAVE_JPEG) || defined (MAC_OS)
6257
6258static int jpeg_image_p P_ ((Lisp_Object object));
6259static int jpeg_load P_ ((struct frame *f, struct image *img));
6260
6261/* The symbol `jpeg' identifying images of this type. */
6262
6263Lisp_Object Qjpeg;
6264
6265/* Indices of image specification fields in gs_format, below. */
6266
6267enum jpeg_keyword_index
6268{
6269 JPEG_TYPE,
6270 JPEG_DATA,
6271 JPEG_FILE,
6272 JPEG_ASCENT,
6273 JPEG_MARGIN,
6274 JPEG_RELIEF,
6275 JPEG_ALGORITHM,
6276 JPEG_HEURISTIC_MASK,
6277 JPEG_MASK,
6278 JPEG_BACKGROUND,
6279 JPEG_LAST
6280};
6281
6282/* Vector of image_keyword structures describing the format
6283 of valid user-defined image specifications. */
6284
6285static struct image_keyword jpeg_format[JPEG_LAST] =
6286{
6287 {":type", IMAGE_SYMBOL_VALUE, 1},
6288 {":data", IMAGE_STRING_VALUE, 0},
6289 {":file", IMAGE_STRING_VALUE, 0},
6290 {":ascent", IMAGE_ASCENT_VALUE, 0},
6291 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6292 {":relief", IMAGE_INTEGER_VALUE, 0},
6293 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6294 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6295 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6296 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6297};
6298
6299/* Structure describing the image type `jpeg'. */
6300
6301static struct image_type jpeg_type =
6302{
6303 &Qjpeg,
6304 jpeg_image_p,
6305 jpeg_load,
6306 x_clear_image,
6307 NULL
6308};
6309
6310/* Return non-zero if OBJECT is a valid JPEG image specification. */
6311
6312static int
6313jpeg_image_p (object)
6314 Lisp_Object object;
6315{
6316 struct image_keyword fmt[JPEG_LAST];
6317
6318 bcopy (jpeg_format, fmt, sizeof fmt);
6319
6320 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6321 return 0;
6322
6323 /* Must specify either the :data or :file keyword. */
6324 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
6325}
6326
6327#endif /* HAVE_JPEG || MAC_OS */
6328
6329#ifdef HAVE_JPEG
6330
6331/* Work around a warning about HAVE_STDLIB_H being redefined in
6332 jconfig.h. */
6333#ifdef HAVE_STDLIB_H
6334#define HAVE_STDLIB_H_1
6335#undef HAVE_STDLIB_H
6336#endif /* HAVE_STLIB_H */
6337
66354420 6338#if defined (HAVE_NTGUI) && !defined (__WIN32__)
28893db2
JB
6339/* In older releases of the jpeg library, jpeglib.h will define boolean
6340 differently depending on __WIN32__, so make sure it is defined. */
66354420
JR
6341#define __WIN32__ 1
6342#endif
6343
4ef0d4d0
KS
6344#include <jpeglib.h>
6345#include <jerror.h>
6346#include <setjmp.h>
6347
6348#ifdef HAVE_STLIB_H_1
6349#define HAVE_STDLIB_H 1
6350#endif
6351
6352#ifdef HAVE_NTGUI
6353
6354/* JPEG library details. */
6355DEF_IMGLIB_FN (jpeg_CreateDecompress);
6356DEF_IMGLIB_FN (jpeg_start_decompress);
6357DEF_IMGLIB_FN (jpeg_finish_decompress);
6358DEF_IMGLIB_FN (jpeg_destroy_decompress);
6359DEF_IMGLIB_FN (jpeg_read_header);
6360DEF_IMGLIB_FN (jpeg_read_scanlines);
6361DEF_IMGLIB_FN (jpeg_stdio_src);
6362DEF_IMGLIB_FN (jpeg_std_error);
6363DEF_IMGLIB_FN (jpeg_resync_to_restart);
6364
6365static int
0855eb52 6366init_jpeg_functions (Lisp_Object libraries)
4ef0d4d0
KS
6367{
6368 HMODULE library;
6369
0855eb52 6370 if (!(library = w32_delayed_load (libraries, Qjpeg)))
4ef0d4d0
KS
6371 return 0;
6372
6373 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
6374 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
6375 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
6376 LOAD_IMGLIB_FN (library, jpeg_read_header);
6377 LOAD_IMGLIB_FN (library, jpeg_stdio_src);
6378 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
6379 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
6380 LOAD_IMGLIB_FN (library, jpeg_std_error);
6381 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
6382 return 1;
6383}
6384
6385/* Wrapper since we can't directly assign the function pointer
6386 to another function pointer that was declared more completely easily. */
6387static boolean
6388jpeg_resync_to_restart_wrapper(cinfo, desired)
6389 j_decompress_ptr cinfo;
6390 int desired;
6391{
6392 return fn_jpeg_resync_to_restart (cinfo, desired);
6393}
6394
6395#else
6396
6397#define fn_jpeg_CreateDecompress(a,b,c) jpeg_create_decompress(a)
6398#define fn_jpeg_start_decompress jpeg_start_decompress
6399#define fn_jpeg_finish_decompress jpeg_finish_decompress
6400#define fn_jpeg_destroy_decompress jpeg_destroy_decompress
6401#define fn_jpeg_read_header jpeg_read_header
6402#define fn_jpeg_read_scanlines jpeg_read_scanlines
6403#define fn_jpeg_stdio_src jpeg_stdio_src
6404#define fn_jpeg_std_error jpeg_std_error
6405#define jpeg_resync_to_restart_wrapper jpeg_resync_to_restart
6406
6407#endif /* HAVE_NTGUI */
6408
6409struct my_jpeg_error_mgr
6410{
6411 struct jpeg_error_mgr pub;
6412 jmp_buf setjmp_buffer;
6413};
6414
6415
6416static void
6417my_error_exit (cinfo)
6418 j_common_ptr cinfo;
6419{
6420 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
6421 longjmp (mgr->setjmp_buffer, 1);
6422}
6423
6424
6425/* Init source method for JPEG data source manager. Called by
6426 jpeg_read_header() before any data is actually read. See
6427 libjpeg.doc from the JPEG lib distribution. */
6428
6429static void
6430our_init_source (cinfo)
6431 j_decompress_ptr cinfo;
6432{
6433}
6434
6435
6436/* Fill input buffer method for JPEG data source manager. Called
6437 whenever more data is needed. We read the whole image in one step,
6438 so this only adds a fake end of input marker at the end. */
6439
6440static boolean
6441our_fill_input_buffer (cinfo)
6442 j_decompress_ptr cinfo;
6443{
6444 /* Insert a fake EOI marker. */
6445 struct jpeg_source_mgr *src = cinfo->src;
6446 static JOCTET buffer[2];
6447
6448 buffer[0] = (JOCTET) 0xFF;
6449 buffer[1] = (JOCTET) JPEG_EOI;
6450
6451 src->next_input_byte = buffer;
6452 src->bytes_in_buffer = 2;
e0e30823 6453 return 1;
4ef0d4d0
KS
6454}
6455
6456
6457/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
6458 is the JPEG data source manager. */
6459
6460static void
6461our_skip_input_data (cinfo, num_bytes)
6462 j_decompress_ptr cinfo;
6463 long num_bytes;
6464{
6465 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
6466
6467 if (src)
6468 {
6469 if (num_bytes > src->bytes_in_buffer)
6470 ERREXIT (cinfo, JERR_INPUT_EOF);
6471
6472 src->bytes_in_buffer -= num_bytes;
6473 src->next_input_byte += num_bytes;
6474 }
6475}
6476
6477
6478/* Method to terminate data source. Called by
6479 jpeg_finish_decompress() after all data has been processed. */
6480
6481static void
6482our_term_source (cinfo)
6483 j_decompress_ptr cinfo;
6484{
6485}
6486
6487
6488/* Set up the JPEG lib for reading an image from DATA which contains
6489 LEN bytes. CINFO is the decompression info structure created for
6490 reading the image. */
6491
6492static void
6493jpeg_memory_src (cinfo, data, len)
6494 j_decompress_ptr cinfo;
6495 JOCTET *data;
6496 unsigned int len;
6497{
6498 struct jpeg_source_mgr *src;
6499
6500 if (cinfo->src == NULL)
6501 {
6502 /* First time for this JPEG object? */
6503 cinfo->src = (struct jpeg_source_mgr *)
6504 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
6505 sizeof (struct jpeg_source_mgr));
6506 src = (struct jpeg_source_mgr *) cinfo->src;
6507 src->next_input_byte = data;
6508 }
6509
6510 src = (struct jpeg_source_mgr *) cinfo->src;
6511 src->init_source = our_init_source;
6512 src->fill_input_buffer = our_fill_input_buffer;
6513 src->skip_input_data = our_skip_input_data;
6514 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6515 src->term_source = our_term_source;
6516 src->bytes_in_buffer = len;
6517 src->next_input_byte = data;
6518}
6519
6520
6521/* Load image IMG for use on frame F. Patterned after example.c
6522 from the JPEG lib. */
6523
6524static int
6525jpeg_load (f, img)
6526 struct frame *f;
6527 struct image *img;
6528{
6529 struct jpeg_decompress_struct cinfo;
6530 struct my_jpeg_error_mgr mgr;
6531 Lisp_Object file, specified_file;
6532 Lisp_Object specified_data;
6533 FILE * volatile fp = NULL;
6534 JSAMPARRAY buffer;
6535 int row_stride, x, y;
6536 XImagePtr ximg = NULL;
6537 int rc;
6538 unsigned long *colors;
6539 int width, height;
6540 struct gcpro gcpro1;
6541
6542 /* Open the JPEG file. */
6543 specified_file = image_spec_value (img->spec, QCfile, NULL);
6544 specified_data = image_spec_value (img->spec, QCdata, NULL);
6545 file = Qnil;
6546 GCPRO1 (file);
6547
6548 if (NILP (specified_data))
6549 {
6550 file = x_find_image_file (specified_file);
6551 if (!STRINGP (file))
6552 {
6553 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6554 UNGCPRO;
6555 return 0;
6556 }
6557
6558 fp = fopen (SDATA (file), "rb");
6559 if (fp == NULL)
6560 {
6561 image_error ("Cannot open `%s'", file, Qnil);
6562 UNGCPRO;
6563 return 0;
6564 }
6565 }
6566
6567 /* Customize libjpeg's error handling to call my_error_exit when an
2e09fef1
EZ
6568 error is detected. This function will perform a longjmp.
6569 Casting return value avoids a GCC warning on W32. */
6570 cinfo.err = (struct jpeg_error_mgr *)fn_jpeg_std_error (&mgr.pub);
4ef0d4d0
KS
6571 mgr.pub.error_exit = my_error_exit;
6572
6573 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
6574 {
6575 if (rc == 1)
6576 {
6577 /* Called from my_error_exit. Display a JPEG error. */
6578 char buffer[JMSG_LENGTH_MAX];
6579 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
6580 image_error ("Error reading JPEG image `%s': %s", img->spec,
6581 build_string (buffer));
6582 }
6583
6584 /* Close the input file and destroy the JPEG object. */
6585 if (fp)
6586 fclose ((FILE *) fp);
6587 fn_jpeg_destroy_decompress (&cinfo);
6588
6589 /* If we already have an XImage, free that. */
6590 x_destroy_x_image (ximg);
6591
6592 /* Free pixmap and colors. */
6593 x_clear_image (f, img);
6594
6595 UNGCPRO;
6596 return 0;
6597 }
6598
6599 /* Create the JPEG decompression object. Let it read from fp.
6600 Read the JPEG image header. */
6601 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6602
6603 if (NILP (specified_data))
6604 fn_jpeg_stdio_src (&cinfo, (FILE *) fp);
6605 else
6606 jpeg_memory_src (&cinfo, SDATA (specified_data),
6607 SBYTES (specified_data));
6608
e0e30823 6609 fn_jpeg_read_header (&cinfo, 1);
4ef0d4d0
KS
6610
6611 /* Customize decompression so that color quantization will be used.
6612 Start decompression. */
e0e30823 6613 cinfo.quantize_colors = 1;
4ef0d4d0
KS
6614 fn_jpeg_start_decompress (&cinfo);
6615 width = img->width = cinfo.output_width;
6616 height = img->height = cinfo.output_height;
6617
6618 /* Create X image and pixmap. */
6619 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
6620 longjmp (mgr.setjmp_buffer, 2);
6621
6622 /* Allocate colors. When color quantization is used,
6623 cinfo.actual_number_of_colors has been set with the number of
6624 colors generated, and cinfo.colormap is a two-dimensional array
6625 of color indices in the range 0..cinfo.actual_number_of_colors.
6626 No more than 255 colors will be generated. */
6627 {
6628 int i, ir, ig, ib;
6629
6630 if (cinfo.out_color_components > 2)
6631 ir = 0, ig = 1, ib = 2;
6632 else if (cinfo.out_color_components > 1)
6633 ir = 0, ig = 1, ib = 0;
6634 else
6635 ir = 0, ig = 0, ib = 0;
6636
6637 /* Use the color table mechanism because it handles colors that
6638 cannot be allocated nicely. Such colors will be replaced with
6639 a default color, and we don't have to care about which colors
6640 can be freed safely, and which can't. */
6641 init_color_table ();
6642 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
6643 * sizeof *colors);
6644
6645 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
6646 {
6647 /* Multiply RGB values with 255 because X expects RGB values
6648 in the range 0..0xffff. */
6649 int r = cinfo.colormap[ir][i] << 8;
6650 int g = cinfo.colormap[ig][i] << 8;
6651 int b = cinfo.colormap[ib][i] << 8;
6652 colors[i] = lookup_rgb_color (f, r, g, b);
6653 }
6654
6655#ifdef COLOR_TABLE_SUPPORT
6656 /* Remember those colors actually allocated. */
6657 img->colors = colors_in_color_table (&img->ncolors);
6658 free_color_table ();
6659#endif /* COLOR_TABLE_SUPPORT */
6660 }
6661
6662 /* Read pixels. */
6663 row_stride = width * cinfo.output_components;
6664 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
6665 row_stride, 1);
6666 for (y = 0; y < height; ++y)
6667 {
6668 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6669 for (x = 0; x < cinfo.output_width; ++x)
6670 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
6671 }
6672
6673 /* Clean up. */
6674 fn_jpeg_finish_decompress (&cinfo);
6675 fn_jpeg_destroy_decompress (&cinfo);
6676 if (fp)
6677 fclose ((FILE *) fp);
6678
6679 /* Maybe fill in the background field while we have ximg handy. */
6680 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
6681 /* Casting avoids a GCC warning. */
6682 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
6683
6684 /* Put the image into the pixmap. */
6685 x_put_x_image (f, ximg, img->pixmap, width, height);
6686 x_destroy_x_image (ximg);
6687 UNGCPRO;
6688 return 1;
6689}
6690
6691#else /* HAVE_JPEG */
6692
6693#ifdef MAC_OS
6694static int
6695jpeg_load (f, img)
6696 struct frame *f;
6697 struct image *img;
6698{
6699#ifdef MAC_OSX
6700 return image_load_quartz2d (f, img, 0);
6701#else
6702 return image_load_quicktime (f, img, kQTFileTypeJPEG);
6703#endif
6704}
6705#endif /* MAC_OS */
6706
6707#endif /* !HAVE_JPEG */
6708
6709
6710\f
6711/***********************************************************************
6712 TIFF
6713 ***********************************************************************/
6714
6715#if defined (HAVE_TIFF) || defined (MAC_OS)
6716
6717static int tiff_image_p P_ ((Lisp_Object object));
6718static int tiff_load P_ ((struct frame *f, struct image *img));
6719
6720/* The symbol `tiff' identifying images of this type. */
6721
6722Lisp_Object Qtiff;
6723
6724/* Indices of image specification fields in tiff_format, below. */
6725
6726enum tiff_keyword_index
6727{
6728 TIFF_TYPE,
6729 TIFF_DATA,
6730 TIFF_FILE,
6731 TIFF_ASCENT,
6732 TIFF_MARGIN,
6733 TIFF_RELIEF,
6734 TIFF_ALGORITHM,
6735 TIFF_HEURISTIC_MASK,
6736 TIFF_MASK,
6737 TIFF_BACKGROUND,
6738 TIFF_LAST
6739};
6740
6741/* Vector of image_keyword structures describing the format
6742 of valid user-defined image specifications. */
6743
6744static struct image_keyword tiff_format[TIFF_LAST] =
6745{
6746 {":type", IMAGE_SYMBOL_VALUE, 1},
6747 {":data", IMAGE_STRING_VALUE, 0},
6748 {":file", IMAGE_STRING_VALUE, 0},
6749 {":ascent", IMAGE_ASCENT_VALUE, 0},
6750 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6751 {":relief", IMAGE_INTEGER_VALUE, 0},
6752 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6753 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6754 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6755 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6756};
6757
6758/* Structure describing the image type `tiff'. */
6759
6760static struct image_type tiff_type =
6761{
6762 &Qtiff,
6763 tiff_image_p,
6764 tiff_load,
6765 x_clear_image,
6766 NULL
6767};
6768
6769/* Return non-zero if OBJECT is a valid TIFF image specification. */
6770
6771static int
6772tiff_image_p (object)
6773 Lisp_Object object;
6774{
6775 struct image_keyword fmt[TIFF_LAST];
6776 bcopy (tiff_format, fmt, sizeof fmt);
6777
6778 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6779 return 0;
6780
6781 /* Must specify either the :data or :file keyword. */
6782 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
6783}
6784
6785#endif /* HAVE_TIFF || MAC_OS */
6786
6787#ifdef HAVE_TIFF
6788
6789#include <tiffio.h>
6790
6791#ifdef HAVE_NTGUI
6792
6793/* TIFF library details. */
6794DEF_IMGLIB_FN (TIFFSetErrorHandler);
6795DEF_IMGLIB_FN (TIFFSetWarningHandler);
6796DEF_IMGLIB_FN (TIFFOpen);
6797DEF_IMGLIB_FN (TIFFClientOpen);
6798DEF_IMGLIB_FN (TIFFGetField);
6799DEF_IMGLIB_FN (TIFFReadRGBAImage);
6800DEF_IMGLIB_FN (TIFFClose);
6801
6802static int
0855eb52 6803init_tiff_functions (Lisp_Object libraries)
4ef0d4d0
KS
6804{
6805 HMODULE library;
6806
0855eb52 6807 if (!(library = w32_delayed_load (libraries, Qtiff)))
4ef0d4d0
KS
6808 return 0;
6809
6810 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
6811 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
6812 LOAD_IMGLIB_FN (library, TIFFOpen);
6813 LOAD_IMGLIB_FN (library, TIFFClientOpen);
6814 LOAD_IMGLIB_FN (library, TIFFGetField);
6815 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
6816 LOAD_IMGLIB_FN (library, TIFFClose);
6817 return 1;
6818}
6819
6820#else
6821
6822#define fn_TIFFSetErrorHandler TIFFSetErrorHandler
6823#define fn_TIFFSetWarningHandler TIFFSetWarningHandler
6824#define fn_TIFFOpen TIFFOpen
6825#define fn_TIFFClientOpen TIFFClientOpen
6826#define fn_TIFFGetField TIFFGetField
6827#define fn_TIFFReadRGBAImage TIFFReadRGBAImage
6828#define fn_TIFFClose TIFFClose
6829
6830#endif /* HAVE_NTGUI */
6831
6832
6833/* Reading from a memory buffer for TIFF images Based on the PNG
6834 memory source, but we have to provide a lot of extra functions.
6835 Blah.
6836
6837 We really only need to implement read and seek, but I am not
6838 convinced that the TIFF library is smart enough not to destroy
6839 itself if we only hand it the function pointers we need to
6840 override. */
6841
6842typedef struct
6843{
6844 unsigned char *bytes;
6845 size_t len;
6846 int index;
6847}
6848tiff_memory_source;
6849
6850static size_t
6851tiff_read_from_memory (data, buf, size)
6852 thandle_t data;
6853 tdata_t buf;
6854 tsize_t size;
6855{
6856 tiff_memory_source *src = (tiff_memory_source *) data;
6857
6858 if (size > src->len - src->index)
6859 return (size_t) -1;
6860 bcopy (src->bytes + src->index, buf, size);
6861 src->index += size;
6862 return size;
6863}
6864
6865static size_t
6866tiff_write_from_memory (data, buf, size)
6867 thandle_t data;
6868 tdata_t buf;
6869 tsize_t size;
6870{
6871 return (size_t) -1;
6872}
6873
6874static toff_t
6875tiff_seek_in_memory (data, off, whence)
6876 thandle_t data;
6877 toff_t off;
6878 int whence;
6879{
6880 tiff_memory_source *src = (tiff_memory_source *) data;
6881 int idx;
6882
6883 switch (whence)
6884 {
6885 case SEEK_SET: /* Go from beginning of source. */
6886 idx = off;
6887 break;
6888
6889 case SEEK_END: /* Go from end of source. */
6890 idx = src->len + off;
6891 break;
6892
6893 case SEEK_CUR: /* Go from current position. */
6894 idx = src->index + off;
6895 break;
6896
6897 default: /* Invalid `whence'. */
6898 return -1;
6899 }
6900
6901 if (idx > src->len || idx < 0)
6902 return -1;
6903
6904 src->index = idx;
6905 return src->index;
6906}
6907
6908static int
6909tiff_close_memory (data)
6910 thandle_t data;
6911{
6912 /* NOOP */
6913 return 0;
6914}
6915
6916static int
6917tiff_mmap_memory (data, pbase, psize)
6918 thandle_t data;
6919 tdata_t *pbase;
6920 toff_t *psize;
6921{
6922 /* It is already _IN_ memory. */
6923 return 0;
6924}
6925
6926static void
6927tiff_unmap_memory (data, base, size)
6928 thandle_t data;
6929 tdata_t base;
6930 toff_t size;
6931{
6932 /* We don't need to do this. */
6933}
6934
6935static toff_t
6936tiff_size_of_memory (data)
6937 thandle_t data;
6938{
6939 return ((tiff_memory_source *) data)->len;
6940}
6941
6942
6943static void
6944tiff_error_handler (title, format, ap)
6945 const char *title, *format;
6946 va_list ap;
6947{
6948 char buf[512];
6949 int len;
6950
6951 len = sprintf (buf, "TIFF error: %s ", title);
6952 vsprintf (buf + len, format, ap);
6953 add_to_log (buf, Qnil, Qnil);
6954}
6955
6956
6957static void
6958tiff_warning_handler (title, format, ap)
6959 const char *title, *format;
6960 va_list ap;
6961{
6962 char buf[512];
6963 int len;
6964
6965 len = sprintf (buf, "TIFF warning: %s ", title);
6966 vsprintf (buf + len, format, ap);
6967 add_to_log (buf, Qnil, Qnil);
6968}
6969
6970
6971/* Load TIFF image IMG for use on frame F. Value is non-zero if
6972 successful. */
6973
6974static int
6975tiff_load (f, img)
6976 struct frame *f;
6977 struct image *img;
6978{
6979 Lisp_Object file, specified_file;
6980 Lisp_Object specified_data;
6981 TIFF *tiff;
6982 int width, height, x, y;
6983 uint32 *buf;
6984 int rc;
6985 XImagePtr ximg;
6986 struct gcpro gcpro1;
6987 tiff_memory_source memsrc;
6988
6989 specified_file = image_spec_value (img->spec, QCfile, NULL);
6990 specified_data = image_spec_value (img->spec, QCdata, NULL);
6991 file = Qnil;
6992 GCPRO1 (file);
6993
6994 fn_TIFFSetErrorHandler (tiff_error_handler);
6995 fn_TIFFSetWarningHandler (tiff_warning_handler);
6996
6997 if (NILP (specified_data))
6998 {
6999 /* Read from a file */
7000 file = x_find_image_file (specified_file);
7001 if (!STRINGP (file))
7002 {
7003 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7004 UNGCPRO;
7005 return 0;
7006 }
7007
2e09fef1
EZ
7008 /* Try to open the image file. Casting return value avoids a
7009 GCC warning on W32. */
7010 tiff = (TIFF *)fn_TIFFOpen (SDATA (file), "r");
4ef0d4d0
KS
7011 if (tiff == NULL)
7012 {
7013 image_error ("Cannot open `%s'", file, Qnil);
7014 UNGCPRO;
7015 return 0;
7016 }
7017 }
7018 else
7019 {
7020 /* Memory source! */
7021 memsrc.bytes = SDATA (specified_data);
7022 memsrc.len = SBYTES (specified_data);
7023 memsrc.index = 0;
7024
2e09fef1
EZ
7025 /* Casting return value avoids a GCC warning on W32. */
7026 tiff = (TIFF *)fn_TIFFClientOpen ("memory_source", "r", &memsrc,
7027 (TIFFReadWriteProc) tiff_read_from_memory,
7028 (TIFFReadWriteProc) tiff_write_from_memory,
7029 tiff_seek_in_memory,
7030 tiff_close_memory,
7031 tiff_size_of_memory,
7032 tiff_mmap_memory,
7033 tiff_unmap_memory);
4ef0d4d0
KS
7034
7035 if (!tiff)
7036 {
7037 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
7038 UNGCPRO;
7039 return 0;
7040 }
7041 }
7042
7043 /* Get width and height of the image, and allocate a raster buffer
7044 of width x height 32-bit values. */
7045 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
7046 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
7047 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7048
7049 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
7050 fn_TIFFClose (tiff);
7051 if (!rc)
7052 {
7053 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
7054 xfree (buf);
7055 UNGCPRO;
7056 return 0;
7057 }
7058
7059 /* Create the X image and pixmap. */
7060 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7061 {
7062 xfree (buf);
7063 UNGCPRO;
7064 return 0;
7065 }
7066
7067 /* Initialize the color table. */
7068 init_color_table ();
7069
7070 /* Process the pixel raster. Origin is in the lower-left corner. */
7071 for (y = 0; y < height; ++y)
7072 {
7073 uint32 *row = buf + y * width;
7074
7075 for (x = 0; x < width; ++x)
7076 {
7077 uint32 abgr = row[x];
7078 int r = TIFFGetR (abgr) << 8;
7079 int g = TIFFGetG (abgr) << 8;
7080 int b = TIFFGetB (abgr) << 8;
7081 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
7082 }
7083 }
7084
7085#ifdef COLOR_TABLE_SUPPORT
7086 /* Remember the colors allocated for the image. Free the color table. */
7087 img->colors = colors_in_color_table (&img->ncolors);
7088 free_color_table ();
7089#endif /* COLOR_TABLE_SUPPORT */
7090
7091 img->width = width;
7092 img->height = height;
7093
7094 /* Maybe fill in the background field while we have ximg handy. */
7095 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
7096 /* Casting avoids a GCC warning on W32. */
7097 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
7098
7099 /* Put the image into the pixmap, then free the X image and its buffer. */
7100 x_put_x_image (f, ximg, img->pixmap, width, height);
7101 x_destroy_x_image (ximg);
7102 xfree (buf);
7103
7104 UNGCPRO;
7105 return 1;
7106}
7107
7108#else /* HAVE_TIFF */
7109
7110#ifdef MAC_OS
7111static int
7112tiff_load (f, img)
7113 struct frame *f;
7114 struct image *img;
7115{
7116 return image_load_quicktime (f, img, kQTFileTypeTIFF);
7117}
7118#endif /* MAC_OS */
7119
7120#endif /* !HAVE_TIFF */
7121
7122
7123\f
7124/***********************************************************************
7125 GIF
7126 ***********************************************************************/
7127
7128#if defined (HAVE_GIF) || defined (MAC_OS)
7129
7130static int gif_image_p P_ ((Lisp_Object object));
7131static int gif_load P_ ((struct frame *f, struct image *img));
7132
7133/* The symbol `gif' identifying images of this type. */
7134
7135Lisp_Object Qgif;
7136
7137/* Indices of image specification fields in gif_format, below. */
7138
7139enum gif_keyword_index
7140{
7141 GIF_TYPE,
7142 GIF_DATA,
7143 GIF_FILE,
7144 GIF_ASCENT,
7145 GIF_MARGIN,
7146 GIF_RELIEF,
7147 GIF_ALGORITHM,
7148 GIF_HEURISTIC_MASK,
7149 GIF_MASK,
7150 GIF_IMAGE,
7151 GIF_BACKGROUND,
7152 GIF_LAST
7153};
7154
7155/* Vector of image_keyword structures describing the format
7156 of valid user-defined image specifications. */
7157
7158static struct image_keyword gif_format[GIF_LAST] =
7159{
7160 {":type", IMAGE_SYMBOL_VALUE, 1},
7161 {":data", IMAGE_STRING_VALUE, 0},
7162 {":file", IMAGE_STRING_VALUE, 0},
7163 {":ascent", IMAGE_ASCENT_VALUE, 0},
7164 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7165 {":relief", IMAGE_INTEGER_VALUE, 0},
7166 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7167 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7168 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7169 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
7170 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7171};
7172
7173/* Structure describing the image type `gif'. */
7174
7175static struct image_type gif_type =
7176{
7177 &Qgif,
7178 gif_image_p,
7179 gif_load,
7180 x_clear_image,
7181 NULL
7182};
7183
7184/* Return non-zero if OBJECT is a valid GIF image specification. */
7185
7186static int
7187gif_image_p (object)
7188 Lisp_Object object;
7189{
7190 struct image_keyword fmt[GIF_LAST];
7191 bcopy (gif_format, fmt, sizeof fmt);
7192
7193 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
7194 return 0;
7195
7196 /* Must specify either the :data or :file keyword. */
7197 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
7198}
7199
7200#endif /* HAVE_GIF || MAC_OS */
7201
7202#ifdef HAVE_GIF
7203
7204#if defined (HAVE_NTGUI) || defined (MAC_OS)
2e09fef1
EZ
7205/* winuser.h might define DrawText to DrawTextA or DrawTextW.
7206 Undefine before redefining to avoid a preprocessor warning. */
7207#ifdef DrawText
7208#undef DrawText
7209#endif
4ef0d4d0
KS
7210/* avoid conflict with QuickdrawText.h */
7211#define DrawText gif_DrawText
7212#include <gif_lib.h>
7213#undef DrawText
7214
7215#else /* HAVE_NTGUI || MAC_OS */
7216
7217#include <gif_lib.h>
7218
7219#endif /* HAVE_NTGUI || MAC_OS */
7220
7221
7222#ifdef HAVE_NTGUI
7223
7224/* GIF library details. */
7225DEF_IMGLIB_FN (DGifCloseFile);
7226DEF_IMGLIB_FN (DGifSlurp);
7227DEF_IMGLIB_FN (DGifOpen);
7228DEF_IMGLIB_FN (DGifOpenFileName);
7229
7230static int
0855eb52 7231init_gif_functions (Lisp_Object libraries)
4ef0d4d0
KS
7232{
7233 HMODULE library;
7234
0855eb52 7235 if (!(library = w32_delayed_load (libraries, Qgif)))
4ef0d4d0
KS
7236 return 0;
7237
7238 LOAD_IMGLIB_FN (library, DGifCloseFile);
7239 LOAD_IMGLIB_FN (library, DGifSlurp);
7240 LOAD_IMGLIB_FN (library, DGifOpen);
7241 LOAD_IMGLIB_FN (library, DGifOpenFileName);
7242 return 1;
7243}
7244
7245#else
7246
7247#define fn_DGifCloseFile DGifCloseFile
7248#define fn_DGifSlurp DGifSlurp
7249#define fn_DGifOpen DGifOpen
7250#define fn_DGifOpenFileName DGifOpenFileName
7251
7252#endif /* HAVE_NTGUI */
7253
7254/* Reading a GIF image from memory
7255 Based on the PNG memory stuff to a certain extent. */
7256
7257typedef struct
7258{
7259 unsigned char *bytes;
7260 size_t len;
7261 int index;
7262}
7263gif_memory_source;
7264
7265/* Make the current memory source available to gif_read_from_memory.
7266 It's done this way because not all versions of libungif support
7267 a UserData field in the GifFileType structure. */
7268static gif_memory_source *current_gif_memory_src;
7269
7270static int
7271gif_read_from_memory (file, buf, len)
7272 GifFileType *file;
7273 GifByteType *buf;
7274 int len;
7275{
7276 gif_memory_source *src = current_gif_memory_src;
7277
7278 if (len > src->len - src->index)
7279 return -1;
7280
7281 bcopy (src->bytes + src->index, buf, len);
7282 src->index += len;
7283 return len;
7284}
7285
7286
7287/* Load GIF image IMG for use on frame F. Value is non-zero if
7288 successful. */
7289
7290static int
7291gif_load (f, img)
7292 struct frame *f;
7293 struct image *img;
7294{
7295 Lisp_Object file, specified_file;
7296 Lisp_Object specified_data;
7297 int rc, width, height, x, y, i;
7298 XImagePtr ximg;
7299 ColorMapObject *gif_color_map;
7300 unsigned long pixel_colors[256];
7301 GifFileType *gif;
7302 struct gcpro gcpro1;
7303 Lisp_Object image;
7304 int ino, image_left, image_top, image_width, image_height;
7305 gif_memory_source memsrc;
7306 unsigned char *raster;
7307
7308 specified_file = image_spec_value (img->spec, QCfile, NULL);
7309 specified_data = image_spec_value (img->spec, QCdata, NULL);
7310 file = Qnil;
7311 GCPRO1 (file);
7312
7313 if (NILP (specified_data))
7314 {
7315 file = x_find_image_file (specified_file);
7316 if (!STRINGP (file))
7317 {
7318 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7319 UNGCPRO;
7320 return 0;
7321 }
7322
2e09fef1
EZ
7323 /* Open the GIF file. Casting return value avoids a GCC warning
7324 on W32. */
7325 gif = (GifFileType *)fn_DGifOpenFileName (SDATA (file));
4ef0d4d0
KS
7326 if (gif == NULL)
7327 {
7328 image_error ("Cannot open `%s'", file, Qnil);
7329 UNGCPRO;
7330 return 0;
7331 }
7332 }
7333 else
7334 {
7335 /* Read from memory! */
7336 current_gif_memory_src = &memsrc;
7337 memsrc.bytes = SDATA (specified_data);
7338 memsrc.len = SBYTES (specified_data);
7339 memsrc.index = 0;
7340
2e09fef1
EZ
7341 /* Casting return value avoids a GCC warning on W32. */
7342 gif = (GifFileType *)fn_DGifOpen(&memsrc, gif_read_from_memory);
4ef0d4d0
KS
7343 if (!gif)
7344 {
7345 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
7346 UNGCPRO;
7347 return 0;
7348 }
7349 }
7350
7351 /* Read entire contents. */
7352 rc = fn_DGifSlurp (gif);
7353 if (rc == GIF_ERROR)
7354 {
7355 image_error ("Error reading `%s'", img->spec, Qnil);
7356 fn_DGifCloseFile (gif);
7357 UNGCPRO;
7358 return 0;
7359 }
7360
7361 image = image_spec_value (img->spec, QCindex, NULL);
7362 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7363 if (ino >= gif->ImageCount)
7364 {
7365 image_error ("Invalid image number `%s' in image `%s'",
7366 image, img->spec);
7367 fn_DGifCloseFile (gif);
7368 UNGCPRO;
7369 return 0;
7370 }
7371
0f4aca46
KS
7372 image_top = gif->SavedImages[ino].ImageDesc.Top;
7373 image_left = gif->SavedImages[ino].ImageDesc.Left;
7374 image_width = gif->SavedImages[ino].ImageDesc.Width;
7375 image_height = gif->SavedImages[ino].ImageDesc.Height;
7376
7377 width = img->width = max (gif->SWidth,
7378 max (gif->Image.Left + gif->Image.Width,
7379 image_left + image_width));
7380 height = img->height = max (gif->SHeight,
7381 max (gif->Image.Top + gif->Image.Height,
7382 image_top + image_height));
4ef0d4d0
KS
7383
7384 /* Create the X image and pixmap. */
7385 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7386 {
7387 fn_DGifCloseFile (gif);
7388 UNGCPRO;
7389 return 0;
7390 }
7391
7392 /* Allocate colors. */
7393 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
7394 if (!gif_color_map)
7395 gif_color_map = gif->SColorMap;
7396 init_color_table ();
7397 bzero (pixel_colors, sizeof pixel_colors);
7398
7399 for (i = 0; i < gif_color_map->ColorCount; ++i)
7400 {
7401 int r = gif_color_map->Colors[i].Red << 8;
7402 int g = gif_color_map->Colors[i].Green << 8;
7403 int b = gif_color_map->Colors[i].Blue << 8;
7404 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
7405 }
7406
7407#ifdef COLOR_TABLE_SUPPORT
7408 img->colors = colors_in_color_table (&img->ncolors);
7409 free_color_table ();
7410#endif /* COLOR_TABLE_SUPPORT */
7411
7412 /* Clear the part of the screen image that are not covered by
7413 the image from the GIF file. Full animated GIF support
7414 requires more than can be done here (see the gif89 spec,
7415 disposal methods). Let's simply assume that the part
7416 not covered by a sub-image is in the frame's background color. */
4ef0d4d0
KS
7417 for (y = 0; y < image_top; ++y)
7418 for (x = 0; x < width; ++x)
7419 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7420
7421 for (y = image_top + image_height; y < height; ++y)
7422 for (x = 0; x < width; ++x)
7423 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7424
7425 for (y = image_top; y < image_top + image_height; ++y)
7426 {
7427 for (x = 0; x < image_left; ++x)
7428 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7429 for (x = image_left + image_width; x < width; ++x)
7430 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
7431 }
7432
7433 /* Read the GIF image into the X image. We use a local variable
7434 `raster' here because RasterBits below is a char *, and invites
7435 problems with bytes >= 0x80. */
7436 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
7437
7438 if (gif->SavedImages[ino].ImageDesc.Interlace)
7439 {
7440 static int interlace_start[] = {0, 4, 2, 1};
7441 static int interlace_increment[] = {8, 8, 4, 2};
7442 int pass;
7443 int row = interlace_start[0];
7444
7445 pass = 0;
7446
7447 for (y = 0; y < image_height; y++)
7448 {
7449 if (row >= image_height)
7450 {
7451 row = interlace_start[++pass];
7452 while (row >= image_height)
7453 row = interlace_start[++pass];
7454 }
7455
7456 for (x = 0; x < image_width; x++)
7457 {
7458 int i = raster[(y * image_width) + x];
7459 XPutPixel (ximg, x + image_left, row + image_top,
7460 pixel_colors[i]);
7461 }
7462
7463 row += interlace_increment[pass];
7464 }
7465 }
7466 else
7467 {
7468 for (y = 0; y < image_height; ++y)
7469 for (x = 0; x < image_width; ++x)
7470 {
7471 int i = raster[y * image_width + x];
7472 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
7473 }
7474 }
7475
7476 fn_DGifCloseFile (gif);
7477
7478 /* Maybe fill in the background field while we have ximg handy. */
7479 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
2e09fef1
EZ
7480 /* Casting avoids a GCC warning. */
7481 IMAGE_BACKGROUND (img, f, (XImagePtr_or_DC)ximg);
4ef0d4d0
KS
7482
7483 /* Put the image into the pixmap, then free the X image and its buffer. */
7484 x_put_x_image (f, ximg, img->pixmap, width, height);
7485 x_destroy_x_image (ximg);
7486
7487 UNGCPRO;
7488 return 1;
7489}
7490
2e09fef1 7491#else /* !HAVE_GIF */
4ef0d4d0
KS
7492
7493#ifdef MAC_OS
7494static int
7495gif_load (f, img)
7496 struct frame *f;
7497 struct image *img;
7498{
7499 Lisp_Object specified_file, file;
7500 Lisp_Object specified_data;
7501 OSErr err;
7502 Boolean graphic_p, movie_p, prefer_graphic_p;
7503 Handle dh = NULL;
7504 Movie movie = NULL;
7505 Lisp_Object image;
7506 Track track = NULL;
7507 Media media = NULL;
7508 long nsamples;
7509 Rect rect;
7510 Lisp_Object specified_bg;
7511 XColor color;
7512 RGBColor bg_color;
7513 int width, height;
7514 XImagePtr ximg;
7515 TimeValue time;
7516 struct gcpro gcpro1;
7517 int ino;
2a316a84
ST
7518 CGrafPtr old_port;
7519 GDHandle old_gdh;
4ef0d4d0
KS
7520
7521 specified_file = image_spec_value (img->spec, QCfile, NULL);
7522 specified_data = image_spec_value (img->spec, QCdata, NULL);
7523
7524 if (NILP (specified_data))
7525 {
7526 /* Read from a file */
7527 FSSpec fss;
7528 short refnum;
7529
7530 err = find_image_fsspec (specified_file, &file, &fss);
7531 if (err != noErr)
7532 {
7533 if (err == fnfErr)
7534 image_error ("Cannot find image file `%s'", specified_file, Qnil);
7535 else
7536 goto open_error;
7537 }
7538
7539 err = CanQuickTimeOpenFile (&fss, kQTFileTypeGIF, 0,
7540 &graphic_p, &movie_p, &prefer_graphic_p, 0);
7541 if (err != noErr)
7542 goto open_error;
7543
7544 if (!graphic_p && !movie_p)
7545 goto open_error;
7546 if (prefer_graphic_p)
7547 return image_load_qt_1 (f, img, kQTFileTypeGIF, &fss, NULL);
7548 err = OpenMovieFile (&fss, &refnum, fsRdPerm);
7549 if (err != noErr)
7550 goto open_error;
7551 err = NewMovieFromFile (&movie, refnum, NULL, NULL, 0, NULL);
7552 CloseMovieFile (refnum);
7553 if (err != noErr)
7554 {
7555 image_error ("Error reading `%s'", file, Qnil);
7556 return 0;
7557 }
7558 }
7559 else
7560 {
7561 /* Memory source! */
7562 Handle dref = NULL;
7563 long file_type_atom[3];
7564
7565 err = PtrToHand (SDATA (specified_data), &dh, SBYTES (specified_data));
7566 if (err != noErr)
7567 {
7568 image_error ("Cannot allocate data handle for `%s'",
7569 img->spec, Qnil);
7570 goto error;
7571 }
7572
7573 file_type_atom[0] = EndianU32_NtoB (sizeof (long) * 3);
7574 file_type_atom[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
7575 file_type_atom[2] = EndianU32_NtoB (kQTFileTypeGIF);
7576 err = PtrToHand (&dh, &dref, sizeof (Handle));
7577 if (err == noErr)
7578 /* no file name */
7579 err = PtrAndHand ("\p", dref, 1);
7580 if (err == noErr)
7581 err = PtrAndHand (file_type_atom, dref, sizeof (long) * 3);
7582 if (err != noErr)
7583 {
7584 image_error ("Cannot allocate handle data ref for `%s'", img->spec, Qnil);
7585 goto error;
7586 }
7587 err = CanQuickTimeOpenDataRef (dref, HandleDataHandlerSubType, &graphic_p,
7588 &movie_p, &prefer_graphic_p, 0);
7589 if (err != noErr)
7590 goto open_error;
7591
7592 if (!graphic_p && !movie_p)
7593 goto open_error;
7594 if (prefer_graphic_p)
7595 {
7596 int success_p;
7597
7598 DisposeHandle (dref);
7599 success_p = image_load_qt_1 (f, img, kQTFileTypeGIF, NULL, dh);
7600 DisposeHandle (dh);
7601 return success_p;
7602 }
7603 err = NewMovieFromDataRef (&movie, 0, NULL, dref,
7604 HandleDataHandlerSubType);
7605 DisposeHandle (dref);
7606 if (err != noErr)
7607 goto open_error;
7608 }
7609
7610 image = image_spec_value (img->spec, QCindex, NULL);
7611 ino = INTEGERP (image) ? XFASTINT (image) : 0;
7612 track = GetMovieIndTrack (movie, 1);
7613 media = GetTrackMedia (track);
7614 nsamples = GetMediaSampleCount (media);
7615 if (ino >= nsamples)
7616 {
7617 image_error ("Invalid image number `%s' in image `%s'",
7618 image, img->spec);
7619 goto error;
7620 }
7621
7622 specified_bg = image_spec_value (img->spec, QCbackground, NULL);
7623 if (!STRINGP (specified_bg) ||
7624 !mac_defined_color (f, SDATA (specified_bg), &color, 0))
7625 {
7626 color.pixel = FRAME_BACKGROUND_PIXEL (f);
7627 color.red = RED16_FROM_ULONG (color.pixel);
7628 color.green = GREEN16_FROM_ULONG (color.pixel);
7629 color.blue = BLUE16_FROM_ULONG (color.pixel);
7630 }
7631 GetMovieBox (movie, &rect);
7632 width = img->width = rect.right - rect.left;
7633 height = img->height = rect.bottom - rect.top;
7634 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
7635 goto error;
7636
2a316a84 7637 GetGWorld (&old_port, &old_gdh);
4ef0d4d0
KS
7638 SetGWorld (ximg, NULL);
7639 bg_color.red = color.red;
7640 bg_color.green = color.green;
7641 bg_color.blue = color.blue;
7642 RGBBackColor (&bg_color);
2a316a84 7643 SetGWorld (old_port, old_gdh);
e0e30823 7644 SetMovieActive (movie, 1);
4ef0d4d0
KS
7645 SetMovieGWorld (movie, ximg, NULL);
7646 SampleNumToMediaTime (media, ino + 1, &time, NULL);
7647 SetMovieTimeValue (movie, time);
7648 MoviesTask (movie, 0L);
7649 DisposeTrackMedia (media);
7650 DisposeMovieTrack (track);
7651 DisposeMovie (movie);
7652 if (dh)
7653 DisposeHandle (dh);
7654 /* Maybe fill in the background field while we have ximg handy. */
7655 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
7656 IMAGE_BACKGROUND (img, f, ximg);
7657
7658 /* Put the image into the pixmap. */
7659 x_put_x_image (f, ximg, img->pixmap, width, height);
7660 x_destroy_x_image (ximg);
7661 return 1;
7662
7663 open_error:
7664 image_error ("Cannot open `%s'", file, Qnil);
7665 error:
7666 if (media)
7667 DisposeTrackMedia (media);
7668 if (track)
7669 DisposeMovieTrack (track);
7670 if (movie)
7671 DisposeMovie (movie);
7672 if (dh)
7673 DisposeHandle (dh);
7674 return 0;
7675}
7676#endif /* MAC_OS */
7677
7678#endif /* HAVE_GIF */
7679
7680
7681\f
7682/***********************************************************************
7683 Ghostscript
7684 ***********************************************************************/
7685
7686#ifdef HAVE_X_WINDOWS
7687#define HAVE_GHOSTSCRIPT 1
7688#endif /* HAVE_X_WINDOWS */
7689
7690/* The symbol `postscript' identifying images of this type. */
7691
7692Lisp_Object Qpostscript;
7693
7694#ifdef HAVE_GHOSTSCRIPT
7695
7696static int gs_image_p P_ ((Lisp_Object object));
7697static int gs_load P_ ((struct frame *f, struct image *img));
7698static void gs_clear_image P_ ((struct frame *f, struct image *img));
7699
7700/* Keyword symbols. */
7701
7702Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
7703
7704/* Indices of image specification fields in gs_format, below. */
7705
7706enum gs_keyword_index
7707{
7708 GS_TYPE,
7709 GS_PT_WIDTH,
7710 GS_PT_HEIGHT,
7711 GS_FILE,
7712 GS_LOADER,
7713 GS_BOUNDING_BOX,
7714 GS_ASCENT,
7715 GS_MARGIN,
7716 GS_RELIEF,
7717 GS_ALGORITHM,
7718 GS_HEURISTIC_MASK,
7719 GS_MASK,
7720 GS_BACKGROUND,
7721 GS_LAST
7722};
7723
7724/* Vector of image_keyword structures describing the format
7725 of valid user-defined image specifications. */
7726
7727static struct image_keyword gs_format[GS_LAST] =
7728{
7729 {":type", IMAGE_SYMBOL_VALUE, 1},
7730 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7731 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
7732 {":file", IMAGE_STRING_VALUE, 1},
7733 {":loader", IMAGE_FUNCTION_VALUE, 0},
7734 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
7735 {":ascent", IMAGE_ASCENT_VALUE, 0},
7736 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
7737 {":relief", IMAGE_INTEGER_VALUE, 0},
7738 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7739 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7740 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
7741 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
7742};
7743
7744/* Structure describing the image type `ghostscript'. */
7745
7746static struct image_type gs_type =
7747{
7748 &Qpostscript,
7749 gs_image_p,
7750 gs_load,
7751 gs_clear_image,
7752 NULL
7753};
7754
7755
7756/* Free X resources of Ghostscript image IMG which is used on frame F. */
7757
7758static void
7759gs_clear_image (f, img)
7760 struct frame *f;
7761 struct image *img;
7762{
7763 /* IMG->data.ptr_val may contain a recorded colormap. */
7764 xfree (img->data.ptr_val);
7765 x_clear_image (f, img);
7766}
7767
7768
7769/* Return non-zero if OBJECT is a valid Ghostscript image
7770 specification. */
7771
7772static int
7773gs_image_p (object)
7774 Lisp_Object object;
7775{
7776 struct image_keyword fmt[GS_LAST];
7777 Lisp_Object tem;
7778 int i;
7779
7780 bcopy (gs_format, fmt, sizeof fmt);
7781
7782 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
7783 return 0;
7784
7785 /* Bounding box must be a list or vector containing 4 integers. */
7786 tem = fmt[GS_BOUNDING_BOX].value;
7787 if (CONSP (tem))
7788 {
7789 for (i = 0; i < 4; ++i, tem = XCDR (tem))
7790 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
7791 return 0;
7792 if (!NILP (tem))
7793 return 0;
7794 }
7795 else if (VECTORP (tem))
7796 {
7797 if (XVECTOR (tem)->size != 4)
7798 return 0;
7799 for (i = 0; i < 4; ++i)
7800 if (!INTEGERP (XVECTOR (tem)->contents[i]))
7801 return 0;
7802 }
7803 else
7804 return 0;
7805
7806 return 1;
7807}
7808
7809
7810/* Load Ghostscript image IMG for use on frame F. Value is non-zero
7811 if successful. */
7812
7813static int
7814gs_load (f, img)
7815 struct frame *f;
7816 struct image *img;
7817{
7818 char buffer[100];
7819 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
7820 struct gcpro gcpro1, gcpro2;
7821 Lisp_Object frame;
7822 double in_width, in_height;
7823 Lisp_Object pixel_colors = Qnil;
7824
7825 /* Compute pixel size of pixmap needed from the given size in the
7826 image specification. Sizes in the specification are in pt. 1 pt
7827 = 1/72 in, xdpi and ydpi are stored in the frame's X display
7828 info. */
7829 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
7830 in_width = XFASTINT (pt_width) / 72.0;
7831 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx;
7832 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
7833 in_height = XFASTINT (pt_height) / 72.0;
7834 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy;
7835
7836 /* Create the pixmap. */
7837 xassert (img->pixmap == NO_PIXMAP);
7838
7839 /* Only W32 version did BLOCK_INPUT here. ++kfs */
7840 BLOCK_INPUT;
7841 img->pixmap = XCreatePixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7842 img->width, img->height,
7843 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
7844 UNBLOCK_INPUT;
7845
7846 if (!img->pixmap)
7847 {
7848 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
7849 return 0;
7850 }
7851
7852 /* Call the loader to fill the pixmap. It returns a process object
7853 if successful. We do not record_unwind_protect here because
7854 other places in redisplay like calling window scroll functions
7855 don't either. Let the Lisp loader use `unwind-protect' instead. */
7856 GCPRO2 (window_and_pixmap_id, pixel_colors);
7857
7858 sprintf (buffer, "%lu %lu",
7859 (unsigned long) FRAME_X_WINDOW (f),
7860 (unsigned long) img->pixmap);
7861 window_and_pixmap_id = build_string (buffer);
7862
7863 sprintf (buffer, "%lu %lu",
7864 FRAME_FOREGROUND_PIXEL (f),
7865 FRAME_BACKGROUND_PIXEL (f));
7866 pixel_colors = build_string (buffer);
7867
7868 XSETFRAME (frame, f);
7869 loader = image_spec_value (img->spec, QCloader, NULL);
7870 if (NILP (loader))
7871 loader = intern ("gs-load-image");
7872
7873 img->data.lisp_val = call6 (loader, frame, img->spec,
7874 make_number (img->width),
7875 make_number (img->height),
7876 window_and_pixmap_id,
7877 pixel_colors);
7878 UNGCPRO;
7879 return PROCESSP (img->data.lisp_val);
7880}
7881
7882
7883/* Kill the Ghostscript process that was started to fill PIXMAP on
7884 frame F. Called from XTread_socket when receiving an event
7885 telling Emacs that Ghostscript has finished drawing. */
7886
7887void
7888x_kill_gs_process (pixmap, f)
7889 Pixmap pixmap;
7890 struct frame *f;
7891{
7892 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7893 int class, i;
7894 struct image *img;
7895
7896 /* Find the image containing PIXMAP. */
7897 for (i = 0; i < c->used; ++i)
7898 if (c->images[i]->pixmap == pixmap)
7899 break;
7900
7901 /* Should someone in between have cleared the image cache, for
7902 instance, give up. */
7903 if (i == c->used)
7904 return;
7905
7906 /* Kill the GS process. We should have found PIXMAP in the image
7907 cache and its image should contain a process object. */
7908 img = c->images[i];
7909 xassert (PROCESSP (img->data.lisp_val));
7910 Fkill_process (img->data.lisp_val, Qnil);
7911 img->data.lisp_val = Qnil;
7912
7913#if defined (HAVE_X_WINDOWS)
7914
7915 /* On displays with a mutable colormap, figure out the colors
7916 allocated for the image by looking at the pixels of an XImage for
7917 img->pixmap. */
7918 class = FRAME_X_VISUAL (f)->class;
7919 if (class != StaticColor && class != StaticGray && class != TrueColor)
7920 {
7921 XImagePtr ximg;
7922
7923 BLOCK_INPUT;
7924
7925 /* Try to get an XImage for img->pixmep. */
7926 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
7927 0, 0, img->width, img->height, ~0, ZPixmap);
7928 if (ximg)
7929 {
7930 int x, y;
7931
7932 /* Initialize the color table. */
7933 init_color_table ();
7934
7935 /* For each pixel of the image, look its color up in the
7936 color table. After having done so, the color table will
7937 contain an entry for each color used by the image. */
7938 for (y = 0; y < img->height; ++y)
7939 for (x = 0; x < img->width; ++x)
7940 {
7941 unsigned long pixel = XGetPixel (ximg, x, y);
7942 lookup_pixel_color (f, pixel);
7943 }
7944
7945 /* Record colors in the image. Free color table and XImage. */
7946#ifdef COLOR_TABLE_SUPPORT
7947 img->colors = colors_in_color_table (&img->ncolors);
7948 free_color_table ();
7949#endif
7950 XDestroyImage (ximg);
7951
7952#if 0 /* This doesn't seem to be the case. If we free the colors
7953 here, we get a BadAccess later in x_clear_image when
7954 freeing the colors. */
7955 /* We have allocated colors once, but Ghostscript has also
7956 allocated colors on behalf of us. So, to get the
7957 reference counts right, free them once. */
7958 if (img->ncolors)
7959 x_free_colors (f, img->colors, img->ncolors);
7960#endif
7961 }
7962 else
7963 image_error ("Cannot get X image of `%s'; colors will not be freed",
7964 img->spec, Qnil);
7965
7966 UNBLOCK_INPUT;
7967 }
7968#endif /* HAVE_X_WINDOWS */
7969
7970 /* Now that we have the pixmap, compute mask and transform the
7971 image if requested. */
7972 BLOCK_INPUT;
7973 postprocess_image (f, img);
7974 UNBLOCK_INPUT;
7975}
7976
7977#endif /* HAVE_GHOSTSCRIPT */
7978
7979\f
7980/***********************************************************************
7981 Tests
7982 ***********************************************************************/
7983
7984#if GLYPH_DEBUG
7985
7986DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
7987 doc: /* Value is non-nil if SPEC is a valid image specification. */)
7988 (spec)
7989 Lisp_Object spec;
7990{
7991 return valid_image_p (spec) ? Qt : Qnil;
7992}
7993
7994
7995DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
7996 (spec)
7997 Lisp_Object spec;
7998{
7999 int id = -1;
8000
8001 if (valid_image_p (spec))
8002 id = lookup_image (SELECTED_FRAME (), spec);
8003
8004 debug_print (spec);
8005 return make_number (id);
8006}
8007
8008#endif /* GLYPH_DEBUG != 0 */
8009
8010
8011/***********************************************************************
8012 Initialization
8013 ***********************************************************************/
8014
0855eb52
JB
8015#ifdef HAVE_NTGUI
8016/* Image types that rely on external libraries are loaded dynamically
8017 if the library is available. */
adac86db 8018#define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
0855eb52
JB
8019 define_image_type (image_type, init_lib_fn (libraries))
8020#else
adac86db 8021#define CHECK_LIB_AVAILABLE(image_type, init_lib_fn, libraries) \
e0e30823 8022 define_image_type (image_type, 1)
0855eb52
JB
8023#endif /* HAVE_NTGUI */
8024
8025DEFUN ("init-image-library", Finit_image_library, Sinit_image_library, 2, 2, 0,
8026 doc: /* Initialize image library implementing image type TYPE.
8027Return non-nil if TYPE is a supported image type.
8028
8029Image types pbm and xbm are prebuilt; other types are loaded here.
8030Libraries to load are specified in alist LIBRARIES (usually, the value
adac86db 8031of `image-library-alist', which see). */)
0855eb52 8032 (type, libraries)
adac86db 8033 Lisp_Object type, libraries;
0855eb52
JB
8034{
8035 Lisp_Object tested;
8036
8037 /* Don't try to reload the library. */
8038 tested = Fassq (type, Vimage_type_cache);
8039 if (CONSP (tested))
8040 return XCDR (tested);
8041
8042#if defined (HAVE_XPM) || defined (MAC_OS)
8043 if (EQ (type, Qxpm))
adac86db 8044 return CHECK_LIB_AVAILABLE (&xpm_type, init_xpm_functions, libraries);
0855eb52
JB
8045#endif
8046
8047#if defined (HAVE_JPEG) || defined (MAC_OS)
8048 if (EQ (type, Qjpeg))
adac86db 8049 return CHECK_LIB_AVAILABLE (&jpeg_type, init_jpeg_functions, libraries);
0855eb52
JB
8050#endif
8051
8052#if defined (HAVE_TIFF) || defined (MAC_OS)
8053 if (EQ (type, Qtiff))
adac86db 8054 return CHECK_LIB_AVAILABLE (&tiff_type, init_tiff_functions, libraries);
0855eb52
JB
8055#endif
8056
8057#if defined (HAVE_GIF) || defined (MAC_OS)
8058 if (EQ (type, Qgif))
adac86db 8059 return CHECK_LIB_AVAILABLE (&gif_type, init_gif_functions, libraries);
0855eb52
JB
8060#endif
8061
8062#if defined (HAVE_PNG) || defined (MAC_OS)
8063 if (EQ (type, Qpng))
adac86db 8064 return CHECK_LIB_AVAILABLE (&png_type, init_png_functions, libraries);
0855eb52
JB
8065#endif
8066
8067#ifdef HAVE_GHOSTSCRIPT
8068 if (EQ (type, Qpostscript))
adac86db 8069 return CHECK_LIB_AVAILABLE (&gs_type, init_gs_functions, libraries);
0855eb52
JB
8070#endif
8071
8072 /* If the type is not recognized, avoid testing it ever again. */
adac86db 8073 CACHE_IMAGE_TYPE (type, Qnil);
0855eb52
JB
8074 return Qnil;
8075}
8076
4ef0d4d0
KS
8077void
8078syms_of_image ()
8079{
2a611c1a
JB
8080 extern Lisp_Object Qrisky_local_variable; /* Syms_of_xdisp has already run. */
8081
6e6fc3fd
RS
8082 /* Initialize this only once, since that's what we do with Vimage_types
8083 and they are supposed to be in sync. Initializing here gives correct
8084 operation on GNU/Linux of calling dump-emacs after loading some images. */
8085 image_types = NULL;
8086
0855eb52
JB
8087 /* Must be defined now becase we're going to update it below, while
8088 defining the supported image types. */
8089 DEFVAR_LISP ("image-types", &Vimage_types,
8090 doc: /* List of potentially supported image types.
8091Each element of the list is a symbol for a image type, like 'jpeg or 'png.
8092To check whether it is really supported, use `image-type-available-p'. */);
8093 Vimage_types = Qnil;
8094
2a611c1a
JB
8095 DEFVAR_LISP ("image-library-alist", &Vimage_library_alist,
8096 doc: /* Alist of image types vs external libraries needed to display them.
8097
8098Each element is a list (IMAGE-TYPE LIBRARY...), where the car is a symbol
8099representing a supported image type, and the rest are strings giving
8100alternate filenames for the corresponding external libraries.
8101
8102Emacs tries to load the libraries in the order they appear on the
8103list; if none is loaded, the running session of Emacs won't
8104support the image type. Types 'pbm and 'xbm don't need to be
8105listed; they're always supported. */);
8106 Vimage_library_alist = Qnil;
8107 Fput (intern ("image-library-alist"), Qrisky_local_variable, Qt);
8108
0855eb52
JB
8109 Vimage_type_cache = Qnil;
8110 staticpro (&Vimage_type_cache);
8111
7c4e3a32
RS
8112 Qpbm = intern ("pbm");
8113 staticpro (&Qpbm);
8114 ADD_IMAGE_TYPE(Qpbm);
8115
8116 Qxbm = intern ("xbm");
8117 staticpro (&Qxbm);
8118 ADD_IMAGE_TYPE(Qxbm);
8119
8120 define_image_type (&xbm_type, 1);
8121 define_image_type (&pbm_type, 1);
8122
4ef0d4d0
KS
8123 QCascent = intern (":ascent");
8124 staticpro (&QCascent);
8125 QCmargin = intern (":margin");
8126 staticpro (&QCmargin);
8127 QCrelief = intern (":relief");
8128 staticpro (&QCrelief);
8129 QCconversion = intern (":conversion");
8130 staticpro (&QCconversion);
8131 QCcolor_symbols = intern (":color-symbols");
8132 staticpro (&QCcolor_symbols);
8133 QCheuristic_mask = intern (":heuristic-mask");
8134 staticpro (&QCheuristic_mask);
8135 QCindex = intern (":index");
8136 staticpro (&QCindex);
8137 QCmatrix = intern (":matrix");
8138 staticpro (&QCmatrix);
8139 QCcolor_adjustment = intern (":color-adjustment");
8140 staticpro (&QCcolor_adjustment);
8141 QCmask = intern (":mask");
8142 staticpro (&QCmask);
8143
8144 Qlaplace = intern ("laplace");
8145 staticpro (&Qlaplace);
8146 Qemboss = intern ("emboss");
8147 staticpro (&Qemboss);
8148 Qedge_detection = intern ("edge-detection");
8149 staticpro (&Qedge_detection);
8150 Qheuristic = intern ("heuristic");
8151 staticpro (&Qheuristic);
4ef0d4d0
KS
8152
8153 Qpostscript = intern ("postscript");
8154 staticpro (&Qpostscript);
8155#ifdef HAVE_GHOSTSCRIPT
0855eb52 8156 ADD_IMAGE_TYPE(Qpostscript);
4ef0d4d0
KS
8157 QCloader = intern (":loader");
8158 staticpro (&QCloader);
8159 QCbounding_box = intern (":bounding-box");
8160 staticpro (&QCbounding_box);
8161 QCpt_width = intern (":pt-width");
8162 staticpro (&QCpt_width);
8163 QCpt_height = intern (":pt-height");
8164 staticpro (&QCpt_height);
8165#endif /* HAVE_GHOSTSCRIPT */
8166
ea1aaa6f 8167#if defined (HAVE_XPM) || defined (MAC_OS)
4ef0d4d0
KS
8168 Qxpm = intern ("xpm");
8169 staticpro (&Qxpm);
0855eb52 8170 ADD_IMAGE_TYPE(Qxpm);
4ef0d4d0
KS
8171#endif
8172
8173#if defined (HAVE_JPEG) || defined (MAC_OS)
8174 Qjpeg = intern ("jpeg");
8175 staticpro (&Qjpeg);
0855eb52 8176 ADD_IMAGE_TYPE(Qjpeg);
4ef0d4d0
KS
8177#endif
8178
8179#if defined (HAVE_TIFF) || defined (MAC_OS)
8180 Qtiff = intern ("tiff");
8181 staticpro (&Qtiff);
0855eb52 8182 ADD_IMAGE_TYPE(Qtiff);
4ef0d4d0
KS
8183#endif
8184
8185#if defined (HAVE_GIF) || defined (MAC_OS)
8186 Qgif = intern ("gif");
8187 staticpro (&Qgif);
0855eb52 8188 ADD_IMAGE_TYPE(Qgif);
4ef0d4d0
KS
8189#endif
8190
8191#if defined (HAVE_PNG) || defined (MAC_OS)
8192 Qpng = intern ("png");
8193 staticpro (&Qpng);
0855eb52 8194 ADD_IMAGE_TYPE(Qpng);
4ef0d4d0
KS
8195#endif
8196
0855eb52 8197 defsubr (&Sinit_image_library);
4ef0d4d0
KS
8198 defsubr (&Sclear_image_cache);
8199 defsubr (&Simage_size);
8200 defsubr (&Simage_mask_p);
8201
8202#if GLYPH_DEBUG
8203 defsubr (&Simagep);
8204 defsubr (&Slookup_image);
8205#endif
8206
8207 DEFVAR_BOOL ("cross-disabled-images", &cross_disabled_images,
8208 doc: /* Non-nil means always draw a cross over disabled images.
8209Disabled images are those having an `:conversion disabled' property.
8210A cross is always drawn on black & white displays. */);
8211 cross_disabled_images = 0;
8212
8213 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
8214 doc: /* List of directories to search for window system bitmap files. */);
8215 Vx_bitmap_file_path = decode_env_path ((char *) 0, PATH_BITMAPS);
8216
8217 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
8218 doc: /* Time after which cached images are removed from the cache.
8219When an image has not been displayed this many seconds, remove it
8220from the image cache. Value must be an integer or nil with nil
8221meaning don't clear the cache. */);
8222 Vimage_cache_eviction_delay = make_number (30 * 60);
8223}
8224
4ef0d4d0
KS
8225void
8226init_image ()
8227{
4ef0d4d0
KS
8228#ifdef MAC_OS
8229 /* Animated gifs use QuickTime Movie Toolbox. So initialize it here. */
8230 EnterMovies ();
8231#ifdef MAC_OSX
8232 init_image_func_pointer ();
8233#endif
8234#endif
8235}
8236
1b9f8cec
MB
8237/* arch-tag: 123c2a5e-14a8-4c53-ab95-af47d7db49b9
8238 (do not change this comment) */