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