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