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