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