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