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