]> code.delx.au - gnu-emacs/blob - lisp/image.el
; Merge from origin/emacs-25
[gnu-emacs] / lisp / image.el
1 ;;; image.el --- image API
2
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: multimedia
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28
29 (defgroup image ()
30 "Image support."
31 :group 'multimedia)
32
33 (defalias 'image-refresh 'image-flush)
34
35 (defconst image-type-header-regexps
36 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
37 ("\\`P[1-6]\\(?:\
38 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[[:space:]]\\)+\
39 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[0-9]\\)+\
40 \\)\\{2\\}" . pbm)
41 ("\\`GIF8[79]a" . gif)
42 ("\\`\x89PNG\r\n\x1a\n" . png)
43 ("\\`[\t\n\r ]*#define \\([a-z0-9_]+\\)_width [0-9]+\n\
44 #define \\1_height [0-9]+\n\\(\
45 #define \\1_x_hot [0-9]+\n\
46 #define \\1_y_hot [0-9]+\n\\)?\
47 static \\(unsigned \\)?char \\1_bits" . xbm)
48 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
49 ("\\`[\t\n\r ]*%!PS" . postscript)
50 ("\\`\xff\xd8" . jpeg) ; used to be (image-jpeg-p . jpeg)
51 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
52 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
53 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
54 comment-re "*"
55 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
56 "[Ss][Vv][Gg]"))
57 . svg)
58 )
59 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
60 When the first bytes of an image file match REGEXP, it is assumed to
61 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
62 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
63 with one argument, a string containing the image data. If PREDICATE returns
64 a non-nil value, TYPE is the image's type.")
65
66 (defvar image-type-file-name-regexps
67 '(("\\.png\\'" . png)
68 ("\\.gif\\'" . gif)
69 ("\\.jpe?g\\'" . jpeg)
70 ("\\.bmp\\'" . bmp)
71 ("\\.xpm\\'" . xpm)
72 ("\\.pbm\\'" . pbm)
73 ("\\.xbm\\'" . xbm)
74 ("\\.ps\\'" . postscript)
75 ("\\.tiff?\\'" . tiff)
76 ("\\.svgz?\\'" . svg)
77 )
78 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
79 When the name of an image file match REGEXP, it is assumed to
80 be of image type IMAGE-TYPE.")
81
82 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
83 ;; of content autodetection. Their contents are just C code, so it is
84 ;; easy to generate false matches.
85 (defvar image-type-auto-detectable
86 '((pbm . t)
87 (xbm . nil)
88 (bmp . maybe)
89 (gif . maybe)
90 (png . maybe)
91 (xpm . nil)
92 (jpeg . maybe)
93 (tiff . maybe)
94 (svg . maybe)
95 (postscript . nil))
96 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
97 \(See `image-type-auto-detected-p').
98
99 AUTODETECT can be
100 - t always auto-detect.
101 - nil never auto-detect.
102 - maybe auto-detect only if the image type is available
103 (see `image-type-available-p').")
104
105 (defvar image-format-suffixes
106 '((image/x-icon "ico"))
107 "An alist associating image types with file name suffixes.
108 This is used as a hint by the ImageMagick library when detecting
109 the type of image data (that does not have an associated file name).
110 Each element has the form (MIME-CONTENT-TYPE EXTENSION).
111 If `create-image' is called with a :format attribute whose value
112 equals a content-type found in this list, the ImageMagick library is
113 told that the data would have the associated suffix if saved to a file.")
114
115 (defcustom image-load-path
116 (list (file-name-as-directory (expand-file-name "images" data-directory))
117 'data-directory 'load-path)
118 "List of locations in which to search for image files.
119 If an element is a string, it defines a directory to search.
120 If an element is a variable symbol whose value is a string, that
121 value defines a directory to search.
122 If an element is a variable symbol whose value is a list, the
123 value is used as a list of directories to search.
124
125 Subdirectories are not automatically included in the search."
126 :type '(repeat (choice directory variable))
127 :initialize 'custom-initialize-delay)
128
129 (defcustom image-scaling-factor 'auto
130 "When displaying images, apply this scaling factor before displaying.
131 This is not supported for all image types, and is mostly useful
132 when you have a high-resolution monitor.
133 The value is either a floating point number (where numbers higher
134 than 1 means to increase the size and lower means to shrink the
135 size), or the symbol `auto', which will compute a scaling factor
136 based on the font pixel size."
137 :type '(choice number
138 (const :tag "Automatically compute" auto))
139 :group 'image
140 :version "25.2")
141
142 ;; Map put into text properties on images.
143 (defvar image-map
144 (let ((map (make-sparse-keymap)))
145 (define-key map "-" 'image-decrease-size)
146 (define-key map "+" 'image-increase-size)
147 (define-key map "r" 'image-rotate)
148 (define-key map "o" 'image-save)
149 map))
150
151 (defun image-load-path-for-library (library image &optional path no-error)
152 "Return a suitable search path for images used by LIBRARY.
153
154 It searches for IMAGE in `image-load-path' (excluding
155 \"`data-directory'/images\") and `load-path', followed by a path
156 suitable for LIBRARY, which includes \"../../etc/images\" and
157 \"../etc/images\" relative to the library file itself, and then
158 in \"`data-directory'/images\".
159
160 Then this function returns a list of directories which contains
161 first the directory in which IMAGE was found, followed by the
162 value of `load-path'. If PATH is given, it is used instead of
163 `load-path'.
164
165 If NO-ERROR is non-nil and a suitable path can't be found, don't
166 signal an error. Instead, return a list of directories as before,
167 except that nil appears in place of the image directory.
168
169 Here is an example that uses a common idiom to provide
170 compatibility with versions of Emacs that lack the variable
171 `image-load-path':
172
173 ;; Shush compiler.
174 (defvar image-load-path)
175
176 (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
177 (image-load-path (cons (car load-path)
178 (when (boundp \\='image-load-path)
179 image-load-path))))
180 (mh-tool-bar-folder-buttons-init))"
181 (unless library (error "No library specified"))
182 (unless image (error "No image specified"))
183 (let (image-directory image-directory-load-path)
184 ;; Check for images in image-load-path or load-path.
185 (let ((img image)
186 (dir (or
187 ;; Images in image-load-path.
188 (image-search-load-path image)
189 ;; Images in load-path.
190 (locate-library image)))
191 parent)
192 ;; Since the image might be in a nested directory (for
193 ;; example, mail/attach.pbm), adjust `image-directory'
194 ;; accordingly.
195 (when dir
196 (setq dir (file-name-directory dir))
197 (while (setq parent (file-name-directory img))
198 (setq img (directory-file-name parent)
199 dir (expand-file-name "../" dir))))
200 (setq image-directory-load-path dir))
201
202 ;; If `image-directory-load-path' isn't Emacs's image directory,
203 ;; it's probably a user preference, so use it. Then use a
204 ;; relative setting if possible; otherwise, use
205 ;; `image-directory-load-path'.
206 (cond
207 ;; User-modified image-load-path?
208 ((and image-directory-load-path
209 (not (equal image-directory-load-path
210 (file-name-as-directory
211 (expand-file-name "images" data-directory)))))
212 (setq image-directory image-directory-load-path))
213 ;; Try relative setting.
214 ((let (library-name d1ei d2ei)
215 ;; First, find library in the load-path.
216 (setq library-name (locate-library library))
217 (if (not library-name)
218 (error "Cannot find library %s in load-path" library))
219 ;; And then set image-directory relative to that.
220 (setq
221 ;; Go down 2 levels.
222 d2ei (file-name-as-directory
223 (expand-file-name
224 (concat (file-name-directory library-name) "../../etc/images")))
225 ;; Go down 1 level.
226 d1ei (file-name-as-directory
227 (expand-file-name
228 (concat (file-name-directory library-name) "../etc/images"))))
229 (setq image-directory
230 ;; Set it to nil if image is not found.
231 (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
232 ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
233 ;; Use Emacs's image directory.
234 (image-directory-load-path
235 (setq image-directory image-directory-load-path))
236 (no-error
237 (message "Could not find image %s for library %s" image library))
238 (t
239 (error "Could not find image %s for library %s" image library)))
240
241 ;; Return an augmented `path' or `load-path'.
242 (nconc (list image-directory)
243 (delete image-directory (copy-sequence (or path load-path))))))
244
245
246 ;; Used to be in image-type-header-regexps, but now not used anywhere
247 ;; (since 2009-08-28).
248 (defun image-jpeg-p (data)
249 "Value is non-nil if DATA, a string, consists of JFIF image data.
250 We accept the tag Exif because that is the same format."
251 (setq data (ignore-errors (string-to-unibyte data)))
252 (when (and data (string-match-p "\\`\xff\xd8" data))
253 (catch 'jfif
254 (let ((len (length data)) (i 2))
255 (while (< i len)
256 (when (/= (aref data i) #xff)
257 (throw 'jfif nil))
258 (setq i (1+ i))
259 (when (>= (+ i 2) len)
260 (throw 'jfif nil))
261 (let ((nbytes (+ (lsh (aref data (+ i 1)) 8)
262 (aref data (+ i 2))))
263 (code (aref data i)))
264 (when (and (>= code #xe0) (<= code #xef))
265 ;; APP0 LEN1 LEN2 "JFIF\0"
266 (throw 'jfif
267 (string-match-p "JFIF\\|Exif"
268 (substring data i (min (+ i nbytes) len)))))
269 (setq i (+ i 1 nbytes))))))))
270
271
272 ;;;###autoload
273 (defun image-type-from-data (data)
274 "Determine the image type from image data DATA.
275 Value is a symbol specifying the image type or nil if type cannot
276 be determined."
277 (let ((types image-type-header-regexps)
278 type)
279 (while types
280 (let ((regexp (car (car types)))
281 (image-type (cdr (car types))))
282 (if (or (and (symbolp image-type)
283 (string-match-p regexp data))
284 (and (consp image-type)
285 (funcall (car image-type) data)
286 (setq image-type (cdr image-type))))
287 (setq type image-type
288 types nil)
289 (setq types (cdr types)))))
290 type))
291
292
293 ;;;###autoload
294 (defun image-type-from-buffer ()
295 "Determine the image type from data in the current buffer.
296 Value is a symbol specifying the image type or nil if type cannot
297 be determined."
298 (let ((types image-type-header-regexps)
299 type
300 (opoint (point)))
301 (goto-char (point-min))
302 (while types
303 (let ((regexp (car (car types)))
304 (image-type (cdr (car types)))
305 data)
306 (if (or (and (symbolp image-type)
307 (looking-at-p regexp))
308 (and (consp image-type)
309 (funcall (car image-type)
310 (or data
311 (setq data
312 (buffer-substring
313 (point-min)
314 (min (point-max)
315 (+ (point-min) 256))))))
316 (setq image-type (cdr image-type))))
317 (setq type image-type
318 types nil)
319 (setq types (cdr types)))))
320 (goto-char opoint)
321 (and type
322 (boundp 'image-types)
323 (memq type image-types)
324 type)))
325
326
327 ;;;###autoload
328 (defun image-type-from-file-header (file)
329 "Determine the type of image file FILE from its first few bytes.
330 Value is a symbol specifying the image type, or nil if type cannot
331 be determined."
332 (unless (or (file-readable-p file)
333 (file-name-absolute-p file))
334 (setq file (image-search-load-path file)))
335 (and file
336 (file-readable-p file)
337 (with-temp-buffer
338 (set-buffer-multibyte nil)
339 (insert-file-contents-literally file nil 0 256)
340 (image-type-from-buffer))))
341
342
343 ;;;###autoload
344 (defun image-type-from-file-name (file)
345 "Determine the type of image file FILE from its name.
346 Value is a symbol specifying the image type, or nil if type cannot
347 be determined."
348 (let (type first)
349 (catch 'found
350 (dolist (elem image-type-file-name-regexps first)
351 (when (string-match-p (car elem) file)
352 (if (image-type-available-p (setq type (cdr elem)))
353 (throw 'found type)
354 ;; If nothing seems to be supported, return first type that matched.
355 (or first (setq first type))))))))
356
357 ;;;###autoload
358 (defun image-type (source &optional type data-p)
359 "Determine and return image type.
360 SOURCE is an image file name or image data.
361 Optional TYPE is a symbol describing the image type. If TYPE is omitted
362 or nil, try to determine the image type from its first few bytes
363 of image data. If that doesn't work, and SOURCE is a file name,
364 use its file extension as image type.
365 Optional DATA-P non-nil means SOURCE is a string containing image data."
366 (when (and (not data-p) (not (stringp source)))
367 (error "Invalid image file name `%s'" source))
368 (unless type
369 (setq type (if data-p
370 (image-type-from-data source)
371 (or (image-type-from-file-header source)
372 (image-type-from-file-name source))))
373 (or type (error "Cannot determine image type")))
374 (or (memq type (and (boundp 'image-types) image-types))
375 (error "Invalid image type `%s'" type))
376 type)
377
378
379 (if (fboundp 'image-metadata) ; eg not --without-x
380 (define-obsolete-function-alias 'image-extension-data
381 'image-metadata "24.1"))
382
383 (define-obsolete-variable-alias
384 'image-library-alist
385 'dynamic-library-alist "24.1")
386
387 ;;;###autoload
388 (defun image-type-available-p (type)
389 "Return non-nil if image type TYPE is available.
390 Image types are symbols like `xbm' or `jpeg'."
391 (and (fboundp 'init-image-library)
392 (init-image-library type)))
393
394
395 ;;;###autoload
396 (defun image-type-auto-detected-p ()
397 "Return t if the current buffer contains an auto-detectable image.
398 This function is intended to be used from `magic-fallback-mode-alist'.
399
400 The buffer is considered to contain an auto-detectable image if
401 its beginning matches an image type in `image-type-header-regexps',
402 and that image type is present in `image-type-auto-detectable' with a
403 non-nil value. If that value is non-nil, but not t, then the image type
404 must be available."
405 (let* ((type (image-type-from-buffer))
406 (auto (and type (cdr (assq type image-type-auto-detectable)))))
407 (and auto
408 (or (eq auto t) (image-type-available-p type)))))
409
410
411 ;;;###autoload
412 (defun create-image (file-or-data &optional type data-p &rest props)
413 "Create an image.
414 FILE-OR-DATA is an image file name or image data.
415 Optional TYPE is a symbol describing the image type. If TYPE is omitted
416 or nil, try to determine the image type from its first few bytes
417 of image data. If that doesn't work, and FILE-OR-DATA is a file name,
418 use its file extension as image type.
419 Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data.
420 Optional PROPS are additional image attributes to assign to the image,
421 like, e.g. `:mask MASK'.
422 Value is the image created, or nil if images of type TYPE are not supported.
423
424 Images should not be larger than specified by `max-image-size'.
425
426 Image file names that are not absolute are searched for in the
427 \"images\" sub-directory of `data-directory' and
428 `x-bitmap-file-path' (in that order)."
429 ;; It is x_find_image_file in image.c that sets the search path.
430 (setq type (image-type file-or-data type data-p))
431 (when (image-type-available-p type)
432 (append (list 'image :type type (if data-p :data :file) file-or-data)
433 (and (not (plist-get props :scale))
434 (list :scale
435 (image-compute-scaling-factor image-scaling-factor)))
436 props)))
437
438 (defun image--set-property (image property value)
439 "Set PROPERTY in IMAGE to VALUE.
440 Internal use only."
441 (if (null value)
442 (while (cdr image)
443 ;; IMAGE starts with the symbol `image', and the rest is a
444 ;; plist. Decouple plist entries where the key matches
445 ;; the property.
446 (if (eq (cadr image) property)
447 (setcdr image (cddr image))
448 (setq image (cddr image))))
449 ;; Just enter the new value.
450 (plist-put (cdr image) property value))
451 value)
452
453 (defun image-property (image property)
454 "Return the value of PROPERTY in IMAGE.
455 Properties can be set with
456
457 (setf (image-property IMAGE PROPERTY) VALUE)
458 If VALUE is nil, PROPERTY is removed from IMAGE."
459 (declare (gv-setter image--set-property))
460 (plist-get (cdr image) property))
461
462 (defun image-compute-scaling-factor (scaling)
463 (cond
464 ((numberp image-scaling-factor)
465 image-scaling-factor)
466 ((eq image-scaling-factor 'auto)
467 (let ((width (/ (float (window-width nil t)) (window-width))))
468 ;; If we assume that a typical character is 10 pixels in width,
469 ;; then we should scale all images according to how wide they
470 ;; are. But don't scale images down.
471 (if (< width 10)
472 1
473 (/ (float width) 10))))
474 (t
475 (error "Invalid scaling factor %s" image-scaling-factor))))
476
477 ;;;###autoload
478 (defun put-image (image pos &optional string area)
479 "Put image IMAGE in front of POS in the current buffer.
480 IMAGE must be an image created with `create-image' or `defimage'.
481 IMAGE is displayed by putting an overlay into the current buffer with a
482 `before-string' STRING that has a `display' property whose value is the
483 image. STRING is defaulted if you omit it.
484 The overlay created will have the `put-image' property set to t.
485 POS may be an integer or marker.
486 AREA is where to display the image. AREA nil or omitted means
487 display it in the text area, a value of `left-margin' means
488 display it in the left marginal area, a value of `right-margin'
489 means display it in the right marginal area."
490 (unless string (setq string "x"))
491 (let ((buffer (current-buffer)))
492 (unless (eq (car-safe image) 'image)
493 (error "Not an image: %s" image))
494 (unless (or (null area) (memq area '(left-margin right-margin)))
495 (error "Invalid area %s" area))
496 (setq string (copy-sequence string))
497 (let ((overlay (make-overlay pos pos buffer))
498 (prop (if (null area) image (list (list 'margin area) image))))
499 (put-text-property 0 (length string) 'display prop string)
500 (overlay-put overlay 'put-image t)
501 (overlay-put overlay 'before-string string)
502 (overlay-put overlay 'map image-map)
503 overlay)))
504
505
506 ;;;###autoload
507 (defun insert-image (image &optional string area slice)
508 "Insert IMAGE into current buffer at point.
509 IMAGE is displayed by inserting STRING into the current buffer
510 with a `display' property whose value is the image. STRING
511 defaults to a single space if you omit it.
512 AREA is where to display the image. AREA nil or omitted means
513 display it in the text area, a value of `left-margin' means
514 display it in the left marginal area, a value of `right-margin'
515 means display it in the right marginal area.
516 SLICE specifies slice of IMAGE to insert. SLICE nil or omitted
517 means insert whole image. SLICE is a list (X Y WIDTH HEIGHT)
518 specifying the X and Y positions and WIDTH and HEIGHT of image area
519 to insert. A float value 0.0 - 1.0 means relative to the width or
520 height of the image; integer values are taken as pixel values."
521 ;; Use a space as least likely to cause trouble when it's a hidden
522 ;; character in the buffer.
523 (unless string (setq string " "))
524 (unless (eq (car-safe image) 'image)
525 (error "Not an image: %s" image))
526 (unless (or (null area) (memq area '(left-margin right-margin)))
527 (error "Invalid area %s" area))
528 (if area
529 (setq image (list (list 'margin area) image))
530 ;; Cons up a new spec equal but not eq to `image' so that
531 ;; inserting it twice in a row (adjacently) displays two copies of
532 ;; the image. Don't try to avoid this by looking at the display
533 ;; properties on either side so that we DTRT more often with
534 ;; cut-and-paste. (Yanking killed image text next to another copy
535 ;; of it loses anyway.)
536 (setq image (cons 'image (cdr image))))
537 (let ((start (point)))
538 (insert string)
539 (add-text-properties start (point)
540 `(display ,(if slice
541 (list (cons 'slice slice) image)
542 image)
543 rear-nonsticky (display)
544 keymap ,image-map))))
545
546
547 ;;;###autoload
548 (defun insert-sliced-image (image &optional string area rows cols)
549 "Insert IMAGE into current buffer at point.
550 IMAGE is displayed by inserting STRING into the current buffer
551 with a `display' property whose value is the image. The default
552 STRING is a single space.
553 AREA is where to display the image. AREA nil or omitted means
554 display it in the text area, a value of `left-margin' means
555 display it in the left marginal area, a value of `right-margin'
556 means display it in the right marginal area.
557 The image is automatically split into ROWS x COLS slices."
558 (unless string (setq string " "))
559 (unless (eq (car-safe image) 'image)
560 (error "Not an image: %s" image))
561 (unless (or (null area) (memq area '(left-margin right-margin)))
562 (error "Invalid area %s" area))
563 (if area
564 (setq image (list (list 'margin area) image))
565 ;; Cons up a new spec equal but not eq to `image' so that
566 ;; inserting it twice in a row (adjacently) displays two copies of
567 ;; the image. Don't try to avoid this by looking at the display
568 ;; properties on either side so that we DTRT more often with
569 ;; cut-and-paste. (Yanking killed image text next to another copy
570 ;; of it loses anyway.)
571 (setq image (cons 'image (cdr image))))
572 (let ((x 0.0) (dx (/ 1.0001 (or cols 1)))
573 (y 0.0) (dy (/ 1.0001 (or rows 1))))
574 (while (< y 1.0)
575 (while (< x 1.0)
576 (let ((start (point)))
577 (insert string)
578 (add-text-properties start (point)
579 `(display ,(list (list 'slice x y dx dy) image)
580 rear-nonsticky (display)
581 keymap ,image-map))
582 (setq x (+ x dx))))
583 (setq x 0.0
584 y (+ y dy))
585 (insert (propertize "\n" 'line-height t)))))
586
587
588
589 ;;;###autoload
590 (defun remove-images (start end &optional buffer)
591 "Remove images between START and END in BUFFER.
592 Remove only images that were put in BUFFER with calls to `put-image'.
593 BUFFER nil or omitted means use the current buffer."
594 (unless buffer
595 (setq buffer (current-buffer)))
596 (let ((overlays (overlays-in start end)))
597 (while overlays
598 (let ((overlay (car overlays)))
599 (when (overlay-get overlay 'put-image)
600 (delete-overlay overlay)))
601 (setq overlays (cdr overlays)))))
602
603 (defun image-search-load-path (file &optional path)
604 (unless path
605 (setq path image-load-path))
606 (let (element found filename)
607 (while (and (not found) (consp path))
608 (setq element (car path))
609 (cond
610 ((stringp element)
611 (setq found
612 (file-readable-p
613 (setq filename (expand-file-name file element)))))
614 ((and (symbolp element) (boundp element))
615 (setq element (symbol-value element))
616 (cond
617 ((stringp element)
618 (setq found
619 (file-readable-p
620 (setq filename (expand-file-name file element)))))
621 ((consp element)
622 (if (setq filename (image-search-load-path file element))
623 (setq found t))))))
624 (setq path (cdr path)))
625 (if found filename)))
626
627 ;;;###autoload
628 (defun find-image (specs)
629 "Find an image, choosing one of a list of image specifications.
630
631 SPECS is a list of image specifications.
632
633 Each image specification in SPECS is a property list. The contents of
634 a specification are image type dependent. All specifications must at
635 least contain the properties `:type TYPE' and either `:file FILE' or
636 `:data DATA', where TYPE is a symbol specifying the image type,
637 e.g. `xbm', FILE is the file to load the image from, and DATA is a
638 string containing the actual image data. The specification whose TYPE
639 is supported, and FILE exists, is used to construct the image
640 specification to be returned. Return nil if no specification is
641 satisfied.
642
643 The image is looked for in `image-load-path'.
644
645 Image files should not be larger than specified by `max-image-size'."
646 (let (image)
647 (while (and specs (null image))
648 (let* ((spec (car specs))
649 (type (plist-get spec :type))
650 (data (plist-get spec :data))
651 (file (plist-get spec :file))
652 found)
653 (when (image-type-available-p type)
654 (cond ((stringp file)
655 (if (setq found (image-search-load-path file))
656 (setq image
657 (cons 'image (plist-put (copy-sequence spec)
658 :file found)))))
659 ((not (null data))
660 (setq image (cons 'image spec)))))
661 (setq specs (cdr specs))))
662 image))
663
664
665 ;;;###autoload
666 (defmacro defimage (symbol specs &optional doc)
667 "Define SYMBOL as an image, and return SYMBOL.
668
669 SPECS is a list of image specifications. DOC is an optional
670 documentation string.
671
672 Each image specification in SPECS is a property list. The contents of
673 a specification are image type dependent. All specifications must at
674 least contain the properties `:type TYPE' and either `:file FILE' or
675 `:data DATA', where TYPE is a symbol specifying the image type,
676 e.g. `xbm', FILE is the file to load the image from, and DATA is a
677 string containing the actual image data. The first image
678 specification whose TYPE is supported, and FILE exists, is used to
679 define SYMBOL.
680
681 Example:
682
683 (defimage test-image ((:type xpm :file \"~/test1.xpm\")
684 (:type xbm :file \"~/test1.xbm\")))"
685 (declare (doc-string 3))
686 `(defvar ,symbol (find-image ',specs) ,doc))
687
688 \f
689 ;;; Animated image API
690
691 (defvar image-default-frame-delay 0.1
692 "Default interval in seconds between frames of a multi-frame image.
693 Only used if the image does not specify a value.")
694
695 (defun image-multi-frame-p (image)
696 "Return non-nil if IMAGE contains more than one frame.
697 The actual return value is a cons (NIMAGES . DELAY), where NIMAGES is
698 the number of frames (or sub-images) in the image and DELAY is the delay
699 in seconds that the image specifies between each frame. DELAY may be nil,
700 in which case you might want to use `image-default-frame-delay'."
701 (when (fboundp 'image-metadata)
702 (let* ((metadata (image-metadata image))
703 (images (plist-get metadata 'count))
704 (delay (plist-get metadata 'delay)))
705 (when (and images (> images 1))
706 (and delay (or (not (numberp delay)) (< delay 0))
707 (setq delay image-default-frame-delay))
708 (cons images delay)))))
709
710 (defun image-animated-p (image)
711 "Like `image-multi-frame-p', but returns nil if no delay is specified."
712 (let ((multi (image-multi-frame-p image)))
713 (and (cdr multi) multi)))
714
715 (make-obsolete 'image-animated-p 'image-multi-frame-p "24.4")
716
717 ;; "Destructively"?
718 (defun image-animate (image &optional index limit)
719 "Start animating IMAGE.
720 Animation occurs by destructively altering the IMAGE spec list.
721
722 With optional INDEX, begin animating from that animation frame.
723 LIMIT specifies how long to animate the image. If omitted or
724 nil, play the animation until the end. If t, loop forever. If a
725 number, play until that number of seconds has elapsed."
726 (let ((animation (image-multi-frame-p image))
727 timer)
728 (when animation
729 (if (setq timer (image-animate-timer image))
730 (cancel-timer timer))
731 (plist-put (cdr image) :animate-buffer (current-buffer))
732 (run-with-timer 0.2 nil 'image-animate-timeout
733 image (or index 0) (car animation)
734 0 limit))))
735
736 (defun image-animate-timer (image)
737 "Return the animation timer for image IMAGE."
738 ;; See cancel-function-timers
739 (let ((tail timer-list) timer)
740 (while tail
741 (setq timer (car tail)
742 tail (cdr tail))
743 (if (and (eq (timer--function timer) 'image-animate-timeout)
744 (eq (car-safe (timer--args timer)) image))
745 (setq tail nil)
746 (setq timer nil)))
747 timer))
748
749 (defconst image-minimum-frame-delay 0.01
750 "Minimum interval in seconds between frames of an animated image.")
751
752 (defun image-current-frame (image)
753 "The current frame number of IMAGE, indexed from 0."
754 (or (plist-get (cdr image) :index) 0))
755
756 (defun image-show-frame (image n &optional nocheck)
757 "Show frame N of IMAGE.
758 Frames are indexed from 0. Optional argument NOCHECK non-nil means
759 do not check N is within the range of frames present in the image."
760 (unless nocheck
761 (if (< n 0) (setq n 0)
762 (setq n (min n (1- (car (image-multi-frame-p image)))))))
763 (plist-put (cdr image) :index n)
764 (force-window-update))
765
766 (defun image-animate-get-speed (image)
767 "Return the speed factor for animating IMAGE."
768 (or (plist-get (cdr image) :speed) 1))
769
770 (defun image-animate-set-speed (image value &optional multiply)
771 "Set the speed factor for animating IMAGE to VALUE.
772 With optional argument MULTIPLY non-nil, treat VALUE as a
773 multiplication factor for the current value."
774 (plist-put (cdr image) :speed
775 (if multiply
776 (* value (image-animate-get-speed image))
777 value)))
778
779 ;; FIXME? The delay may not be the same for different sub-images,
780 ;; hence we need to call image-multi-frame-p to return it.
781 ;; But it also returns count, so why do we bother passing that as an
782 ;; argument?
783 (defun image-animate-timeout (image n count time-elapsed limit)
784 "Display animation frame N of IMAGE.
785 N=0 refers to the initial animation frame.
786 COUNT is the total number of frames in the animation.
787 TIME-ELAPSED is the total time that has elapsed since
788 `image-animate-start' was called.
789 LIMIT determines when to stop. If t, loop forever. If nil, stop
790 after displaying the last animation frame. Otherwise, stop
791 after LIMIT seconds have elapsed.
792 The minimum delay between successive frames is `image-minimum-frame-delay'.
793
794 If the image has a non-nil :speed property, it acts as a multiplier
795 for the animation speed. A negative value means to animate in reverse."
796 (when (buffer-live-p (plist-get (cdr image) :animate-buffer))
797 (image-show-frame image n t)
798 (let* ((speed (image-animate-get-speed image))
799 (time (float-time))
800 (animation (image-multi-frame-p image))
801 ;; Subtract off the time we took to load the image from the
802 ;; stated delay time.
803 (delay (max (+ (* (or (cdr animation) image-default-frame-delay)
804 (/ 1.0 (abs speed)))
805 time (- (float-time)))
806 image-minimum-frame-delay))
807 done)
808 (setq n (if (< speed 0)
809 (1- n)
810 (1+ n)))
811 (if limit
812 (cond ((>= n count) (setq n 0))
813 ((< n 0) (setq n (1- count))))
814 (and (or (>= n count) (< n 0)) (setq done t)))
815 (setq time-elapsed (+ delay time-elapsed))
816 (if (numberp limit)
817 (setq done (>= time-elapsed limit)))
818 (unless done
819 (run-with-timer delay nil 'image-animate-timeout
820 image n count time-elapsed limit)))))
821
822 \f
823 (defvar imagemagick-types-inhibit)
824 (defvar imagemagick-enabled-types)
825
826 (defun imagemagick-filter-types ()
827 "Return a list of the ImageMagick types to be treated as images, or nil.
828 This is the result of `imagemagick-types', including only elements
829 that match `imagemagick-enabled-types' and do not match
830 `imagemagick-types-inhibit'."
831 (when (fboundp 'imagemagick-types)
832 (cond ((null imagemagick-enabled-types) nil)
833 ((eq imagemagick-types-inhibit t) nil)
834 (t
835 (delq nil
836 (mapcar
837 (lambda (type)
838 (unless (memq type imagemagick-types-inhibit)
839 (if (eq imagemagick-enabled-types t) type
840 (catch 'found
841 (dolist (enable imagemagick-enabled-types nil)
842 (if (cond ((symbolp enable) (eq enable type))
843 ((stringp enable)
844 (string-match enable
845 (symbol-name type))))
846 (throw 'found type)))))))
847 (imagemagick-types)))))))
848
849 (defvar imagemagick--file-regexp nil
850 "File extension regexp for ImageMagick files, if any.
851 This is the extension installed into `auto-mode-alist' and
852 `image-type-file-name-regexps' by `imagemagick-register-types'.")
853
854 ;;;###autoload
855 (defun imagemagick-register-types ()
856 "Register file types that can be handled by ImageMagick.
857 This function is called at startup, after loading the init file.
858 It registers the ImageMagick types returned by `imagemagick-filter-types'.
859
860 Registered image types are added to `auto-mode-alist', so that
861 Emacs visits them in Image mode. They are also added to
862 `image-type-file-name-regexps', so that the `image-type' function
863 recognizes these files as having image type `imagemagick'.
864
865 If Emacs is compiled without ImageMagick support, this does nothing."
866 (when (fboundp 'imagemagick-types)
867 (let* ((types (mapcar (lambda (type) (downcase (symbol-name type)))
868 (imagemagick-filter-types)))
869 (re (if types (concat "\\." (regexp-opt types) "\\'")))
870 (ama-elt (car (member (cons imagemagick--file-regexp 'image-mode)
871 auto-mode-alist)))
872 (itfnr-elt (car (member (cons imagemagick--file-regexp 'imagemagick)
873 image-type-file-name-regexps))))
874 (if (not re)
875 (setq auto-mode-alist (delete ama-elt auto-mode-alist)
876 image-type-file-name-regexps
877 (delete itfnr-elt image-type-file-name-regexps))
878 (if ama-elt
879 (setcar ama-elt re)
880 (push (cons re 'image-mode) auto-mode-alist))
881 (if itfnr-elt
882 (setcar itfnr-elt re)
883 ;; Append to `image-type-file-name-regexps', so that we
884 ;; preferentially use specialized image libraries.
885 (add-to-list 'image-type-file-name-regexps
886 (cons re 'imagemagick) t)))
887 (setq imagemagick--file-regexp re))))
888
889 (defcustom imagemagick-types-inhibit
890 '(C HTML HTM INFO M TXT PDF)
891 "List of ImageMagick types that should never be treated as images.
892 This should be a list of symbols, each of which should be one of
893 the ImageMagick types listed by `imagemagick-types'. The listed
894 image types are not registered by `imagemagick-register-types'.
895
896 If the value is t, inhibit the use of ImageMagick for images.
897
898 If you change this without using customize, you must call
899 `imagemagick-register-types' afterwards.
900
901 If Emacs is compiled without ImageMagick support, this variable
902 has no effect."
903 :type '(choice (const :tag "Support all ImageMagick types" nil)
904 (const :tag "Disable all ImageMagick types" t)
905 (repeat symbol))
906 :initialize 'custom-initialize-default
907 :set (lambda (symbol value)
908 (set-default symbol value)
909 (imagemagick-register-types))
910 :version "24.3"
911 :group 'image)
912
913 (defcustom imagemagick-enabled-types
914 '(3FR ART ARW AVS BMP BMP2 BMP3 CAL CALS CMYK CMYKA CR2 CRW
915 CUR CUT DCM DCR DCX DDS DJVU DNG DPX EXR FAX FITS GBR GIF
916 GIF87 GRB HRZ ICB ICO ICON J2C JNG JP2 JPC JPEG JPG JPX K25
917 KDC MIFF MNG MRW MSL MSVG MTV NEF ORF OTB PBM PCD PCDS PCL
918 PCT PCX PDB PEF PGM PICT PIX PJPEG PNG PNG24 PNG32 PNG8 PNM
919 PPM PSD PTIF PWP RAF RAS RBG RGB RGBA RGBO RLA RLE SCR SCT
920 SFW SGI SR2 SRF SUN SVG SVGZ TGA TIFF TIFF64 TILE TIM TTF
921 UYVY VDA VICAR VID VIFF VST WBMP WPG X3F XBM XC XCF XPM XV
922 XWD YCbCr YCbCrA YUV)
923 "List of ImageMagick types to treat as images.
924 Each list element should be a string or symbol, representing one
925 of the image types returned by `imagemagick-types'. If the
926 element is a string, it is handled as a regexp that enables all
927 matching types.
928
929 The value of `imagemagick-enabled-types' may also be t, meaning
930 to enable all types that ImageMagick supports.
931
932 The variable `imagemagick-types-inhibit' overrides this variable.
933
934 If you change this without using customize, you must call
935 `imagemagick-register-types' afterwards.
936
937 If Emacs is compiled without ImageMagick support, this variable
938 has no effect."
939 :type '(choice (const :tag "Support all ImageMagick types" t)
940 (const :tag "Disable all ImageMagick types" nil)
941 (repeat :tag "List of types"
942 (choice (symbol :tag "type")
943 (regexp :tag "regexp"))))
944 :initialize 'custom-initialize-default
945 :set (lambda (symbol value)
946 (set-default symbol value)
947 (imagemagick-register-types))
948 :version "24.3"
949 :group 'image)
950
951 (imagemagick-register-types)
952
953 (defun image-increase-size (n)
954 "Increase the image size by a factor of N.
955 If N is 3, then the image size will be increased by 30%. The
956 default is 20%."
957 (interactive "P")
958 (image--change-size (if n
959 (1+ (/ n 10))
960 1.2)))
961
962 (defun image-decrease-size (n)
963 "Decrease the image size by a factor of N.
964 If N is 3, then the image size will be decreased by 30%. The
965 default is 20%."
966 (interactive "P")
967 (image--change-size (if n
968 (- 1 (/ n 10))
969 0.8)))
970
971 (defun image--get-image ()
972 (let ((image (or (get-text-property (point) 'display)
973 ;; `put-image' uses overlays, so find an image in
974 ;; the overlays.
975 (seq-find (lambda (overlay)
976 (overlay-get overlay 'display))
977 (overlays-at (point))))))
978 (when (or (not (consp image))
979 (not (eq (car image) 'image)))
980 (error "No image under point"))
981 image))
982
983 (defun image--get-imagemagick-and-warn ()
984 (unless (fboundp 'imagemagick-types)
985 (error "Can't rescale images without ImageMagick support"))
986 (let ((image (image--get-image)))
987 (image-flush image)
988 (plist-put (cdr image) :type 'imagemagick)
989 image))
990
991 (defun image--change-size (factor)
992 (let* ((image (image--get-imagemagick-and-warn))
993 (new-image (image--image-without-parameters image))
994 (scale (image--current-scaling image new-image)))
995 (setcdr image (cdr new-image))
996 (plist-put (cdr image) :scale (* scale factor))))
997
998 (defun image--image-without-parameters (image)
999 (cons (pop image)
1000 (let ((new nil))
1001 (while image
1002 (let ((key (pop image))
1003 (val (pop image)))
1004 (unless (memq key '(:scale :width :height :max-width :max-height))
1005 (setq new (nconc new (list key val))))))
1006 new)))
1007
1008 (defun image--current-scaling (image new-image)
1009 ;; The image may be scaled due to many reasons (:scale, :max-width,
1010 ;; etc), so find out what the current scaling is based on the
1011 ;; original image size and the displayed size.
1012 (let ((image-width (car (image-size new-image t)))
1013 (display-width (car (image-size image t))))
1014 (/ (float display-width) image-width)))
1015
1016 (defun image-rotate ()
1017 "Rotate the image under point by 90 degrees clockwise."
1018 (interactive)
1019 (let ((image (image--get-imagemagick-and-warn)))
1020 (plist-put (cdr image) :rotation
1021 (float (+ (or (plist-get (cdr image) :rotation) 0) 90)))))
1022
1023 (defun image-save ()
1024 "Save the image under point."
1025 (interactive)
1026 (let ((image (get-text-property (point) 'display)))
1027 (when (or (not (consp image))
1028 (not (eq (car image) 'image)))
1029 (error "No image under point"))
1030 (with-temp-buffer
1031 (let ((file (plist-get (cdr image) :file)))
1032 (if file
1033 (if (not (file-exists-p file))
1034 (error "File %s no longer exists" file)
1035 (insert-file-contents-literally file))
1036 (insert (plist-get (cdr image) :data))))
1037 (write-region (point-min) (point-max)
1038 (read-file-name "Write image to file: ")))))
1039
1040 (provide 'image)
1041
1042 ;;; image.el ends here