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