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