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