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