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