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