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