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