Merge from emacs-24; up to 2013-01-02T10:15:31Z!michael.albinus@gmx.de
[emacs.git] / lisp / image-mode.el
blob30dfd045b466e7105164b8544b42774154e900cb
1 ;;; image-mode.el --- support for visiting image files -*- lexical-binding: t -*-
2 ;;
3 ;; Copyright (C) 2005-2013 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Richard Stallman <rms@gnu.org>
6 ;; Keywords: multimedia
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Defines a major mode for visiting image files
27 ;; that allows conversion between viewing the text of the file
28 ;; and viewing the file as an image. Viewing the image
29 ;; works by putting a `display' text-property on the
30 ;; image data, with the image-data still present underneath; if the
31 ;; resulting buffer file is saved to another name it will correctly save
32 ;; the image data to the new file.
34 ;; Todo:
36 ;; Consolidate with doc-view to make them work on directories of images or on
37 ;; image files containing various "pages".
39 ;;; Code:
41 (require 'image)
42 (eval-when-compile (require 'cl-lib))
44 ;;; Image mode window-info management.
46 (defvar-local image-mode-winprops-alist t)
48 (defvar image-mode-new-window-functions nil
49 "Special hook run when image data is requested in a new window.
50 It is called with one argument, the initial WINPROPS.")
52 (defun image-mode-winprops (&optional window cleanup)
53 "Return winprops of WINDOW.
54 A winprops object has the shape (WINDOW . ALIST).
55 WINDOW defaults to `selected-window' if it displays the current buffer, and
56 otherwise it defaults to t, used for times when the buffer is not displayed."
57 (cond ((null window)
58 (setq window
59 (if (eq (current-buffer) (window-buffer)) (selected-window) t)))
60 ((eq window t))
61 ((not (windowp window))
62 (error "Not a window: %s" window)))
63 (when cleanup
64 (setq image-mode-winprops-alist
65 (delq nil (mapcar (lambda (winprop)
66 (let ((w (car-safe winprop)))
67 (if (or (not (windowp w)) (window-live-p w))
68 winprop)))
69 image-mode-winprops-alist))))
70 (let ((winprops (assq window image-mode-winprops-alist)))
71 ;; For new windows, set defaults from the latest.
72 (if winprops
73 ;; Move window to front.
74 (setq image-mode-winprops-alist
75 (cons winprops (delq winprops image-mode-winprops-alist)))
76 (setq winprops (cons window
77 (copy-alist (cdar image-mode-winprops-alist))))
78 ;; Add winprops before running the hook, to avoid inf-loops if the hook
79 ;; triggers window-configuration-change-hook.
80 (setq image-mode-winprops-alist
81 (cons winprops image-mode-winprops-alist))
82 (run-hook-with-args 'image-mode-new-window-functions winprops))
83 winprops))
85 (defun image-mode-window-get (prop &optional winprops)
86 (declare (gv-setter (lambda (val)
87 `(image-mode-window-put ,prop ,val ,winprops))))
88 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
89 (cdr (assq prop (cdr winprops))))
91 (defun image-mode-window-put (prop val &optional winprops)
92 (unless (consp winprops) (setq winprops (image-mode-winprops winprops)))
93 (setcdr winprops (cons (cons prop val)
94 (delq (assq prop (cdr winprops)) (cdr winprops)))))
96 (defun image-set-window-vscroll (vscroll)
97 (setf (image-mode-window-get 'vscroll) vscroll)
98 (set-window-vscroll (selected-window) vscroll))
100 (defun image-set-window-hscroll (ncol)
101 (setf (image-mode-window-get 'hscroll) ncol)
102 (set-window-hscroll (selected-window) ncol))
104 (defun image-mode-reapply-winprops ()
105 ;; When set-window-buffer, set hscroll and vscroll to what they were
106 ;; last time the image was displayed in this window.
107 (when (listp image-mode-winprops-alist)
108 ;; Beware: this call to image-mode-winprops can't be optimized away,
109 ;; because it not only gets the winprops data but sets it up if needed
110 ;; (e.g. it's used by doc-view to display the image in a new window).
111 (let* ((winprops (image-mode-winprops nil t))
112 (hscroll (image-mode-window-get 'hscroll winprops))
113 (vscroll (image-mode-window-get 'vscroll winprops)))
114 (when (image-get-display-property) ;Only do it if we display an image!
115 (if hscroll (set-window-hscroll (selected-window) hscroll))
116 (if vscroll (set-window-vscroll (selected-window) vscroll))))))
118 (defun image-mode-setup-winprops ()
119 ;; Record current scroll settings.
120 (unless (listp image-mode-winprops-alist)
121 (setq image-mode-winprops-alist nil))
122 (add-hook 'window-configuration-change-hook
123 'image-mode-reapply-winprops nil t))
125 ;;; Image scrolling functions
127 (defun image-get-display-property ()
128 (get-char-property (point-min) 'display
129 ;; There might be different images for different displays.
130 (if (eq (window-buffer) (current-buffer))
131 (selected-window))))
133 (declare-function image-size "image.c" (spec &optional pixels frame))
135 (defun image-display-size (spec &optional pixels frame)
136 "Wrapper around `image-size', handling slice display properties.
137 Like `image-size', the return value is (WIDTH . HEIGHT).
138 WIDTH and HEIGHT are in canonical character units if PIXELS is
139 nil, and in pixel units if PIXELS is non-nil.
141 If SPEC is an image display property, this function is equivalent
142 to `image-size'. If SPEC is a list of properties containing
143 `image' and `slice' properties, return the display size taking
144 the slice property into account. If the list contains `image'
145 but not `slice', return the `image-size' of the specified image."
146 (if (eq (car spec) 'image)
147 (image-size spec pixels frame)
148 (let ((image (assoc 'image spec))
149 (slice (assoc 'slice spec)))
150 (cond ((and image slice)
151 (if pixels
152 (cons (nth 3 slice) (nth 4 slice))
153 (cons (/ (float (nth 3 slice)) (frame-char-width frame))
154 (/ (float (nth 4 slice)) (frame-char-height frame)))))
155 (image
156 (image-size image pixels frame))
158 (error "Invalid image specification: %s" spec))))))
160 (defun image-forward-hscroll (&optional n)
161 "Scroll image in current window to the left by N character widths.
162 Stop if the right edge of the image is reached."
163 (interactive "p")
164 (cond ((= n 0) nil)
165 ((< n 0)
166 (image-set-window-hscroll (max 0 (+ (window-hscroll) n))))
168 (let* ((image (image-get-display-property))
169 (edges (window-inside-edges))
170 (win-width (- (nth 2 edges) (nth 0 edges)))
171 (img-width (ceiling (car (image-display-size image)))))
172 (image-set-window-hscroll (min (max 0 (- img-width win-width))
173 (+ n (window-hscroll))))))))
175 (defun image-backward-hscroll (&optional n)
176 "Scroll image in current window to the right by N character widths.
177 Stop if the left edge of the image is reached."
178 (interactive "p")
179 (image-forward-hscroll (- n)))
181 (defun image-next-line (n)
182 "Scroll image in current window upward by N lines.
183 Stop if the bottom edge of the image is reached."
184 (interactive "p")
185 (cond ((= n 0) nil)
186 ((< n 0)
187 (image-set-window-vscroll (max 0 (+ (window-vscroll) n))))
189 (let* ((image (image-get-display-property))
190 (edges (window-inside-edges))
191 (win-height (- (nth 3 edges) (nth 1 edges)))
192 (img-height (ceiling (cdr (image-display-size image)))))
193 (image-set-window-vscroll (min (max 0 (- img-height win-height))
194 (+ n (window-vscroll))))))))
196 (defun image-previous-line (&optional n)
197 "Scroll image in current window downward by N lines.
198 Stop if the top edge of the image is reached."
199 (interactive "p")
200 (image-next-line (- n)))
202 (defun image-scroll-up (&optional n)
203 "Scroll image in current window upward by N lines.
204 Stop if the bottom edge of the image is reached.
205 If ARG is omitted or nil, scroll upward by a near full screen.
206 A near full screen is `next-screen-context-lines' less than a full screen.
207 Negative ARG means scroll downward.
208 If ARG is the atom `-', scroll downward by nearly full screen.
209 When calling from a program, supply as argument a number, nil, or `-'."
210 (interactive "P")
211 (cond ((null n)
212 (let* ((edges (window-inside-edges))
213 (win-height (- (nth 3 edges) (nth 1 edges))))
214 (image-next-line
215 (max 0 (- win-height next-screen-context-lines)))))
216 ((eq n '-)
217 (let* ((edges (window-inside-edges))
218 (win-height (- (nth 3 edges) (nth 1 edges))))
219 (image-next-line
220 (min 0 (- next-screen-context-lines win-height)))))
221 (t (image-next-line (prefix-numeric-value n)))))
223 (defun image-scroll-down (&optional n)
224 "Scroll image in current window downward by N lines.
225 Stop if the top edge of the image is reached.
226 If ARG is omitted or nil, scroll downward by a near full screen.
227 A near full screen is `next-screen-context-lines' less than a full screen.
228 Negative ARG means scroll upward.
229 If ARG is the atom `-', scroll upward by nearly full screen.
230 When calling from a program, supply as argument a number, nil, or `-'."
231 (interactive "P")
232 (cond ((null n)
233 (let* ((edges (window-inside-edges))
234 (win-height (- (nth 3 edges) (nth 1 edges))))
235 (image-next-line
236 (min 0 (- next-screen-context-lines win-height)))))
237 ((eq n '-)
238 (let* ((edges (window-inside-edges))
239 (win-height (- (nth 3 edges) (nth 1 edges))))
240 (image-next-line
241 (max 0 (- win-height next-screen-context-lines)))))
242 (t (image-next-line (- (prefix-numeric-value n))))))
244 (defun image-bol (arg)
245 "Scroll horizontally to the left edge of the image in the current window.
246 With argument ARG not nil or 1, move forward ARG - 1 lines first,
247 stopping if the top or bottom edge of the image is reached."
248 (interactive "p")
249 (and arg
250 (/= (setq arg (prefix-numeric-value arg)) 1)
251 (image-next-line (- arg 1)))
252 (image-set-window-hscroll 0))
254 (defun image-eol (arg)
255 "Scroll horizontally to the right edge of the image in the current window.
256 With argument ARG not nil or 1, move forward ARG - 1 lines first,
257 stopping if the top or bottom edge of the image is reached."
258 (interactive "p")
259 (and arg
260 (/= (setq arg (prefix-numeric-value arg)) 1)
261 (image-next-line (- arg 1)))
262 (let* ((image (image-get-display-property))
263 (edges (window-inside-edges))
264 (win-width (- (nth 2 edges) (nth 0 edges)))
265 (img-width (ceiling (car (image-display-size image)))))
266 (image-set-window-hscroll (max 0 (- img-width win-width)))))
268 (defun image-bob ()
269 "Scroll to the top-left corner of the image in the current window."
270 (interactive)
271 (image-set-window-hscroll 0)
272 (image-set-window-vscroll 0))
274 (defun image-eob ()
275 "Scroll to the bottom-right corner of the image in the current window."
276 (interactive)
277 (let* ((image (image-get-display-property))
278 (edges (window-inside-edges))
279 (win-width (- (nth 2 edges) (nth 0 edges)))
280 (img-width (ceiling (car (image-display-size image))))
281 (win-height (- (nth 3 edges) (nth 1 edges)))
282 (img-height (ceiling (cdr (image-display-size image)))))
283 (image-set-window-hscroll (max 0 (- img-width win-width)))
284 (image-set-window-vscroll (max 0 (- img-height win-height)))))
286 ;; Adjust frame and image size.
288 (defun image-mode-fit-frame (&optional frame toggle)
289 "Fit FRAME to the current image.
290 If FRAME is omitted or nil, it defaults to the selected frame.
291 All other windows on the frame are deleted.
293 If called interactively, or if TOGGLE is non-nil, toggle between
294 fitting FRAME to the current image and restoring the size and
295 window configuration prior to the last `image-mode-fit-frame'
296 call."
297 (interactive (list nil t))
298 (let* ((buffer (current-buffer))
299 (display (image-get-display-property))
300 (size (image-display-size display))
301 (saved (frame-parameter frame 'image-mode-saved-params))
302 (window-configuration (current-window-configuration frame))
303 (width (frame-width frame))
304 (height (frame-height frame)))
305 (with-selected-frame (or frame (selected-frame))
306 (if (and toggle saved
307 (= (caar saved) width)
308 (= (cdar saved) height))
309 (progn
310 (set-frame-width frame (car (nth 1 saved)))
311 (set-frame-height frame (cdr (nth 1 saved)))
312 (set-window-configuration (nth 2 saved))
313 (set-frame-parameter frame 'image-mode-saved-params nil))
314 (delete-other-windows)
315 (switch-to-buffer buffer t t)
316 (let* ((edges (window-inside-edges))
317 (inner-width (- (nth 2 edges) (nth 0 edges)))
318 (inner-height (- (nth 3 edges) (nth 1 edges))))
319 (set-frame-width frame (+ (ceiling (car size))
320 width (- inner-width)))
321 (set-frame-height frame (+ (ceiling (cdr size))
322 height (- inner-height)))
323 ;; The frame size after the above `set-frame-*' calls may
324 ;; differ from what we specified, due to window manager
325 ;; interference. We have to call `frame-width' and
326 ;; `frame-height' to get the actual results.
327 (set-frame-parameter frame 'image-mode-saved-params
328 (list (cons (frame-width)
329 (frame-height))
330 (cons width height)
331 window-configuration)))))))
333 ;;; Image Mode setup
335 (defvar-local image-type nil
336 "The image type for the current Image mode buffer.")
338 (defvar-local image-multi-frame nil
339 "Non-nil if image for the current Image mode buffer has multiple frames.")
341 (defvar image-mode-previous-major-mode nil
342 "Internal variable to keep the previous non-image major mode.")
344 (defvar image-mode-map
345 (let ((map (make-sparse-keymap)))
346 (set-keymap-parent map special-mode-map)
347 (define-key map "\C-c\C-c" 'image-toggle-display)
348 (define-key map (kbd "SPC") 'image-scroll-up)
349 (define-key map (kbd "S-SPC") 'image-scroll-down)
350 (define-key map (kbd "DEL") 'image-scroll-down)
351 (define-key map (kbd "RET") 'image-toggle-animation)
352 (define-key map "F" 'image-goto-frame)
353 (define-key map "f" 'image-next-frame)
354 (define-key map "b" 'image-previous-frame)
355 (define-key map "n" 'image-next-file)
356 (define-key map "p" 'image-previous-file)
357 (define-key map [remap forward-char] 'image-forward-hscroll)
358 (define-key map [remap backward-char] 'image-backward-hscroll)
359 (define-key map [remap right-char] 'image-forward-hscroll)
360 (define-key map [remap left-char] 'image-backward-hscroll)
361 (define-key map [remap previous-line] 'image-previous-line)
362 (define-key map [remap next-line] 'image-next-line)
363 (define-key map [remap scroll-up] 'image-scroll-up)
364 (define-key map [remap scroll-down] 'image-scroll-down)
365 (define-key map [remap scroll-up-command] 'image-scroll-up)
366 (define-key map [remap scroll-down-command] 'image-scroll-down)
367 (define-key map [remap move-beginning-of-line] 'image-bol)
368 (define-key map [remap move-end-of-line] 'image-eol)
369 (define-key map [remap beginning-of-buffer] 'image-bob)
370 (define-key map [remap end-of-buffer] 'image-eob)
371 (easy-menu-define image-mode-menu map "Menu for Image mode."
372 '("Image"
373 ["Show as Text" image-toggle-display :active t
374 :help "Show image as text"]
375 "--"
376 ["Fit Frame to Image" image-mode-fit-frame :active t
377 :help "Resize frame to match image"]
378 ["Fit to Window Height" image-transform-fit-to-height
379 :visible (eq image-type 'imagemagick)
380 :help "Resize image to match the window height"]
381 ["Fit to Window Width" image-transform-fit-to-width
382 :visible (eq image-type 'imagemagick)
383 :help "Resize image to match the window width"]
384 ["Rotate Image..." image-transform-set-rotation
385 :visible (eq image-type 'imagemagick)
386 :help "Rotate the image"]
387 "--"
388 ["Show Thumbnails"
389 (lambda ()
390 (interactive)
391 (image-dired default-directory))
392 :active default-directory
393 :help "Show thumbnails for all images in this directory"]
394 ["Next Image" image-next-file :active buffer-file-name
395 :help "Move to next image in this directory"]
396 ["Previous Image" image-previous-file :active buffer-file-name
397 :help "Move to previous image in this directory"]
398 "--"
399 ["Animate Image" image-toggle-animation :style toggle
400 :selected (let ((image (image-get-display-property)))
401 (and image (image-animate-timer image)))
402 :active image-multi-frame
403 :help "Toggle image animation"]
404 ["Loop Animation"
405 (lambda () (interactive)
406 (setq image-animate-loop (not image-animate-loop))
407 ;; FIXME this is a hacky way to make it affect a currently
408 ;; animating image.
409 (when (let ((image (image-get-display-property)))
410 (and image (image-animate-timer image)))
411 (image-toggle-animation)
412 (image-toggle-animation)))
413 :style toggle :selected image-animate-loop
414 :active image-multi-frame
415 :help "Animate images once, or forever?"]
416 ["Next Frame" image-next-frame :active image-multi-frame
417 :help "Show the next frame of this image"]
418 ["Previous Frame" image-previous-frame :active image-multi-frame
419 :help "Show the previous frame of this image"]
420 ["Goto Frame..." image-goto-frame :active image-multi-frame
421 :help "Show a specific frame of this image"]
423 map)
424 "Mode keymap for `image-mode'.")
426 (defvar image-minor-mode-map
427 (let ((map (make-sparse-keymap)))
428 (define-key map "\C-c\C-c" 'image-toggle-display)
429 map)
430 "Mode keymap for `image-minor-mode'.")
432 (defvar bookmark-make-record-function)
434 (put 'image-mode 'mode-class 'special)
436 ;;;###autoload
437 (defun image-mode ()
438 "Major mode for image files.
439 You can use \\<image-mode-map>\\[image-toggle-display]
440 to toggle between display as an image and display as text."
441 (interactive)
442 (condition-case err
443 (progn
444 (unless (display-images-p)
445 (error "Display does not support images"))
447 (kill-all-local-variables)
448 (setq major-mode 'image-mode)
450 (if (not (image-get-display-property))
451 (progn
452 (image-toggle-display-image)
453 ;; If attempt to display the image fails.
454 (if (not (image-get-display-property))
455 (error "Invalid image")))
456 ;; Set next vars when image is already displayed but local
457 ;; variables were cleared by kill-all-local-variables
458 (setq cursor-type nil truncate-lines t
459 image-type (plist-get (cdr (image-get-display-property)) :type)))
461 (setq mode-name (if image-type (format "Image[%s]" image-type) "Image"))
462 (use-local-map image-mode-map)
464 ;; Use our own bookmarking function for images.
465 (setq-local bookmark-make-record-function
466 #'image-bookmark-make-record)
468 ;; Keep track of [vh]scroll when switching buffers
469 (image-mode-setup-winprops)
471 (add-hook 'change-major-mode-hook 'image-toggle-display-text nil t)
472 (add-hook 'after-revert-hook 'image-after-revert-hook nil t)
473 (run-mode-hooks 'image-mode-hook)
474 (let ((image (image-get-display-property))
475 (msg1 (substitute-command-keys
476 "Type \\[image-toggle-display] to view the image as "))
477 animated)
478 (cond
479 ((null image)
480 (message "%s" (concat msg1 "an image.")))
481 ((setq animated (image-multi-frame-p image))
482 (setq image-multi-frame t
483 mode-line-process
484 `(:eval
485 (concat " "
486 (propertize
487 (format "[%s/%s]"
488 (1+ (image-current-frame ',image))
489 ,(car animated))
490 'help-echo "Frames
491 mouse-1: Next frame
492 mouse-3: Previous frame"
493 'mouse-face 'mode-line-highlight
494 'local-map
495 '(keymap
496 (mode-line
497 keymap
498 (down-mouse-1 . image-next-frame)
499 (down-mouse-3 . image-previous-frame)))))))
500 (message "%s"
501 (concat msg1 "text. This image has multiple frames.")))
502 ;;; (substitute-command-keys
503 ;;; "\\[image-toggle-animation] to animate."))))
505 (message "%s" (concat msg1 "text."))))))
507 (error
508 (image-mode-as-text)
509 (funcall
510 (if (called-interactively-p 'any) 'error 'message)
511 "Cannot display image: %s" (cdr err)))))
513 ;;;###autoload
514 (define-minor-mode image-minor-mode
515 "Toggle Image minor mode in this buffer.
516 With a prefix argument ARG, enable Image minor mode if ARG is
517 positive, and disable it otherwise. If called from Lisp, enable
518 the mode if ARG is omitted or nil.
520 Image minor mode provides the key \\<image-mode-map>\\[image-toggle-display],
521 to switch back to `image-mode' and display an image file as the
522 actual image."
523 nil (:eval (if image-type (format " Image[%s]" image-type) " Image"))
524 image-minor-mode-map
525 :group 'image
526 :version "22.1"
527 (if image-minor-mode
528 (add-hook 'change-major-mode-hook (lambda () (image-minor-mode -1)) nil t)))
530 ;;;###autoload
531 (defun image-mode-as-text ()
532 "Set a non-image mode as major mode in combination with image minor mode.
533 A non-image major mode found from `auto-mode-alist' or Fundamental mode
534 displays an image file as text. `image-minor-mode' provides the key
535 \\<image-mode-map>\\[image-toggle-display] to switch back to `image-mode'
536 to display an image file as the actual image.
538 You can use `image-mode-as-text' in `auto-mode-alist' when you want
539 to display an image file as text initially.
541 See commands `image-mode' and `image-minor-mode' for more information
542 on these modes."
543 (interactive)
544 ;; image-mode-as-text = normal-mode + image-minor-mode
545 (let ((previous-image-type image-type)) ; preserve `image-type'
546 (if image-mode-previous-major-mode
547 ;; Restore previous major mode that was already found by this
548 ;; function and cached in `image-mode-previous-major-mode'
549 (funcall image-mode-previous-major-mode)
550 (let ((auto-mode-alist
551 (delq nil (mapcar
552 (lambda (elt)
553 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
554 '(image-mode image-mode-maybe image-mode-as-text))
555 elt))
556 auto-mode-alist)))
557 (magic-fallback-mode-alist
558 (delq nil (mapcar
559 (lambda (elt)
560 (unless (memq (or (car-safe (cdr elt)) (cdr elt))
561 '(image-mode image-mode-maybe image-mode-as-text))
562 elt))
563 magic-fallback-mode-alist))))
564 (normal-mode)
565 (setq-local image-mode-previous-major-mode major-mode)))
566 ;; Restore `image-type' after `kill-all-local-variables' in `normal-mode'.
567 (setq image-type previous-image-type)
568 ;; Enable image minor mode with `C-c C-c'.
569 (image-minor-mode 1)
570 ;; Show the image file as text.
571 (image-toggle-display-text)
572 (message "%s" (concat
573 (substitute-command-keys
574 "Type \\[image-toggle-display] to view the image as ")
575 (if (image-get-display-property)
576 "text" "an image") "."))))
578 (define-obsolete-function-alias 'image-mode-maybe 'image-mode "23.2")
580 (defun image-toggle-display-text ()
581 "Show the image file as text.
582 Remove text properties that display the image."
583 (let ((inhibit-read-only t)
584 (buffer-undo-list t)
585 (modified (buffer-modified-p)))
586 (remove-list-of-text-properties (point-min) (point-max)
587 '(display read-nonsticky ;; intangible
588 read-only front-sticky))
589 (set-buffer-modified-p modified)
590 (if (called-interactively-p 'any)
591 (message "Repeat this command to go back to displaying the image"))))
593 (defvar archive-superior-buffer)
594 (defvar tar-superior-buffer)
595 (declare-function image-flush "image.c" (spec &optional frame))
597 (defun image-toggle-display-image ()
598 "Show the image of the image file.
599 Turn the image data into a real image, but only if the whole file
600 was inserted."
601 (unless (derived-mode-p 'image-mode)
602 (error "The buffer is not in Image mode"))
603 (let* ((filename (buffer-file-name))
604 (data-p (not (and filename
605 (file-readable-p filename)
606 (not (file-remote-p filename))
607 (not (buffer-modified-p))
608 (not (and (boundp 'archive-superior-buffer)
609 archive-superior-buffer))
610 (not (and (boundp 'tar-superior-buffer)
611 tar-superior-buffer)))))
612 (file-or-data (if data-p
613 (string-make-unibyte
614 (buffer-substring-no-properties (point-min) (point-max)))
615 filename))
616 (type (image-type file-or-data nil data-p))
617 (image (create-image file-or-data type data-p))
618 (inhibit-read-only t)
619 (buffer-undo-list t)
620 (modified (buffer-modified-p))
621 props)
623 ;; Discard any stale image data before looking it up again.
624 (image-flush image)
625 (setq image (append image (image-transform-properties image)))
626 (setq props
627 `(display ,image
628 ;; intangible ,image
629 rear-nonsticky (display) ;; intangible
630 read-only t front-sticky (read-only)))
632 (let ((buffer-file-truename nil)) ; avoid changing dir mtime by lock_file
633 (add-text-properties (point-min) (point-max) props)
634 (restore-buffer-modified-p modified))
635 ;; Inhibit the cursor when the buffer contains only an image,
636 ;; because cursors look very strange on top of images.
637 (setq cursor-type nil)
638 ;; This just makes the arrow displayed in the right fringe
639 ;; area look correct when the image is wider than the window.
640 (setq truncate-lines t)
641 ;; Disable adding a newline at the end of the image file when it
642 ;; is written with, e.g., C-x C-w.
643 (if (coding-system-equal (coding-system-base buffer-file-coding-system)
644 'no-conversion)
645 (setq-local find-file-literally t))
646 ;; Allow navigation of large images.
647 (setq-local auto-hscroll-mode nil)
648 (setq image-type type)
649 (if (eq major-mode 'image-mode)
650 (setq mode-name (format "Image[%s]" type)))
651 (image-transform-check-size)
652 (if (called-interactively-p 'any)
653 (message "Repeat this command to go back to displaying the file as text"))))
655 (defun image-toggle-display ()
656 "Toggle between image and text display.
657 If the current buffer is displaying an image file as an image,
658 call `image-mode-as-text' to switch to text. Otherwise, display
659 the image by calling `image-mode'."
660 (interactive)
661 (if (image-get-display-property)
662 (image-mode-as-text)
663 (image-mode)))
665 (defun image-after-revert-hook ()
666 (when (image-get-display-property)
667 (image-toggle-display-text)
668 ;; Update image display.
669 (mapc (lambda (window) (redraw-frame (window-frame window)))
670 (get-buffer-window-list (current-buffer) 'nomini 'visible))
671 (image-toggle-display-image)))
674 ;;; Animated images
676 (defcustom image-animate-loop nil
677 "Non-nil means animated images loop forever, rather than playing once."
678 :type 'boolean
679 :version "24.1"
680 :group 'image)
682 (defun image-toggle-animation ()
683 "Start or stop animating the current image.
684 If `image-animate-loop' is non-nil, animation loops forever.
685 Otherwise it plays once, then stops."
686 (interactive)
687 (let ((image (image-get-display-property))
688 animation)
689 (cond
690 ((null image)
691 (error "No image is present"))
692 ((null (setq animation (image-multi-frame-p image)))
693 (message "No image animation."))
695 (let ((timer (image-animate-timer image)))
696 (if timer
697 (cancel-timer timer)
698 (let ((index (plist-get (cdr image) :index)))
699 ;; If we're at the end, restart.
700 (and index
701 (>= index (1- (car animation)))
702 (setq index nil))
703 (image-animate image index
704 (if image-animate-loop t)))))))))
706 (defun image-goto-frame (n &optional relative)
707 "Show frame N of a multi-frame image.
708 Optional argument OFFSET non-nil means interpret N as relative to the
709 current frame. Frames are indexed from 1."
710 (interactive
711 (list (or current-prefix-arg
712 (read-number "Show frame number: "))))
713 (let ((image (image-get-display-property)))
714 (cond
715 ((null image)
716 (error "No image is present"))
717 ((null image-multi-frame)
718 (message "No image animation."))
720 (image-show-frame image
721 (if relative
722 (+ n (image-current-frame image))
723 (1- n)))))))
725 (defun image-next-frame (&optional n)
726 "Switch to the next frame of a multi-frame image.
727 With optional argument N, switch to the Nth frame after the current one.
728 If N is negative, switch to the Nth frame before the current one."
729 (interactive "p")
730 (image-goto-frame n t))
732 (defun image-previous-frame (&optional n)
733 "Switch to the previous frame of a multi-frame image.
734 With optional argument N, switch to the Nth frame before the current one.
735 If N is negative, switch to the Nth frame after the current one."
736 (interactive "p")
737 (image-next-frame (- n)))
740 ;;; Switching to the next/previous image
742 (defun image-next-file (&optional n)
743 "Visit the next image in the same directory as the current image file.
744 With optional argument N, visit the Nth image file after the
745 current one, in cyclic alphabetical order.
747 This command visits the specified file via `find-alternate-file',
748 replacing the current Image mode buffer."
749 (interactive "p")
750 (unless (derived-mode-p 'image-mode)
751 (error "The buffer is not in Image mode"))
752 (unless buffer-file-name
753 (error "The current image is not associated with a file"))
754 (let* ((file (file-name-nondirectory buffer-file-name))
755 (images (image-mode--images-in-directory file))
756 (idx 0))
757 (catch 'image-visit-next-file
758 (dolist (f images)
759 (if (string= f file)
760 (throw 'image-visit-next-file (1+ idx)))
761 (setq idx (1+ idx))))
762 (setq idx (mod (+ idx (or n 1)) (length images)))
763 (find-alternate-file (nth idx images))))
765 (defun image-previous-file (&optional n)
766 "Visit the preceding image in the same directory as the current file.
767 With optional argument N, visit the Nth image file preceding the
768 current one, in cyclic alphabetical order.
770 This command visits the specified file via `find-alternate-file',
771 replacing the current Image mode buffer."
772 (interactive "p")
773 (image-next-file (- n)))
775 (defun image-mode--images-in-directory (file)
776 (let* ((dir (file-name-directory buffer-file-name))
777 (files (directory-files dir nil
778 (image-file-name-regexp) t)))
779 ;; Add the current file to the list of images if necessary, in
780 ;; case it does not match `image-file-name-regexp'.
781 (unless (member file files)
782 (push file files))
783 (sort files 'string-lessp)))
786 ;;; Support for bookmark.el
787 (declare-function bookmark-make-record-default
788 "bookmark" (&optional no-file no-context posn))
789 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
790 (declare-function bookmark-default-handler "bookmark" (bmk))
792 (defun image-bookmark-make-record ()
793 `(,@(bookmark-make-record-default nil 'no-context 0)
794 (image-type . ,image-type)
795 (handler . image-bookmark-jump)))
797 ;;;###autoload
798 (defun image-bookmark-jump (bmk)
799 ;; This implements the `handler' function interface for record type
800 ;; returned by `bookmark-make-record-function', which see.
801 (prog1 (bookmark-default-handler bmk)
802 (when (not (string= image-type (bookmark-prop-get bmk 'image-type)))
803 (image-toggle-display))))
806 ;; Not yet implemented.
807 ;; (defvar image-transform-minor-mode-map
808 ;; (let ((map (make-sparse-keymap)))
809 ;; ;; (define-key map [(control ?+)] 'image-scale-in)
810 ;; ;; (define-key map [(control ?-)] 'image-scale-out)
811 ;; ;; (define-key map [(control ?=)] 'image-scale-none)
812 ;; ;; (define-key map "c f h" 'image-scale-fit-height)
813 ;; ;; (define-key map "c ]" 'image-rotate-right)
814 ;; map)
815 ;; "Minor mode keymap `image-transform-mode'.")
817 ;; (define-minor-mode image-transform-mode
818 ;; "Minor mode for scaling and rotating images.
819 ;; With a prefix argument ARG, enable the mode if ARG is positive,
820 ;; and disable it otherwise. If called from Lisp, enable the mode
821 ;; if ARG is omitted or nil. This minor mode requires Emacs to have
822 ;; been compiled with ImageMagick support."
823 ;; nil "image-transform" image-transform-minor-mode-map)
826 ;; FIXME this doesn't seem mature yet. Document in manual when it is.
827 (defvar image-transform-resize nil
828 "The image resize operation.
829 Its value should be one of the following:
830 - nil, meaning no resizing.
831 - `fit-height', meaning to fit the image to the window height.
832 - `fit-width', meaning to fit the image to the window width.
833 - A number, which is a scale factor (the default size is 1).")
835 (defvar image-transform-scale 1.0
836 "The scale factor of the image being displayed.")
838 (defvar image-transform-rotation 0.0
839 "Rotation angle for the image in the current Image mode buffer.")
841 (defvar image-transform-right-angle-fudge 0.0001
842 "Snap distance to a multiple of a right angle.
843 There's no deep theory behind the default value, it should just
844 be somewhat larger than ImageMagick's MagickEpsilon.")
846 (defsubst image-transform-width (width height)
847 "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle.
848 The rotation angle is the value of `image-transform-rotation' in degrees."
849 (let ((angle (degrees-to-radians image-transform-rotation)))
850 ;; Assume, w.l.o.g., that the vertices of the rectangle have the
851 ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the
852 ;; rotation by the angle A. The projections onto the first axis
853 ;; of the vertices of the rotated rectangle are +- (w/2) cos A +-
854 ;; (h/2) sin A, and the difference between the largest and the
855 ;; smallest of the four values is the expression below.
856 (+ (* width (abs (cos angle))) (* height (abs (sin angle))))))
858 ;; The following comment and code snippet are from
859 ;; ImageMagick-6.7.4-4/magick/distort.c
861 ;; /* Set the output image geometry to calculated 'best fit'.
862 ;; Yes this tends to 'over do' the file image size, ON PURPOSE!
863 ;; Do not do this for DePolar which needs to be exact for virtual tiling.
864 ;; */
865 ;; if ( fix_bounds ) {
866 ;; geometry.x = (ssize_t) floor(min.x-0.5);
867 ;; geometry.y = (ssize_t) floor(min.y-0.5);
868 ;; geometry.width=(size_t) ceil(max.x-geometry.x+0.5);
869 ;; geometry.height=(size_t) ceil(max.y-geometry.y+0.5);
870 ;; }
872 ;; Other parts of the same file show that here the origin is in the
873 ;; left lower corner of the image rectangle, the center of the
874 ;; rotation is the center of the rectangle and min.x and max.x
875 ;; (resp. min.y and max.y) are the smallest and the largest of the
876 ;; projections of the vertices onto the first (resp. second) axis.
878 (defun image-transform-fit-width (width height length)
879 "Return (w . h) so that a rotated w x h image has exactly width LENGTH.
880 The rotation angle is the value of `image-transform-rotation'.
881 Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is
882 an \"approximately uniformly\" scaled W x H rectangle, which
883 currently means that w is one of floor(s W) + {0, 1, -1} and h is
884 floor(s H), where s can be recovered as the value of `image-transform-scale'.
885 The value of `image-transform-rotation' may be replaced by
886 a slightly different angle. Currently this is done for values
887 close to a multiple of 90, see `image-transform-right-angle-fudge'."
888 (cond ((< (abs (- (mod (+ image-transform-rotation 90) 180) 90))
889 image-transform-right-angle-fudge)
890 (cl-assert (not (zerop width)) t)
891 (setq image-transform-rotation
892 (float (round image-transform-rotation))
893 image-transform-scale (/ (float length) width))
894 (cons length nil))
895 ((< (abs (- (mod (+ image-transform-rotation 45) 90) 45))
896 image-transform-right-angle-fudge)
897 (cl-assert (not (zerop height)) t)
898 (setq image-transform-rotation
899 (float (round image-transform-rotation))
900 image-transform-scale (/ (float length) height))
901 (cons nil length))
903 (cl-assert (not (and (zerop width) (zerop height))) t)
904 (setq image-transform-scale
905 (/ (float (1- length)) (image-transform-width width height)))
906 ;; Assume we have a w x h image and an angle A, and let l =
907 ;; l(w, h) = w |cos A| + h |sin A|, which is the actual width
908 ;; of the bounding box of the rotated image, as calculated by
909 ;; `image-transform-width'. The code snippet quoted above
910 ;; means that ImageMagick puts the rotated image in
911 ;; a bounding box of width L = 2 ceil((w+l+1)/2) - w.
912 ;; Elementary considerations show that this is equivalent to
913 ;; L - w being even and L-3 < l(w, h) <= L-1. In our case, L is
914 ;; the given `length' parameter and our job is to determine
915 ;; reasonable values for w and h which satisfy these
916 ;; conditions.
917 (let ((w (floor (* image-transform-scale width)))
918 (h (floor (* image-transform-scale height))))
919 ;; Let w and h as bound above. Then l(w, h) <= l(s W, s H)
920 ;; = L-1 < l(w+1, h+1) = l(w, h) + l(1, 1) <= l(w, h) + 2,
921 ;; hence l(w, h) > (L-1) - 2 = L-3.
922 (cons
923 (cond ((= (mod w 2) (mod length 2))
925 ;; l(w+1, h) >= l(w, h) > L-3, but does l(w+1, h) <=
926 ;; L-1 hold?
927 ((<= (image-transform-width (1+ w) h) (1- length))
928 (1+ w))
929 ;; No, it doesn't, but this implies that l(w-1, h) =
930 ;; l(w+1, h) - l(2, 0) >= l(w+1, h) - 2 > (L-1) -
931 ;; 2 = L-3. Clearly, l(w-1, h) <= l(w, h) <= L-1.
933 (1- w)))
934 h)))))
936 (defun image-transform-check-size ()
937 "Check that the image exactly fits the width/height of the window.
939 Do this for an image of type `imagemagick' to make sure that the
940 elisp code matches the way ImageMagick computes the bounding box
941 of a rotated image."
942 (when (and (not (numberp image-transform-resize))
943 (boundp 'image-type)
944 (eq image-type 'imagemagick))
945 (let ((size (image-display-size (image-get-display-property) t)))
946 (cond ((eq image-transform-resize 'fit-width)
947 (cl-assert (= (car size)
948 (- (nth 2 (window-inside-pixel-edges))
949 (nth 0 (window-inside-pixel-edges))))
951 ((eq image-transform-resize 'fit-height)
952 (cl-assert (= (cdr size)
953 (- (nth 3 (window-inside-pixel-edges))
954 (nth 1 (window-inside-pixel-edges))))
955 t))))))
957 (defun image-transform-properties (spec)
958 "Return rescaling/rotation properties for image SPEC.
959 These properties are determined by the Image mode variables
960 `image-transform-resize' and `image-transform-rotation'. The
961 return value is suitable for appending to an image spec.
963 Rescaling and rotation properties only take effect if Emacs is
964 compiled with ImageMagick support."
965 (setq image-transform-scale 1.0)
966 (when (or image-transform-resize
967 (/= image-transform-rotation 0.0))
968 ;; Note: `image-size' looks up and thus caches the untransformed
969 ;; image. There's no easy way to prevent that.
970 (let* ((size (image-size spec t))
971 (resized
972 (cond
973 ((numberp image-transform-resize)
974 (unless (= image-transform-resize 1)
975 (setq image-transform-scale image-transform-resize)
976 (cons nil (floor (* image-transform-resize (cdr size))))))
977 ((eq image-transform-resize 'fit-width)
978 (image-transform-fit-width
979 (car size) (cdr size)
980 (- (nth 2 (window-inside-pixel-edges))
981 (nth 0 (window-inside-pixel-edges)))))
982 ((eq image-transform-resize 'fit-height)
983 (let ((res (image-transform-fit-width
984 (cdr size) (car size)
985 (- (nth 3 (window-inside-pixel-edges))
986 (nth 1 (window-inside-pixel-edges))))))
987 (cons (cdr res) (car res)))))))
988 `(,@(when (car resized)
989 (list :width (car resized)))
990 ,@(when (cdr resized)
991 (list :height (cdr resized)))
992 ,@(unless (= 0.0 image-transform-rotation)
993 (list :rotation image-transform-rotation))))))
995 (defun image-transform-set-scale (scale)
996 "Prompt for a number, and resize the current image by that amount.
997 This command has no effect unless Emacs is compiled with
998 ImageMagick support."
999 (interactive "nScale: ")
1000 (setq image-transform-resize scale)
1001 (image-toggle-display-image))
1003 (defun image-transform-fit-to-height ()
1004 "Fit the current image to the height of the current window.
1005 This command has no effect unless Emacs is compiled with
1006 ImageMagick support."
1007 (interactive)
1008 (setq image-transform-resize 'fit-height)
1009 (image-toggle-display-image))
1011 (defun image-transform-fit-to-width ()
1012 "Fit the current image to the width of the current window.
1013 This command has no effect unless Emacs is compiled with
1014 ImageMagick support."
1015 (interactive)
1016 (setq image-transform-resize 'fit-width)
1017 (image-toggle-display-image))
1019 (defun image-transform-set-rotation (rotation)
1020 "Prompt for an angle ROTATION, and rotate the image by that amount.
1021 ROTATION should be in degrees. This command has no effect unless
1022 Emacs is compiled with ImageMagick support."
1023 (interactive "nRotation angle (in degrees): ")
1024 (setq image-transform-rotation (float (mod rotation 360)))
1025 (image-toggle-display-image))
1027 (provide 'image-mode)
1029 ;;; image-mode.el ends here