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