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