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