]> code.delx.au - gnu-emacs/blob - lisp/image.el
Merge from origin/emacs-25
[gnu-emacs] / lisp / image.el
1 ;;; image.el --- image API
2
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
4
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: multimedia
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28
29 (defgroup image ()
30 "Image support."
31 :group 'multimedia)
32
33 (defalias 'image-refresh 'image-flush)
34
35 (defconst image-type-header-regexps
36 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
37 ("\\`P[1-6]\\(?:\
38 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[[:space:]]\\)+\
39 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[0-9]\\)+\
40 \\)\\{2\\}" . pbm)
41 ("\\`GIF8[79]a" . gif)
42 ("\\`\x89PNG\r\n\x1a\n" . png)
43 ("\\`[\t\n\r ]*#define \\([a-z0-9_]+\\)_width [0-9]+\n\
44 #define \\1_height [0-9]+\n\\(\
45 #define \\1_x_hot [0-9]+\n\
46 #define \\1_y_hot [0-9]+\n\\)?\
47 static \\(unsigned \\)?char \\1_bits" . xbm)
48 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
49 ("\\`[\t\n\r ]*%!PS" . postscript)
50 ("\\`\xff\xd8" . jpeg) ; used to be (image-jpeg-p . jpeg)
51 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
52 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
53 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
54 comment-re "*"
55 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
56 "[Ss][Vv][Gg]"))
57 . svg)
58 )
59 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
60 When the first bytes of an image file match REGEXP, it is assumed to
61 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
62 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
63 with one argument, a string containing the image data. If PREDICATE returns
64 a non-nil value, TYPE is the image's type.")
65
66 (defvar image-type-file-name-regexps
67 '(("\\.png\\'" . png)
68 ("\\.gif\\'" . gif)
69 ("\\.jpe?g\\'" . jpeg)
70 ("\\.bmp\\'" . bmp)
71 ("\\.xpm\\'" . xpm)
72 ("\\.pbm\\'" . pbm)
73 ("\\.xbm\\'" . xbm)
74 ("\\.ps\\'" . postscript)
75 ("\\.tiff?\\'" . tiff)
76 ("\\.svgz?\\'" . svg)
77 )
78 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
79 When the name of an image file match REGEXP, it is assumed to
80 be of image type IMAGE-TYPE.")
81
82 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
83 ;; of content autodetection. Their contents are just C code, so it is
84 ;; easy to generate false matches.
85 (defvar image-type-auto-detectable
86 '((pbm . t)
87 (xbm . nil)
88 (bmp . maybe)
89 (gif . maybe)
90 (png . maybe)
91 (xpm . nil)
92 (jpeg . maybe)
93 (tiff . maybe)
94 (svg . maybe)
95 (postscript . nil))
96 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
97 \(See `image-type-auto-detected-p').
98
99 AUTODETECT can be
100 - t always auto-detect.
101 - nil never auto-detect.
102 - maybe auto-detect only if the image type is available
103 (see `image-type-available-p').")
104
105 (defvar image-format-suffixes
106 '((image/x-icon "ico"))
107 "An alist associating image types with file name suffixes.
108 This is used as a hint by the ImageMagick library when detecting
109 the type of image data (that does not have an associated file name).
110 Each element has the form (MIME-CONTENT-TYPE EXTENSION).
111 If `create-image' is called with a :format attribute whose value
112 equals a content-type found in this list, the ImageMagick library is
113 told that the data would have the associated suffix if saved to a file.")
114
115 (defcustom image-load-path
116 (list (file-name-as-directory (expand-file-name "images" data-directory))
117 'data-directory 'load-path)
118 "List of locations in which to search for image files.
119 If an element is a string, it defines a directory to search.
120 If an element is a variable symbol whose value is a string, that
121 value defines a directory to search.
122 If an element is a variable symbol whose value is a list, the
123 value is used as a list of directories to search.
124
125 Subdirectories are not automatically included in the search."
126 :type '(repeat (choice directory variable))
127 :initialize 'custom-initialize-delay)
128
129 (defcustom image-scaling-factor 'auto
130 "When displaying images, apply this scaling factor before displaying.
131 This is not supported for all image types, and is mostly useful
132 when you have a high-resolution monitor.
133 The value is either a floating point number (where numbers higher
134 than 1 means to increase the size and lower means to shrink the
135 size), or the symbol `auto', which will compute a scaling factor
136 based on the font pixel size."
137 :type '(choice number
138 (const :tag "Automatically compute" auto))
139 :group 'image
140 :version "25.2")
141
142 ;; Map put into text properties on images.
143 (defvar image-map
144 (let ((map (make-sparse-keymap)))
145 (set-keymap-parent map special-mode-map)
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))
151
152 (defun image-load-path-for-library (library image &optional path no-error)
153 "Return a suitable search path for images used by LIBRARY.
154
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\".
160
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'.
165
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.
169
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':
173
174 ;; Shush compiler.
175 (defvar image-load-path)
176
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))
202
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))
239 (t
240 (error "Could not find image %s for library %s" image library)))
241
242 ;; Return an augmented `path' or `load-path'.
243 (nconc (list image-directory)
244 (delete image-directory (copy-sequence (or path load-path))))))
245
246
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))))))))
271
272
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))
292
293
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)))
326
327
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))))
342
343
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)
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))))))))
357
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)
378
379
380 (if (fboundp 'image-metadata) ; eg not --without-x
381 (define-obsolete-function-alias 'image-extension-data
382 'image-metadata "24.1"))
383
384 (define-obsolete-variable-alias
385 'image-library-alist
386 'dynamic-library-alist "24.1")
387
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)))
394
395
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'.
400
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)))))
410
411
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.
424
425 Images should not be larger than specified by `max-image-size'.
426
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)))
438
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)
453
454 (defun image-property (image property)
455 "Return the value of PROPERTY in IMAGE.
456 Properties can be set with
457
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))
462
463 (defun image-compute-scaling-factor (scaling)
464 (cond
465 ((numberp image-scaling-factor)
466 image-scaling-factor)
467 ((eq image-scaling-factor '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)
473 1
474 (/ (float width) 10))))
475 (t
476 (error "Invalid scaling factor %s" image-scaling-factor))))
477
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)))
505
506
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))))
546
547
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)))))
587
588
589
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)))))
603
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)))
627
628 ;;;###autoload
629 (defun find-image (specs)
630 "Find an image, choosing one of a list of image specifications.
631
632 SPECS is a list of image specifications.
633
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.
643
644 The image is looked for in `image-load-path'.
645
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))
664
665
666 ;;;###autoload
667 (defmacro defimage (symbol specs &optional doc)
668 "Define SYMBOL as an image, and return SYMBOL.
669
670 SPECS is a list of image specifications. DOC is an optional
671 documentation string.
672
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.
681
682 Example:
683
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))
688
689 \f
690 ;;; Animated image API
691
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.")
695
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)))))
710
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)))
715
716 (make-obsolete 'image-animated-p 'image-multi-frame-p "24.4")
717
718 ;; "Destructively"?
719 (defun image-animate (image &optional index limit)
720 "Start animating IMAGE.
721 Animation occurs by destructively altering the IMAGE spec list.
722
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))))
736
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))
749
750 (defconst image-minimum-frame-delay 0.01
751 "Minimum interval in seconds between frames of an animated image.")
752
753 (defun image-current-frame (image)
754 "The current frame number of IMAGE, indexed from 0."
755 (or (plist-get (cdr image) :index) 0))
756
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))
766
767 (defun image-animate-get-speed (image)
768 "Return the speed factor for animating IMAGE."
769 (or (plist-get (cdr image) :speed) 1))
770
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)))
779
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)
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'.
794
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 (buffer-live-p (plist-get (cdr image) :animate-buffer))
798 (image-show-frame image n t)
799 (let* ((speed (image-animate-get-speed image))
800 (time (float-time))
801 (animation (image-multi-frame-p image))
802 ;; Subtract off the time we took to load the image from the
803 ;; stated delay time.
804 (delay (max (+ (* (or (cdr animation) image-default-frame-delay)
805 (/ 1.0 (abs speed)))
806 time (- (float-time)))
807 image-minimum-frame-delay))
808 done)
809 (setq n (if (< speed 0)
810 (1- n)
811 (1+ n)))
812 (if limit
813 (cond ((>= n count) (setq n 0))
814 ((< n 0) (setq n (1- count))))
815 (and (or (>= n count) (< n 0)) (setq done t)))
816 (setq time-elapsed (+ delay time-elapsed))
817 (if (numberp limit)
818 (setq done (>= time-elapsed limit)))
819 (unless done
820 (run-with-timer delay nil 'image-animate-timeout
821 image n count time-elapsed limit)))))
822
823 \f
824 (defvar imagemagick-types-inhibit)
825 (defvar imagemagick-enabled-types)
826
827 (defun imagemagick-filter-types ()
828 "Return a list of the ImageMagick types to be treated as images, or nil.
829 This is the result of `imagemagick-types', including only elements
830 that match `imagemagick-enabled-types' and do not match
831 `imagemagick-types-inhibit'."
832 (when (fboundp 'imagemagick-types)
833 (cond ((null imagemagick-enabled-types) nil)
834 ((eq imagemagick-types-inhibit t) nil)
835 (t
836 (delq nil
837 (mapcar
838 (lambda (type)
839 (unless (memq type imagemagick-types-inhibit)
840 (if (eq imagemagick-enabled-types t) type
841 (catch 'found
842 (dolist (enable imagemagick-enabled-types nil)
843 (if (cond ((symbolp enable) (eq enable type))
844 ((stringp enable)
845 (string-match enable
846 (symbol-name type))))
847 (throw 'found type)))))))
848 (imagemagick-types)))))))
849
850 (defvar imagemagick--file-regexp nil
851 "File extension regexp for ImageMagick files, if any.
852 This is the extension installed into `auto-mode-alist' and
853 `image-type-file-name-regexps' by `imagemagick-register-types'.")
854
855 ;;;###autoload
856 (defun imagemagick-register-types ()
857 "Register file types that can be handled by ImageMagick.
858 This function is called at startup, after loading the init file.
859 It registers the ImageMagick types returned by `imagemagick-filter-types'.
860
861 Registered image types are added to `auto-mode-alist', so that
862 Emacs visits them in Image mode. They are also added to
863 `image-type-file-name-regexps', so that the `image-type' function
864 recognizes these files as having image type `imagemagick'.
865
866 If Emacs is compiled without ImageMagick support, this does nothing."
867 (when (fboundp 'imagemagick-types)
868 (let* ((types (mapcar (lambda (type) (downcase (symbol-name type)))
869 (imagemagick-filter-types)))
870 (re (if types (concat "\\." (regexp-opt types) "\\'")))
871 (ama-elt (car (member (cons imagemagick--file-regexp 'image-mode)
872 auto-mode-alist)))
873 (itfnr-elt (car (member (cons imagemagick--file-regexp 'imagemagick)
874 image-type-file-name-regexps))))
875 (if (not re)
876 (setq auto-mode-alist (delete ama-elt auto-mode-alist)
877 image-type-file-name-regexps
878 (delete itfnr-elt image-type-file-name-regexps))
879 (if ama-elt
880 (setcar ama-elt re)
881 (push (cons re 'image-mode) auto-mode-alist))
882 (if itfnr-elt
883 (setcar itfnr-elt re)
884 ;; Append to `image-type-file-name-regexps', so that we
885 ;; preferentially use specialized image libraries.
886 (add-to-list 'image-type-file-name-regexps
887 (cons re 'imagemagick) t)))
888 (setq imagemagick--file-regexp re))))
889
890 (defcustom imagemagick-types-inhibit
891 '(C HTML HTM INFO M TXT PDF)
892 "List of ImageMagick types that should never be treated as images.
893 This should be a list of symbols, each of which should be one of
894 the ImageMagick types listed by `imagemagick-types'. The listed
895 image types are not registered by `imagemagick-register-types'.
896
897 If the value is t, inhibit the use of ImageMagick for images.
898
899 If you change this without using customize, you must call
900 `imagemagick-register-types' afterwards.
901
902 If Emacs is compiled without ImageMagick support, this variable
903 has no effect."
904 :type '(choice (const :tag "Support all ImageMagick types" nil)
905 (const :tag "Disable all ImageMagick types" t)
906 (repeat symbol))
907 :initialize 'custom-initialize-default
908 :set (lambda (symbol value)
909 (set-default symbol value)
910 (imagemagick-register-types))
911 :version "24.3"
912 :group 'image)
913
914 (defcustom imagemagick-enabled-types
915 '(3FR ART ARW AVS BMP BMP2 BMP3 CAL CALS CMYK CMYKA CR2 CRW
916 CUR CUT DCM DCR DCX DDS DJVU DNG DPX EXR FAX FITS GBR GIF
917 GIF87 GRB HRZ ICB ICO ICON J2C JNG JP2 JPC JPEG JPG JPX K25
918 KDC MIFF MNG MRW MSL MSVG MTV NEF ORF OTB PBM PCD PCDS PCL
919 PCT PCX PDB PEF PGM PICT PIX PJPEG PNG PNG24 PNG32 PNG8 PNM
920 PPM PSD PTIF PWP RAF RAS RBG RGB RGBA RGBO RLA RLE SCR SCT
921 SFW SGI SR2 SRF SUN SVG SVGZ TGA TIFF TIFF64 TILE TIM TTF
922 UYVY VDA VICAR VID VIFF VST WBMP WPG X3F XBM XC XCF XPM XV
923 XWD YCbCr YCbCrA YUV)
924 "List of ImageMagick types to treat as images.
925 Each list element should be a string or symbol, representing one
926 of the image types returned by `imagemagick-types'. If the
927 element is a string, it is handled as a regexp that enables all
928 matching types.
929
930 The value of `imagemagick-enabled-types' may also be t, meaning
931 to enable all types that ImageMagick supports.
932
933 The variable `imagemagick-types-inhibit' overrides this variable.
934
935 If you change this without using customize, you must call
936 `imagemagick-register-types' afterwards.
937
938 If Emacs is compiled without ImageMagick support, this variable
939 has no effect."
940 :type '(choice (const :tag "Support all ImageMagick types" t)
941 (const :tag "Disable all ImageMagick types" nil)
942 (repeat :tag "List of types"
943 (choice (symbol :tag "type")
944 (regexp :tag "regexp"))))
945 :initialize 'custom-initialize-default
946 :set (lambda (symbol value)
947 (set-default symbol value)
948 (imagemagick-register-types))
949 :version "24.3"
950 :group 'image)
951
952 (imagemagick-register-types)
953
954 (defun image-increase-size (n)
955 "Increase the image size by a factor of N.
956 If N is 3, then the image size will be increased by 30%. The
957 default is 20%."
958 (interactive "P")
959 (image--change-size (if n
960 (1+ (/ n 10))
961 1.2)))
962
963 (defun image-decrease-size (n)
964 "Decrease the image size by a factor of N.
965 If N is 3, then the image size will be decreased by 30%. The
966 default is 20%."
967 (interactive "P")
968 (image--change-size (if n
969 (- 1 (/ n 10))
970 0.8)))
971
972 (defun image--get-image ()
973 (let ((image (or (get-text-property (point) 'display)
974 ;; `put-image' uses overlays, so find an image in
975 ;; the overlays.
976 (seq-find (lambda (overlay)
977 (overlay-get overlay 'display))
978 (overlays-at (point))))))
979 (when (or (not (consp image))
980 (not (eq (car image) 'image)))
981 (error "No image under point"))
982 image))
983
984 (defun image--get-imagemagick-and-warn ()
985 (unless (fboundp 'imagemagick-types)
986 (error "Can't rescale images without ImageMagick support"))
987 (let ((image (image--get-image)))
988 (image-flush image)
989 (plist-put (cdr image) :type 'imagemagick)
990 image))
991
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))))
998
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)))
1008
1009 (defun image--current-scaling (image new-image)
1010 ;; The image may be scaled due to many reasons (:scale, :max-width,
1011 ;; etc), so find out what the current scaling is based on the
1012 ;; original image size and the displayed size.
1013 (let ((image-width (car (image-size new-image t)))
1014 (display-width (car (image-size image t))))
1015 (/ (float display-width) image-width)))
1016
1017 (defun image-rotate ()
1018 "Rotate the image under point by 90 degrees clockwise."
1019 (interactive)
1020 (let ((image (image--get-imagemagick-and-warn)))
1021 (plist-put (cdr image) :rotation
1022 (float (+ (or (plist-get (cdr image) :rotation) 0) 90)))))
1023
1024 (defun image-save ()
1025 "Save the image under point."
1026 (interactive)
1027 (let ((image (get-text-property (point) 'display)))
1028 (when (or (not (consp image))
1029 (not (eq (car image) 'image)))
1030 (error "No image under point"))
1031 (with-temp-buffer
1032 (let ((file (plist-get (cdr image) :file)))
1033 (if file
1034 (if (not (file-exists-p file))
1035 (error "File %s no longer exists" file)
1036 (insert-file-contents-literally file))
1037 (insert (plist-get (cdr image) :data))))
1038 (write-region (point-min) (point-max)
1039 (read-file-name "Write image to file: ")))))
1040
1041 (provide 'image)
1042
1043 ;;; image.el ends here