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