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