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