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