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