image.c 279 KB
Newer Older
1
/* Functions for image support on window system.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1989, 1992-2019 Free Software Foundation, Inc.
4 5 6

This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
11 12 13 14 15 16 17

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
18
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
19 20

#include <config.h>
21 22

#include <fcntl.h>
23 24
#include <unistd.h>

25 26 27 28 29 30
/* Include this before including <setjmp.h> to work around bugs with
   older libpng; see Bug#17429.  */
#if defined HAVE_PNG && !defined HAVE_NS
# include <png.h>
#endif

31
#include <setjmp.h>
32

33
#include <stdint.h>
34
#include <c-ctype.h>
35
#include <flexmember.h>
36

37 38
#include "lisp.h"
#include "frame.h"
39
#include "process.h"
40
#include "window.h"
41
#include "buffer.h"
42 43
#include "dispextern.h"
#include "blockinput.h"
44
#include "sysstdio.h"
45 46
#include "systime.h"
#include <epaths.h>
47
#include "coding.h"
48
#include "termhooks.h"
49
#include "font.h"
Daniel Colascione's avatar
Daniel Colascione committed
50
#include "pdumper.h"
51

52
#ifdef HAVE_SYS_STAT_H
53
#include <sys/stat.h>
54 55 56 57 58 59 60 61 62
#endif /* HAVE_SYS_STAT_H */

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */

#ifdef HAVE_WINDOW_SYSTEM
#include TERM_HEADER
#endif /* HAVE_WINDOW_SYSTEM */
63

64 65 66 67 68
/* Work around GCC bug 54561.  */
#if GNUC_PREREQ (4, 3, 0)
# pragma GCC diagnostic ignored "-Wclobbered"
#endif

69
#ifdef HAVE_X_WINDOWS
70
typedef struct x_bitmap_record Bitmap_Record;
71
#ifndef USE_CAIRO
Juanma Barranquero's avatar
Juanma Barranquero committed
72
#define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
73
#define PUT_PIXEL XPutPixel
74 75
#define NO_PIXMAP None

76 77
#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	1
78
#endif	/* !USE_CAIRO */
79 80
#endif /* HAVE_X_WINDOWS */

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#ifdef USE_CAIRO
#define GET_PIXEL image_pix_context_get_pixel
#define PUT_PIXEL image_pix_container_put_pixel
#define NO_PIXMAP 0

#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	255

#define RGB_TO_ULONG(r, g, b) (((r) << 16) | ((g) << 8) | (b))
#define ARGB_TO_ULONG(a, r, g, b) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
#define RED_FROM_ULONG(color)	(((color) >> 16) & 0xff)
#define GREEN_FROM_ULONG(color)	(((color) >> 8) & 0xff)
#define BLUE_FROM_ULONG(color)	((color) & 0xff)
#define RED16_FROM_ULONG(color)		(RED_FROM_ULONG (color) * 0x101)
#define GREEN16_FROM_ULONG(color)	(GREEN_FROM_ULONG (color) * 0x101)
#define BLUE16_FROM_ULONG(color)	(BLUE_FROM_ULONG (color) * 0x101)

static unsigned long image_alloc_image_color (struct frame *, struct image *,
					      Lisp_Object, unsigned long);
#endif	/* USE_CAIRO */

102
#ifdef HAVE_NTGUI
103 104 105

/* We need (or want) w32.h only when we're _not_ compiling for Cygwin.  */
#ifdef WINDOWSNT
106
# include "w32common.h"
Daniel Colascione's avatar
Daniel Colascione committed
107
# include "w32.h"
108 109
#endif

110
typedef struct w32_bitmap_record Bitmap_Record;
Juanma Barranquero's avatar
Juanma Barranquero committed
111
#define GET_PIXEL(ximg, x, y) GetPixel (ximg, x, y)
112
#define PUT_PIXEL XPutPixel
113 114
#define NO_PIXMAP 0

115 116
#define PIX_MASK_RETAIN	0
#define PIX_MASK_DRAW	1
117 118 119

#endif /* HAVE_NTGUI */

120 121 122
#ifdef HAVE_NS
typedef struct ns_bitmap_record Bitmap_Record;

Juanma Barranquero's avatar
Juanma Barranquero committed
123
#define GET_PIXEL(ximg, x, y) XGetPixel (ximg, x, y)
124
#define PUT_PIXEL XPutPixel
125 126 127 128 129 130
#define NO_PIXMAP 0

#define PIX_MASK_RETAIN	0

#endif /* HAVE_NS */

131 132 133 134 135 136
#if (defined HAVE_X_WINDOWS \
     && ! (defined HAVE_NTGUI || defined USE_CAIRO || defined HAVE_NS))
/* W32_TODO : Color tables on W32.  */
# define COLOR_TABLE_SUPPORT 1
#endif

137 138 139
static void image_disable_image (struct frame *, struct image *);
static void image_edge_detection (struct frame *, struct image *, Lisp_Object,
                                  Lisp_Object);
140

141 142
static void init_color_table (void);
static unsigned long lookup_rgb_color (struct frame *f, int r, int g, int b);
143
#ifdef COLOR_TABLE_SUPPORT
144 145
static void free_color_table (void);
static unsigned long *colors_in_color_table (int *n);
146 147
#endif

148
#ifdef USE_CAIRO
149

150 151 152 153 154
static Emacs_Pix_Container
image_create_pix_container (struct frame *f, unsigned int width,
			    unsigned int height, unsigned int depth)
{
  Emacs_Pix_Container pimg;
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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
  pimg = xmalloc (sizeof (*pimg));
  pimg->width = width;
  pimg->height = height;
  pimg->bits_per_pixel = depth == 1 ? 8 : 32;
  pimg->bytes_per_line = cairo_format_stride_for_width ((depth == 1
							 ? CAIRO_FORMAT_A8
							 : CAIRO_FORMAT_RGB24),
							width);
  pimg->data = xmalloc (pimg->bytes_per_line * height);

  return pimg;
}

static void
image_pix_container_put_pixel (Emacs_Pix_Container image,
			       int x, int y, unsigned long pixel)
{
  if (image->bits_per_pixel == 32)
    ((uint32_t *)(image->data + y * image->bytes_per_line))[x] = pixel;
  else
    ((uint8_t *)(image->data + y * image->bytes_per_line))[x] = pixel;
}

static unsigned long
image_pix_context_get_pixel (Emacs_Pix_Context image, int x, int y)
{
  if (image->bits_per_pixel == 32)
    return ((uint32_t *)(image->data + y * image->bytes_per_line))[x];
  else
    return ((uint8_t *)(image->data + y * image->bytes_per_line))[x];
}

static Emacs_Pix_Container
image_pix_container_create_from_bitmap_data (struct frame *f,
					     char *data, unsigned int width,
					     unsigned int height,
					     unsigned long fg,
					     unsigned long bg)
{
  Emacs_Pix_Container pimg = image_create_pix_container (f, width, height, 0);
  int bytes_per_line = (width + (CHAR_BIT - 1)) / CHAR_BIT;

  for (int y = 0; y < height; y++)
    {
      for (int x = 0; x < width; x++)
	PUT_PIXEL (pimg, x, y,
		   (data[x / CHAR_BIT] >> (x % CHAR_BIT)) & 1 ? fg : bg);
      data += bytes_per_line;
    }

  return pimg;
}

static cairo_surface_t *
210 211
cr_create_surface_from_pix_containers (Emacs_Pix_Container pimg,
				       Emacs_Pix_Container mask)
212 213 214
{
  cairo_surface_t *surface;

215
  if (mask)
216 217 218 219 220 221 222 223 224 225
    {
      int x, y;

      for (y = 0; y < pimg->height; y++)
	for (x = 0; x < pimg->width; x++)
	  {
	    unsigned long color, alpha;
	    int r, g, b;

	    color = GET_PIXEL (pimg, x, y);
226
	    alpha = GET_PIXEL (mask, x, y);
227 228 229 230 231
	    r = (RED_FROM_ULONG (color) * alpha + 0x7f) / 0xff;
	    g = (GREEN_FROM_ULONG (color) * alpha + 0x7f) / 0xff;
	    b = (BLUE_FROM_ULONG (color) * alpha + 0x7f) / 0xff;
	    PUT_PIXEL (pimg, x, y, ARGB_TO_ULONG (alpha, r, g, b));
	  }
232 233
      xfree (mask->data);
      mask->data = NULL;
234 235
    }
  surface = cairo_image_surface_create_for_data ((unsigned char *) pimg->data,
236
						 (mask ? CAIRO_FORMAT_ARGB32
237 238 239
						  : CAIRO_FORMAT_RGB24),
						 pimg->width, pimg->height,
						 pimg->bytes_per_line);
240
  static const cairo_user_data_key_t key;
241 242 243 244 245 246
  cairo_surface_set_user_data (surface, &key, pimg->data, xfree);
  pimg->data = NULL;

  return surface;
}

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
static void
cr_put_image_to_cr_data (struct image *img)
{
  cairo_pattern_t *pattern = NULL;
  cairo_surface_t *surface = cr_create_surface_from_pix_containers (img->pixmap,
								    img->mask);
  if (surface)
    {
      pattern = cairo_pattern_create_for_surface (surface);
      if (img->cr_data)
	{
	  cairo_matrix_t matrix;
	  cairo_pattern_get_matrix (img->cr_data, &matrix);
	  cairo_pattern_set_matrix (pattern, &matrix);
	  cairo_pattern_destroy (img->cr_data);
	}
      cairo_surface_destroy (surface);
    }

  img->cr_data = pattern;
}

269
#endif	/* USE_CAIRO */
270

271
#ifdef HAVE_NS
Paul Eggert's avatar
Paul Eggert committed
272
/* Use with images created by ns_image_for_XPM.  */
273
static unsigned long
274
XGetPixel (Emacs_Pix_Container image, int x, int y)
275
{
276
  return ns_get_pixel (image, x, y);
277 278
}

Paul Eggert's avatar
Paul Eggert committed
279 280
/* Use with images created by ns_image_for_XPM; alpha set to 1;
   pixel is assumed to be in RGB form.  */
281
static void
282
XPutPixel (Emacs_Pix_Container image, int x, int y, unsigned long pixel)
283
{
284
  ns_put_pixel (image, x, y, pixel);
285 286 287
}
#endif /* HAVE_NS */

288 289 290 291 292 293 294 295 296 297
/* 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 image_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.  */
298 299 300

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

301
#ifdef HAVE_X_WINDOWS
302
static int
Dmitry Antipov's avatar
Dmitry Antipov committed
303
x_bitmap_height (struct frame *f, ptrdiff_t id)
304
{
305
  return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].height;
306 307
}

308
static int
Dmitry Antipov's avatar
Dmitry Antipov committed
309
x_bitmap_width (struct frame *f, ptrdiff_t id)
310
{
311
  return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].width;
312
}
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

#ifdef USE_CAIRO
cairo_pattern_t *
x_bitmap_stipple (struct frame *f, Pixmap pixmap)
{
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);

  for (ptrdiff_t i = 0; i < dpyinfo->bitmaps_last; i++)
    {
      struct x_bitmap_record *bm = dpyinfo->bitmaps + i;

      if (bm->refcount && bm->pixmap == pixmap && bm->depth == 1)
	{
	  if (bm->stipple == NULL)
	    {
	      cairo_surface_t *surface
		= cairo_xlib_surface_create_for_bitmap (FRAME_X_DISPLAY (f),
							pixmap,
							FRAME_X_SCREEN (f),
							bm->width, bm->height);
	      cairo_pattern_t *pattern
		= cairo_pattern_create_for_surface (surface);
	      cairo_surface_destroy (surface);
	      cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT);
	      bm->stipple = pattern;
	    }

	  return bm->stipple;
	}
    }

  return NULL;
}

#endif	/* USE_CAIRO */
348
#endif
349 350

#if defined (HAVE_X_WINDOWS) || defined (HAVE_NTGUI)
351
ptrdiff_t
352
image_bitmap_pixmap (struct frame *f, ptrdiff_t id)
353
{
354
  /* HAVE_NTGUI needs the explicit cast here.  */
355
  return (ptrdiff_t) FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
356 357 358 359 360
}
#endif

#ifdef HAVE_X_WINDOWS
int
Dmitry Antipov's avatar
Dmitry Antipov committed
361
x_bitmap_mask (struct frame *f, ptrdiff_t id)
362
{
363
  return FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].mask;
364 365 366 367 368
}
#endif

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

369
static ptrdiff_t
370
image_allocate_bitmap_record (struct frame *f)
371
{
372
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
373
  ptrdiff_t i;
374 375 376 377 378 379 380 381

  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;

Paul Eggert's avatar
Paul Eggert committed
382 383 384
  dpyinfo->bitmaps =
    xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
	     10, -1, sizeof *dpyinfo->bitmaps);
385 386 387 388 389 390
  return ++dpyinfo->bitmaps_last;
}

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

void
391
image_reference_bitmap (struct frame *f, ptrdiff_t id)
392
{
393
  ++FRAME_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
394 395 396 397
}

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

398
ptrdiff_t
399 400
image_create_bitmap_from_data (struct frame *f, char *bits,
                               unsigned int width, unsigned int height)
401
{
402
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
403
  ptrdiff_t id;
404 405 406

#ifdef HAVE_X_WINDOWS
  Pixmap bitmap;
407
  bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
408 409 410 411 412 413
				  bits, width, height);
  if (! bitmap)
    return -1;
#endif /* HAVE_X_WINDOWS */

#ifdef HAVE_NTGUI
414
  Lisp_Object frame UNINIT;	/* The value is not used.  */
415
  Emacs_Pixmap bitmap;
416
  bitmap = CreateBitmap (width, height,
417 418
			 FRAME_DISPLAY_INFO (XFRAME (frame))->n_planes,
			 FRAME_DISPLAY_INFO (XFRAME (frame))->n_cbits,
419 420 421 422 423
			 bits);
  if (! bitmap)
    return -1;
#endif /* HAVE_NTGUI */

424
#ifdef HAVE_NS
425
  void *bitmap = ns_image_from_XBM (bits, width, height, 0, 0);
426 427 428 429
  if (!bitmap)
      return -1;
#endif

430
  id = image_allocate_bitmap_record (f);
431

432 433 434 435 436
#ifdef HAVE_NS
  dpyinfo->bitmaps[id - 1].img = bitmap;
  dpyinfo->bitmaps[id - 1].depth = 1;
#endif

437 438 439 440 441 442 443
  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;
444
  dpyinfo->bitmaps[id - 1].have_mask = false;
445
  dpyinfo->bitmaps[id - 1].depth = 1;
446 447 448
#ifdef USE_CAIRO
  dpyinfo->bitmaps[id - 1].stipple = NULL;
#endif	/* USE_CAIRO */
449 450 451 452 453 454 455 456 457 458 459 460 461
#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.  */

462
ptrdiff_t
463
image_create_bitmap_from_file (struct frame *f, Lisp_Object file)
464 465 466
{
#ifdef HAVE_NTGUI
  return -1;  /* W32_TODO : bitmap support */
467
#else
468
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
469
#endif
470

471
#ifdef HAVE_NS
472
  ptrdiff_t id;
473
  void *bitmap = ns_image_from_file (file);
474 475 476 477 478

  if (!bitmap)
      return -1;


479
  id = image_allocate_bitmap_record (f);
480 481
  dpyinfo->bitmaps[id - 1].img = bitmap;
  dpyinfo->bitmaps[id - 1].refcount = 1;
482
  dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
483
  dpyinfo->bitmaps[id - 1].depth = 1;
484 485
  dpyinfo->bitmaps[id - 1].height = ns_image_width (bitmap);
  dpyinfo->bitmaps[id - 1].width = ns_image_height (bitmap);
486 487 488
  return id;
#endif

489 490 491
#ifdef HAVE_X_WINDOWS
  unsigned int width, height;
  Pixmap bitmap;
492 493
  int xhot, yhot, result;
  ptrdiff_t id;
494 495 496 497 498 499 500 501
  Lisp_Object found;
  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
502
	  && !strcmp (dpyinfo->bitmaps[id].file, SSDATA (file)))
503 504 505 506 507 508 509
	{
	  ++dpyinfo->bitmaps[id].refcount;
	  return id + 1;
	}
    }

  /* Search bitmap-file-path for the file, if appropriate.  */
510
  if (openp (Vx_bitmap_file_path, file, Qnil, &found,
511
	     make_fixnum (R_OK), false)
512
      < 0)
513 514
    return -1;

515
  filename = SSDATA (found);
516

517
  result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
518 519 520 521
			    filename, &width, &height, &bitmap, &xhot, &yhot);
  if (result != BitmapSuccess)
    return -1;

522
  id = image_allocate_bitmap_record (f);
523
  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
524
  dpyinfo->bitmaps[id - 1].have_mask = false;
525
  dpyinfo->bitmaps[id - 1].refcount = 1;
526
  dpyinfo->bitmaps[id - 1].file = xlispstrdup (file);
527 528 529
  dpyinfo->bitmaps[id - 1].depth = 1;
  dpyinfo->bitmaps[id - 1].height = height;
  dpyinfo->bitmaps[id - 1].width = width;
530 531 532
#ifdef USE_CAIRO
  dpyinfo->bitmaps[id - 1].stipple = NULL;
#endif	/* USE_CAIRO */
533 534 535 536 537 538 539 540

  return id;
#endif /* HAVE_X_WINDOWS */
}

/* Free bitmap B.  */

static void
541
free_bitmap_record (Display_Info *dpyinfo, Bitmap_Record *bm)
542 543 544 545 546
{
#ifdef HAVE_X_WINDOWS
  XFreePixmap (dpyinfo->display, bm->pixmap);
  if (bm->have_mask)
    XFreePixmap (dpyinfo->display, bm->mask);
547 548 549 550
#ifdef USE_CAIRO
  if (bm->stipple)
    cairo_pattern_destroy (bm->stipple);
#endif	/* USE_CAIRO */
551 552 553 554 555 556
#endif /* HAVE_X_WINDOWS */

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

557
#ifdef HAVE_NS
558
  ns_release_object (bm->img);
559 560
#endif

561 562 563 564 565 566 567 568 569 570
  if (bm->file)
    {
      xfree (bm->file);
      bm->file = NULL;
    }
}

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

void
571
image_destroy_bitmap (struct frame *f, ptrdiff_t id)
572
{
573
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
574 575 576 577 578 579 580

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

      if (--bm->refcount == 0)
	{
581
	  block_input ();
582
	  free_bitmap_record (dpyinfo, bm);
583
	  unblock_input ();
584 585 586 587 588 589 590
	}
    }
}

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

void
591
image_destroy_all_bitmaps (Display_Info *dpyinfo)
592
{
593
  ptrdiff_t i;
594 595 596 597
  Bitmap_Record *bm = dpyinfo->bitmaps;

  for (i = 0; i < dpyinfo->bitmaps_last; i++, bm++)
    if (bm->refcount > 0)
598
      free_bitmap_record (dpyinfo, bm);
599 600 601 602

  dpyinfo->bitmaps_last = 0;
}

603
#ifndef HAVE_XRENDER
604
/* Required for the definition of image_create_x_image_and_pixmap_1 below.  */
605 606 607
typedef void Picture;
#endif

608
static bool image_create_x_image_and_pixmap_1 (struct frame *, int, int, int,
609 610 611
                                               Emacs_Pix_Container *,
                                               Emacs_Pixmap *, Picture *);
static void image_destroy_x_image (Emacs_Pix_Container);
612

613
#ifdef HAVE_NTGUI
614 615 616 617
static HDC image_get_x_image_or_dc (struct frame *, struct image *,
                                    bool, HGDIOBJ *);
static void image_unget_x_image_or_dc (struct image *, bool,
                                       HDC, HGDIOBJ);
618
#else
619 620 621
static Emacs_Pix_Container image_get_x_image (struct frame *, struct image *,
                                              bool);
static void image_unget_x_image (struct image *, bool, Emacs_Pix_Container);
622 623 624 625 626 627
#define image_get_x_image_or_dc(f, img, mask_p, dummy)	\
  image_get_x_image (f, img, mask_p)
#define image_unget_x_image_or_dc(img, mask_p, ximg, dummy)	\
  image_unget_x_image (img, mask_p, ximg)
#endif

628 629
#ifdef HAVE_X_WINDOWS

630
#ifndef USE_CAIRO
631
static void image_sync_to_pixmaps (struct frame *, struct image *);
632
#endif	/* !USE_CAIRO */
633

634 635 636
/* We are working on X-specific data structures here even with cairo.
   So we use X-specific versions of image construction/destruction
   functions and inline the specific case of four_corners_best.  */
637

638 639 640
static bool x_create_x_image_and_pixmap (struct frame *, int, int, int,
					 XImage **, Pixmap *);
static void x_destroy_x_image (XImage *);
641 642 643 644

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

645
void
646
x_create_bitmap_mask (struct frame *f, ptrdiff_t id)
647 648
{
  Pixmap pixmap, mask;
649
  XImage *ximg, *mask_img;
650
  unsigned long width, height;
651
  bool result;
652
  unsigned long bg UNINIT;
653 654 655
  unsigned long x, y, xp, xm, yp, ym;
  GC gc;

656
  Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
657 658

  if (!(id > 0))
659
    return;
660

661
  pixmap = image_bitmap_pixmap (f, id);
662 663 664
  width = x_bitmap_width (f, id);
  height = x_bitmap_height (f, id);

665
  block_input ();
666 667 668 669 670
  ximg = XGetImage (FRAME_X_DISPLAY (f), pixmap, 0, 0, width, height,
		    ~0, ZPixmap);

  if (!ximg)
    {
671
      unblock_input ();
672
      return;
673 674
    }

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

677
  unblock_input ();
678 679 680
  if (!result)
    {
      XDestroyImage (ximg);
681
      return;
682 683
    }

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
  unsigned long corner_pixels[4];
  corner_pixels[0] = XGetPixel (ximg, 0, 0);
  corner_pixels[1] = XGetPixel (ximg, width - 1, 0);
  corner_pixels[2] = XGetPixel (ximg, width - 1, height - 1);
  corner_pixels[3] = XGetPixel (ximg, 0, height - 1);
  int i, best_count;
  for (i = best_count = 0; i < 4; ++i)
    {
      int j, n;

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

      if (n > best_count)
	bg = corner_pixels[i], best_count = n;
    }
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724

  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);
	}
    }

725
  eassert (input_blocked_p ());
726 727 728 729 730
  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);

731
  dpyinfo->bitmaps[id - 1].have_mask = true;
732 733 734
  dpyinfo->bitmaps[id - 1].mask = mask;

  XDestroyImage (ximg);
735
  x_destroy_x_image (mask_img);
736 737 738 739 740 741 742 743
}

#endif /* HAVE_X_WINDOWS */

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

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
/* Each image format (JPEG, TIFF, ...) supported is described by
   a structure of the type below.  */

struct image_type
{
  /* Index of a symbol uniquely identifying the image type, e.g., 'jpeg'.  */
  int type;

  /* Check that SPEC is a valid image specification for the given
     image type.  Value is true if SPEC is valid.  */
  bool (*valid_p) (Lisp_Object spec);

  /* Load IMG which is used on frame F from information contained in
     IMG->spec.  Value is true if successful.  */
  bool (*load) (struct frame *f, struct image *img);

  /* Free resources of image IMG which is used on frame F.  */
  void (*free) (struct frame *f, struct image *img);

763
#ifdef WINDOWSNT
764 765 766
  /* Initialization function (used for dynamic loading of image
     libraries on Windows), or NULL if none.  */
  bool (*init) (void);
767 768 769 770 771
  /* An initializer for the init field.  */
# define IMAGE_TYPE_INIT(f) f
#else
# define IMAGE_TYPE_INIT(f)
#endif
772 773
};

774
/* Forward function prototypes.  */
775

776
static struct image_type const *lookup_image_type (Lisp_Object);
777 778 779
static void image_laplace (struct frame *, struct image *);
static void image_emboss (struct frame *, struct image *);
static void image_build_heuristic_mask (struct frame *, struct image *,
Daniel Colascione's avatar
Daniel Colascione committed
780
                                    Lisp_Object);
781

782 783
static void
add_image_type (Lisp_Object type)
784
{
785
  Vimage_types = Fcons (type, Vimage_types);
786 787 788
}


789
/* Value is true if OBJECT is a valid Lisp image specification.  A
790 791 792 793 794 795
   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.  */

796
bool
797
valid_image_p (Lisp_Object object)
798 799 800
{
  if (IMAGEP (object))
    {
801 802 803
      Lisp_Object tail = XCDR (object);
      FOR_EACH_TAIL_SAFE (tail)
	if (EQ (XCAR (tail), QCtype))
804
	  {
805 806
	    tail = XCDR (tail);
	    if (CONSP (tail))
807
	      {
808
		struct image_type const *type = lookup_image_type (XCAR (tail));
809
		if (type)
810
		  return type->valid_p (object);
811 812 813 814 815
	      }
	    break;
	  }
    }

816
  return false;
817 818 819
}


Paul Eggert's avatar
Paul Eggert committed
820
/* Log error message with format string FORMAT and trailing arguments.
821 822 823 824 825 826
   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
Paul Eggert's avatar
Paul Eggert committed
827
image_error (const char *format, ...)
828
{
Paul Eggert's avatar
Paul Eggert committed
829 830 831 832
  va_list ap;
  va_start (ap, format);
  vadd_to_log (format, ap);
  va_end (ap);
833 834
}

835 836 837
static void
image_size_error (void)
{
838
  image_error ("Invalid image size (see `max-image-size')");
839
}
840 841 842 843 844 845 846 847 848 849 850 851 852


/***********************************************************************
			 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,
853
  IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR,
854 855 856 857 858 859 860 861 862 863 864 865 866
  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.  */
867
  const char *name;
868 869 870 871

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

872 873
  /* True means key must be present.  */
  bool mandatory_p;
874 875 876 877 878 879 880 881 882 883 884 885 886

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

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


/* 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
887
   allowed keyword/value pairs.  Value is true if SPEC is valid.  */
888

889
static bool
890 891
parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
		  int nkeywords, Lisp_Object type)
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
{
  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)
918
	if (strcmp (keywords[i].name, SSDATA (SYMBOL_NAME (key))) == 0)
919 920 921 922 923 924 925 926 927 928
	  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;
      if (keywords[i].count > 1)
	return 0;
929
      ++keywords[i].count;
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

      /* 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:
950
	  if (! RANGED_FIXNUMP (1, value, INT_MAX))
951 952 953
	    return 0;
	  break;

954
	case IMAGE_NON_NEGATIVE_INTEGER_VALUE_OR_PAIR:
955
	  if (RANGED_FIXNUMP (0, value, INT_MAX))
956 957
	    break;
	  if (CONSP (value)
958 959
	      && RANGED_FIXNUMP (0, XCAR (value), INT_MAX)
	      && RANGED_FIXNUMP (0, XCDR (value), INT_MAX))
960 961 962 963 964 965
	    break;
	  return 0;

	case IMAGE_ASCENT_VALUE:
	  if (SYMBOLP (value) && EQ (value, Qcenter))
	    break;
966
	  else if (RANGED_FIXNUMP (0, value, 100))
967 968 969 970
	    break;
	  return 0;

	case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
971 972 973
	  /* Unlike the other integer-related cases, this one does not
	     verify that VALUE fits in 'int'.  This is because callers
	     want EMACS_INT.  */
Tom Tromey's avatar
Tom Tromey committed
974
	  if (!FIXNUMP (value) || XFIXNUM (value) < 0)
975 976 977 978 979 980 981 982
	    return 0;
	  break;

	case IMAGE_DONT_CHECK_VALUE_TYPE:
	  break;

	case IMAGE_FUNCTION_VALUE:
	  value = indirect_function (value);
983
	  if (FUNCTIONP (value))
984 985 986 987
	    break;
	  return 0;

	case IMAGE_NUMBER_VALUE:
988
	  if (! NUMBERP (value))
989 990 991 992
	    return 0;
	  break;

	case IMAGE_INTEGER_VALUE:
993
	  if (! TYPE_RANGED_FIXNUMP (int, value))
994 995 996 997 998 999 1000 1001 1002
	    return 0;
	  break;

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

	default:
1003
	  emacs_abort ();
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
	  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
1021 1022
   if KEY is not present in SPEC.  Set *FOUND depending on whether KEY
   was found in SPEC.  */
1023 1024

static Lisp_Object
1025
image_spec_value (Lisp_Object spec, Lisp_Object key, bool *found)
1026 1027 1028
{
  Lisp_Object tail;

1029
  eassert (valid_image_p (spec));
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

  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.  */)
1055
  (Lisp_Object spec, Lisp_Object pixels, Lisp_Object frame)
1056 1057 1058 1059 1060 1061
{
  Lisp_Object size;

  size = Qnil;
  if (valid_image_p (spec))
    {
1062
      struct frame *f = decode_window_system_frame (frame);
1063
      ptrdiff_t id = lookup_image (f, spec);
1064 1065 1066 1067 1068 1069 1070 1071
      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
1072
	size = Fcons (make_fixnum (width), make_fixnum (height));
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    }
  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.  */)
1085
  (Lisp_Object spec, Lisp_Object frame)
1086 1087 1088 1089 1090 1091
{
  Lisp_Object mask;

  mask = Qnil;
  if (valid_image_p (spec))
    {
1092
      struct frame *f = decode_window_system_frame (frame);
1093
      ptrdiff_t id = lookup_image (f, spec);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
      struct image *img = IMAGE_FROM_ID (f, id);
      if (img->mask)
	mask = Qt;
    }
  else
    error ("Invalid image specification");

  return mask;
}

1104 1105
DEFUN ("image-metadata", Fimage_metadata, Simage_metadata, 1, 2, 0,
       doc: /* Return metadata for image SPEC.
1106 1107
FRAME is the frame on which the image will be displayed.  FRAME nil
or omitted means use the selected frame.  */)
1108
  (Lisp_Object spec, Lisp_Object frame)
1109 1110 1111 1112 1113 1114
{
  Lisp_Object ext;

  ext = Qnil;
  if (valid_image_p (spec))
    {
1115
      struct frame *f = decode_window_system_frame (frame);
1116
      ptrdiff_t id = lookup_image (f, spec);
1117
      struct image *img = IMAGE_FROM_ID (f, id);
1118
      ext = img->lisp_data;
1119 1120 1121 1122 1123
    }

  return ext;
}

1124 1125 1126 1127 1128

/***********************************************************************
		 Image type independent image structures
 ***********************************************************************/

1129
#define MAX_IMAGE_SIZE 10.0
1130 1131 1132 1133
/* Allocate and return a new image structure for image specification
   SPEC.  SPEC has a hash value of HASH.  */

static struct image *
1134
make_image (Lisp_Object spec, EMACS_UINT hash)
1135
{
Dmitry Antipov's avatar
Dmitry Antipov committed
1136
  struct image *img = xzalloc (sizeof *img);
1137
  Lisp_Object file = image_spec_value (spec, QCfile, NULL);
1138

1139
  eassert (valid_image_p (spec));
1140
  img->dependencies = NILP (file) ? Qnil : list1 (file);
1141
  img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
1142
  eassert (img->type != NULL);
1143
  img->spec = spec;
1144
  img->lisp_data = Qnil;
1145 1146
  img->ascent = DEFAULT_IMAGE_ASCENT;
  img->hash = hash;
1147
  img->corners[BOT_CORNER] = -1;  /* Full image */
1148 1149 1150 1151 1152 1153 1154
  return img;
}


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

static void
1155
free_image (struct frame *f, struct image *img)
1156 1157 1158
{
  if (img)
    {
1159
      struct image_cache *c = FRAME_IMAGE_CACHE (f);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

      /* 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;

1172
#if !defined USE_CAIRO && defined HAVE_XRENDER
1173 1174 1175 1176 1177 1178
      if (img->picture)
        XRenderFreePicture (FRAME_X_DISPLAY (f), img->picture);
      if (img->mask_picture)
        XRenderFreePicture (FRAME_X_DISPLAY (f), img->mask_picture);
#endif

1179 1180 1181 1182 1183
      /* Windows NT redefines 'free', but in this file, we need to
         avoid the redefinition.  */
#ifdef WINDOWSNT
#undef free
#endif
1184 1185 1186 1187 1188 1189
      /* Free resources, then free IMG.  */
      img->type->free (f, img);
      xfree (img);
    }
}

1190
/* Return true if the given widths and heights are valid for display.  */
1191

1192
static bool
1193
check_image_size (struct frame *f, int width, int height)
1194
{
1195
  int w, h;
1196

1197
  if (width <= 0 || height <= 0)
1198 1199
    return 0;

1200
  if (FIXNUMP (Vmax_image_size))
Tom Tromey's avatar
Tom Tromey committed
1201 1202
    return (width <= XFIXNUM (Vmax_image_size)
	    && height <= XFIXNUM (Vmax_image_size));
1203 1204
  else if (FLOATP (Vmax_image_size))
    {
1205 1206 1207 1208 1209 1210 1211
      if (f != NULL)
	{
	  w = FRAME_PIXEL_WIDTH (f);
	  h = FRAME_PIXEL_HEIGHT (f);
	}
      else
	w = h = 1024;  /* Arbitrary size for unknown frame. */
1212 1213
      return (width <= XFLOAT_DATA (Vmax_image_size) * w
	      && height <= XFLOAT_DATA (Vmax_image_size) * h);
1214 1215 1216
    }
  else
    return 1;
1217
}
1218 1219 1220 1221 1222

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

void
1223
prepare_image_for_display (struct frame *f, struct image *img)
1224 1225
{
  /* We're about to display IMG, so set its timestamp to `now'.  */
1226
  img->timestamp = current_timespec ();
1227 1228 1229 1230

  /* 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)
1231
    img->load_failed_p = ! img->type->load (f, img);
1232

1233
#ifdef USE_CAIRO
1234
  if (!img->load_failed_p)
1235
    {
1236 1237 1238
      block_input ();
      if (img->cr_data == NULL || (cairo_pattern_get_type (img->cr_data)
				   != CAIRO_PATTERN_TYPE_SURFACE))
1239
	{
1240 1241 1242 1243 1244 1245
	  cr_put_image_to_cr_data (img);
	  if (img->cr_data == NULL)
	    {
	      img->load_failed_p = 1;
	      img->type->free (f, img);
	    }
1246
	}
1247
      unblock_input ();
1248 1249
    }
#elif defined HAVE_X_WINDOWS
1250 1251 1252 1253 1254 1255 1256
  if (!img->load_failed_p)
    {
      block_input ();
      image_sync_to_pixmaps (f, img);
      unblock_input ();
    }
#endif
1257 1258