image.c 220 KB
Newer Older
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, 2011
4
                 Free Software Foundation, Inc.
5 6 7

This file is part of GNU Emacs.

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 11
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

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 22 23

#include <config.h>
#include <stdio.h>
#include <math.h>
Andreas Schwab's avatar
Andreas Schwab committed
24
#include <ctype.h>
25 26 27 28 29

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

30 31 32 33 34 35
#ifdef HAVE_PNG
#if defined HAVE_LIBPNG_PNG_H
# include <libpng/png.h>
#else
# include <png.h>
#endif
36
#endif
37

38 39
#include <setjmp.h>

40 41 42 43 44 45 46 47 48 49 50
/* This makes the fields of a Display accessible, in Xlib header files.  */

#define XLIB_ILLEGAL_ACCESS

#include "lisp.h"
#include "frame.h"
#include "window.h"
#include "dispextern.h"
#include "blockinput.h"
#include "systime.h"
#include <epaths.h>
51
#include "character.h"
52
#include "coding.h"
53
#include "termhooks.h"
54
#include "font.h"
55 56 57 58 59 60 61 62 63 64 65 66 67 68

#ifdef HAVE_X_WINDOWS
#include "xterm.h"
#include <sys/types.h>
#include <sys/stat.h>

#define COLOR_TABLE_SUPPORT 1

typedef struct x_bitmap_record Bitmap_Record;
#define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
#define NO_PIXMAP None

#define RGB_PIXEL_COLOR unsigned long

69 70
#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	1
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#endif /* HAVE_X_WINDOWS */


#ifdef HAVE_NTGUI
#include "w32term.h"

/* W32_TODO : Color tables on W32.  */
#undef COLOR_TABLE_SUPPORT

typedef struct w32_bitmap_record Bitmap_Record;
#define GET_PIXEL(ximg, x, y) GetPixel(ximg, x, y)
#define NO_PIXMAP 0

#define RGB_PIXEL_COLOR COLORREF

86 87
#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	1
88 89 90 91

#define FRAME_X_VISUAL(f) FRAME_X_DISPLAY_INFO (f)->visual
#define x_defined_color w32_defined_color
#define DefaultDepthOfScreen(screen) (one_w32_display_info.n_cbits)
92 93 94 95 96

/* Functions from w32term.c that depend on XColor (so can't go in w32term.h
   without modifying lots of files).  */
extern void x_query_colors (struct frame *f, XColor *colors, int ncolors);
extern void x_query_color (struct frame *f, XColor *color);
97 98 99 100 101

/* Version of libpng that we were compiled with, or -1 if no PNG
   support was compiled in.  This is tested by w32-win.el to correctly
   set up the alist used to search for PNG libraries.  */
Lisp_Object Qlibpng_version;
102 103
#endif /* HAVE_NTGUI */

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
#ifdef HAVE_NS
#include "nsterm.h"
#include <sys/types.h>
#include <sys/stat.h>

#undef COLOR_TABLE_SUPPORT

typedef struct ns_bitmap_record Bitmap_Record;

#define GET_PIXEL(ximg, x, y) XGetPixel(ximg, x, y)
#define NO_PIXMAP 0

#define RGB_PIXEL_COLOR unsigned long
#define ZPixmap 0

#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	1

#define FRAME_X_VISUAL FRAME_NS_DISPLAY_INFO(f)->visual
#define x_defined_color(f, name, color_def, alloc) \
  ns_defined_color (f, name, color_def, alloc, 0)
#define FRAME_X_SCREEN(f) 0
126
#define DefaultDepthOfScreen(screen) x_display_list->n_planes
127 128 129
#endif /* HAVE_NS */


130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
/* Search path for bitmap files.  */

Lisp_Object Vx_bitmap_file_path;


static void x_disable_image P_ ((struct frame *, struct image *));
static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
				  Lisp_Object));

static void init_color_table P_ ((void));
static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
#ifdef COLOR_TABLE_SUPPORT
static void free_color_table P_ ((void));
static unsigned long *colors_in_color_table P_ ((int *n));
static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
#endif

/* Code to deal with bitmaps.  Bitmaps are referenced by their bitmap
   id, which is just an int that this section returns.  Bitmaps are
   reference counted so they can be shared among frames.

   Bitmap indices are guaranteed to be > 0, so a negative number can
   be used to indicate no bitmap.

   If you use x_create_bitmap_from_data, then you must keep track of
   the bitmaps yourself.  That is, creating a bitmap from the same
   data more than once will not be caught.  */

158 159 160 161 162 163
#ifdef HAVE_NS
XImagePtr
XGetImage (Display *display, Pixmap pixmap, int x, int y,
           unsigned int width, unsigned int height,
           unsigned long plane_mask, int format)
{
164
  /* TODO: not sure what this function is supposed to do.. */
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  ns_retain_object(pixmap);
  return pixmap;
}

/* use with imgs created by ns_image_for_XPM */
unsigned long
XGetPixel (XImagePtr ximage, int x, int y)
{
  return ns_get_pixel(ximage, x, y);
}

/* use with imgs created by ns_image_for_XPM; alpha set to 1;
   pixel is assumed to be in form RGB */
void
XPutPixel (XImagePtr ximage, int x, int y, unsigned long pixel)
{
  ns_put_pixel(ximage, x, y, pixel);
}
#endif /* HAVE_NS */

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

/* Functions to access the contents of a bitmap, given an id.  */

int
x_bitmap_height (f, id)
     FRAME_PTR f;
     int id;
{
  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
}

int
x_bitmap_width (f, id)
     FRAME_PTR f;
     int id;
{
  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
}

#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
int
x_bitmap_pixmap (f, id)
     FRAME_PTR f;
     int id;
{
  return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
}
#endif

#ifdef HAVE_X_WINDOWS
int
x_bitmap_mask (f, id)
     FRAME_PTR f;
     int id;
{
  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
}
#endif

/* Allocate a new bitmap record.  Returns index of new record.  */

static int
x_allocate_bitmap_record (f)
     FRAME_PTR f;
{
  Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  int i;

  if (dpyinfo->bitmaps == NULL)
    {
      dpyinfo->bitmaps_size = 10;
      dpyinfo->bitmaps
	= (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
      dpyinfo->bitmaps_last = 1;
      return 1;
    }

  if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
    return ++dpyinfo->bitmaps_last;

  for (i = 0; i < dpyinfo->bitmaps_size; ++i)
    if (dpyinfo->bitmaps[i].refcount == 0)
      return i + 1;

  dpyinfo->bitmaps_size *= 2;
  dpyinfo->bitmaps
    = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
				  dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
  return ++dpyinfo->bitmaps_last;
}

/* Add one reference to the reference count of the bitmap with id ID.  */

void
x_reference_bitmap (f, id)
     FRAME_PTR f;
     int id;
{
  ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
}

/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS.  */

int
x_create_bitmap_from_data (f, bits, width, height)
     struct frame *f;
     char *bits;
     unsigned int width, height;
{
  Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  int id;

#ifdef HAVE_X_WINDOWS
  Pixmap bitmap;
  bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
				  bits, width, height);
  if (! bitmap)
    return -1;
#endif /* HAVE_X_WINDOWS */

#ifdef HAVE_NTGUI
  Pixmap bitmap;
  bitmap = CreateBitmap (width, height,
			 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes,
			 FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_cbits,
			 bits);
  if (! bitmap)
    return -1;
#endif /* HAVE_NTGUI */

295 296 297 298 299 300
#ifdef HAVE_NS
  void *bitmap = ns_image_from_XBM(bits, width, height);
  if (!bitmap)
      return -1;
#endif

301 302
  id = x_allocate_bitmap_record (f);

303 304 305 306 307
#ifdef HAVE_NS
  dpyinfo->bitmaps[id - 1].img = bitmap;
  dpyinfo->bitmaps[id - 1].depth = 1;
#endif

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  dpyinfo->bitmaps[id - 1].file = NULL;
  dpyinfo->bitmaps[id - 1].height = height;
  dpyinfo->bitmaps[id - 1].width = width;
  dpyinfo->bitmaps[id - 1].refcount = 1;

#ifdef HAVE_X_WINDOWS
  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
  dpyinfo->bitmaps[id - 1].have_mask = 0;
  dpyinfo->bitmaps[id - 1].depth = 1;
#endif /* HAVE_X_WINDOWS */

#ifdef HAVE_NTGUI
  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
  dpyinfo->bitmaps[id - 1].hinst = NULL;
  dpyinfo->bitmaps[id - 1].depth = 1;
#endif /* HAVE_NTGUI */

  return id;
}

/* Create bitmap from file FILE for frame F.  */

int
x_create_bitmap_from_file (f, file)
     struct frame *f;
     Lisp_Object file;
{
335 336
  Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);

337 338 339 340
#ifdef HAVE_NTGUI
  return -1;  /* W32_TODO : bitmap support */
#endif /* HAVE_NTGUI */

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
#ifdef HAVE_NS
  int id;
  void *bitmap = ns_image_from_file(file);

  if (!bitmap)
      return -1;


  id = x_allocate_bitmap_record (f);
  dpyinfo->bitmaps[id - 1].img = bitmap;
  dpyinfo->bitmaps[id - 1].refcount = 1;
  dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
  dpyinfo->bitmaps[id - 1].depth = 1;
  dpyinfo->bitmaps[id - 1].height = ns_image_width(bitmap);
  dpyinfo->bitmaps[id - 1].width = ns_image_height(bitmap);
  strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
  return id;
#endif

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
#ifdef HAVE_X_WINDOWS
  unsigned int width, height;
  Pixmap bitmap;
  int xhot, yhot, result, id;
  Lisp_Object found;
  int fd;
  char *filename;

  /* Look for an existing bitmap with the same name.  */
  for (id = 0; id < dpyinfo->bitmaps_last; ++id)
    {
      if (dpyinfo->bitmaps[id].refcount
	  && dpyinfo->bitmaps[id].file
	  && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
	{
	  ++dpyinfo->bitmaps[id].refcount;
	  return id + 1;
	}
    }

  /* Search bitmap-file-path for the file, if appropriate.  */
  fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
  if (fd < 0)
    return -1;
  emacs_close (fd);

  filename = (char *) SDATA (found);

  result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
			    filename, &width, &height, &bitmap, &xhot, &yhot);
  if (result != BitmapSuccess)
    return -1;

  id = x_allocate_bitmap_record (f);
  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
  dpyinfo->bitmaps[id - 1].have_mask = 0;
  dpyinfo->bitmaps[id - 1].refcount = 1;
  dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SBYTES (file) + 1);
  dpyinfo->bitmaps[id - 1].depth = 1;
  dpyinfo->bitmaps[id - 1].height = height;
  dpyinfo->bitmaps[id - 1].width = width;
  strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));

  return id;
#endif /* HAVE_X_WINDOWS */
}

/* Free bitmap B.  */

static void
410
free_bitmap_record (dpyinfo, bm)
411 412 413 414 415 416 417 418 419 420 421 422 423
     Display_Info *dpyinfo;
     Bitmap_Record *bm;
{
#ifdef HAVE_X_WINDOWS
  XFreePixmap (dpyinfo->display, bm->pixmap);
  if (bm->have_mask)
    XFreePixmap (dpyinfo->display, bm->mask);
#endif /* HAVE_X_WINDOWS */

#ifdef HAVE_NTGUI
  DeleteObject (bm->pixmap);
#endif /* HAVE_NTGUI */

424 425 426 427
#ifdef HAVE_NS
  ns_release_object(bm->img);
#endif

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  if (bm->file)
    {
      xfree (bm->file);
      bm->file = NULL;
    }
}

/* Remove reference to bitmap with id number ID.  */

void
x_destroy_bitmap (f, id)
     FRAME_PTR f;
     int id;
{
  Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);

  if (id > 0)
    {
      Bitmap_Record *bm = &dpyinfo->bitmaps[id - 1];

      if (--bm->refcount == 0)
	{
	  BLOCK_INPUT;
451
	  free_bitmap_record (dpyinfo, bm);
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	  UNBLOCK_INPUT;
	}
    }
}

/* Free all the bitmaps for the display specified by DPYINFO.  */

void
x_destroy_all_bitmaps (dpyinfo)
     Display_Info *dpyinfo;
{
  int i;
  Bitmap_Record *bm = dpyinfo->bitmaps;

  for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
    if (bm->refcount > 0)
468
      free_bitmap_record (dpyinfo, bm);
469 470 471 472 473 474 475 476 477 478

  dpyinfo->bitmaps_last = 0;
}


#ifdef HAVE_X_WINDOWS

/* Useful functions defined in the section
   `Image type independent image structures' below. */

479 480 481
static unsigned long four_corners_best P_ ((XImagePtr ximg,
					    int *corners,
					    unsigned long width,
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
					    unsigned long height));

static int x_create_x_image_and_pixmap P_ ((struct frame *f, int width, int height,
					    int depth, XImagePtr *ximg,
					    Pixmap *pixmap));

static void x_destroy_x_image P_ ((XImagePtr ximg));


/* Create a mask of a bitmap. Note is this not a perfect mask.
   It's nicer with some borders in this context */

int
x_create_bitmap_mask (f, id)
     struct frame *f;
     int id;
{
  Pixmap pixmap, mask;
  XImagePtr ximg, mask_img;
  unsigned long width, height;
  int result;
  unsigned long bg;
  unsigned long x, y, xp, xm, yp, ym;
  GC gc;

  Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);

  if (!(id > 0))
    return -1;

  pixmap = x_bitmap_pixmap (f, id);
  width = x_bitmap_width (f, id);
  height = x_bitmap_height (f, id);

  BLOCK_INPUT;
  ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
		    ~0, ZPixmap);

  if (!ximg)
    {
      UNBLOCK_INPUT;
      return -1;
    }

  result = x_create_x_image_and_pixmap (f, width, height, 1, &mask_img, &mask);

  UNBLOCK_INPUT;
  if (!result)
    {
      XDestroyImage (ximg);
      return -1;
    }

535
  bg = four_corners_best (ximg, NULL, width, height);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

  for (y = 0; y < ximg->height; ++y)
    {
      for (x = 0; x < ximg->width; ++x)
	{
	  xp = x != ximg->width - 1 ? x + 1 : 0;
	  xm = x != 0 ? x - 1 : ximg->width - 1;
	  yp = y != ximg->height - 1 ? y + 1 : 0;
	  ym = y != 0 ? y - 1 : ximg->height - 1;
	  if (XGetPixel (ximg, x, y) == bg
	      && XGetPixel (ximg, x, yp) == bg
	      && XGetPixel (ximg, x, ym) == bg
	      && XGetPixel (ximg, xp, y) == bg
	      && XGetPixel (ximg, xp, yp) == bg
	      && XGetPixel (ximg, xp, ym) == bg
	      && XGetPixel (ximg, xm, y) == bg
	      && XGetPixel (ximg, xm, yp) == bg
	      && XGetPixel (ximg, xm, ym) == bg)
	    XPutPixel (mask_img, x, y, 0);
	  else
	    XPutPixel (mask_img, x, y, 1);
	}
    }

  xassert (interrupt_input_blocked);
  gc = XCreateGC (FRAME_X_DISPLAY (f), mask, 0, NULL);
  XPutImage (FRAME_X_DISPLAY (f), mask, gc, mask_img, 0, 0, 0, 0,
	     width, height);
  XFreeGC (FRAME_X_DISPLAY (f), gc);

  dpyinfo->bitmaps[id - 1].have_mask = 1;
  dpyinfo->bitmaps[id - 1].mask = mask;

  XDestroyImage (ximg);
  x_destroy_x_image (mask_img);

  return 0;
}

#endif /* HAVE_X_WINDOWS */


/***********************************************************************
			    Image types
 ***********************************************************************/

/* Value is the number of elements of vector VECTOR.  */

#define DIM(VECTOR)	(sizeof (VECTOR) / sizeof *(VECTOR))

/* List of supported image types.  Use define_image_type to add new
   types.  Use lookup_image_type to find a type for a given symbol.  */

static struct image_type *image_types;

591 592 593 594
/* A list of symbols, one for each supported image type.  */

Lisp_Object Vimage_types;

595 596 597 598
/* An alist of image types and libraries that implement the type.  */

Lisp_Object Vimage_library_alist;

599 600 601 602
/* Cache for delayed-loading image types.  */

static Lisp_Object Vimage_type_cache;

603 604 605 606 607 608 609
/* The symbol `xbm' which is used as the type symbol for XBM images.  */

Lisp_Object Qxbm;

/* Keywords.  */

extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
Stefan Monnier's avatar
Stefan Monnier committed
610
extern Lisp_Object QCdata, QCtype;
Kim F. Storm's avatar
Kim F. Storm committed
611
extern Lisp_Object Qcenter;
Stefan Monnier's avatar
Stefan Monnier committed
612
Lisp_Object QCascent, QCmargin, QCrelief, Qcount;
613 614 615 616 617 618 619 620 621 622 623 624 625 626
Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;

/* Other symbols.  */

Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;

/* Time in seconds after which images should be removed from the cache
   if not displayed.  */

Lisp_Object Vimage_cache_eviction_delay;

/* Function prototypes.  */

627
static Lisp_Object define_image_type P_ ((struct image_type *type, int loaded));
628 629 630 631 632 633 634
static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
static void x_laplace P_ ((struct frame *, struct image *));
static void x_emboss P_ ((struct frame *, struct image *));
static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
				       Lisp_Object));

635 636 637 638 639
#define CACHE_IMAGE_TYPE(type, status) \
  do { Vimage_type_cache = Fcons (Fcons (type, status), Vimage_type_cache); } while (0)

#define ADD_IMAGE_TYPE(type) \
  do { Vimage_types = Fcons (type, Vimage_types); } while (0)
640 641

/* Define a new image type from TYPE.  This adds a copy of TYPE to
642
   image_types and caches the loading status of TYPE.  */
643

644 645
static Lisp_Object
define_image_type (type, loaded)
646
     struct image_type *type;
647
     int loaded;
648
{
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  Lisp_Object success;

  if (!loaded)
    success = Qnil;
  else
    {
      /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
         The initialized data segment is read-only.  */
      struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
      bcopy (type, p, sizeof *p);
      p->next = image_types;
      image_types = p;
      success = Qt;
    }

664
  CACHE_IMAGE_TYPE (*type->type, success);
665
  return success;
666 667 668 669 670 671 672 673 674 675 676 677
}


/* Look up image type SYMBOL, and return a pointer to its image_type
   structure.  Value is null if SYMBOL is not a known image type.  */

static INLINE struct image_type *
lookup_image_type (symbol)
     Lisp_Object symbol;
{
  struct image_type *type;

678
  /* We must initialize the image-type if it hasn't been already.  */
679
  if (NILP (Finit_image_library (symbol, Vimage_library_alist)))
680 681
    return 0;			/* unimplemented */

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
  for (type = image_types; type; type = type->next)
    if (EQ (symbol, *type->type))
      break;

  return type;
}


/* Value is non-zero if OBJECT is a valid Lisp image specification.  A
   valid image specification is a list whose car is the symbol
   `image', and whose rest is a property list.  The property list must
   contain a value for key `:type'.  That value must be the name of a
   supported image type.  The rest of the property list depends on the
   image type.  */

int
valid_image_p (object)
     Lisp_Object object;
{
  int valid_p = 0;

  if (IMAGEP (object))
    {
      Lisp_Object tem;

      for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
	if (EQ (XCAR (tem), QCtype))
	  {
	    tem = XCDR (tem);
	    if (CONSP (tem) && SYMBOLP (XCAR (tem)))
	      {
		struct image_type *type;
		type = lookup_image_type (XCAR (tem));
		if (type)
		  valid_p = type->valid_p (object);
	      }

	    break;
	  }
    }

  return valid_p;
}


/* Log error message with format string FORMAT and argument ARG.
   Signaling an error, e.g. when an image cannot be loaded, is not a
   good idea because this would interrupt redisplay, and the error
   message display would lead to another redisplay.  This function
   therefore simply displays a message.  */

static void
image_error (format, arg1, arg2)
     char *format;
     Lisp_Object arg1, arg2;
{
  add_to_log (format, arg1, arg2);
}



/***********************************************************************
			 Image specifications
 ***********************************************************************/

enum image_value_type
{
  IMAGE_DONT_CHECK_VALUE_TYPE,
  IMAGE_STRING_VALUE,
  IMAGE_STRING_OR_NIL_VALUE,
  IMAGE_SYMBOL_VALUE,
  IMAGE_POSITIVE_INTEGER_VALUE,
  IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
  IMAGE_NON_NEGATIVE_INTEGER_VALUE,
  IMAGE_ASCENT_VALUE,
  IMAGE_INTEGER_VALUE,
  IMAGE_FUNCTION_VALUE,
  IMAGE_NUMBER_VALUE,
  IMAGE_BOOL_VALUE
};

/* Structure used when parsing image specifications.  */

struct image_keyword
{
  /* Name of keyword.  */
  char *name;

  /* The type of value allowed.  */
  enum image_value_type type;

  /* Non-zero means key must be present.  */
  int mandatory_p;

  /* Used to recognize duplicate keywords in a property list.  */
  int count;

  /* The value that was found.  */
  Lisp_Object value;
};


static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
				 int, Lisp_Object));
static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));


/* Parse image spec SPEC according to KEYWORDS.  A valid image spec
   has the format (image KEYWORD VALUE ...).  One of the keyword/
   value pairs must be `:type TYPE'.  KEYWORDS is a vector of
   image_keywords structures of size NKEYWORDS describing other
   allowed keyword/value pairs.  Value is non-zero if SPEC is valid.  */

static int
parse_image_spec (spec, keywords, nkeywords, type)
     Lisp_Object spec;
     struct image_keyword *keywords;
     int nkeywords;
     Lisp_Object type;
{
  int i;
  Lisp_Object plist;

  if (!IMAGEP (spec))
    return 0;

  plist = XCDR (spec);
  while (CONSP (plist))
    {
      Lisp_Object key, value;

      /* First element of a pair must be a symbol.  */
      key = XCAR (plist);
      plist = XCDR (plist);
      if (!SYMBOLP (key))
	return 0;

      /* There must follow a value.  */
      if (!CONSP (plist))
	return 0;
      value = XCAR (plist);
      plist = XCDR (plist);

      /* Find key in KEYWORDS.  Error if not found.  */
      for (i = 0; i < nkeywords; ++i)
	if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
	  break;

      if (i == nkeywords)
	continue;

      /* Record that we recognized the keyword.  If a keywords
	 was found more than once, it's an error.  */
      keywords[i].value = value;
      ++keywords[i].count;

      if (keywords[i].count > 1)
	return 0;

      /* Check type of value against allowed type.  */
      switch (keywords[i].type)
	{
	case IMAGE_STRING_VALUE:
	  if (!STRINGP (value))
	    return 0;
	  break;

	case IMAGE_STRING_OR_NIL_VALUE:
	  if (!STRINGP (value) && !NILP (value))
	    return 0;
	  break;

	case IMAGE_SYMBOL_VALUE:
	  if (!SYMBOLP (value))
	    return 0;
	  break;

	case IMAGE_POSITIVE_INTEGER_VALUE:
	  if (!INTEGERP (value) || XINT (value) <= 0)
	    return 0;
	  break;

	case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
	  if (INTEGERP (value) && XINT (value) >= 0)
	    break;
	  if (CONSP (value)
	      && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
	      && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
	    break;
	  return 0;

	case IMAGE_ASCENT_VALUE:
	  if (SYMBOLP (value) && EQ (value, Qcenter))
	    break;
	  else if (INTEGERP (value)
		   && XINT (value) >= 0
		   && XINT (value) <= 100)
	    break;
	  return 0;

	case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
	  if (!INTEGERP (value) || XINT (value) < 0)
	    return 0;
	  break;

	case IMAGE_DONT_CHECK_VALUE_TYPE:
	  break;

	case IMAGE_FUNCTION_VALUE:
	  value = indirect_function (value);
	  if (SUBRP (value)
	      || COMPILEDP (value)
	      || (CONSP (value) && EQ (XCAR (value), Qlambda)))
	    break;
	  return 0;

	case IMAGE_NUMBER_VALUE:
	  if (!INTEGERP (value) && !FLOATP (value))
	    return 0;
	  break;

	case IMAGE_INTEGER_VALUE:
	  if (!INTEGERP (value))
	    return 0;
	  break;

	case IMAGE_BOOL_VALUE:
	  if (!NILP (value) && !EQ (value, Qt))
	    return 0;
	  break;

	default:
	  abort ();
	  break;
	}

      if (EQ (key, QCtype) && !EQ (type, value))
	return 0;
    }

  /* Check that all mandatory fields are present.  */
  for (i = 0; i < nkeywords; ++i)
    if (keywords[i].mandatory_p && keywords[i].count == 0)
      return 0;

  return NILP (plist);
}


/* Return the value of KEY in image specification SPEC.  Value is nil
   if KEY is not present in SPEC.  if FOUND is not null, set *FOUND
   to 1 if KEY was found in SPEC, set it to 0 otherwise.  */

static Lisp_Object
image_spec_value (spec, key, found)
     Lisp_Object spec, key;
     int *found;
{
  Lisp_Object tail;

  xassert (valid_image_p (spec));

  for (tail = XCDR (spec);
       CONSP (tail) && CONSP (XCDR (tail));
       tail = XCDR (XCDR (tail)))
    {
      if (EQ (XCAR (tail), key))
	{
	  if (found)
	    *found = 1;
	  return XCAR (XCDR (tail));
	}
    }

  if (found)
    *found = 0;
  return Qnil;
}


DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
       doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
PIXELS non-nil means return the size in pixels, otherwise return the
size in canonical character units.
FRAME is the frame on which the image will be displayed.  FRAME nil
or omitted means use the selected frame.  */)
     (spec, pixels, frame)
     Lisp_Object spec, pixels, frame;
{
  Lisp_Object size;

  size = Qnil;
  if (valid_image_p (spec))
    {
      struct frame *f = check_x_frame (frame);
      int id = lookup_image (f, spec);
      struct image *img = IMAGE_FROM_ID (f, id);
      int width = img->width + 2 * img->hmargin;
      int height = img->height + 2 * img->vmargin;

      if (NILP (pixels))
	size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
		      make_float ((double) height / FRAME_LINE_HEIGHT (f)));
      else
	size = Fcons (make_number (width), make_number (height));
    }
  else
    error ("Invalid image specification");

  return size;
}


DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
       doc: /* Return t if image SPEC has a mask bitmap.
FRAME is the frame on which the image will be displayed.  FRAME nil
or omitted means use the selected frame.  */)
     (spec, frame)
     Lisp_Object spec, frame;
{
  Lisp_Object mask;

  mask = Qnil;
  if (valid_image_p (spec))
    {
      struct frame *f = check_x_frame (frame);
      int id = lookup_image (f, spec);
      struct image *img = IMAGE_FROM_ID (f, id);
      if (img->mask)
	mask = Qt;
    }
  else
    error ("Invalid image specification");

  return mask;
}

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
DEFUN ("image-extension-data", Fimage_extension_data, Simage_extension_data, 1, 2, 0,
       doc: /* Return extension data for image SPEC.
FRAME is the frame on which the image will be displayed.  FRAME nil
or omitted means use the selected frame.  */)
     (spec, frame)
     Lisp_Object spec, frame;
{
  Lisp_Object ext;

  ext = Qnil;
  if (valid_image_p (spec))
    {
      struct frame *f = check_x_frame (frame);
      int id = lookup_image (f, spec);
      struct image *img = IMAGE_FROM_ID (f, id);
      ext = img->data.lisp_val;
    }

  return ext;
}

1040 1041 1042 1043 1044 1045 1046

/***********************************************************************
		 Image type independent image structures
 ***********************************************************************/

static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
static void free_image P_ ((struct frame *f, struct image *img));
1047
static int check_image_size P_ ((struct frame *f, int width, int height));
1048

1049 1050
#define MAX_IMAGE_SIZE 6.0
Lisp_Object Vmax_image_size;
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

/* Allocate and return a new image structure for image specification
   SPEC.  SPEC has a hash value of HASH.  */

static struct image *
make_image (spec, hash)
     Lisp_Object spec;
     unsigned hash;
{
  struct image *img = (struct image *) xmalloc (sizeof *img);
1061
  Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1062 1063 1064

  xassert (valid_image_p (spec));
  bzero (img, sizeof *img);
1065
  img->dependencies = NILP (file) ? Qnil : list1 (file);
1066 1067 1068 1069 1070 1071
  img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
  xassert (img->type != NULL);
  img->spec = spec;
  img->data.lisp_val = Qnil;
  img->ascent = DEFAULT_IMAGE_ASCENT;
  img->hash = hash;
1072
  img->corners[BOT_CORNER] = -1;  /* Full image */
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  return img;
}


/* Free image IMG which was used on frame F, including its resources.  */

static void
free_image (f, img)
     struct frame *f;
     struct image *img;
{
  if (img)
    {
1086
      struct image_cache *c = FRAME_IMAGE_CACHE (f);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

      /* Remove IMG from the hash table of its cache.  */
      if (img->prev)
	img->prev->next = img->next;
      else
	c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;

      if (img->next)
	img->next->prev = img->prev;

      c->images[img->id] = NULL;

      /* Free resources, then free IMG.  */
      img->type->free (f, img);
      xfree (img);
    }
}

1105 1106 1107 1108 1109 1110 1111 1112 1113
/* Return 1 if the given widths and heights are valid for display;
   otherwise, return 0. */

int
check_image_size (f, width, height)
     struct frame *f;
     int width;
     int height;
{
1114
  int w, h;
1115

1116
  if (width <= 0 || height <= 0)
1117 1118
    return 0;

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  if (INTEGERP (Vmax_image_size))
    w = h = XINT (Vmax_image_size);
  else if (FLOATP (Vmax_image_size))
    {
      if (f != NULL)
	{
	  w = FRAME_PIXEL_WIDTH (f);
	  h = FRAME_PIXEL_HEIGHT (f);
	}
      else
	w = h = 1024;  /* Arbitrary size for unknown frame. */
      w = (int) (XFLOAT_DATA (Vmax_image_size) * w);
      h = (int) (XFLOAT_DATA (Vmax_image_size) * h);
    }
  else
    return 1;

  return (width <= w && height <= h);
1137
}
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

/* Prepare image IMG for display on frame F.  Must be called before
   drawing an image.  */

void
prepare_image_for_display (f, img)
     struct frame *f;
     struct image *img;
{
  EMACS_TIME t;

  /* We're about to display IMG, so set its timestamp to `now'.  */
  EMACS_GET_TIME (t);
  img->timestamp = EMACS_SECS (t);

  /* If IMG doesn't have a pixmap yet, load it now, using the image
     type dependent loader function.  */
  if (img->pixmap == NO_PIXMAP && !img->load_failed_p)
    img->load_failed_p = img->type->load (f, img) == 0;
1157

1158 1159 1160 1161 1162 1163 1164
}


/* Value is the number of pixels for the ascent of image IMG when
   drawn in face FACE.  */

int
1165
image_ascent (img, face, slice)
1166 1167
     struct image *img;
     struct face *face;
1168
     struct glyph_slice *slice;
1169
{
1170
  int height;
1171 1172
  int ascent;

1173 1174 1175 1176 1177 1178 1179
  if (slice->height == img->height)
    height = img->height + img->vmargin;
  else if (slice->y == 0)
    height = slice->height + img->vmargin;
  else
    height = slice->height;

1180 1181 1182 1183 1184 1185
  if (img->ascent == CENTERED_IMAGE_ASCENT)
    {
      if (face->font)
	{
#ifdef HAVE_NTGUI
	  /* W32 specific version.  Why?. ++kfs  */
1186 1187
	  ascent = height / 2 - (FONT_DESCENT (face->font)
				 - FONT_BASE (face->font)) / 2;
1188 1189 1190 1191 1192 1193
#else
	  /* This expression is arranged so that if the image can't be
	     exactly centered, it will be moved slightly up.  This is
	     because a typical font is `top-heavy' (due to the presence
	     uppercase letters), so the image placement should err towards
	     being top-heavy too.  It also just generally looks better.  */
1194 1195
	  ascent = (height + FONT_BASE(face->font)
                    - FONT_DESCENT(face->font) + 1) / 2;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
#endif /* HAVE_NTGUI */
	}
      else
	ascent = height / 2;
    }
  else
    ascent = (int) (height * img->ascent / 100.0);

  return ascent;
}


/* Image background colors.  */

/* Find the "best" corner color of a bitmap.
   On W32, XIMG is assumed to a device context with the bitmap selected.  */

static RGB_PIXEL_COLOR
1214
four_corners_best (ximg, corners, width, height)
1215
     XImagePtr_or_DC ximg;
1216
     int *corners;
1217 1218
     unsigned long width, height;
{
1219
  RGB_PIXEL_COLOR corner_pixels[4], best;
1220 1221
  int i, best_count;

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  if (corners && corners[BOT_CORNER] >= 0)
    {
      /* Get the colors at the corner_pixels of ximg.  */
      corner_pixels[0] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[TOP_CORNER]);
      corner_pixels[1] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[TOP_CORNER]);
      corner_pixels[2] = GET_PIXEL (ximg, corners[RIGHT_CORNER] - 1, corners[BOT_CORNER] - 1);
      corner_pixels[3] = GET_PIXEL (ximg, corners[LEFT_CORNER], corners[BOT_CORNER] - 1);
    }
  else
    {
      /* Get the colors at the corner_pixels of ximg.  */
      corner_pixels[0] = GET_PIXEL (ximg, 0, 0);
      corner_pixels[1] = GET_PIXEL (ximg, width - 1, 0);
      corner_pixels[2] = GET_PIXEL (ximg, width - 1, height - 1);
      corner_pixels[3] = GET_PIXEL (ximg, 0, height - 1);
    }
1238 1239 1240 1241 1242 1243
  /* Choose the most frequently found color as background.  */
  for (i = best_count = 0; i < 4; ++i)
    {
      int j, n;

      for (j = n = 0; j < 4; ++j)
1244
	if (corner_pixels[i] == corner_pixels[j])
1245 1246 1247
	  ++n;

      if (n > best_count)
1248
	best = corner_pixels[i], best_count = n;
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    }

  return best;
}

/* Portability macros */

#ifdef HAVE_NTGUI

#define Destroy_Image(img_dc, prev) \
  do { SelectObject (img_dc, prev); DeleteDC (img_dc); } while (0)

#define Free_Pixmap(display, pixmap) \
  DeleteObject (pixmap)

1264 1265 1266 1267 1268 1269 1270 1271
#elif defined (HAVE_NS)

#define Destroy_Image(ximg, dummy) \
  ns_release_object(ximg)

#define Free_Pixmap(display, pixmap) \
  ns_release_object(pixmap)

1272 1273 1274 1275 1276 1277 1278 1279
#else

#define Destroy_Image(ximg, dummy) \
  XDestroyImage (ximg)

#define Free_Pixmap(display, pixmap) \
  XFreePixmap (display, pixmap)

1280
#endif /* !HAVE_NTGUI && !HAVE_NS */
1281 1282 1283 1284 1285


/* Return the `background' field of IMG.  If IMG doesn't have one yet,
   it is guessed heuristically.  If non-zero, XIMG is an existing
   XImage object (or device context with the image selected on W32) to
Kim F. Storm's avatar
Kim F. Storm committed
1286
   use for the heuristic.  */
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

RGB_PIXEL_COLOR
image_background (img, f, ximg)
     struct image *img;
     struct frame *f;
     XImagePtr_or_DC ximg;
{
  if (! img->background_valid)
    /* IMG doesn't have a background yet, try to guess a reasonable value.  */
    {
      int free_ximg = !ximg;
#ifdef HAVE_NTGUI
      HGDIOBJ prev;
#endif /* HAVE_NTGUI */

      if (free_ximg)
	{
#ifndef HAVE_NTGUI
	  ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
			    0, 0, img->width, img->height, ~0, ZPixmap);
#else
	  HDC frame_dc = get_frame_dc (f);
	  ximg = CreateCompatibleDC (frame_dc);
	  release_frame_dc (f, frame_dc);
	  prev = SelectObject (ximg, img->pixmap);
#endif /* !HAVE_NTGUI */
	}

1315
      img->background = four_corners_best (ximg, img->corners, img->width, img->height);
1316 1317 1318

      if (free_ximg)
	Destroy_Image (ximg, prev);
Kim F. Storm's avatar
Kim F. Storm committed
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
      img->background_valid = 1;
    }

  return img->background;
}

/* Return the `background_transparent' field of IMG.  If IMG doesn't
   have one yet, it is guessed heuristically.  If non-zero, MASK is an
   existing XImage object to use for the heuristic.  */

int
image_background_transparent (img, f, mask)
     struct image *img;
     struct frame *f;
     XImagePtr_or_DC mask;
{
  if (! img->background_transparent_valid)
    /* IMG doesn't have a background yet, try to guess a reasonable value.  */
    {
      if (img->mask)
	{
	  int free_mask = !mask;
#ifdef HAVE_NTGUI
	  HGDIOBJ prev;
#endif /* HAVE_NTGUI */

	  if (free_mask)
	    {
#ifndef HAVE_NTGUI
	      mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
				0, 0, img->width, img->height, ~0, ZPixmap);
#else
	      HDC frame_dc = get_frame_dc (f);
	      mask = CreateCompatibleDC (frame_dc);
	      release_frame_dc (f, frame_dc);
	      prev = SelectObject (mask, img->mask);
#endif /* HAVE_NTGUI */
	    }

	  img->background_transparent
1360
	    = (four_corners_best (mask, img->corners, img->width, img->height) == PIX_MASK_RETAIN);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

	  if (free_mask)
	    Destroy_Image (mask, prev);
	}
      else
	img->background_transparent = 0;

      img->background_transparent_valid = 1;
    }

  return img->background_transparent;
}


/***********************************************************************
		  Helper functions for X image types
 ***********************************************************************/

static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
				 int, int));
static void x_clear_image P_ ((struct frame *f, struct image *img));
static unsigned long x_alloc_image_color P_ ((struct frame *f,
					      struct image *img,
					      Lisp_Object color_name,
					      unsigned long dflt));


/* Clear X resources of image IMG on frame F.  PIXMAP_P non-zero means
   free the pixmap if any.  MASK_P non-zero means clear the mask
   pixmap if any.  COLORS_P non-zero means free colors allocated for
   the image, if any.  */

static void
x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
     struct frame *f;
     struct image *img;
     int pixmap_p, mask_p, colors_p;
{
  if (pixmap_p && img->pixmap)
    {
      Free_Pixmap (FRAME_X_DISPLAY (f), img->pixmap);
      img->pixmap = NO_PIXMAP;
1403
      /* NOTE (HAVE_NS): background color is NOT an indexed color! */
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
      img->background_valid = 0;
    }

  if (mask_p && img->mask)
    {
      Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
      img->mask = NO_PIXMAP;
      img->background_transparent_valid = 0;
    }

  if (colors_p && img->ncolors)
    {
      /* W32_TODO: color table support.  */
#ifdef HAVE_X_WINDOWS
      x_free_colors (f, img->colors, img->ncolors);
#endif /* HAVE_X_WINDOWS */
      xfree (img->colors);
      img->colors = NULL;
      img->ncolors = 0;
    }
1424

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
}

/* Free X resources of image IMG which is used on frame F.  */

static void
x_clear_image (f, img)
     struct frame *f;
     struct image *img;
{
  BLOCK_INPUT;
  x_clear_image_1 (f, img, 1, 1, 1);
  UNBLOCK_INPUT;
}


/* Allocate color COLOR_NAME for image IMG on frame F.  If color
   cannot be allocated, use DFLT.  Add a newly allocated color to
   IMG->colors, so that it can be freed again.  Value is the pixel
   color.  */

static unsigned long
x_alloc_image_color (f, img, color_name, dflt)
     struct frame *f;
     struct image *img;
     Lisp_Object color_name;
     unsigned long dflt;
{
  XColor color;
  unsigned long result;

  xassert (STRINGP (color_name));

  if (x_defined_color (f, SDATA (color_name), &color, 1))
    {
      /* This isn't called frequently so we get away with simply
	 reallocating the color vector to the needed size, here.  */
      ++img->ncolors;
      img->colors =
	(unsigned long *) xrealloc (img->colors,
				    img->ncolors * sizeof *img->colors);
      img->colors[img->ncolors - 1] = color.pixel;
      result = color.pixel;
    }
  else
    result = dflt;

  return result;
}



/***********************************************************************
			     Image Cache
 ***********************************************************************/

1480
static struct image *search_image_cache P_ ((struct frame *, Lisp_Object, unsigned));
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
static void cache_image P_ ((struct frame *f, struct image *img));
static void postprocess_image P_ ((struct frame *, struct image *));

/* Return a new, initialized image cache that is allocated from the
   heap.  Call free_image_cache to free an image cache.  */

struct image_cache *
make_image_cache ()
{
  struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
  int size;

  bzero (c, sizeof *c);
  c->size = 50;
  c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
  size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
  c->buckets = (struct image **) xmalloc (size);
  bzero (c->buckets, size);
  return c;
}


1503 1504 1505 1506
/* Find an image matching SPEC in the cache, and return it.  If no
   image is found, return NULL.  */
static struct image *
search_image_cache (f, spec, hash)
Chong Yidong's avatar
Chong Yidong committed
1507 1508
     struct frame *f;
     Lisp_Object spec;
1509
     unsigned hash;
Chong Yidong's avatar
Chong Yidong committed
1510
{
Chong Yidong's avatar
Chong Yidong committed
1511
  struct image *img;
1512
  struct image_cache *c = FRAME_IMAGE_CACHE (f);
Chong Yidong's avatar
Chong Yidong committed
1513 1514
  int i = hash % IMAGE_CACHE_BUCKETS_SIZE;

Chong Yidong's avatar
Chong Yidong committed
1515 1516
  if (!c) return NULL;

1517 1518
  /* If the image spec does not specify a background color, the cached
     image must have the same background color as the current frame.
1519 1520 1521 1522 1523 1524 1525 1526 1527
     The foreground color must also match, for the sake of monochrome
     images.

     In fact, we could ignore the foreground color matching condition
     for color images, or if the image spec specifies :foreground;
     similarly we could ignore the background color matching condition
     for formats that don't use transparency (such as jpeg), or if the
     image spec specifies :background.  However, the extra memory
     usage is probably negligible in practice, so we don't bother.  */
1528

Chong Yidong's avatar
Chong Yidong committed
1529
  for (img = c->buckets[i]; img; img = img->next)
1530 1531
    if (img->hash == hash
	&& !NILP (Fequal (img->spec, spec))
1532 1533
	&& img->frame_foreground == FRAME_FOREGROUND_PIXEL (f)
	&& img->frame_background == FRAME_BACKGROUND_PIXEL (f))
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
      break;
  return img;
}


/* Search frame F for an image with spec SPEC, and free it.  */

static void
uncache_image (f, spec)
     struct frame *f;
     Lisp_Object spec;
{
  struct image *img = search_image_cache (f, spec, sxhash (spec, 0));
  if (img)
1548 1549 1550 1551 1552 1553
    {
      free_image (f, img);
      /* As display glyphs may still be referring to the image ID, we
	 must garbage the frame (Bug#6426).  */
      SET_FRAME_GARBAGED (f);
    }
Chong Yidong's avatar
Chong Yidong committed
1554 1555 1556
}


1557 1558 1559 1560 1561 1562 1563
/* Free image cache of frame F.  Be aware that X frames share images
   caches.  */

void
free_image_cache (f)
     struct frame *f;
{
1564
  struct image_cache *c = FRAME_IMAGE_CACHE (f);
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  if (c)
    {
      int i;

      /* Cache should not be referenced by any frame when freed.  */
      xassert (c->refcount == 0);

      for (i = 0; i < c->used; ++i)
	free_image (f, c->images[i]);
      xfree (c->images);
      xfree (c->buckets);
      xfree (c);
1577
      FRAME_IMAGE_CACHE (f) = NULL;
1578 1579 1580 1581
    }
}


1582 1583 1584 1585 1586 1587 1588
/* Clear image cache of frame F.  FILTER=t means free all images.
   FILTER=nil means clear only images that haven't been
   displayed for some time.
   Else, only free the images which have FILTER in their `dependencies'.
   Should be called from time to time to reduce the number of loaded images.
   If image-cache-eviction-delay is non-nil, this frees images in the cache
   which weren't displayed for at least that many seconds.  */
1589 1590

void
1591
clear_image_cache (struct frame *f, Lisp_Object filter)
1592
{
1593
  struct image_cache *c = FRAME_IMAGE_CACHE (f);
1594

1595
  if (c && (!NILP (filter) || INTEGERP (Vimage_cache_eviction_delay)))
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    {
      EMACS_TIME t;
      unsigned long old;
      int i, nfreed;

      EMACS_GET_TIME (t);
      old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);

      /* Block input so that we won't be interrupted by a SIGIO
	 while being in an inconsistent state.  */
      BLOCK_INPUT;

      for (i = nfreed = 0; i < c->used; ++i)
	{
	  struct image *img = c->images[i];
	  if (img != NULL
1612 1613 1614
	      && (NILP (filter) ? img->timestamp < old
		  : (EQ (Qt, filter)
		     || !NILP (Fmember (filter, img->dependencies)))))
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
	    {
	      free_image (f, img);
	      ++nfreed;
	    }
	}

      /* We may be clearing the image cache because, for example,
	 Emacs was iconified for a longer period of time.  In that
	 case, current matrices may still contain references to
	 images freed above.  So, clear these matrices.  */
      if (nfreed)
	{
	  Lisp_Object tail, frame;

	  FOR_EACH_FRAME (tail, frame)
	    {
	      struct frame *f = XFRAME (frame);
1632
	      if (FRAME_IMAGE_CACHE (f) == c)
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
		clear_current_matrices (f);
	    }

	  ++windows_or_buffers_changed;
	}

      UNBLOCK_INPUT;
    }
}

1643
void
1644
clear_image_caches (Lisp_Object filter)
1645 1646 1647 1648 1649 1650 1651 1652
{
  /* FIXME: We want to do
   * struct terminal *t;
   * for (t = terminal_list; t; t = t->next_terminal)
   *   clear_image_cache (t, filter); */
  Lisp_Object tail, frame;
  FOR_EACH_FRAME (tail, frame)
    if (FRAME_WINDOW_P (XFRAME (frame)))
1653
      clear_image_cache (XFRAME (frame), filter);
1654
}
1655 1656 1657

DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
       0, 1, 0,
1658 1659 1660 1661 1662 1663 1664
       doc: /* Clear the image cache.
FILTER nil or a frame means clear all images in the selected frame.
FILTER t means clear the image caches of all frames.
Anything else, means only clear those images which refer to FILTER,
which is then usually a filename.  */)
     (filter)
     Lisp_Object filter;
1665
{
1666 1667
  if (!(EQ (filter, Qnil) || FRAMEP (filter)))
    clear_image_caches (filter);
1668
  else
1669
    clear_image_cache (check_x_frame (filter), Qt);
1670 1671 1672 1673 1674

  return Qnil;
}


Chong Yidong's avatar
Chong Yidong committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
DEFUN ("image-refresh", Fimage_refresh, Simage_refresh,
       1, 2, 0,
       doc: /* Refresh the image with specification SPEC on frame FRAME.
If SPEC specifies an image file, the displayed image is updated with
the current contents of that file.
FRAME nil or omitted means use the selected frame.
FRAME t means refresh the image on all frames.  */)
     (spec, frame)
     Lisp_Object spec, frame;
{
  if (!valid_image_p (spec))
    error ("Invalid image specification");

  if (EQ (frame, Qt))
    {
      Lisp_Object tail;
      FOR_EACH_FRAME (tail, frame)
	{
	  struct frame *f = XFRAME (frame);
	  if (FRAME_WINDOW_P (f))
	    uncache_image (f, spec);
	}
    }
  else
    uncache_image (check_x_frame (frame), spec);

  return Qnil;
}


1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
/* Compute masks and transform image IMG on frame F, as specified
   by the image's specification,  */

static void
postprocess_image (f, img)
     struct frame *f;
     struct image *img;
{
  /* Manipulation of the image's mask.  */
  if (img->pixmap)
    {
      Lisp_Object conversion, spec;
      Lisp_Object mask;

      spec = img->spec;

      /* `:heuristic-mask t'
	 `:mask heuristic'
	 means build a mask heuristically.
	 `:heuristic-mask (R G B)'
	 `:mask (heuristic (R G B))'
	 means build a mask from color (R G B) in the
	 image.
	 `:mask nil'
	 means remove a mask, if any.  */

      mask = image_spec_value (spec, QCheuristic_mask, NULL);
      if (!NILP (mask))
	x_build_heuristic_mask (f, img, mask);
      else
	{
	  int found_p;

	  mask = image_spec_value (spec, QCmask, &found_p);

	  if (EQ (mask, Qheuristic))
	    x_build_heuristic_mask (f, img, Qt);
	  else if (CONSP (mask)
		   && EQ (XCAR (mask), Qheuristic))
	    {
	      if (CONSP (XCDR (mask)))
		x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
	      else
		x_build_heuristic_mask (f, img, XCDR (mask));
	    }
	  else if (NILP (mask) && found_p && img->mask)
	    {
	      Free_Pixmap (FRAME_X_DISPLAY (f), img->mask);
	      img->mask = NO_PIXMAP;
	    }
	}


      /* Should we apply an image transformation algorithm?  */
      conversion = image_spec_value (spec, QCconversion, NULL);
      if (EQ (conversion, Qdisabled))
	x_disable_image (f, img);
      else if (EQ (conversion, Qlaplace))
	x_laplace (f, img);
      else if (EQ (conversion, Qemboss))
	x_emboss (f, img);
      else if (CONSP (conversion)
	       && EQ (XCAR (conversion), Qedge_detection))
	{
	  Lisp_Object tem;
	  tem = XCDR (conversion);
	  if (CONSP (tem))
	    x_edge_detection (f, img,
			      Fplist_get (tem, QCmatrix),
			      Fplist_get (tem, QCcolor_adjustment));
	}
    }
}


/* Return the id of image with Lisp specification SPEC on frame F.
   SPEC must be a valid Lisp image specification (see valid_image_p).  */

int
lookup_image (f, spec)
     struct frame *f;
     Lisp_Object spec;
{
1788
  struct image_cache *c;
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
  struct image *img;
  unsigned hash;
  struct gcpro gcpro1;
  EMACS_TIME now;

  /* F must be a window-system frame, and SPEC must be a valid image
     specification.  */
  xassert (FRAME_WINDOW_P (f));
  xassert (valid_image_p (spec));

1799
  c = FRAME_IMAGE_CACHE (f);
1800

1801 1802 1803 1804
  GCPRO1 (spec);

  /* Look up SPEC in the hash table of the image cache.  */
  hash = sxhash (spec, 0);
1805
  img = search_image_cache (f, spec, hash);
1806 1807 1808 1809 1810 1811
  if (img && img->load_failed_p)
    {
      free_image (f, img);
      img = NULL;
    }

1812 1813 1814 1815 1816 1817 1818 1819 1820
  /* If not found, create a new image and cache it.  */
  if (img == NULL)
    {
      extern Lisp_Object Qpostscript;

      BLOCK_INPUT;
      img = make_image (spec, hash);
      cache_image (f, img);
      img->load_failed_p = img->type->load (f, img) == 0;
1821 1822
      img->frame_foreground = FRAME_FOREGROUND_PIXEL (f);
      img->frame_background = FRAME_BACKGROUND_PIXEL (f);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866

      /* If we can't load the image, and we don't have a width and
	 height, use some arbitrary width and height so that we can
	 draw a rectangle for it.  */
      if (img->load_failed_p)
	{
	  Lisp_Object value;

	  value = image_spec_value (spec, QCwidth, NULL);
	  img->width = (INTEGERP (value)
			? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
	  value = image_spec_value (spec, QCheight, NULL);
	  img->height = (INTEGERP (value)
			 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
	}
      else
	{
	  /* Handle image type independent image attributes
	     `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
	     `:background COLOR'.  */
	  Lisp_Object ascent, margin, relief, bg;

	  ascent = image_spec_value (spec, QCascent, NULL);
	  if (INTEGERP (ascent))
	    img->ascent = XFASTINT (ascent);
	  else if (EQ (ascent, Qcenter))
	    img->ascent = CENTERED_IMAGE_ASCENT;

	  margin = image_spec_value (spec, QCmargin, NULL);
	  if (INTEGERP (margin) && XINT (margin) >= 0)
	    img->vmargin = img->hmargin = XFASTINT (margin);
	  else if (CONSP (margin) && INTEGERP (XCAR (margin))
		   && INTEGERP (XCDR (margin)))
	    {
	      if (XINT (XCAR (margin)) > 0)
		img->hmargin = XFASTINT (XCAR (margin));
	      if (XINT (XCDR (margin)) > 0)
		img->vmargin = XFASTINT (XCDR (margin));
	    }

	  relief = image_spec_value (spec, QCrelief, NULL);
	  if (INTEGERP (relief))
	    {
	      img->relief = XINT (relief);
Eli Zaretskii's avatar
Eli Zaretskii committed
1867 1868
	      img->hmargin += eabs (img->relief);
	      img->vmargin += eabs (img->relief);
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885