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