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