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