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