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