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