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