]> code.delx.au - gnu-emacs/blob - lisp/image.el
Add missing dependencies to seq.el
[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 (require 'seq)
29
30 (defgroup image ()
31 "Image support."
32 :group 'multimedia)
33
34 (defalias 'image-refresh 'image-flush)
35
36 (defconst image-type-header-regexps
37 `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
38 ("\\`P[1-6]\\(?:\
39 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[[:space:]]\\)+\
40 \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[0-9]\\)+\
41 \\)\\{2\\}" . pbm)
42 ("\\`GIF8[79]a" . gif)
43 ("\\`\x89PNG\r\n\x1a\n" . png)
44 ("\\`[\t\n\r ]*#define \\([a-z0-9_]+\\)_width [0-9]+\n\
45 #define \\1_height [0-9]+\n\\(\
46 #define \\1_x_hot [0-9]+\n\
47 #define \\1_y_hot [0-9]+\n\\)?\
48 static \\(unsigned \\)?char \\1_bits" . xbm)
49 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
50 ("\\`[\t\n\r ]*%!PS" . postscript)
51 ("\\`\xff\xd8" . jpeg) ; used to be (image-jpeg-p . jpeg)
52 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
53 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
54 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
55 comment-re "*"
56 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
57 "[Ss][Vv][Gg]"))
58 . svg)
59 )
60 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
61 When the first bytes of an image file match REGEXP, it is assumed to
62 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
63 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
64 with one argument, a string containing the image data. If PREDICATE returns
65 a non-nil value, TYPE is the image's type.")
66
67 (defvar image-type-file-name-regexps
68 '(("\\.png\\'" . png)
69 ("\\.gif\\'" . gif)
70 ("\\.jpe?g\\'" . jpeg)
71 ("\\.bmp\\'" . bmp)
72 ("\\.xpm\\'" . xpm)
73 ("\\.pbm\\'" . pbm)
74 ("\\.xbm\\'" . xbm)
75 ("\\.ps\\'" . postscript)
76 ("\\.tiff?\\'" . tiff)
77 ("\\.svgz?\\'" . svg)
78 )
79 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
80 When the name of an image file match REGEXP, it is assumed to
81 be of image type IMAGE-TYPE.")
82
83 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
84 ;; of content autodetection. Their contents are just C code, so it is
85 ;; easy to generate false matches.
86 (defvar image-type-auto-detectable
87 '((pbm . t)
88 (xbm . nil)
89 (bmp . maybe)
90 (gif . maybe)
91 (png . maybe)
92 (xpm . nil)
93 (jpeg . maybe)
94 (tiff . maybe)
95 (svg . maybe)
96 (postscript . nil))
97 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
98 \(See `image-type-auto-detected-p').
99
100 AUTODETECT can be
101 - t always auto-detect.
102 - nil never auto-detect.
103 - maybe auto-detect only if the image type is available
104 (see `image-type-available-p').")
105
106 (defvar image-format-suffixes
107 '((image/x-icon "ico"))
108 "An alist associating image types with file name suffixes.
109 This is used as a hint by the ImageMagick library when detecting
110 the type of image data (that does not have an associated file name).
111 Each element has the form (MIME-CONTENT-TYPE EXTENSION).
112 If `create-image' is called with a :format attribute whose value
113 equals a content-type found in this list, the ImageMagick library is
114 told that the data would have the associated suffix if saved to a file.")
115
116 (defcustom image-load-path
117 (list (file-name-as-directory (expand-file-name "images" data-directory))
118 'data-directory 'load-path)
119 "List of locations in which to search for image files.
120 If an element is a string, it defines a directory to search.
121 If an element is a variable symbol whose value is a string, that
122 value defines a directory to search.
123 If an element is a variable symbol whose value is a list, the
124 value is used as a list of directories to search.
125
126 Subdirectories are not automatically included in the search."
127 :type '(repeat (choice directory variable))
128 :initialize 'custom-initialize-delay)
129
130 (defcustom image-scaling-factor 'auto
131 "When displaying images, apply this scaling factor before displaying.
132 This is not supported for all image types, and is mostly useful
133 when you have a high-resolution monitor.
134 The value is either a floating point number (where numbers higher
135 than 1 means to increase the size and lower means to shrink the
136 size), or the symbol `auto', which will compute a scaling factor
137 based on the font pixel size."
138 :type '(choice number
139 (const :tag "Automatically compute" auto))
140 :group 'image
141 :version "25.2")
142
143 ;; Map put into text properties on images.
144 (defvar image-map
145 (let ((map (make-sparse-keymap)))
146 (define-key map "-" 'image-decrease-size)
147 (define-key map "+" 'image-increase-size)
148 (define-key map "r" 'image-rotate)
149 (define-key map "o" 'image-save)
150 map))
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 (+ (float-time) 0.2)))))
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 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'.
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 (and (buffer-live-p (plist-get (cdr image) :animate-buffer))
798 ;; Delayed more than two seconds more than expected.
799 (when (> (- (float-time) target-time) 2)
800 (message "Stopping animation; animation possibly too big")
801 nil))
802 (image-show-frame image n t)
803 (let* ((speed (image-animate-get-speed image))
804 (time (float-time))
805 (animation (image-multi-frame-p image))
806 ;; Subtract off the time we took to load the image from the
807 ;; stated delay time.
808 (delay (max (+ (* (or (cdr animation) image-default-frame-delay)
809 (/ 1.0 (abs speed)))
810 time (- (float-time)))
811 image-minimum-frame-delay))
812 done)
813 (setq n (if (< speed 0)
814 (1- n)
815 (1+ n)))
816 (if limit
817 (cond ((>= n count) (setq n 0))
818 ((< n 0) (setq n (1- count))))
819 (and (or (>= n count) (< n 0)) (setq done t)))
820 (setq time-elapsed (+ delay time-elapsed))
821 (if (numberp limit)
822 (setq done (>= time-elapsed limit)))
823 (unless done
824 (run-with-timer delay nil 'image-animate-timeout
825 image n count time-elapsed limit
826 (+ (float-time) delay))))))
827
828 \f
829 (defvar imagemagick-types-inhibit)
830 (defvar imagemagick-enabled-types)
831
832 (defun imagemagick-filter-types ()
833 "Return a list of the ImageMagick types to be treated as images, or nil.
834 This is the result of `imagemagick-types', including only elements
835 that match `imagemagick-enabled-types' and do not match
836 `imagemagick-types-inhibit'."
837 (when (fboundp 'imagemagick-types)
838 (cond ((null imagemagick-enabled-types) nil)
839 ((eq imagemagick-types-inhibit t) nil)
840 (t
841 (delq nil
842 (mapcar
843 (lambda (type)
844 (unless (memq type imagemagick-types-inhibit)
845 (if (eq imagemagick-enabled-types t) type
846 (catch 'found
847 (dolist (enable imagemagick-enabled-types nil)
848 (if (cond ((symbolp enable) (eq enable type))
849 ((stringp enable)
850 (string-match enable
851 (symbol-name type))))
852 (throw 'found type)))))))
853 (imagemagick-types)))))))
854
855 (defvar imagemagick--file-regexp nil
856 "File extension regexp for ImageMagick files, if any.
857 This is the extension installed into `auto-mode-alist' and
858 `image-type-file-name-regexps' by `imagemagick-register-types'.")
859
860 ;;;###autoload
861 (defun imagemagick-register-types ()
862 "Register file types that can be handled by ImageMagick.
863 This function is called at startup, after loading the init file.
864 It registers the ImageMagick types returned by `imagemagick-filter-types'.
865
866 Registered image types are added to `auto-mode-alist', so that
867 Emacs visits them in Image mode. They are also added to
868 `image-type-file-name-regexps', so that the `image-type' function
869 recognizes these files as having image type `imagemagick'.
870
871 If Emacs is compiled without ImageMagick support, this does nothing."
872 (when (fboundp 'imagemagick-types)
873 (let* ((types (mapcar (lambda (type) (downcase (symbol-name type)))
874 (imagemagick-filter-types)))
875 (re (if types (concat "\\." (regexp-opt types) "\\'")))
876 (ama-elt (car (member (cons imagemagick--file-regexp 'image-mode)
877 auto-mode-alist)))
878 (itfnr-elt (car (member (cons imagemagick--file-regexp 'imagemagick)
879 image-type-file-name-regexps))))
880 (if (not re)
881 (setq auto-mode-alist (delete ama-elt auto-mode-alist)
882 image-type-file-name-regexps
883 (delete itfnr-elt image-type-file-name-regexps))
884 (if ama-elt
885 (setcar ama-elt re)
886 (push (cons re 'image-mode) auto-mode-alist))
887 (if itfnr-elt
888 (setcar itfnr-elt re)
889 ;; Append to `image-type-file-name-regexps', so that we
890 ;; preferentially use specialized image libraries.
891 (add-to-list 'image-type-file-name-regexps
892 (cons re 'imagemagick) t)))
893 (setq imagemagick--file-regexp re))))
894
895 (defcustom imagemagick-types-inhibit
896 '(C HTML HTM INFO M TXT PDF)
897 "List of ImageMagick types that should never be treated as images.
898 This should be a list of symbols, each of which should be one of
899 the ImageMagick types listed by `imagemagick-types'. The listed
900 image types are not registered by `imagemagick-register-types'.
901
902 If the value is t, inhibit the use of ImageMagick for images.
903
904 If you change this without using customize, you must call
905 `imagemagick-register-types' afterwards.
906
907 If Emacs is compiled without ImageMagick support, this variable
908 has no effect."
909 :type '(choice (const :tag "Support all ImageMagick types" nil)
910 (const :tag "Disable all ImageMagick types" t)
911 (repeat symbol))
912 :initialize 'custom-initialize-default
913 :set (lambda (symbol value)
914 (set-default symbol value)
915 (imagemagick-register-types))
916 :version "24.3"
917 :group 'image)
918
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.
934
935 The value of `imagemagick-enabled-types' may also be t, meaning
936 to enable all types that ImageMagick supports.
937
938 The variable `imagemagick-types-inhibit' overrides this variable.
939
940 If you change this without using customize, you must call
941 `imagemagick-register-types' afterwards.
942
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"
955 :group 'image)
956
957 (imagemagick-register-types)
958
959 (defun image-increase-size (n)
960 "Increase the image size by a factor of N.
961 If N is 3, then the image size will be increased by 30%. The
962 default is 20%."
963 (interactive "P")
964 (image--change-size (if n
965 (1+ (/ n 10))
966 1.2)))
967
968 (defun image-decrease-size (n)
969 "Decrease the image size by a factor of N.
970 If N is 3, then the image size will be decreased by 30%. The
971 default is 20%."
972 (interactive "P")
973 (image--change-size (if n
974 (- 1 (/ n 10))
975 0.8)))
976
977 (defun image--get-image ()
978 (let ((image (or (get-text-property (point) 'display)
979 ;; `put-image' uses overlays, so find an image in
980 ;; the overlays.
981 (seq-find (lambda (overlay)
982 (overlay-get overlay 'display))
983 (overlays-at (point))))))
984 (when (or (not (consp image))
985 (not (eq (car image) 'image)))
986 (error "No image under point"))
987 image))
988
989 (defun image--get-imagemagick-and-warn ()
990 (unless (fboundp 'imagemagick-types)
991 (error "Can't rescale images without ImageMagick support"))
992 (let ((image (image--get-image)))
993 (image-flush image)
994 (plist-put (cdr image) :type 'imagemagick)
995 image))
996
997 (defun image--change-size (factor)
998 (let* ((image (image--get-imagemagick-and-warn))
999 (new-image (image--image-without-parameters image))
1000 (scale (image--current-scaling image new-image)))
1001 (setcdr image (cdr new-image))
1002 (plist-put (cdr image) :scale (* scale factor))))
1003
1004 (defun image--image-without-parameters (image)
1005 (cons (pop image)
1006 (let ((new nil))
1007 (while image
1008 (let ((key (pop image))
1009 (val (pop image)))
1010 (unless (memq key '(:scale :width :height :max-width :max-height))
1011 (setq new (nconc new (list key val))))))
1012 new)))
1013
1014 (defun image--current-scaling (image new-image)
1015 ;; The image may be scaled due to many reasons (:scale, :max-width,
1016 ;; etc), so find out what the current scaling is based on the
1017 ;; original image size and the displayed size.
1018 (let ((image-width (car (image-size new-image t)))
1019 (display-width (car (image-size image t))))
1020 (/ (float display-width) image-width)))
1021
1022 (defun image-rotate ()
1023 "Rotate the image under point by 90 degrees clockwise."
1024 (interactive)
1025 (let ((image (image--get-imagemagick-and-warn)))
1026 (plist-put (cdr image) :rotation
1027 (float (+ (or (plist-get (cdr image) :rotation) 0) 90)))))
1028
1029 (defun image-save ()
1030 "Save the image under point."
1031 (interactive)
1032 (let ((image (get-text-property (point) 'display)))
1033 (when (or (not (consp image))
1034 (not (eq (car image) 'image)))
1035 (error "No image under point"))
1036 (with-temp-buffer
1037 (let ((file (plist-get (cdr image) :file)))
1038 (if file
1039 (if (not (file-exists-p file))
1040 (error "File %s no longer exists" file)
1041 (insert-file-contents-literally file))
1042 (insert (plist-get (cdr image) :data))))
1043 (write-region (point-min) (point-max)
1044 (read-file-name "Write image to file: ")))))
1045
1046 (provide 'image)
1047
1048 ;;; image.el ends here