Improve responsiveness while in 'replace-buffer-contents'
[emacs.git] / lisp / image.el
blobdb820949eda3d03bb92b61d0aab07050163fc9b3
1 ;;; image.el --- image API -*- lexical-binding:t -*-
3 ;; Copyright (C) 1998-2018 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: multimedia
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
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.
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
28 (defgroup image ()
29 "Image support."
30 :group 'multimedia)
32 (defalias 'image-refresh 'image-flush)
34 (defconst image-type-header-regexps
35 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
36 ("\\`P[1-6]\\(?:\
37 \\(?:\\(?:#[^\r\n]*[\r\n]\\)*[[:space:]]\\)+\
38 \\(?:\\(?:#[^\r\n]*[\r\n]\\)*[0-9]\\)+\
39 \\)\\{2\\}" . pbm)
40 ("\\`GIF8[79]a" . gif)
41 ("\\`\x89PNG\r\n\x1a\n" . png)
42 ("\\`[\t\n\r ]*#define \\([a-z0-9_]+\\)_width [0-9]+\n\
43 #define \\1_height [0-9]+\n\\(\
44 #define \\1_x_hot [0-9]+\n\
45 #define \\1_y_hot [0-9]+\n\\)?\
46 static \\(unsigned \\)?char \\1_bits" . xbm)
47 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
48 ("\\`[\t\n\r ]*%!PS" . postscript)
49 ("\\`\xff\xd8" . jpeg) ; used to be (image-jpeg-p . jpeg)
50 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
51 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
52 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
53 comment-re "*"
54 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
55 "[Ss][Vv][Gg]"))
56 . svg)
58 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
59 When the first bytes of an image file match REGEXP, it is assumed to
60 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
61 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
62 with one argument, a string containing the image data. If PREDICATE returns
63 a non-nil value, TYPE is the image's type.")
65 (defvar image-type-file-name-regexps
66 '(("\\.png\\'" . png)
67 ("\\.gif\\'" . gif)
68 ("\\.jpe?g\\'" . jpeg)
69 ("\\.bmp\\'" . bmp)
70 ("\\.xpm\\'" . xpm)
71 ("\\.pbm\\'" . pbm)
72 ("\\.xbm\\'" . xbm)
73 ("\\.ps\\'" . postscript)
74 ("\\.tiff?\\'" . tiff)
75 ("\\.svgz?\\'" . svg)
77 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
78 When the name of an image file match REGEXP, it is assumed to
79 be of image type IMAGE-TYPE.")
81 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
82 ;; of content autodetection. Their contents are just C code, so it is
83 ;; easy to generate false matches.
84 (defvar image-type-auto-detectable
85 '((pbm . t)
86 (xbm . nil)
87 (bmp . maybe)
88 (gif . maybe)
89 (png . maybe)
90 (xpm . nil)
91 (jpeg . maybe)
92 (tiff . maybe)
93 (svg . maybe)
94 (postscript . nil))
95 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
96 \(See `image-type-auto-detected-p').
98 AUTODETECT can be
99 - t always auto-detect.
100 - nil never auto-detect.
101 - maybe auto-detect only if the image type is available
102 (see `image-type-available-p').")
104 (defvar image-format-suffixes
105 '((image/x-rgb "rgb") (image/x-icon "ico"))
106 "An alist associating image types with file name suffixes.
107 This is used as a hint by the ImageMagick library when detecting
108 the type of image data (that does not have an associated file name).
109 Each element has the form (MIME-CONTENT-TYPE EXTENSION).
110 If `create-image' is called with a :format attribute whose value
111 equals a content-type found in this list, the ImageMagick library is
112 told that the data would have the associated suffix if saved to a file.")
114 (defcustom image-load-path
115 (list (file-name-as-directory (expand-file-name "images" data-directory))
116 'data-directory 'load-path)
117 "List of locations in which to search for image files.
118 The images for icons shown in the tool bar are also looked up
119 in these locations.
121 If an element is a string, it defines a directory to search.
122 If an element is a variable symbol whose value is a string, that
123 value defines a directory to search.
124 If an element is a variable symbol whose value is a list, the
125 value is used as a list of directories to search.
127 Subdirectories are not automatically included in the search."
128 :type '(repeat (choice directory variable))
129 :initialize #'custom-initialize-delay)
131 (defcustom image-scaling-factor 'auto
132 "When displaying images, apply this scaling factor before displaying.
133 This is not supported for all image types, and is mostly useful
134 when you have a high-resolution monitor.
135 The value is either a floating point number (where numbers higher
136 than 1 means to increase the size and lower means to shrink the
137 size), or the symbol `auto', which will compute a scaling factor
138 based on the font pixel size."
139 :type '(choice number
140 (const :tag "Automatically compute" auto))
141 :version "26.1")
143 ;; Map put into text properties on images.
144 (defvar image-map
145 (let ((map (make-sparse-keymap)))
146 (define-key map "-" 'image-decrease-size)
147 (define-key map "+" 'image-increase-size)
148 (define-key map "r" 'image-rotate)
149 (define-key map "o" 'image-save)
150 map))
152 (defun image-load-path-for-library (library image &optional path no-error)
153 "Return a suitable search path for images used by LIBRARY.
155 It searches for IMAGE in `image-load-path' (excluding
156 \"`data-directory'/images\") and `load-path', followed by a path
157 suitable for LIBRARY, which includes \"../../etc/images\" and
158 \"../etc/images\" relative to the library file itself, and then
159 in \"`data-directory'/images\".
161 Then this function returns a list of directories which contains
162 first the directory in which IMAGE was found, followed by the
163 value of `load-path'. If PATH is given, it is used instead of
164 `load-path'.
166 If NO-ERROR is non-nil and a suitable path can't be found, don't
167 signal an error. Instead, return a list of directories as before,
168 except that nil appears in place of the image directory.
170 Here is an example that uses a common idiom to provide
171 compatibility with versions of Emacs that lack the variable
172 `image-load-path':
174 ;; Shush compiler.
175 (defvar image-load-path)
177 (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
178 (image-load-path (cons (car load-path)
179 (when (boundp \\='image-load-path)
180 image-load-path))))
181 (mh-tool-bar-folder-buttons-init))"
182 (unless library (error "No library specified"))
183 (unless image (error "No image specified"))
184 (let (image-directory image-directory-load-path)
185 ;; Check for images in image-load-path or load-path.
186 (let ((img image)
187 (dir (or
188 ;; Images in image-load-path.
189 (image-search-load-path image)
190 ;; Images in load-path.
191 (locate-library image)))
192 parent)
193 ;; Since the image might be in a nested directory (for
194 ;; example, mail/attach.pbm), adjust `image-directory'
195 ;; accordingly.
196 (when dir
197 (setq dir (file-name-directory dir))
198 (while (setq parent (file-name-directory img))
199 (setq img (directory-file-name parent)
200 dir (expand-file-name "../" dir))))
201 (setq image-directory-load-path dir))
203 ;; If `image-directory-load-path' isn't Emacs's image directory,
204 ;; it's probably a user preference, so use it. Then use a
205 ;; relative setting if possible; otherwise, use
206 ;; `image-directory-load-path'.
207 (cond
208 ;; User-modified image-load-path?
209 ((and image-directory-load-path
210 (not (equal image-directory-load-path
211 (file-name-as-directory
212 (expand-file-name "images" data-directory)))))
213 (setq image-directory image-directory-load-path))
214 ;; Try relative setting.
215 ((let (library-name d1ei d2ei)
216 ;; First, find library in the load-path.
217 (setq library-name (locate-library library))
218 (if (not library-name)
219 (error "Cannot find library %s in load-path" library))
220 ;; And then set image-directory relative to that.
221 (setq
222 ;; Go down 2 levels.
223 d2ei (file-name-as-directory
224 (expand-file-name
225 (concat (file-name-directory library-name) "../../etc/images")))
226 ;; Go down 1 level.
227 d1ei (file-name-as-directory
228 (expand-file-name
229 (concat (file-name-directory library-name) "../etc/images"))))
230 (setq image-directory
231 ;; Set it to nil if image is not found.
232 (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
233 ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
234 ;; Use Emacs's image directory.
235 (image-directory-load-path
236 (setq image-directory image-directory-load-path))
237 (no-error
238 (message "Could not find image %s for library %s" image library))
240 (error "Could not find image %s for library %s" image library)))
242 ;; Return an augmented `path' or `load-path'.
243 (nconc (list image-directory)
244 (delete image-directory (copy-sequence (or path load-path))))))
247 ;; Used to be in image-type-header-regexps, but now not used anywhere
248 ;; (since 2009-08-28).
249 (defun image-jpeg-p (data)
250 "Value is non-nil if DATA, a string, consists of JFIF image data.
251 We accept the tag Exif because that is the same format."
252 (setq data (ignore-errors (string-to-unibyte data)))
253 (when (and data (string-match-p "\\`\xff\xd8" data))
254 (catch 'jfif
255 (let ((len (length data)) (i 2))
256 (while (< i len)
257 (when (/= (aref data i) #xff)
258 (throw 'jfif nil))
259 (setq i (1+ i))
260 (when (>= (+ i 2) len)
261 (throw 'jfif nil))
262 (let ((nbytes (+ (lsh (aref data (+ i 1)) 8)
263 (aref data (+ i 2))))
264 (code (aref data i)))
265 (when (and (>= code #xe0) (<= code #xef))
266 ;; APP0 LEN1 LEN2 "JFIF\0"
267 (throw 'jfif
268 (string-match-p "JFIF\\|Exif"
269 (substring data i (min (+ i nbytes) len)))))
270 (setq i (+ i 1 nbytes))))))))
273 ;;;###autoload
274 (defun image-type-from-data (data)
275 "Determine the image type from image data DATA.
276 Value is a symbol specifying the image type or nil if type cannot
277 be determined."
278 (let ((types image-type-header-regexps)
279 type)
280 (while types
281 (let ((regexp (car (car types)))
282 (image-type (cdr (car types))))
283 (if (or (and (symbolp image-type)
284 (string-match-p regexp data))
285 (and (consp image-type)
286 (funcall (car image-type) data)
287 (setq image-type (cdr image-type))))
288 (setq type image-type
289 types nil)
290 (setq types (cdr types)))))
291 type))
294 ;;;###autoload
295 (defun image-type-from-buffer ()
296 "Determine the image type from data in the current buffer.
297 Value is a symbol specifying the image type or nil if type cannot
298 be determined."
299 (let ((types image-type-header-regexps)
300 type
301 (opoint (point)))
302 (goto-char (point-min))
303 (while types
304 (let ((regexp (car (car types)))
305 (image-type (cdr (car types)))
306 data)
307 (if (or (and (symbolp image-type)
308 (looking-at-p regexp))
309 (and (consp image-type)
310 (funcall (car image-type)
311 (or data
312 (setq data
313 (buffer-substring
314 (point-min)
315 (min (point-max)
316 (+ (point-min) 256))))))
317 (setq image-type (cdr image-type))))
318 (setq type image-type
319 types nil)
320 (setq types (cdr types)))))
321 (goto-char opoint)
322 (and type
323 (boundp 'image-types)
324 (memq type image-types)
325 type)))
328 ;;;###autoload
329 (defun image-type-from-file-header (file)
330 "Determine the type of image file FILE from its first few bytes.
331 Value is a symbol specifying the image type, or nil if type cannot
332 be determined."
333 (unless (or (file-readable-p file)
334 (file-name-absolute-p file))
335 (setq file (image-search-load-path file)))
336 (and file
337 (file-readable-p file)
338 (with-temp-buffer
339 (set-buffer-multibyte nil)
340 (insert-file-contents-literally file nil 0 256)
341 (image-type-from-buffer))))
344 ;;;###autoload
345 (defun image-type-from-file-name (file)
346 "Determine the type of image file FILE from its name.
347 Value is a symbol specifying the image type, or nil if type cannot
348 be determined."
349 (let (type first (case-fold-search t))
350 (catch 'found
351 (dolist (elem image-type-file-name-regexps first)
352 (when (string-match-p (car elem) file)
353 (if (image-type-available-p (setq type (cdr elem)))
354 (throw 'found type)
355 ;; If nothing seems to be supported, return first type that matched.
356 (or first (setq first type))))))))
358 ;;;###autoload
359 (defun image-type (source &optional type data-p)
360 "Determine and return image type.
361 SOURCE is an image file name or image data.
362 Optional TYPE is a symbol describing the image type. If TYPE is omitted
363 or nil, try to determine the image type from its first few bytes
364 of image data. If that doesn't work, and SOURCE is a file name,
365 use its file extension as image type.
366 Optional DATA-P non-nil means SOURCE is a string containing image data."
367 (when (and (not data-p) (not (stringp source)))
368 (error "Invalid image file name `%s'" source))
369 (unless type
370 (setq type (if data-p
371 (image-type-from-data source)
372 (or (image-type-from-file-header source)
373 (image-type-from-file-name source))))
374 (or type (error "Cannot determine image type")))
375 (or (memq type (and (boundp 'image-types) image-types))
376 (error "Invalid image type `%s'" type))
377 type)
380 (if (fboundp 'image-metadata) ; eg not --without-x
381 (define-obsolete-function-alias 'image-extension-data
382 'image-metadata "24.1"))
384 (define-obsolete-variable-alias
385 'image-library-alist
386 'dynamic-library-alist "24.1")
388 ;;;###autoload
389 (defun image-type-available-p (type)
390 "Return non-nil if image type TYPE is available.
391 Image types are symbols like `xbm' or `jpeg'."
392 (and (fboundp 'init-image-library)
393 (init-image-library type)))
396 ;;;###autoload
397 (defun image-type-auto-detected-p ()
398 "Return t if the current buffer contains an auto-detectable image.
399 This function is intended to be used from `magic-fallback-mode-alist'.
401 The buffer is considered to contain an auto-detectable image if
402 its beginning matches an image type in `image-type-header-regexps',
403 and that image type is present in `image-type-auto-detectable' with a
404 non-nil value. If that value is non-nil, but not t, then the image type
405 must be available."
406 (let* ((type (image-type-from-buffer))
407 (auto (and type (cdr (assq type image-type-auto-detectable)))))
408 (and auto
409 (or (eq auto t) (image-type-available-p type)))))
412 ;;;###autoload
413 (defun create-image (file-or-data &optional type data-p &rest props)
414 "Create an image.
415 FILE-OR-DATA is an image file name or image data.
416 Optional TYPE is a symbol describing the image type. If TYPE is omitted
417 or nil, try to determine the image type from its first few bytes
418 of image data. If that doesn't work, and FILE-OR-DATA is a file name,
419 use its file extension as image type.
420 Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data.
421 Optional PROPS are additional image attributes to assign to the image,
422 like, e.g. `:mask MASK'.
423 Value is the image created, or nil if images of type TYPE are not supported.
425 Images should not be larger than specified by `max-image-size'.
427 Image file names that are not absolute are searched for in the
428 \"images\" sub-directory of `data-directory' and
429 `x-bitmap-file-path' (in that order)."
430 ;; It is x_find_image_file in image.c that sets the search path.
431 (setq type (image-type file-or-data type data-p))
432 (when (image-type-available-p type)
433 (append (list 'image :type type (if data-p :data :file) file-or-data)
434 (and (not (plist-get props :scale))
435 (list :scale
436 (image-compute-scaling-factor image-scaling-factor)))
437 props)))
439 (defun image--set-property (image property value)
440 "Set PROPERTY in IMAGE to VALUE.
441 Internal use only."
442 (if (null value)
443 (while (cdr image)
444 ;; IMAGE starts with the symbol `image', and the rest is a
445 ;; plist. Decouple plist entries where the key matches
446 ;; the property.
447 (if (eq (cadr image) property)
448 (setcdr image (cddr image))
449 (setq image (cddr image))))
450 ;; Just enter the new value.
451 (plist-put (cdr image) property value))
452 value)
454 (defun image-property (image property)
455 "Return the value of PROPERTY in IMAGE.
456 Properties can be set with
458 (setf (image-property IMAGE PROPERTY) VALUE)
459 If VALUE is nil, PROPERTY is removed from IMAGE."
460 (declare (gv-setter image--set-property))
461 (plist-get (cdr image) property))
463 (defun image-compute-scaling-factor (scaling)
464 (cond
465 ((numberp scaling) scaling)
466 ((eq scaling '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)
473 (/ (float width) 10))))
475 (error "Invalid scaling factor %s" scaling))))
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)))
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))))
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)))))
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)))))
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)))
627 ;;;###autoload
628 (defun find-image (specs)
629 "Find an image, choosing one of a list of image specifications.
631 SPECS is a list of image specifications.
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.
643 The image is looked for in `image-load-path'.
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))
665 ;;;###autoload
666 (defmacro defimage (symbol specs &optional doc)
667 "Define SYMBOL as an image, and return SYMBOL.
669 SPECS is a list of image specifications. DOC is an optional
670 documentation string.
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.
681 Example:
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))
689 ;;; Animated image API
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.")
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)))))
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)))
715 (make-obsolete 'image-animated-p 'image-multi-frame-p "24.4")
717 ;; "Destructively"?
718 (defun image-animate (image &optional index limit)
719 "Start animating IMAGE.
720 Animation occurs by destructively altering the IMAGE spec list.
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 (+ (float-time) 0.2)))))
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))
749 (defconst image-minimum-frame-delay 0.01
750 "Minimum interval in seconds between frames of an animated image.")
752 (defun image-current-frame (image)
753 "The current frame number of IMAGE, indexed from 0."
754 (or (plist-get (cdr image) :index) 0))
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))
766 (defun image-animate-get-speed (image)
767 "Return the speed factor for animating IMAGE."
768 (or (plist-get (cdr image) :speed) 1))
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)))
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 target-time)
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'.
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 (and (buffer-live-p (plist-get (cdr image) :animate-buffer))
797 ;; Delayed more than two seconds more than expected.
798 (or (<= (- (float-time) target-time) 2)
799 (progn
800 (message "Stopping animation; animation possibly too big")
801 nil)))
802 (image-show-frame image n t)
803 (let* ((speed (image-animate-get-speed image))
804 (time (float-time))
805 (animation (image-multi-frame-p image))
806 ;; Subtract off the time we took to load the image from the
807 ;; stated delay time.
808 (delay (max (+ (* (or (cdr animation) image-default-frame-delay)
809 (/ 1.0 (abs speed)))
810 time (- (float-time)))
811 image-minimum-frame-delay))
812 done)
813 (setq n (if (< speed 0)
814 (1- n)
815 (1+ n)))
816 (if limit
817 (cond ((>= n count) (setq n 0))
818 ((< n 0) (setq n (1- count))))
819 (and (or (>= n count) (< n 0)) (setq done t)))
820 (setq time-elapsed (+ delay time-elapsed))
821 (if (numberp limit)
822 (setq done (>= time-elapsed limit)))
823 (unless done
824 (run-with-timer delay nil #'image-animate-timeout
825 image n count time-elapsed limit
826 (+ (float-time) delay))))))
829 (defvar imagemagick-types-inhibit)
830 (defvar imagemagick-enabled-types)
832 (defun imagemagick-filter-types ()
833 "Return a list of the ImageMagick types to be treated as images, or nil.
834 This is the result of `imagemagick-types', including only elements
835 that match `imagemagick-enabled-types' and do not match
836 `imagemagick-types-inhibit'."
837 (when (fboundp 'imagemagick-types)
838 (cond ((null imagemagick-enabled-types) nil)
839 ((eq imagemagick-types-inhibit t) nil)
841 (delq nil
842 (mapcar
843 (lambda (type)
844 (unless (memq type imagemagick-types-inhibit)
845 (if (eq imagemagick-enabled-types t) type
846 (catch 'found
847 (dolist (enable imagemagick-enabled-types nil)
848 (if (cond ((symbolp enable) (eq enable type))
849 ((stringp enable)
850 (string-match enable
851 (symbol-name type))))
852 (throw 'found type)))))))
853 (imagemagick-types)))))))
855 (defvar imagemagick--file-regexp nil
856 "File extension regexp for ImageMagick files, if any.
857 This is the extension installed into `auto-mode-alist' and
858 `image-type-file-name-regexps' by `imagemagick-register-types'.")
860 ;;;###autoload
861 (defun imagemagick-register-types ()
862 "Register file types that can be handled by ImageMagick.
863 This function is called at startup, after loading the init file.
864 It registers the ImageMagick types returned by `imagemagick-filter-types'.
866 Registered image types are added to `auto-mode-alist', so that
867 Emacs visits them in Image mode. They are also added to
868 `image-type-file-name-regexps', so that the `image-type' function
869 recognizes these files as having image type `imagemagick'.
871 If Emacs is compiled without ImageMagick support, this does nothing."
872 (when (fboundp 'imagemagick-types)
873 (let* ((types (mapcar (lambda (type) (downcase (symbol-name type)))
874 (imagemagick-filter-types)))
875 (re (if types (concat "\\." (regexp-opt types) "\\'")))
876 (ama-elt (car (member (cons imagemagick--file-regexp 'image-mode)
877 auto-mode-alist)))
878 (itfnr-elt (car (member (cons imagemagick--file-regexp 'imagemagick)
879 image-type-file-name-regexps))))
880 (if (not re)
881 (setq auto-mode-alist (delete ama-elt auto-mode-alist)
882 image-type-file-name-regexps
883 (delete itfnr-elt image-type-file-name-regexps))
884 (if ama-elt
885 (setcar ama-elt re)
886 (push (cons re 'image-mode) auto-mode-alist))
887 (if itfnr-elt
888 (setcar itfnr-elt re)
889 ;; Append to `image-type-file-name-regexps', so that we
890 ;; preferentially use specialized image libraries.
891 (add-to-list 'image-type-file-name-regexps
892 (cons re 'imagemagick) t)))
893 (setq imagemagick--file-regexp re))))
895 (defcustom imagemagick-types-inhibit
896 '(C HTML HTM INFO M TXT PDF)
897 "List of ImageMagick types that should never be treated as images.
898 This should be a list of symbols, each of which should be one of
899 the ImageMagick types listed by `imagemagick-types'. The listed
900 image types are not registered by `imagemagick-register-types'.
902 If the value is t, inhibit the use of ImageMagick for images.
904 If you change this without using customize, you must call
905 `imagemagick-register-types' afterwards.
907 If Emacs is compiled without ImageMagick support, this variable
908 has no effect."
909 :type '(choice (const :tag "Support all ImageMagick types" nil)
910 (const :tag "Disable all ImageMagick types" t)
911 (repeat symbol))
912 :initialize #'custom-initialize-default
913 :set (lambda (symbol value)
914 (set-default symbol value)
915 (imagemagick-register-types))
916 :version "24.3")
918 (defcustom imagemagick-enabled-types
919 '(3FR ART ARW AVS BMP BMP2 BMP3 CAL CALS CMYK CMYKA CR2 CRW
920 CUR CUT DCM DCR DCX DDS DJVU DNG DPX EXR FAX FITS GBR GIF
921 GIF87 GRB HRZ ICB ICO ICON J2C JNG JP2 JPC JPEG JPG JPX K25
922 KDC MIFF MNG MRW MSL MSVG MTV NEF ORF OTB PBM PCD PCDS PCL
923 PCT PCX PDB PEF PGM PICT PIX PJPEG PNG PNG24 PNG32 PNG8 PNM
924 PPM PSD PTIF PWP RAF RAS RBG RGB RGBA RGBO RLA RLE SCR SCT
925 SFW SGI SR2 SRF SUN SVG SVGZ TGA TIFF TIFF64 TILE TIM TTF
926 UYVY VDA VICAR VID VIFF VST WBMP WPG X3F XBM XC XCF XPM XV
927 XWD YCbCr YCbCrA YUV)
928 "List of ImageMagick types to treat as images.
929 Each list element should be a string or symbol, representing one
930 of the image types returned by `imagemagick-types'. If the
931 element is a string, it is handled as a regexp that enables all
932 matching types.
934 The value of `imagemagick-enabled-types' may also be t, meaning
935 to enable all types that ImageMagick supports.
937 The variable `imagemagick-types-inhibit' overrides this variable.
939 If you change this without using customize, you must call
940 `imagemagick-register-types' afterwards.
942 If Emacs is compiled without ImageMagick support, this variable
943 has no effect."
944 :type '(choice (const :tag "Support all ImageMagick types" t)
945 (const :tag "Disable all ImageMagick types" nil)
946 (repeat :tag "List of types"
947 (choice (symbol :tag "type")
948 (regexp :tag "regexp"))))
949 :initialize #'custom-initialize-default
950 :set (lambda (symbol value)
951 (set-default symbol value)
952 (imagemagick-register-types))
953 :version "24.3")
955 (imagemagick-register-types)
957 (defun image-increase-size (n)
958 "Increase the image size by a factor of N.
959 If N is 3, then the image size will be increased by 30%. The
960 default is 20%."
961 (interactive "P")
962 (image--change-size (if n
963 (1+ (/ n 10.0))
964 1.2)))
966 (defun image-decrease-size (n)
967 "Decrease the image size by a factor of N.
968 If N is 3, then the image size will be decreased by 30%. The
969 default is 20%."
970 (interactive "P")
971 (image--change-size (if n
972 (- 1 (/ n 10.0))
973 0.8)))
975 (defun image--get-image ()
976 (let ((image (get-text-property (point) 'display)))
977 (unless (eq (car-safe image) 'image)
978 (error "No image under point"))
979 image))
981 (defun image--get-imagemagick-and-warn ()
982 (unless (fboundp 'imagemagick-types)
983 (error "Cannot rescale images without ImageMagick support"))
984 (let ((image (image--get-image)))
985 (image-flush image)
986 (plist-put (cdr image) :type 'imagemagick)
987 image))
989 (defun image--change-size (factor)
990 (let* ((image (image--get-imagemagick-and-warn))
991 (new-image (image--image-without-parameters image))
992 (scale (image--current-scaling image new-image)))
993 (setcdr image (cdr new-image))
994 (plist-put (cdr image) :scale (* scale factor))))
996 (defun image--image-without-parameters (image)
997 (cons (pop image)
998 (let ((new nil))
999 (while image
1000 (let ((key (pop image))
1001 (val (pop image)))
1002 (unless (memq key '(:scale :width :height :max-width :max-height))
1003 (setq new (nconc new (list key val))))))
1004 new)))
1006 (defun image--current-scaling (image new-image)
1007 ;; The image may be scaled due to many reasons (:scale, :max-width,
1008 ;; etc), so find out what the current scaling is based on the
1009 ;; original image size and the displayed size.
1010 (let ((image-width (car (image-size new-image t)))
1011 (display-width (car (image-size image t))))
1012 (/ (float display-width) image-width)))
1014 (defun image-rotate ()
1015 "Rotate the image under point by 90 degrees clockwise."
1016 (interactive)
1017 (let ((image (image--get-imagemagick-and-warn)))
1018 (plist-put (cdr image) :rotation
1019 (float (mod (+ (or (plist-get (cdr image) :rotation) 0) 90)
1020 ;; We don't want to exceed 360 degrees
1021 ;; rotation, because it's not seen as valid
1022 ;; in exif data.
1023 360)))))
1025 (defun image-save ()
1026 "Save the image under point."
1027 (interactive)
1028 (let ((image (get-text-property (point) 'display)))
1029 (when (or (not (consp image))
1030 (not (eq (car image) 'image)))
1031 (error "No image under point"))
1032 (with-temp-buffer
1033 (let ((file (plist-get (cdr image) :file)))
1034 (if file
1035 (if (not (file-exists-p file))
1036 (error "File %s no longer exists" file)
1037 (insert-file-contents-literally file))
1038 (insert (plist-get (cdr image) :data))))
1039 (write-region (point-min) (point-max)
1040 (read-file-name "Write image to file: ")))))
1042 (provide 'image)
1044 ;;; image.el ends here