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