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