1 ;;; image.el --- image API
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: multimedia
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 <http://www.gnu.org/licenses/>.
33 (defalias 'image-refresh
'image-flush
)
35 (defconst image-type-header-regexps
36 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm
)
38 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[[:space:]]\\)+\
39 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[0-9]\\)+\
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]*<"
55 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re
"*\\)?"
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.")
66 (defvar image-type-file-name-regexps
69 ("\\.jpe?g\\'" . jpeg
)
74 ("\\.ps\\'" . postscript
)
75 ("\\.tiff?\\'" . tiff
)
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.")
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
96 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
97 \(See `image-type-auto-detected-p').
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').")
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.")
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.
125 Subdirectories are not automatically included in the search."
126 :type
'(repeat (choice directory variable
))
127 :initialize
'custom-initialize-delay
)
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
))
142 ;; Map put into text properties on images.
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
)
151 (defun image-load-path-for-library (library image
&optional path no-error
)
152 "Return a suitable search path for images used by LIBRARY.
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\".
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
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.
169 Here is an example that uses a common idiom to provide
170 compatibility with versions of Emacs that lack the variable
174 (defvar image-load-path)
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)
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.
187 ;; Images in image-load-path.
188 (image-search-load-path image
)
189 ;; Images in load-path.
190 (locate-library image
)))
192 ;; Since the image might be in a nested directory (for
193 ;; example, mail/attach.pbm), adjust `image-directory'
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
))
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'.
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.
222 d2ei
(file-name-as-directory
224 (concat (file-name-directory library-name
) "../../etc/images")))
226 d1ei
(file-name-as-directory
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
))
237 (message "Could not find image %s for library %s" image library
))
239 (error "Could not find image %s for library %s" image library
)))
241 ;; Return an augmented `path' or `load-path'.
242 (nconc (list image-directory
)
243 (delete image-directory
(copy-sequence (or path load-path
))))))
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
))
254 (let ((len (length data
)) (i 2))
256 (when (/= (aref data i
) #xff
)
259 (when (>= (+ i
2) len
)
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"
267 (string-match-p "JFIF\\|Exif"
268 (substring data i
(min (+ i nbytes
) len
)))))
269 (setq i
(+ i
1 nbytes
))))))))
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
277 (let ((types image-type-header-regexps
)
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
289 (setq types
(cdr types
)))))
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
298 (let ((types image-type-header-regexps
)
301 (goto-char (point-min))
303 (let ((regexp (car (car types
)))
304 (image-type (cdr (car types
)))
306 (if (or (and (symbolp image-type
)
307 (looking-at-p regexp
))
308 (and (consp image-type
)
309 (funcall (car image-type
)
315 (+ (point-min) 256))))))
316 (setq image-type
(cdr image-type
))))
317 (setq type image-type
319 (setq types
(cdr types
)))))
322 (boundp 'image-types
)
323 (memq type image-types
)
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
332 (unless (or (file-readable-p file
)
333 (file-name-absolute-p file
))
334 (setq file
(image-search-load-path file
)))
336 (file-readable-p file
)
338 (set-buffer-multibyte nil
)
339 (insert-file-contents-literally file nil
0 256)
340 (image-type-from-buffer))))
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
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
)))
354 ;; If nothing seems to be supported, return first type that matched.
355 (or first
(setq first type
))))))))
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
))
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
))
379 (if (fboundp 'image-metadata
) ; eg not --without-x
380 (define-obsolete-function-alias 'image-extension-data
381 'image-metadata
"24.1"))
383 (define-obsolete-variable-alias
385 'dynamic-library-alist
"24.1")
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
)))
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'.
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
405 (let* ((type (image-type-from-buffer))
406 (auto (and type
(cdr (assq type image-type-auto-detectable
)))))
408 (or (eq auto t
) (image-type-available-p type
)))))
412 (defun create-image (file-or-data &optional type data-p
&rest props
)
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.
424 Images should not be larger than specified by `max-image-size'.
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
))
435 (image-compute-scaling-factor image-scaling-factor
)))
438 (defun image--set-property (image property value
)
439 "Set PROPERTY in IMAGE to VALUE.
443 ;; IMAGE starts with the symbol `image', and the rest is a
444 ;; plist. Decouple plist entries where the key matches
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
))
453 (defun image-property (image property
)
454 "Return the value of PROPERTY in IMAGE.
455 Properties can be set with
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
))
462 (defun image-compute-scaling-factor (scaling)
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.
473 (/ (float width
) 10))))
475 (error "Invalid scaling factor %s" image-scaling-factor
))))
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
)
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
))
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)))
539 (add-text-properties start
(point)
541 (list (cons 'slice slice
) image
)
543 rear-nonsticky
(display)
544 keymap
,image-map
))))
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
))
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))))
576 (let ((start (point)))
578 (add-text-properties start
(point)
579 `(display ,(list (list 'slice x y dx dy
) image
)
580 rear-nonsticky
(display)
585 (insert (propertize "\n" 'line-height t
)))))
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."
595 (setq buffer
(current-buffer)))
596 (let ((overlays (overlays-in start end
)))
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
)
605 (setq path image-load-path
))
606 (let (element found filename
)
607 (while (and (not found
) (consp path
))
608 (setq element
(car path
))
613 (setq filename
(expand-file-name file element
)))))
614 ((and (symbolp element
) (boundp element
))
615 (setq element
(symbol-value element
))
620 (setq filename
(expand-file-name file element
)))))
622 (if (setq filename
(image-search-load-path file element
))
624 (setq path
(cdr path
)))
625 (if found filename
)))
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
643 The image is looked for in `image-load-path'.
645 Image files should not be larger than specified by `max-image-size'."
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
))
653 (when (image-type-available-p type
)
654 (cond ((stringp file
)
655 (if (setq found
(image-search-load-path file
))
657 (cons 'image
(plist-put (copy-sequence spec
)
660 (setq image
(cons 'image spec
)))))
661 (setq specs
(cdr specs
))))
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
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")
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
))
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
)
741 (setq timer
(car tail
)
743 (if (and (eq (timer--function timer
) 'image-animate-timeout
)
744 (eq (car-safe (timer--args timer
)) image
))
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."
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
776 (* value
(image-animate-get-speed image
))
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
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 (when (> (- (float-time) target-time
) 2)
799 (message "Stopping animation; animation possibly too big")
801 (image-show-frame image n t
)
802 (let* ((speed (image-animate-get-speed image
))
804 (animation (image-multi-frame-p image
))
805 ;; Subtract off the time we took to load the image from the
806 ;; stated delay time.
807 (delay (max (+ (* (or (cdr animation
) image-default-frame-delay
)
809 time
(- (float-time)))
810 image-minimum-frame-delay
))
812 (setq n
(if (< speed
0)
816 (cond ((>= n count
) (setq n
0))
817 ((< n
0) (setq n
(1- count
))))
818 (and (or (>= n count
) (< n
0)) (setq done t
)))
819 (setq time-elapsed
(+ delay time-elapsed
))
821 (setq done
(>= time-elapsed limit
)))
823 (run-with-timer delay nil
'image-animate-timeout
824 image n count time-elapsed limit
825 (+ (float-time) delay
))))))
828 (defvar imagemagick-types-inhibit
)
829 (defvar imagemagick-enabled-types
)
831 (defun imagemagick-filter-types ()
832 "Return a list of the ImageMagick types to be treated as images, or nil.
833 This is the result of `imagemagick-types', including only elements
834 that match `imagemagick-enabled-types' and do not match
835 `imagemagick-types-inhibit'."
836 (when (fboundp 'imagemagick-types
)
837 (cond ((null imagemagick-enabled-types
) nil
)
838 ((eq imagemagick-types-inhibit t
) nil
)
843 (unless (memq type imagemagick-types-inhibit
)
844 (if (eq imagemagick-enabled-types t
) type
846 (dolist (enable imagemagick-enabled-types nil
)
847 (if (cond ((symbolp enable
) (eq enable type
))
850 (symbol-name type
))))
851 (throw 'found type
)))))))
852 (imagemagick-types)))))))
854 (defvar imagemagick--file-regexp nil
855 "File extension regexp for ImageMagick files, if any.
856 This is the extension installed into `auto-mode-alist' and
857 `image-type-file-name-regexps' by `imagemagick-register-types'.")
860 (defun imagemagick-register-types ()
861 "Register file types that can be handled by ImageMagick.
862 This function is called at startup, after loading the init file.
863 It registers the ImageMagick types returned by `imagemagick-filter-types'.
865 Registered image types are added to `auto-mode-alist', so that
866 Emacs visits them in Image mode. They are also added to
867 `image-type-file-name-regexps', so that the `image-type' function
868 recognizes these files as having image type `imagemagick'.
870 If Emacs is compiled without ImageMagick support, this does nothing."
871 (when (fboundp 'imagemagick-types
)
872 (let* ((types (mapcar (lambda (type) (downcase (symbol-name type
)))
873 (imagemagick-filter-types)))
874 (re (if types
(concat "\\." (regexp-opt types
) "\\'")))
875 (ama-elt (car (member (cons imagemagick--file-regexp
'image-mode
)
877 (itfnr-elt (car (member (cons imagemagick--file-regexp
'imagemagick
)
878 image-type-file-name-regexps
))))
880 (setq auto-mode-alist
(delete ama-elt auto-mode-alist
)
881 image-type-file-name-regexps
882 (delete itfnr-elt image-type-file-name-regexps
))
885 (push (cons re
'image-mode
) auto-mode-alist
))
887 (setcar itfnr-elt re
)
888 ;; Append to `image-type-file-name-regexps', so that we
889 ;; preferentially use specialized image libraries.
890 (add-to-list 'image-type-file-name-regexps
891 (cons re
'imagemagick
) t
)))
892 (setq imagemagick--file-regexp re
))))
894 (defcustom imagemagick-types-inhibit
895 '(C HTML HTM INFO M TXT PDF
)
896 "List of ImageMagick types that should never be treated as images.
897 This should be a list of symbols, each of which should be one of
898 the ImageMagick types listed by `imagemagick-types'. The listed
899 image types are not registered by `imagemagick-register-types'.
901 If the value is t, inhibit the use of ImageMagick for images.
903 If you change this without using customize, you must call
904 `imagemagick-register-types' afterwards.
906 If Emacs is compiled without ImageMagick support, this variable
908 :type
'(choice (const :tag
"Support all ImageMagick types" nil
)
909 (const :tag
"Disable all ImageMagick types" t
)
911 :initialize
'custom-initialize-default
912 :set
(lambda (symbol value
)
913 (set-default symbol value
)
914 (imagemagick-register-types))
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
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
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))
956 (imagemagick-register-types)
958 (defun image-increase-size (n)
959 "Increase the image size by a factor of N.
960 If N is 3, then the image size will be increased by 30%. The
963 (image--change-size (if n
967 (defun image-decrease-size (n)
968 "Decrease the image size by a factor of N.
969 If N is 3, then the image size will be decreased by 30%. The
972 (image--change-size (if n
976 (defun image--get-image ()
977 (let ((image (or (get-text-property (point) 'display
)
978 ;; `put-image' uses overlays, so find an image in
980 (seq-find (lambda (overlay)
981 (overlay-get overlay
'display
))
982 (overlays-at (point))))))
983 (when (or (not (consp image
))
984 (not (eq (car image
) 'image
)))
985 (error "No image under point"))
988 (defun image--get-imagemagick-and-warn ()
989 (unless (fboundp 'imagemagick-types
)
990 (error "Can't rescale images without ImageMagick support"))
991 (let ((image (image--get-image)))
993 (plist-put (cdr image
) :type
'imagemagick
)
996 (defun image--change-size (factor)
997 (let* ((image (image--get-imagemagick-and-warn))
998 (new-image (image--image-without-parameters image
))
999 (scale (image--current-scaling image new-image
)))
1000 (setcdr image
(cdr new-image
))
1001 (plist-put (cdr image
) :scale
(* scale factor
))))
1003 (defun image--image-without-parameters (image)
1007 (let ((key (pop image
))
1009 (unless (memq key
'(:scale
:width
:height
:max-width
:max-height
))
1010 (setq new
(nconc new
(list key val
))))))
1013 (defun image--current-scaling (image new-image
)
1014 ;; The image may be scaled due to many reasons (:scale, :max-width,
1015 ;; etc), so find out what the current scaling is based on the
1016 ;; original image size and the displayed size.
1017 (let ((image-width (car (image-size new-image t
)))
1018 (display-width (car (image-size image t
))))
1019 (/ (float display-width
) image-width
)))
1021 (defun image-rotate ()
1022 "Rotate the image under point by 90 degrees clockwise."
1024 (let ((image (image--get-imagemagick-and-warn)))
1025 (plist-put (cdr image
) :rotation
1026 (float (+ (or (plist-get (cdr image
) :rotation
) 0) 90)))))
1028 (defun image-save ()
1029 "Save the image under point."
1031 (let ((image (get-text-property (point) 'display
)))
1032 (when (or (not (consp image
))
1033 (not (eq (car image
) 'image
)))
1034 (error "No image under point"))
1036 (let ((file (plist-get (cdr image
) :file
)))
1038 (if (not (file-exists-p file
))
1039 (error "File %s no longer exists" file
)
1040 (insert-file-contents-literally file
))
1041 (insert (plist-get (cdr image
) :data
))))
1042 (write-region (point-min) (point-max)
1043 (read-file-name "Write image to file: ")))))
1047 ;;; image.el ends here