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