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