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