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