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