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