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