From mboxrd@z Thu Jan 1 00:00:00 1970 Path: news.gmane.org!not-for-mail From: Vitalie Spinu Newsgroups: gmane.emacs.devel Subject: Re: image-transform.el and image-mode.el rewrite Date: Mon, 15 Dec 2014 01:33:03 -0800 Organization: UCLA Anderson School of Management Message-ID: <87tx0xdzqo.fsf@gmail.com> References: <87a9lp8uxk.fsf@gmail.com> <87ppuk6qqb.fsf@gmail.com> <87vc49y793.fsf@gmail.com> <87ppuhxk04.fsf@gmail.com> <87ehavihbp.fsf_-_@gmail.com> <1a7ggiwcta.fsf@fencepost.gnu.org> <1uwqlnr5yh.fsf@fencepost.gnu.org> <87siwbnxan.fsf@gmail.com> <878uy348h3.fsf@web.de> NNTP-Posting-Host: plane.gmane.org Mime-Version: 1.0 Content-Type: multipart/mixed; boundary="=-=-=" X-Trace: ger.gmane.org 1418636018 15350 80.91.229.3 (15 Dec 2014 09:33:38 GMT) X-Complaints-To: usenet@ger.gmane.org NNTP-Posting-Date: Mon, 15 Dec 2014 09:33:38 +0000 (UTC) Cc: emacs-devel@gnu.org To: Michael Heerdegen , Glenn Morris Original-X-From: emacs-devel-bounces+ged-emacs-devel=m.gmane.org@gnu.org Mon Dec 15 10:33:33 2014 Return-path: Envelope-to: ged-emacs-devel@m.gmane.org Original-Received: from lists.gnu.org ([208.118.235.17]) by plane.gmane.org with esmtp (Exim 4.69) (envelope-from ) id 1Y0S20-0000fY-Hq for ged-emacs-devel@m.gmane.org; Mon, 15 Dec 2014 10:33:33 +0100 Original-Received: from localhost ([::1]:38680 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1Y0S1z-0003bh-J1 for ged-emacs-devel@m.gmane.org; Mon, 15 Dec 2014 04:33:31 -0500 Original-Received: from eggs.gnu.org ([2001:4830:134:3::10]:52935) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1Y0S1p-0003aJ-7R for emacs-devel@gnu.org; Mon, 15 Dec 2014 04:33:26 -0500 Original-Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1Y0S1j-0003pP-EL for emacs-devel@gnu.org; Mon, 15 Dec 2014 04:33:21 -0500 Original-Received: from mail-pa0-x229.google.com ([2607:f8b0:400e:c03::229]:49987) by eggs.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1Y0S1d-0003og-8D; Mon, 15 Dec 2014 04:33:10 -0500 Original-Received: by mail-pa0-f41.google.com with SMTP id rd3so11526608pab.28 for ; Mon, 15 Dec 2014 01:33:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=from:to:cc:subject:organization:references:date:in-reply-to :message-id:user-agent:mime-version:content-type; bh=ufxnXaKt/Gb6tf25apGb9k7AQNsBTgyMyAtO/LgygTs=; b=hZM1wsyXEjSuO4ZMGeJ8LzwuDHRjHm3HYhEQB4qb5sx9jH1nQOySJ0FjGTU2ZkC+Cs moCJksW1he1rusiJK/ia2UwOwHsN/aFjFfp5fS8Q0KrBmSjXRst8/4Z8LS87H2Po3Agh mrKIy9wGPJhiiBLKy5Hxyq6bG18JsHl7yL1mq78sT5DQsPYb5NxCie0Rn7rlgiXxUVCg wPNiXIyPWzriDEi0CM4WT2pjWr8piS4vEMBe4vElUSjMoHVAAYnG8eg0WJkAuzCotAt1 +9N1ot6NgumEe/vTI35AszJtli5lz11ZGxBtLeBegb+1x//Y1vXYELqFj4w737Y7w8r2 tRhQ== X-Received: by 10.66.246.130 with SMTP id xw2mr48816057pac.55.1418635987171; Mon, 15 Dec 2014 01:33:07 -0800 (PST) Original-Received: from localhost ([2607:f010:2e9:9:acfb:40a8:266a:ade1]) by mx.google.com with ESMTPSA id e2sm8696058pdo.11.2014.12.15.01.33.04 for (version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Mon, 15 Dec 2014 01:33:04 -0800 (PST) In-Reply-To: <878uy348h3.fsf@web.de> (Michael Heerdegen's message of "Wed, 09 Oct 2013 02:02:32 +0200") User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.0.50 (gnu/linux) X-detected-operating-system: by eggs.gnu.org: Error: Malformed IPv6 address (bad octet value). X-Received-From: 2607:f8b0:400e:c03::229 X-BeenThere: emacs-devel@gnu.org X-Mailman-Version: 2.1.14 Precedence: list List-Id: "Emacs development discussions." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: emacs-devel-bounces+ged-emacs-devel=m.gmane.org@gnu.org Original-Sender: emacs-devel-bounces+ged-emacs-devel=m.gmane.org@gnu.org Xref: news.gmane.org gmane.emacs.devel:180137 Archived-At: --=-=-= Content-Type: text/plain Hi, I have finally got down to this. The image-transform.el and refactored image-mode.el: https://github.com/vspinu/image-transform Diff: https://github.com/vspinu/image-transform/compare/emacs...master Tests and examples: https://github.com/vspinu/image-transform/blob/master/tests.el The documentation is in `image-transform` and `image-transform-backends` docstrings. The biggest change on image-mode.el side is the introduction of the local `image-manipulation-map` that includes all commands that are also meaningful outside of `image-mode.el`. I changed functions that are meaningful outside of `image-mode` not to include "-mode-" infix and to operate on &optional image instead of current image. Once the patch is agreed upon, I would like to isolate all these functions into a separate `image-manip.el`. The `image-mode.el` is better kept for image-mode, image-minor-mode and multi-image-mode (still to be written). At this stage the stuff is ready for a review as I have only minor things to fix. I will be traveling till 18th and will resume once I am back. Would be really great if interested people could have a quick look till then. Thanks, Vitalie --=-=-= Content-Type: text/x-diff Content-Disposition: inline Modified image-mode.el diff --git a/image-mode.el b/image-mode.el index b94162d..630b2e0 100644 --- a/image-mode.el +++ b/image-mode.el @@ -39,9 +39,50 @@ ;;; Code: (require 'image) -(eval-when-compile (require 'cl-lib)) +(require 'image-transform) +;; fixme: VS: why did I remove this? +;; (eval-when-compile (require 'cl-lib)) + +(defgroup image-mode () + "Support for visiting image files." + :group 'multimedia) + +(defcustom image-mode-auto-resize 'fit-if-large + "Image auto-resize default. + +If null, don't auto resize. If set to a symbol, must take one of +the following values: + + *`fit' - maximally scale IMAGE to fit into window + *`fit-if-large' - like `fit', but only when image is larger than window + *`fit-height' - fit the image to window height + *`fit-width' - fit the image to window width + *`fit-stretch' - stretch the image to fit to both height and + width of the window + +A number is interpreted as width in pixels. Cons cell, string and +list values are as the VALUE argument of `image-transform-spec:geometry'." + :type '(choice + (const :tag "No Resize" nil) + (const :tag "Fit" fit) + (const :tag "Fit if Large" fit-if-large) + (const :tag "Fit Height" fit-height) + (const :tag "Fit Width" fit-width) + (const :tag "Fit Stretch" fit-stretch) + (number :tag "Width") + (string) + (cons number number) + (list number number string)) + :group 'image-mode + :version "25.1") + +(defcustom image-mode-show-cursor t + "Non-nil if the cursor should be shown in `image-mode'." + :group 'image-mode + :type 'boolean) -;;; Image mode window-info management. + +;;; Window Info Management. (defvar-local image-mode-winprops-alist t) @@ -49,31 +90,13 @@ "Special hook run when image data is requested in a new window. It is called with one argument, the initial WINPROPS.") -;; FIXME this doesn't seem mature yet. Document in manual when it is. -(defvar image-transform-resize nil - "The image resize operation. -Its value should be one of the following: - - nil, meaning no resizing. - - `fit-height', meaning to fit the image to the window height. - - `fit-width', meaning to fit the image to the window width. - - A number, which is a scale factor (the default size is 1).") - -(defvar image-transform-scale 1.0 - "The scale factor of the image being displayed.") - -(defvar image-transform-rotation 0.0 - "Rotation angle for the image in the current Image mode buffer.") - -(defvar image-transform-right-angle-fudge 0.0001 - "Snap distance to a multiple of a right angle. -There's no deep theory behind the default value, it should just -be somewhat larger than ImageMagick's MagickEpsilon.") - (defun image-mode-winprops (&optional window cleanup) "Return winprops of WINDOW. -A winprops object has the shape (WINDOW . ALIST). -WINDOW defaults to `selected-window' if it displays the current buffer, and -otherwise it defaults to t, used for times when the buffer is not displayed." +A winprops object has the shape (WINDOW . ALIST). WINDOW defaults +to `selected-window' if it displays the current buffer, and +otherwise it defaults to t, used for times when the buffer is not +displayed. When CLEANUP is non-nil, remove all winprops with +deleted window." (cond ((null window) (setq window (if (eq (current-buffer) (window-buffer)) (selected-window) t))) @@ -144,13 +167,45 @@ otherwise it defaults to t, used for times when the buffer is not displayed." (add-hook 'window-configuration-change-hook 'image-mode-reapply-winprops nil t)) -;;; Image scrolling functions - -(defun image-get-display-property () - (get-char-property (point-min) 'display - ;; There might be different images for different displays. - (if (eq (window-buffer) (current-buffer)) - (selected-window)))) + +;;; Access Images at Point + +(defun image-get-display-property (&optional pos) + (setq pos (or pos (point))) + (or (get-char-property pos 'display + ;; There might be different images for different displays. + (if (eq (window-buffer) (current-buffer)) + (selected-window))) + ;; overlay before-string/after-string display property, like in put-image + (let ((OVS (overlays-at pos)) + ov disp) + (while (setq ov (pop OVS)) + (let ((bs (overlay-get ov 'before-string)) + (as (overlay-get ov 'after-string))) + ;; last one takes precedence + (setq disp (or (and as (get-text-property 0 'display as)) + (and bs (get-text-property 0 'display bs)))))) + disp))) + +(defun image-at-point (&optional pos) + "Return image at POS if there is one, or nil otherwise. +Search text and overlays at POS for a 'display' property that +holds an image. POS defaults to point." + ;; fixme: check preceding point as well + (let* ((disp (image-get-display-property pos))) + (or (and (eq (car-safe disp) 'image) + disp) + ;; margin images + (and (eq (car-safe (cdr-safe disp)) 'image) + (cdr disp))))) + +(defun image-get-transforms (&optional image) + "Return transformation chain of the IMAGE. +IMAGE defaults to `image-at-point'." + (interactive) + (setq image (or image (image-at-point))) + (or (plist-get (cdr image) :transforms) + '(tr))) (declare-function image-size "image.c" (spec &optional pixels frame)) @@ -179,6 +234,10 @@ but not `slice', return the `image-size' of the specified image." (t (error "Invalid image specification: %s" spec)))))) + +;;; Image Scrolling +;; fixme: operate on images? + (defun image-forward-hscroll (&optional n) "Scroll image in current window to the left by N character widths. Stop if the right edge of the image is reached." @@ -305,21 +364,22 @@ stopping if the top or bottom edge of the image is reached." (image-set-window-hscroll (max 0 (- img-width win-width))) (image-set-window-vscroll (max 0 (- img-height win-height))))) -;; Adjust frame and image size. + +;;; Adjust frame and image size. -(defun image-mode-fit-frame (&optional frame toggle) - "Fit FRAME to the current image. +(defun image-scale-frame-to-fit-image (&optional frame toggle image) + "Fit FRAME to the image. If FRAME is omitted or nil, it defaults to the selected frame. All other windows on the frame are deleted. If called interactively, or if TOGGLE is non-nil, toggle between -fitting FRAME to the current image and restoring the size and -window configuration prior to the last `image-mode-fit-frame' -call." +fitting FRAME to the IMAGE and restoring the size and window +configuration prior to the last `image-scale-frame-to-fit-image' +call. IMAGE defaults to `image-at-point'." (interactive (list nil t)) (let* ((buffer (current-buffer)) - (display (image-get-display-property)) - (size (image-display-size display)) + (image (image-at-point)) + (size (image-display-size image)) (saved (frame-parameter frame 'image-mode-saved-params)) (window-configuration (current-window-configuration frame)) (width (frame-width frame)) @@ -352,34 +412,27 @@ call." (cons width height) window-configuration))))))) -;;; Image Mode setup +(define-obsolete-function-alias 'image-mode-fit-frame 'image-scale-frame-to-fit-image "25.1") + + +;;; Image Mode (defvar-local image-type nil "The image type for the current Image mode buffer.") -(defvar-local image-multi-frame nil - "Non-nil if image for the current Image mode buffer has multiple frames.") - (defvar image-mode-previous-major-mode nil "Internal variable to keep the previous non-image major mode.") (defvar image-mode-map (let ((map (make-sparse-keymap))) (set-keymap-parent map special-mode-map) - (define-key map "\C-c\C-c" 'image-toggle-display) + (define-key map "\C-c\C-c" 'image-mode-toggle-display) (define-key map (kbd "SPC") 'image-scroll-up) (define-key map (kbd "S-SPC") 'image-scroll-down) (define-key map (kbd "DEL") 'image-scroll-down) (define-key map (kbd "RET") 'image-toggle-animation) - (define-key map "F" 'image-goto-frame) - (define-key map "f" 'image-next-frame) - (define-key map "b" 'image-previous-frame) - (define-key map "n" 'image-next-file) - (define-key map "p" 'image-previous-file) - (define-key map "a+" 'image-increase-speed) - (define-key map "a-" 'image-decrease-speed) - (define-key map "a0" 'image-reset-speed) - (define-key map "ar" 'image-reverse-speed) + (define-key map "n" 'image-mode-next-file) + (define-key map "p" 'image-mode-previous-file) (define-key map [remap forward-char] 'image-forward-hscroll) (define-key map [remap backward-char] 'image-backward-hscroll) (define-key map [remap right-char] 'image-forward-hscroll) @@ -396,82 +449,22 @@ call." (define-key map [remap end-of-buffer] 'image-eob) (easy-menu-define image-mode-menu map "Menu for Image mode." '("Image" - ["Show as Text" image-toggle-display :active t + ["Show as Text" image-mode-toggle-display :active t :help "Show image as text"] "--" - ["Fit to Window Height" image-transform-fit-to-height - :visible (eq image-type 'imagemagick) - :help "Resize image to match the window height"] - ["Fit to Window Width" image-transform-fit-to-width - :visible (eq image-type 'imagemagick) - :help "Resize image to match the window width"] - ["Rotate Image..." image-transform-set-rotation - :visible (eq image-type 'imagemagick) - :help "Rotate the image"] - ["Reset Transformations" image-transform-reset - :visible (eq image-type 'imagemagick) - :help "Reset all image transformations"] - "--" - ["Show Thumbnails" - (lambda () - (interactive) - (image-dired default-directory)) - :active default-directory + ["Show Thumbnails" image-mode-show-thumbnails :active default-directory :help "Show thumbnails for all images in this directory"] - ["Next Image" image-next-file :active buffer-file-name + ["Next Image" image-mode-next-file :active buffer-file-name :help "Move to next image in this directory"] - ["Previous Image" image-previous-file :active buffer-file-name + ["Previous Image" image-mode-previous-file :active buffer-file-name :help "Move to previous image in this directory"] - "--" - ["Fit Frame to Image" image-mode-fit-frame :active t - :help "Resize frame to match image"] - "--" - ["Animate Image" image-toggle-animation :style toggle - :selected (let ((image (image-get-display-property))) - (and image (image-animate-timer image))) - :active image-multi-frame - :help "Toggle image animation"] - ["Loop Animation" - (lambda () (interactive) - (setq image-animate-loop (not image-animate-loop)) - ;; FIXME this is a hacky way to make it affect a currently - ;; animating image. - (when (let ((image (image-get-display-property))) - (and image (image-animate-timer image))) - (image-toggle-animation) - (image-toggle-animation))) - :style toggle :selected image-animate-loop - :active image-multi-frame - :help "Animate images once, or forever?"] - ["Reverse Animation" image-reverse-speed - :style toggle :selected (let ((image (image-get-display-property))) - (and image (< - (image-animate-get-speed image) - 0))) - :active image-multi-frame - :help "Reverse direction of this image's animation?"] - ["Speed Up Animation" image-increase-speed - :active image-multi-frame - :help "Speed up this image's animation"] - ["Slow Down Animation" image-decrease-speed - :active image-multi-frame - :help "Slow down this image's animation"] - ["Reset Animation Speed" image-reset-speed - :active image-multi-frame - :help "Reset the speed of this image's animation"] - ["Next Frame" image-next-frame :active image-multi-frame - :help "Show the next frame of this image"] - ["Previous Frame" image-previous-frame :active image-multi-frame - :help "Show the previous frame of this image"] - ["Goto Frame..." image-goto-frame :active image-multi-frame - :help "Show a specific frame of this image"] )) map) "Mode keymap for `image-mode'.") (defvar image-minor-mode-map (let ((map (make-sparse-keymap))) - (define-key map "\C-c\C-c" 'image-toggle-display) + (define-key map "\C-c\C-c" 'image-mode-toggle-display) map) "Mode keymap for `image-minor-mode'.") @@ -482,7 +475,7 @@ call." ;;;###autoload (defun image-mode () "Major mode for image files. -You can use \\\\[image-toggle-display] +You can use \\\\[image-mode-toggle-display] to toggle between display as an image and display as text. Key bindings: @@ -498,7 +491,7 @@ Key bindings: (if (not (image-get-display-property)) (progn - (image-toggle-display-image) + (image-mode-toggle-display-image) ;; If attempt to display the image fails. (if (not (image-get-display-property)) (error "Invalid image"))) @@ -512,24 +505,25 @@ Key bindings: ;; Use our own bookmarking function for images. (setq-local bookmark-make-record-function - #'image-bookmark-make-record) + #'image-bookmark-make-record) ;; Keep track of [vh]scroll when switching buffers (image-mode-setup-winprops) - (add-hook 'change-major-mode-hook 'image-toggle-display-text nil t) - (add-hook 'after-revert-hook 'image-after-revert-hook nil t) + (setq-local revert-buffer-function 'image-mode-revert-buffer) + + (add-hook 'change-major-mode-hook 'image-mode-toggle-display-text nil t) + (add-hook 'after-revert-hook 'image-mode-after-revert nil t) (run-mode-hooks 'image-mode-hook) (let ((image (image-get-display-property)) (msg1 (substitute-command-keys - "Type \\[image-toggle-display] to view the image as ")) + "Type \\[image-mode-toggle-display] to view the image as ")) animated) (cond ((null image) (message "%s" (concat msg1 "an image."))) ((setq animated (image-multi-frame-p image)) - (setq image-multi-frame t - mode-line-process + (setq mode-line-process `(:eval (concat " " (propertize @@ -559,6 +553,12 @@ mouse-3: Previous frame" (if (called-interactively-p 'any) 'error 'message) "Cannot display image: %s" (cdr err))))) +(defun image-mode-revert-buffer (ignore noconfirm) + ;; fixme: revert without re-installing the mode; deriving modes is difficult + ;; don't ask on reversion + (let ((revert-buffer-function nil)) + (revert-buffer ignore t))) + ;;;###autoload (define-minor-mode image-minor-mode "Toggle Image minor mode in this buffer. @@ -566,7 +566,7 @@ With a prefix argument ARG, enable Image minor mode if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil. -Image minor mode provides the key \\\\[image-toggle-display], +Image minor mode provides the key \\\\[image-mode-toggle-display], to switch back to `image-mode' and display an image file as the actual image." nil (:eval (if image-type (format " Image[%s]" image-type) " Image")) @@ -581,7 +581,7 @@ actual image." "Set a non-image mode as major mode in combination with image minor mode. A non-image major mode found from `auto-mode-alist' or Fundamental mode displays an image file as text. `image-minor-mode' provides the key -\\\\[image-toggle-display] to switch back to `image-mode' +\\\\[image-mode-toggle-display] to switch back to `image-mode' to display an image file as the actual image. You can use `image-mode-as-text' in `auto-mode-alist' when you want @@ -617,16 +617,16 @@ on these modes." ;; Enable image minor mode with `C-c C-c'. (image-minor-mode 1) ;; Show the image file as text. - (image-toggle-display-text) + (image-mode-toggle-display-text) (message "%s" (concat (substitute-command-keys - "Type \\[image-toggle-display] to view the image as ") + "Type \\[image-mode-toggle-display] to view the image as ") (if (image-get-display-property) "text" "an image") ".")))) (define-obsolete-function-alias 'image-mode-maybe 'image-mode "23.2") -(defun image-toggle-display-text () +(defun image-mode-toggle-display-text () "Show the image file as text. Remove text properties that display the image." (let ((inhibit-read-only t) @@ -639,11 +639,19 @@ Remove text properties that display the image." (if (called-interactively-p 'any) (message "Repeat this command to go back to displaying the image")))) +(define-obsolete-function-alias 'image-toggle-display-text 'image-mode-toggle-display-text "25.1") + +(defun image-mode-show-thumbnails () + "Show thumbnails alongside dired buffer. +Based on `image-dired'" + (interactive) + (image-dired default-directory)) + (defvar archive-superior-buffer) (defvar tar-superior-buffer) (declare-function image-flush "image.c" (spec &optional frame)) -(defun image-toggle-display-image () +(defun image-mode-toggle-display-image () "Show the image of the image file. Turn the image data into a real image, but only if the whole file was inserted." @@ -662,19 +670,9 @@ was inserted." (string-make-unibyte (buffer-substring-no-properties (point-min) (point-max))) filename)) - ;; If we have a `fit-width' or a `fit-height', don't limit - ;; the size of the image to the window size. - (edges (and (null image-transform-resize) - (window-inside-pixel-edges - (get-buffer-window (current-buffer))))) - (type (if (fboundp 'imagemagick-types) - 'imagemagick - (image-type file-or-data nil data-p))) - (image (if (not edges) - (create-image file-or-data type data-p) - (create-image file-or-data type data-p - :max-width (- (nth 2 edges) (nth 0 edges)) - :max-height (- (nth 3 edges) (nth 1 edges))))) + (image (create-image file-or-data nil data-p)) + (type (plist-get (cdr image) :type)) + ;; (type (image-type file-or-data nil data-p)) (inhibit-read-only t) (buffer-undo-list t) (modified (buffer-modified-p)) @@ -682,19 +680,23 @@ was inserted." ;; Discard any stale image data before looking it up again. (image-flush image) - (setq image (append image (image-transform-properties image))) + (image-transform-interactive image :resize image-mode-auto-resize) + (setq props `(display ,image ;; intangible ,image rear-nonsticky (display) ;; intangible - read-only t front-sticky (read-only))) + read-only t front-sticky (read-only) + keymap ,image-manipulation-map)) (let ((buffer-file-truename nil)) ; avoid changing dir mtime by lock_file (add-text-properties (point-min) (point-max) props) (restore-buffer-modified-p modified)) - ;; Inhibit the cursor when the buffer contains only an image, - ;; because cursors look very strange on top of images. - (setq cursor-type nil) + + ;; It's important to distinguish active buffer/image. + (unless image-mode-show-cursor + (setq cursor-type nil)) + ;; This just makes the arrow displayed in the right fringe ;; area look correct when the image is wider than the window. (setq truncate-lines t) @@ -708,11 +710,12 @@ was inserted." (setq image-type type) (if (eq major-mode 'image-mode) (setq mode-name (format "Image[%s]" type))) - (image-transform-check-size) (if (called-interactively-p 'any) (message "Repeat this command to go back to displaying the file as text")))) -(defun image-toggle-display () +(define-obsolete-function-alias 'image-toggle-display-image 'image-mode-toggle-display-image "25.1") + +(defun image-mode-toggle-display () "Toggle between image and text display. If the current buffer is displaying an image file as an image, call `image-mode-as-text' to switch to text. Otherwise, display @@ -722,13 +725,17 @@ the image by calling `image-mode'." (image-mode-as-text) (image-mode))) -(defun image-after-revert-hook () +(define-obsolete-function-alias 'image-toggle-display 'image-mode-toggle-display "25.1") + +(defun image-mode-after-revert () (when (image-get-display-property) - (image-toggle-display-text) + (image-mode-toggle-display-text) ;; Update image display. (mapc (lambda (window) (redraw-frame (window-frame window))) - (get-buffer-window-list (current-buffer) 'nomini 'visible)) - (image-toggle-display-image))) + (get-buffer-window-list (current-buffer) 'nomini 'visible)) + (image-mode-toggle-display-image))) + +(define-obsolete-function-alias 'image-after-revert-hook 'image-mode-after-revert "25.1") ;;; Animated images @@ -739,12 +746,13 @@ the image by calling `image-mode'." :version "24.1" :group 'image) -(defun image-toggle-animation () - "Start or stop animating the current image. -If `image-animate-loop' is non-nil, animation loops forever. -Otherwise it plays once, then stops." +(defun image-toggle-animation (&optional image) + "Start or stop animating IMAGE. +If `image-animate-loop' is non-nil, animation loops +forever. Otherwise it plays once, then stops. IMAGE defaults to +the image at point." (interactive) - (let ((image (image-get-display-property)) + (let ((image (or image (image-at-point))) animation) (cond ((null image) @@ -763,15 +771,16 @@ Otherwise it plays once, then stops." (image-animate image index (if image-animate-loop t))))))))) -(defun image--set-speed (speed &optional multiply) - "Set speed of an animated image to SPEED. +(defun image--set-speed (image speed &optional multiply) + "Set speed of an animated IMAGE to SPEED. If MULTIPLY is non-nil, treat SPEED as a multiplication factor. -If SPEED is `reset', reset the magnitude of the speed to 1." - (let ((image (image-get-display-property))) +If SPEED is `reset', reset the magnitude of the speed to 1. +IMAGE defaults to `image-at-point'." + (let ((image (or image (image-at-point)))) (cond ((null image) (error "No image is present")) - ((null image-multi-frame) + ((null (image-multi-frame-p image)) (message "No image animation.")) (t (if (eq speed 'reset) @@ -785,38 +794,46 @@ If SPEED is `reset', reset the magnitude of the speed to 1." (image-toggle-animation)) (message "Image speed is now %s" (image-animate-get-speed image)))))) -(defun image-increase-speed () - "Increase the speed of current animated image by a factor of 2." +(defun image-increase-speed (&optional image) + "Increase the speed of animated IMAGE by a factor of 2. +IMAGE defaults to `image-at-point'." (interactive) - (image--set-speed 2 t)) + (image--set-speed image 2 t)) -(defun image-decrease-speed () - "Decrease the speed of current animated image by a factor of 2." +(defun image-decrease-speed (&optional image) + "Decrease the speed of animated IMAGE by a factor of 2. +IMAGE defaults to `image-at-point'" (interactive) - (image--set-speed 0.5 t)) + (image--set-speed image 0.5 t)) -(defun image-reverse-speed () - "Reverse the animation of the current image." +(defun image-reverse-speed (&optional image) + "Reverse the animation of the IMAGE. +IMAGE defaults to `image-at-point'." (interactive) - (image--set-speed -1 t)) + (image--set-speed image -1 t)) -(defun image-reset-speed () - "Reset the animation speed of the current image." +(defun image-reset-speed (&optional image) + "Reset the animation speed of the IMAGE. +IMAGE defaults to `image-at-point'." (interactive) (image--set-speed 'reset)) -(defun image-goto-frame (n &optional relative) + +;;; Multiframe Images + +(defun image-goto-frame (n &optional relative image) "Show frame N of a multi-frame image. -Optional argument OFFSET non-nil means interpret N as relative to the -current frame. Frames are indexed from 1." +Optional argument RELATIVE non-nil means interpret N as relative +to the current frame. Frames are indexed from 1. IMAGE defaults +to `image-at-point'." (interactive (list (or current-prefix-arg (read-number "Show frame number: ")))) - (let ((image (image-get-display-property))) + (let ((image (or image (image-at-point)))) (cond ((null image) (error "No image is present")) - ((null image-multi-frame) + ((null (image-multi-frame-p image)) (message "No image animation.")) (t (image-show-frame image @@ -824,24 +841,26 @@ current frame. Frames are indexed from 1." (+ n (image-current-frame image)) (1- n))))))) -(defun image-next-frame (&optional n) +(defun image-next-frame (&optional n image) "Switch to the next frame of a multi-frame image. With optional argument N, switch to the Nth frame after the current one. -If N is negative, switch to the Nth frame before the current one." +If N is negative, switch to the Nth frame before the current one. +IMAGE defaults to `image-at-point'." (interactive "p") (image-goto-frame n t)) -(defun image-previous-frame (&optional n) +(defun image-previous-frame (&optional n image) "Switch to the previous frame of a multi-frame image. -With optional argument N, switch to the Nth frame before the current one. -If N is negative, switch to the Nth frame after the current one." +With optional argument N, switch to the Nth frame before the +current one. If N is negative, switch to the Nth frame after the +current one. IMAGE defaults to `image-at-point'." (interactive "p") (image-next-frame (- n))) ;;; Switching to the next/previous image -(defun image-next-file (&optional n) +(defun image-mode-next-file (&optional n) "Visit the next image in the same directory as the current image file. With optional argument N, visit the Nth image file after the current one, in cyclic alphabetical order. @@ -864,7 +883,9 @@ replacing the current Image mode buffer." (setq idx (mod (+ idx (or n 1)) (length images))) (find-alternate-file (nth idx images)))) -(defun image-previous-file (&optional n) +(define-obsolete-function-alias 'image-next-file 'image-mode-next-file "25.1") + +(defun image-mode-previous-file (&optional n) "Visit the preceding image in the same directory as the current file. With optional argument N, visit the Nth image file preceding the current one, in cyclic alphabetical order. @@ -872,7 +893,7 @@ current one, in cyclic alphabetical order. This command visits the specified file via `find-alternate-file', replacing the current Image mode buffer." (interactive "p") - (image-next-file (- n))) + (image-mode-next-file (- n))) (defun image-mode--images-in-directory (file) (let* ((dir (file-name-directory buffer-file-name)) @@ -884,6 +905,8 @@ replacing the current Image mode buffer." (push file files)) (sort files 'string-lessp))) +(define-obsolete-function-alias 'image-previous-file 'image-mode-previous-file "25.1") + ;;; Support for bookmark.el (declare-function bookmark-make-record-default @@ -902,219 +925,236 @@ replacing the current Image mode buffer." ;; returned by `bookmark-make-record-function', which see. (prog1 (bookmark-default-handler bmk) (when (not (string= image-type (bookmark-prop-get bmk 'image-type))) - (image-toggle-display)))) + (image-mode-toggle-display)))) + +;;; Image Local Manipulation Map -;; Not yet implemented. -;; (defvar image-transform-minor-mode-map -;; (let ((map (make-sparse-keymap))) -;; ;; (define-key map [(control ?+)] 'image-scale-in) -;; ;; (define-key map [(control ?-)] 'image-scale-out) -;; ;; (define-key map [(control ?=)] 'image-scale-none) -;; ;; (define-key map "c f h" 'image-scale-fit-height) -;; ;; (define-key map "c ]" 'image-rotate-right) -;; map) -;; "Minor mode keymap `image-transform-mode'.") -;; -;; (define-minor-mode image-transform-mode -;; "Minor mode for scaling and rotating images. -;; With a prefix argument ARG, enable the mode if ARG is positive, -;; and disable it otherwise. If called from Lisp, enable the mode -;; if ARG is omitted or nil. This minor mode requires Emacs to have -;; been compiled with ImageMagick support." -;; nil "image-transform" image-transform-minor-mode-map) - - -(defsubst image-transform-width (width height) - "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle. -The rotation angle is the value of `image-transform-rotation' in degrees." - (let ((angle (degrees-to-radians image-transform-rotation))) - ;; Assume, w.l.o.g., that the vertices of the rectangle have the - ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the - ;; rotation by the angle A. The projections onto the first axis - ;; of the vertices of the rotated rectangle are +- (w/2) cos A +- - ;; (h/2) sin A, and the difference between the largest and the - ;; smallest of the four values is the expression below. - (+ (* width (abs (cos angle))) (* height (abs (sin angle)))))) - -;; The following comment and code snippet are from -;; ImageMagick-6.7.4-4/magick/distort.c - -;; /* Set the output image geometry to calculated 'best fit'. -;; Yes this tends to 'over do' the file image size, ON PURPOSE! -;; Do not do this for DePolar which needs to be exact for virtual tiling. -;; */ -;; if ( fix_bounds ) { -;; geometry.x = (ssize_t) floor(min.x-0.5); -;; geometry.y = (ssize_t) floor(min.y-0.5); -;; geometry.width=(size_t) ceil(max.x-geometry.x+0.5); -;; geometry.height=(size_t) ceil(max.y-geometry.y+0.5); -;; } - -;; Other parts of the same file show that here the origin is in the -;; left lower corner of the image rectangle, the center of the -;; rotation is the center of the rectangle and min.x and max.x -;; (resp. min.y and max.y) are the smallest and the largest of the -;; projections of the vertices onto the first (resp. second) axis. - -(defun image-transform-fit-width (width height length) - "Return (w . h) so that a rotated w x h image has exactly width LENGTH. -The rotation angle is the value of `image-transform-rotation'. -Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is -an \"approximately uniformly\" scaled W x H rectangle, which -currently means that w is one of floor(s W) + {0, 1, -1} and h is -floor(s H), where s can be recovered as the value of `image-transform-scale'. -The value of `image-transform-rotation' may be replaced by -a slightly different angle. Currently this is done for values -close to a multiple of 90, see `image-transform-right-angle-fudge'." - (cond ((< (abs (- (mod (+ image-transform-rotation 90) 180) 90)) - image-transform-right-angle-fudge) - (cl-assert (not (zerop width)) t) - (setq image-transform-rotation - (float (round image-transform-rotation)) - image-transform-scale (/ (float length) width)) - (cons length nil)) - ((< (abs (- (mod (+ image-transform-rotation 45) 90) 45)) - image-transform-right-angle-fudge) - (cl-assert (not (zerop height)) t) - (setq image-transform-rotation - (float (round image-transform-rotation)) - image-transform-scale (/ (float length) height)) - (cons nil length)) - (t - (cl-assert (not (and (zerop width) (zerop height))) t) - (setq image-transform-scale - (/ (float (1- length)) (image-transform-width width height))) - ;; Assume we have a w x h image and an angle A, and let l = - ;; l(w, h) = w |cos A| + h |sin A|, which is the actual width - ;; of the bounding box of the rotated image, as calculated by - ;; `image-transform-width'. The code snippet quoted above - ;; means that ImageMagick puts the rotated image in - ;; a bounding box of width L = 2 ceil((w+l+1)/2) - w. - ;; Elementary considerations show that this is equivalent to - ;; L - w being even and L-3 < l(w, h) <= L-1. In our case, L is - ;; the given `length' parameter and our job is to determine - ;; reasonable values for w and h which satisfy these - ;; conditions. - (let ((w (floor (* image-transform-scale width))) - (h (floor (* image-transform-scale height)))) - ;; Let w and h as bound above. Then l(w, h) <= l(s W, s H) - ;; = L-1 < l(w+1, h+1) = l(w, h) + l(1, 1) <= l(w, h) + 2, - ;; hence l(w, h) > (L-1) - 2 = L-3. - (cons - (cond ((= (mod w 2) (mod length 2)) - w) - ;; l(w+1, h) >= l(w, h) > L-3, but does l(w+1, h) <= - ;; L-1 hold? - ((<= (image-transform-width (1+ w) h) (1- length)) - (1+ w)) - ;; No, it doesn't, but this implies that l(w-1, h) = - ;; l(w+1, h) - l(2, 0) >= l(w+1, h) - 2 > (L-1) - - ;; 2 = L-3. Clearly, l(w-1, h) <= l(w, h) <= L-1. - (t - (1- w))) - h))))) - -(defun image-transform-check-size () - "Check that the image exactly fits the width/height of the window. - -Do this for an image of type `imagemagick' to make sure that the -elisp code matches the way ImageMagick computes the bounding box -of a rotated image." - (when (and (not (numberp image-transform-resize)) - (boundp 'image-type) - (eq image-type 'imagemagick)) - (let ((size (image-display-size (image-get-display-property) t))) - (cond ((eq image-transform-resize 'fit-width) - (cl-assert (= (car size) - (- (nth 2 (window-inside-pixel-edges)) - (nth 0 (window-inside-pixel-edges)))) - t)) - ((eq image-transform-resize 'fit-height) - (cl-assert (= (cdr size) - (- (nth 3 (window-inside-pixel-edges)) - (nth 1 (window-inside-pixel-edges)))) - t)))))) - -(defun image-transform-properties (spec) - "Return rescaling/rotation properties for image SPEC. -These properties are determined by the Image mode variables -`image-transform-resize' and `image-transform-rotation'. The -return value is suitable for appending to an image spec. - -Rescaling and rotation properties only take effect if Emacs is -compiled with ImageMagick support." - (setq image-transform-scale 1.0) - (when (or image-transform-resize - (/= image-transform-rotation 0.0)) - ;; Note: `image-size' looks up and thus caches the untransformed - ;; image. There's no easy way to prevent that. - (let* ((size (image-size spec t)) - (resized - (cond - ((numberp image-transform-resize) - (unless (= image-transform-resize 1) - (setq image-transform-scale image-transform-resize) - (cons nil (floor (* image-transform-resize (cdr size)))))) - ((eq image-transform-resize 'fit-width) - (image-transform-fit-width - (car size) (cdr size) - (- (nth 2 (window-inside-pixel-edges)) - (nth 0 (window-inside-pixel-edges))))) - ((eq image-transform-resize 'fit-height) - (let ((res (image-transform-fit-width - (cdr size) (car size) - (- (nth 3 (window-inside-pixel-edges)) - (nth 1 (window-inside-pixel-edges)))))) - (cons (cdr res) (car res))))))) - `(,@(when (car resized) - (list :width (car resized))) - ,@(when (cdr resized) - (list :height (cdr resized))) - ,@(unless (= 0.0 image-transform-rotation) - (list :rotation image-transform-rotation)))))) - -(defun image-transform-set-scale (scale) - "Prompt for a number, and resize the current image by that amount. -This command has no effect unless Emacs is compiled with -ImageMagick support." - (interactive "nScale: ") - (setq image-transform-resize scale) - (image-toggle-display-image)) - -(defun image-transform-fit-to-height () - "Fit the current image to the height of the current window. -This command has no effect unless Emacs is compiled with -ImageMagick support." +(defcustom image-scale-step 1.1 + "Each step scales the image by this amount." + :type 'number + :group 'image) + +(defun image-scale-adjust (&optional N) + "Adjust the scale of the image by N steps. + +N may be passed as a numeric prefix argument. Each step scales +the image by the value of `image-scale-step' (a negative number +of steps decreases the height by the same amount). As a special +case, an argument of 0 will remove any scaling currently active. + +The actual adjustment depends on the final element of the +key binding used to invoke this command: + + +, = Increase the size of the image by one step + - Decrease the size of the image by one step + 0 Reset to the original image size + +When adjusting with `+' or `-', continue to read input events and +further adjust the scale as long as the input event read \(with +all modifiers removed) is `+' or `-'. + +This command is a special-purpose wrapper around the +`image-scale-increase'." + ;; fixme: doesn't work with universal arg + (interactive "p") + (let ((ev last-command-event) + (echo-keystrokes nil)) + (let* ((base (event-basic-type ev)) + (step + (pcase base + ((or ?+ ?=) N) + (?- (- N)) + (?0 0) + (t N)))) + (image-scale-increase step) + (message "Use +,-,0 for further adjustment") + (set-temporary-overlay-map + (let ((map (make-sparse-keymap))) + (dolist (mods '(() (control))) + (dolist (key '(?- ?+ ?= ?0)) ;; = is often unshifted +. + (define-key map (vector (append mods (list key))) + `(lambda () (interactive) (image-scale-adjust (floor (abs ,N))))))) + map))))) + +(defun image-scale-increase (&optional inc image) + "Scale the the IMAGE by INC steps. +Each step scales up the size of the IMAGE the value of +`text-scale-mode-step' (a negative number of steps decreases the +size by the same amount). As a special case, an argument of 0 +will remove any scaling currently active. IMAGE defaults to +`image-at-point'." + (interactive "p") + (let ((image (or image + (image-at-point) + (error "No image at point")))) + (if (/= inc 0) + (image-transform image :scale (* 100 (expt image-scale-step inc))) + (image-tr--delete-properties image '(:width :height :resize)) + ;; don't touch :resize, It might have been set by initial 'fit-xxx operation + (image-tr--delete-transforms image '(:scale)) + (image-transform image)) + (force-window-update (selected-window)))) + +(defun image-scale-decrease (&optional inc image) + "Scale the IMAGE by INC steps. +Each step scales down the size of the IMAGE the value of +`text-scale-mode-step' (a negative number of steps increases the +size by the same amount). As a special case, an argument of 0 +will remove any scaling currently active. IMAGE defaults to +`image-at-point'." + (interactive "p") + (image-scale-increase (- inc) image)) + +(defun image-scale-to-fit-height (&optional image) + "Fit IMAGE to the height of the current window. +IMAGE defaults to `image-at-point'." (interactive) - (setq image-transform-resize 'fit-height) - (image-toggle-display-image)) + (image-transform-interactive image :resize 'fit-height)) -(defun image-transform-fit-to-width () - "Fit the current image to the width of the current window. -This command has no effect unless Emacs is compiled with -ImageMagick support." +(defun image-scale-to-fit-width (&optional image) + "Fit IMAGE to the width of the current window. +IMAGE defaults to `image-at-point'." (interactive) - (setq image-transform-resize 'fit-width) - (image-toggle-display-image)) + (image-transform-interactive image :resize 'fit-width)) -(defun image-transform-set-rotation (rotation) - "Prompt for an angle ROTATION, and rotate the image by that amount. -ROTATION should be in degrees. This command has no effect unless -Emacs is compiled with ImageMagick support." +(defun image-scale-to-fit-window (&optional image) + "Maximally fit IMAGE into current window. +IMAGE defaults to `image-at-point'." + (interactive) + (image-transform-interactive image :resize 'fit)) + +(defun image-stretch-to-fit-window (&optional image) + "Stretch IMAGE into current window. +IMAGE defaults to `image-at-point'." + (interactive) + (image-transform-interactive image :resize 'fit-stretch)) + +(defun image-rotate (rotation &optional image) + "Prompt for an angle ROTATION, and rotate the IMAGE by that amount. +ROTATION should be in degrees. IMAGE defaults to `image-at-point'." (interactive "nRotation angle (in degrees): ") - (setq image-transform-rotation (float (mod rotation 360))) - (image-toggle-display-image)) + (image-transform-interactive image :rotate rotation)) -(defun image-transform-reset () - "Display the current image with the default size and rotation. -This command has no effect unless Emacs is compiled with -ImageMagick support." +(defun image-rotate-right (&optional image) + "Rotate the IMAGE clockwise by 90 degrees. +IMAGE defaults to `image-at-point'." (interactive) - (setq image-transform-resize nil - image-transform-rotation 0.0 - image-transform-scale 1) - (image-toggle-display-image)) + (image-transform-interactive image :rotate 90)) + +(defun image-rotate-left (&optional image) + "Rotate the IMAGE counter-clockwise by 90 degrees. +IMAGE defaults to `image-at-point'." + (interactive) + (image-transform-interactive image :rotate -90)) + +(defun image-change-background (&optional background image) + "Set the BACKGROUND of the IMAGE. +For this to work, image must have a transparent background. IMAGE +defaults to `image-at-point'." + (interactive) + (let ((bg (or background (read-color "Background: " t)))) + (unless image + (unless (setq image (image-at-point)) + (error "No image at point"))) + (image-transform-interactive image :background bg))) + +(defvar image-manipulation-map + (let ((map (make-sparse-keymap))) + (define-key map "F" 'image-goto-frame) + (define-key map "f" 'image-next-frame) + (define-key map "b" 'image-previous-frame) + (define-key map "a+" 'image-increase-speed) + (define-key map "a-" 'image-decrease-speed) + (define-key map "a0" 'image-reset-speed) + (define-key map "ar" 'image-reverse-speed) + (define-key map "+" 'image-scale-adjust) + (define-key map "-" 'image-scale-adjust) + (define-key map "=" 'image-scale-adjust) + (define-key map "0" 'image-scale-adjust) + (define-key map "r" 'image-rotate) + (define-key map "]" 'image-rotate-right) + (define-key map "[" 'image-rotate-left) + (define-key map "ss" 'image-scale-to-fit-window) + (define-key map "sh" 'image-scale-to-fit-height) + (define-key map "sw" 'image-scale-to-fit-width) + (define-key map "sS" 'image-stretch-to-fit-window) + (define-key map "sf" 'image-scale-frame-to-fit-image) + (define-key map "ta" 'image-add-transform) + (define-key map "tk" 'image-delete-transform) + (define-key map "td" 'image-delete-transform) + (define-key map "tl" 'image-list-transforms) + (define-key map "B" 'image-change-background) + (easy-menu-define image-mode-menu map "Local Image Menu." + '("Manipulate" + ["Scale to Window" image-scale-to-fit-window + :help "Maximally resize image to fit into window"] + ["Scale to Window Height" image-scale-to-fit-height + :help "Resize image to match the window height"] + ["Scale to Window Width" image-scale-to-fit-width + :help "Resize image to match the window width"] + ["Scale Frame to Image" image-scale-frame-to-fit-image :active t + :help "Resize frame to match image"] + "--" + ["Rotate Image..." image-rotate] + ["Rotate Image Right" image-rotate-right] + ["Rotate Image Left" image-rotate-left] + "--" + ["Change Image Background..." image-change-background] + "--" + ["Add Transform" image-add-transform] + ["Delete Transform" image-delete-transform] + ["List Transforms" image-list-transforms] + "--" + ["Animate Image" image-toggle-animation :style toggle + :selected (let ((image (image-at-point))) + (and image (image-animate-timer image))) + :active (image-multi-frame-p (image-at-point)) + :help "Toggle image animation"] + ["Loop Animation" + (lambda () (interactive) + (setq image-animate-loop (not image-animate-loop)) + ;; FIXME this is a hacky way to make it affect a currently + ;; animating image. + (when (let ((image (image-get-display-property))) + (and image (image-animate-timer image))) + (image-toggle-animation) + (image-toggle-animation))) + :style toggle :selected image-animate-loop + :active (image-multi-frame-p (image-at-point)) + :help "Animate images once, or forever?"] + ["Reverse Animation" image-reverse-speed + :style toggle :selected (let ((image (image-get-display-property))) + (and image (< + (image-animate-get-speed image) + 0))) + :active (image-multi-frame-p (image-at-point)) + :help "Reverse direction of this image's animation?"] + ["Speed Up Animation" image-increase-speed + :active (image-multi-frame-p (image-at-point)) + :help "Speed up this image's animation"] + ["Slow Down Animation" image-decrease-speed + :active (image-multi-frame-p (image-at-point)) + :help "Slow down this image's animation"] + ["Reset Animation Speed" image-reset-speed + :active (image-multi-frame-p (image-at-point)) + :help "Reset the speed of this image's animation"] + ["Next Frame" image-next-frame + :active (image-multi-frame-p (image-at-point)) + :help "Show the next frame of this image"] + ["Previous Frame" image-previous-frame + :active (image-multi-frame-p (image-at-point)) + :help "Show the previous frame of this image"] + ["Goto Frame..." image-goto-frame + :active (image-multi-frame-p (image-at-point)) + :help "Show a specific frame of this image"] + )) + map) + "Image local manipulation keymap. +Usually used as keymap text property for images. + +\\{image-manipulation-map}") + (provide 'image-mode) --=-=-= Content-Type: text/x-diff Content-Disposition: inline Modified image.el diff --git a/image.el b/image.el index 8430d36..1535567 100644 --- a/image.el +++ b/image.el @@ -441,7 +441,7 @@ means display it in the right marginal area." ;;;###autoload -(defun insert-image (image &optional string area slice) +(defun insert-image (image &optional string area slice map) "Insert IMAGE into current buffer at point. IMAGE is displayed by inserting STRING into the current buffer with a `display' property whose value is the image. STRING @@ -454,7 +454,10 @@ SLICE specifies slice of IMAGE to insert. SLICE nil or omitted means insert whole image. SLICE is a list (X Y WIDTH HEIGHT) specifying the X and Y positions and WIDTH and HEIGHT of image area to insert. A float value 0.0 - 1.0 means relative to the width or -height of the image; integer values are taken as pixel values." +height of the image; integer values are taken as pixel values. +If MAP is provided, it must be a keymap what will be used as +text property keymap. A special value of t means to use +`image-manipulation-map'" ;; Use a space as least likely to cause trouble when it's a hidden ;; character in the buffer. (unless string (setq string " ")) @@ -471,12 +474,16 @@ height of the image; integer values are taken as pixel values." ;; cut-and-paste. (Yanking killed image text next to another copy ;; of it loses anyway.) (setq image (cons 'image (cdr image)))) + (when (eq map t) + (setq map image-manipulation-map)) (let ((start (point))) (insert string) (add-text-properties start (point) `(display ,(if slice (list (cons 'slice slice) image) - image) rear-nonsticky (display))))) + image) + rear-nonsticky (display) + keymap ,map)))) ;;;###autoload @@ -519,7 +526,6 @@ The image is automatically split into ROWS x COLS slices." (insert (propertize "\n" 'line-height t))))) - ;;;###autoload (defun remove-images (start end &optional buffer) "Remove images between START and END in BUFFER. @@ -558,6 +564,7 @@ BUFFER nil or omitted means use the current buffer." (setq path (cdr path))) (if found filename))) + ;;;###autoload (defun find-image (specs) "Find an image, choosing one of a list of image specifications. --=-=-= Content-Type: application/emacs-lisp Content-Disposition: attachment; filename=image-transform.el Content-Transfer-Encoding: quoted-printable ;;; image-transform.el --- Support for image transformations -*- lexical-b= inding: t -*- ;; ;; Copyright (C) 2014 Free Software Foundation, Inc. ;; ;; Author: Vitalie Spinu ;; Keywords: multimedia ;; Package: emacs ;; ;; This file is part of GNU Emacs. ;; ;; GNU Emacs is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs. If not, see . ;; ;;; Commentary: ;; ;; Documentation is in `image-transform` and `image-transform-backends` ;; ;;; TODO: ;; ;; Make `image-tranform:convert' operate on :data ;;=20 ;; Allow multi-image transformations by allowing IMAGE argument to ;; `image-transform' to be a list of images. ;; ;;; Code: (require 'image) (require 'pcase) (eval-when-compile (require 'cl-macs)) (defcustom image-transform-backends '(native convert) "List of backends which are tried in turn by `image-transform'. The `native' backend uses internal Emacs ImageMagick support; `convert' backed uses external ImageMagick 'convert' utility. If Emacs was not compiled with ImageMagick support `native' backend is ignored. Each backend 'BACKEND' consists of the following components: 1) Transformation function 'image-transform:BACKEND' that takes as input an image and transform specs. Currently implemented functions are `image-transform:native' and `image-transform:convert'. =20 2) Supported transforms for each backend are stored in 'image-transform-features:BACKEND' list of lists of of the form (FEATURE DOC TYPE), where: - FEATURE is a keyword naming a transformation. =20=20=20 - DOC is a string describing the feature. =20=20=20 - TYPE is a symbol such that 'image-transform-spec:TYPE' is a declared function that accepts KEY and VALUE arguments and returns a list of one or more canonical pairs (NEWKEY NEWVALUE) to be passed to the appropriate backend. NEWVALUE is a string that can be passed directly to ImageMagick 'convert' program. For a complete list, see http://www.imagemagick.org/script/command-line-options.php Most common examples of normalizers are `image-transform-spec:number' and `image-transform-spec:geometry'. See `image-transform-features:native' and `image-transform-features:convert' for available features." :group 'image :type '(repeat symbol)) (defcustom image-transform-convert-program (executable-find "convert") "Path to \"convert\" program." :group 'image :type 'string) (put 'next-backend 'error-conditions '(error next-backend)) ;;; Internal Utilities (defun image-tr--delete-properties (list props) "Remove PROPS from LIST destructively. LIST is like plist, but possibly with repeated keys. Return transformed LIST." (let ((p list)) (while p (if (member (cadr p) props) (setcdr p (nthcdr 3 p)) (setq p (cdr p)))) list)) (defun image-tr--delete-transforms (image transforms) "Remove TRANSFORMS from IMAGE destructively." (image-tr--delete-properties (plist-get (cdr image) :transforms) transfor= ms) image) ;; (defun image-tr--add (trlist key value) ;; (if (not (null trlist)) ;; (let ((lcdr (nthcdr (1- (length trlist)) trlist))) ;; (setcdr lcdr (list key value))) ;; (push value trlist) ;; (push key trlist)) ;; trlist) (defun image-tr--osize (image) (let ((osize (plist-get (cdr image) :osize))) (unless osize (setq osize (image-size image t)) (plist-put (cdr image) :osize osize)) osize)) (defun image-tr--rescale (image sw &optional sh) ;; used by native backend (setq sh (or sh sw)) (unless (and (=3D sw 100) (=3D sh 100)) (let ((sw (/ sw 100.0)) (sh (/ sh 100.0)) (uw (plist-get (cdr image) :width)) (uh (plist-get (cdr image) :height))) (let ((size (image-tr--osize image))) (if (or uw uh) (if (=3D sw sh) ;; only one could have been supplied, keep it (progn (when uw (plist-put (cdr image) :width (floor (* sw uw)))) (when uh (plist-put (cdr image) :height (floor (* sh uh))))) (plist-put (cdr image) :width (floor (* sw (or uw (* (/ (car size) (float (c= dr size))) uh))))) (plist-put (cdr image) :height (floor (* sh (or uh (* (/ (cdr size) (float (= car size))) uw)))))) (plist-put (cdr image) :width (floor (* sw (car size)))) (when (/=3D sw sh) (plist-put (cdr image) :height (floor (* sh (cdr size)))))))))) (defvar image-tr--right-angle-fudge 0.0001 "Snap distance to a multiple of a right angle. There's no deep theory behind the default value, it should just be somewhat larger than ImageMagick's MagickEpsilon.") ;; These two functions are slightly adapted from the old image-mode.el and = were ;; authored by by Wolfgang Jenkner (defsubst image-tr--get-rotated-width (width height rotation) "Return the bounding box width of a rotated WIDTH x HEIGHT rectangle. ROTATION is the rotation angle in degrees." (let ((angle (degrees-to-radians rotation))) ;; Assume, w.l.o.g., that the vertices of the rectangle have the ;; coordinates (+-w/2, +-h/2) and that (0, 0) is the center of the ;; rotation by the angle A. The projections onto the first axis ;; of the vertices of the rotated rectangle are +- (w/2) cos A +- ;; (h/2) sin A, and the difference between the largest and the ;; smallest of the four values is the expression below. (+ (* width (abs (cos angle))) (* height (abs (sin angle)))))) ;; The following comment and code snippet are from ;; ImageMagick-6.7.4-4/magick/distort.c ;; /* Set the output image geometry to calculated 'best fit'. ;; Yes this tends to 'over do' the file image size, ON PURPOSE! ;; Do not do this for DePolar which needs to be exact for virtual til= ing. ;; */ ;; if ( fix_bounds ) { ;; geometry.x =3D (ssize_t) floor(min.x-0.5); ;; geometry.y =3D (ssize_t) floor(min.y-0.5); ;; geometry.width=3D(size_t) ceil(max.x-geometry.x+0.5); ;; geometry.height=3D(size_t) ceil(max.y-geometry.y+0.5); ;; } ;; Other parts of the same file show that here the origin is in the ;; left lower corner of the image rectangle, the center of the ;; rotation is the center of the rectangle and min.x and max.x ;; (resp. min.y and max.y) are the smallest and the largest of the ;; projections of the vertices onto the first (resp. second) axis. (defun image-tr--get-rotated-size (width height length &optional rotation) "Return (w . h) so that a rotated w x h image has exactly width LENGTH. The ROTATION angle defaults 0. Write W for WIDTH and H for HEIGHT. Then the w x h rectangle is an \"approximately uniformly\" scaled W x H rectangle, which currently means that w is one of floor(s W) + {0, 1, -1} and h is floor(s H), where s is a scale factor. The value of ROTATION may be replaced by a slightly different angle. Currently this is done for values close to a multiple of 90, see `image-tr--right-angle-fudge'." (setq rotation (or rotation 0.0)) (cond ((< (abs (- (mod (+ rotation 90) 180) 90)) image-tr--right-angle-fudge) (cl-assert (not (zerop width)) t) (cons length nil)) ((< (abs (- (mod (+ rotation 45) 90) 45)) image-tr--right-angle-fudge) (cl-assert (not (zerop height)) t) (cons nil length)) (t (let (scale) (cl-assert (not (and (zerop width) (zerop height))) t) (setq scale (/ (float (1- length)) (image-tr--get-rotated-width width height rotation))) ;; Assume we have a w x h image and an angle A, and let l =3D ;; l(w, h)) =3D w |cos A| + h |sin A|, which is the actual width ;; of the bounding box of the rotated image, as calculated by ;; `image-tr--get-rotated-width'. The code snippet quoted above ;; means that ImageMagick puts the rotated image in ;; a bounding box of width L =3D 2 ceil((w+l+1)/2) - w. ;; Elementary considerations show that this is equivalent to ;; L - w being even and L-3 < l(w, h) <=3D L-1. In our case, L = is ;; the given `length' parameter and our job is to determine ;; reasonable values for w and h which satisfy these ;; conditions. (let ((w (floor (* scale width))) (h (floor (* scale height)))) ;; Let w and h as bound above. Then l(w, h) <=3D l(s W, s H) ;; =3D L-1 < l(w+1, h+1) =3D l(w, h) + l(1, 1) <=3D l(w, h) + = 2, ;; hence l(w, h) > (L-1) - 2 =3D L-3. (cons (cond ((=3D (mod w 2) (mod length 2)) w) ;; l(w+1, h) >=3D l(w, h) > L-3, but does l(w+1, h) <=3D ;; L-1 hold? ((<=3D (image-tr--get-rotated-width (1+ w) h rotation) (1- length)) (1+ w)) ;; No, it doesn't, but this implies that l(w-1, h) =3D ;; l(w+1, h) - l(2, 0) >=3D l(w+1, h) - 2 > (L-1) - ;; 2 =3D L-3. Clearly, l(w-1, h) <=3D l(w, h) <=3D L-1. (t (1- w))) h)))))) ;;; Parsers ;; Parser converts a 'convert' style string specification into a meaningful ;; elisp representation. (defun image-transform-parse:number (str) "Parse a numeric string STR. String can contain leading or trailing spaces. If STR is a number simply return it." (if (numberp str) str (when (string-match "^ *\\([+-]?[0-9.]+\\) *$" str) (string-to-number (match-string 1 str))))) (defun image-transform-parse:scale (str) "Parse a numeric string STR as scale. Like `image-transform-parse:number' but expects % at the end of the number." (if (numberp str) str (when (string-match "^ *\\([0-9.]+\\)% *$" str) (string-to-number (match-string 1 str))))) (defun image-transform-parse:geometry (geom) "Parse ImageMagick geometry specification. X can be either \"x\",\"X\" or \" \" (space). scale% Height and width both scaled by specified percentage. xscaleXyscale% Height and width individually scaled by specified percentag= es. width Width given, height automagically selected to preserve aspect rati= o. Xheight Height given, width automagically selected to preserve aspect rati= o. widthXheight Maximum values of height and width given, aspect ratio preser= ved. widthXheight^ Minimum values of width and height given, aspect ratio prese= rved. widthXheight! Width and height emphatically given, original aspect ratio i= gnored. widthXheight> Shrinks an image with dimension(s) larger than the width and= height arguments. widthXheight< Enlarges an image with dimension(s) smaller than the width a= nd height arguments. area@ Resize image to have specified area in pixels. Aspect ratio is pre= served. Return a list of the form (W H o) where o is an operator giving an additional meaning to W and H. Can be ^ ! > < or @. Offset geometry from \"convert\" specifications is not yet supported. See http://www.imagemagick.org/script/command-line-processing.ph= p#geometry" (when (and (stringp geom) (string-match "^ *\\([0-9.]+\\)?[xX ]?\\([0-9.]+\\)?\\([@><^!%]\\)? *$" geom)) (let ((W (match-string 1 geom)) (H (match-string 2 geom)) (o (match-string 3 geom))) (list (and W (string-to-number W)) (and H (string-to-number H)) o)))) ;;; Normalizers ;; convert backend can accept a multitude of string inputs.=20 (defvar image-transform-accept-unparsed nil "Non-nil when numeric writers should accepts non passable strings as a va= lid input.") (defun image-transform-spec:number (key value) "Basic processor of numeric transform specifications. KEY names the transformation. VALUE must be a number or a string that could be converted into a number. If the conversion has failed and `image-transform-accept-unparsed' is nil, signal 'next-backend." (setq value (pcase value ((or (pred null) (pred numberp)) value) ((pred stringp) (or (image-transform-parse:number value) (if image-transform-accept-unparsed value (signal 'next-backend (list (format "Cannot parse %s value" key)))))) (_ (signal 'next-backend (list (format "Invalid type of argument %s" key)))))) (list key (if (numberp value) (number-to-string value) value))) (defalias 'image-transform-spec:degrees 'image-transform-spec:number) (defalias 'image-transform-spec:value 'image-transform-spec:number) (defun image-transform-spec:scale (tr value) "Process scale argument of transformation TR. VALUE must be a number or string of the form \"N%\" where N is a number, giving the percentage by which to scale the image. For \"convert\" backend scale can take additional geometry specifications." (setq value (pcase value ((or (pred null) (pred numberp)) value) ((pred stringp) (or (image-transform-parse:scale value) (if image-transform-accept-unparsed value (signal 'next-backend (list (format "Cannot parse %s value" tr)))))) (_ (signal 'next-backend (list (format "Invalid type of argument %s" tr)))))) (list tr (if (numberp value) (concat (number-to-string value) "%") value))) (defun image-transform-spec:boolean (key value) "Simply return (KEY VALUE) list." (list key value)) (defun image-transform-spec:geometry (tr value) "Normalize geometry VALUE for transformation TR. VALUE can be - numeric - interpreted as width. - string - interpreted as \"convert\" program specification. It is parsed by `image-transform-parse:geometry' for 'native' backend and is passed as is to 'convert' backend. - cons (W . H) or list (W H) - rescale the image maximally such that new image fits into (W . H) box. Aspect ratio preserved. Equivalent to WxH \"convert\" specification. - list (W H o) - Similar to \"WxHo\" convert geometry specification where 'o' can be \"!\",\"%\",\"^\",\"@\",\">\" or \"<\". For example, to force the new dimensions of the image you should supply (list W H \"!\")." ;; If `image-transform-accept-unparsed' is non-nil, accepts strings that ;; don't match the above pattern. Otherwise pass to next backend by ;; signaling 'next-backend. (setq value (pcase value ((pred null) value) ((pred numberp) (number-to-string value)) (`(,w ,h ,o . nil) (concat (and w (number-to-string w)) "x" (and h (number-to-string h)) o)) ;; (`(,w . nil) (number-to-string w)) ((or `(,w ,h . nil) `(,w . ,h)) (concat (and w (number-to-string w)) "x" (and h (number-to-string h)))) ((pred stringp) (if (or (image-transform-parse:geometry value) image-transform-accept-unparsed) value (signal 'next-backend (list (format "Cannot parse %s geometry argument" tr))= ))) (_ (signal 'next-backend (list (format "Invalid %s geometry specification" tr))= )))) (list tr value)) (defun image-transform-spec:choice (TR value &rest choices) "For transformation TR, check if VALUE is in CHOICES list. Return '(TR value) if true, and signal 'next-backend error otherwise." (if (member value choices) (list TR value) (signal 'next-backend (list (format "%s is not a valid value of option %s" value TR))= ))) ;;; Transform API utilities (defun image-tr--unsupported-features (specs backend) "Return unsupported features from SPECS by BACKEND. SPECS are as in `image-transform'. BACKEND is a symbol or a string." (let ((features (cl-loop for s in specs if (keywordp s) collect s)) (available (symbol-value (intern (concat "image-transform-features:" (if (symbolp backend) (symbol-name backend) backend)))))) (cl-loop for f in features unless (assoc f available) collect f))) (defun image-tr--check-unsupported-features (image newspecs backend) "Signal 'next-backend if any of IMAGE's specs or NEWSPECS are unsupported= by BACKEND. NEWSPECS are as SPECS in `image-transform'." (let* ((trlist (image-get-transforms image)) (un-specs (image-tr--unsupported-features newspecs backend)) (un-tr (image-tr--unsupported-features (cdr trlist) backend))) (when un-specs (signal 'next-backend (list (format "Unsupported features: %s" un-specs)))) (when un-tr (signal 'next-backend (list (format "Unsupported existing transforms: %s" un-tr))))= )) (defun image-tr--normalize-boolean-specs (specs backend) "Insert missing boolean values into SPECS given BACKEND's features. SPECS are as in `image-transform'." (let ((p specs) (features (symbol-value (intern (format "image-transform-features:%= s" backend))))) (while p (when (and (keywordp (car p)) (or (keywordp (cadr p)) (eq 1 (length p)))) (if (eq 'boolean (nth 2 (assoc (car p) features))) (setcdr p (push t (cdr p))) (signal 'next-backend (list "Missing value for non-boolean %s" (c= ar p))))) (setq p (cdr p))) specs)) (defun image-tr--normalize-specs (specs backend) "Normalize SPECS given the spec types declared in the BACKEND." (cl-loop for s on specs by 'cddr append (let* ((el (assoc (car s) (symbol-value (intern (concat "image-transform-features:" (symbol-name backend)))))) (read-type (nth 2 el)) (reader (intern (concat "image-transform-spec:" (if (listp read-type) (symbol-name (car read-type)) (symbol-name read-type)))))) (unless el (error "No reader for %s in %s backend" (car s) backend)) (if (fboundp reader) (if (listp read-type) (apply reader (car s) (cadr s) (cdr read-type)) (funcall reader (car s) (cadr s))) (list (car s) (cadr s)))))) (defun image-tr--add-transforms (trs newtrs) "Destructively populate TRS with NEWTRS transforms. Return new TRS. Both TRS and NEWTRS are list of pairs :TR VALUE, with possibly repeated keys. If VALUE is nil, all :TR key-values are removed from TRS." (cl-loop for s on newtrs by 'cddr do (let ((kwd (car s)) (val (cadr s))) (if (null val) ;; API: remove null properties=20 (image-tr--delete-properties trs (list kwd)) (setq trs (append trs (list kwd val)))))) trs) (defun image-tr--adjust-specs-for-fit (image newspecs) "Adjust IMAGE's specs by processing :resize spec from NEWSPECS. Return a transformed NEWSPECS list." (let ((resize (cadr (memq :resize newspecs))) ) (when (and resize (symbolp resize)) (let* ((rotate (cadr (memq :rotate newspecs))) (orot (plist-get (cdr image) :rotation)) (win (or (cadr (memq :window newspecs)) (selected-window))) ;; Note: `image-size' looks up and thus caches the ;; untransformed image. There's no easy way to prevent ;; that. VS[17-07-2013]: This seems not to be true ;; anymore, `image-size' does return the size of ;; transformed image. (size (image-tr--osize image)) ;; user-size (usize (cons (plist-get (cdr image) :width) (plist-get (cdr image) :height))) (newrot (float (mod (+ (or rotate 0.0) (or orot 0.0)) 360))) (newsize (cons (image-tr--get-rotated-width (car size) (cdr size) newrot) (image-tr--get-rotated-width (cdr size) (car size) newrot)))) (unless (member resize '(nil fit fit-if-large fit-width fit-height fit-stretch)) (error "Invalid :resize argument")) =20=20=20=20=20=20=20=20 (plist-put newspecs :resize (let* ((wedges (window-inside-pixel-edges win)) (wsize (cons (- (nth 2 wedges) (nth 0 wedges)) (- (nth 3 wedges) (nth 1 wedges)))) (resize (if (and (eq resize 'fit-if-large) (or (> (car newsize) (car wsize)) (> (cdr newsize) (cdr wsize)= ))) 'fit resize)) (resize (if (eq resize 'fit) (if (< (/ (float (car wsize)) (cdr ws= ize)) (/ (float (car newsize)) (cdr = newsize))) 'fit-width 'fit-height) resize))) (cond ((eq resize 'fit-stretch) (let ((res (image-tr--get-rotated-size (car wsize) (cdr wsize) (car wsize) newr= ot))) ;; fixme: stretching doesn't work correctly with r= otation (when (null (car res)) (setcar res (car wsize))) (when (null (cdr res)) (setcdr res (cdr wsize))) (list (car res) (cdr res) "!"))) ((eq resize 'fit-width) (let ((res (image-tr--get-rotated-size (car size) (cdr size) (car wsize) newrot= ))) ;; don't provide both W and H unnecessarily (list (car res) (unless (car res) (cdr res))))) ((eq resize 'fit-height) (let ((res (image-tr--get-rotated-size (cdr size) (car size) (cdr wsize) newrot= ))) (list (unless (car res) (cdr res)) (car res)))))))= ))) newspecs) ;;; Transform API ;;;###autoload (defun image-transform (image &rest specs) "Transform IMAGE by applying transformation SPECS. Transformation backends listed in `image-transform-backends' are tried in turn and the first suitable backend is applied. If none of the backends can be applied an error is thrown. SPECS is a list of key-value pairs giving the name and parameters of the transformation. See `image-transform-features:native' and `image-transform-features:convert' for lists of supported features. Boolean specs can miss the value, in which case t is assumed. Specs's values are either strings encoded with image 'convert' conventions or elisp objects that are normalized to canonical string form with `image-transform-spec:TYPE' functions, where TYPE is the type of the spec. Examples of normalizers are `image-transform-spec:geometry', `image-transform-spec:number', `image-transform-spec:scale' and `image-transform-spec:choice'. All the transformations applied so far are stored as part of the Emacs image data structure. Each time a new transformation is applied, the whole transformation chain is re-applied to the original image. This ensures that internal optimization of the 'convert' backend can be used and the image doesn't unnecessarily loose quality on repeated transformation. This function acts destructively. Use `copy-list' to avoid modifying existing images. Several specs are treated specially or are pre-processed before being dispatched to the backend functions: :backend - enforce a specific backend. :resize can be: - a number, giving new width of the image - a cons, giving the size (w x h) in pixels. - a symbol: *`fit' - maximally scale IMAGE to fit into WIN. *`fit-height' - fit the image to WIN's height. *`fit-width' - fit the image to WIN's width. *`fit-stretch' - stretch the image to fit to both height and width of WIN. :save-to-file - save the transformed image into file and replace the current image specification with the new file (not implemented yet) =20 :window - a window to be used when :resize is a symbol. Defaults to the selected window. Examples: (image-transform img :resize 'fit-width) (image-transform img :resize 'fit-height) (image-transform img :resize 'fit) (image-transform img :resize 'fit :backend 'convert) (image-transform img :resize 'fit :rotate 45) (image-transform img :resize 'fit-height :rotate 60) (image-transform img :resize 200) (image-transform img :resize '(500 . 500)) (image-transform img :resize '(500 500 \"!\")) (image-transform img :background \"pink\") (image-transform img :background \"pink\" :flatten :backend 'convert)" ;;cannot use plist-get to extract :backend, because of boolean specs (let* ((force-backend (cl-loop for val on specs=20 if (eq (car val) :backend) return (cadr val))) (backends (if (null force-backend) (copy-sequence image-transform-backends) (setq specs (image-tr--delete-properties specs '(:back= end))) (list force-backend))) (bknd-errors "") out bknd bknd-specs) (image-tr--osize image) ;; side effect of caching :osize ;; adjust for 'fit 'fit-width etc (setq specs (image-tr--adjust-specs-for-fit image specs)) =20=20=20=20 (while (and (null out) (setq bknd (pop backends))) =20=20=20=20=20=20 (let ((bknd-fun (intern (concat "image-transform:" (symbol-name bknd))))) (condition-case data (progn=20 (setq bknd-specs (image-tr--normalize-boolean-specs (copy-list specs= ) bknd)) (image-tr--check-unsupported-features image bknd-specs bknd) (setq out (apply bknd-fun image bknd-specs))) (next-backend (setq bknd-errors (format "%s\n%s: %s" bknd-errors bknd (cadr data))))))) (unless out (error "All backends failed with the following errors: %s" bknd-error= s)) out)) (defun image-transform-interactive (&optional image &rest specs) "Like `image-transform' but also refresh window display. Intended to be used for user level commands. IMAGE defaults to `image-at-point'. SPECS is as in `image-transform'." (let ((image (or image (image-at-point)))) (unless image (error "No image at point")) (prog1 (apply 'image-transform image specs) (force-window-update (selected-window))))) ;;;; Native Backend (defvar image-transform-features:native '((:background "Background for images with transparent background") (:resize "Resize the image" geometry) (:rotate "Rotation in degrees" degrees) (:scale "Scale in percent. Can be a number or numeric string." scale) (:flatten "Does nothing. It's here for compatibility with 'convert' bac= kend only." boolean)) "Alist of supported features by 'native' backend. Each element is a list of the form (FEATURE DOC READER-TYPE). See `image-transform-backends' for a full description.") (defun image-transform:native (image &rest specs) "Emacs's native ImageMagick transform backend. IMAGE and SPECS are as in `image-transform'. See `image-transform-features:native' for transform specifications accepted by this backend." (unless (image-type-available-p 'imagemagick) (signal 'next-backend '("Emacs wasn't built with ImageMagick support"))) =20=20 (let* ((newtrs (image-tr--normalize-specs specs 'native)) (trlist (image-tr--add-transforms (image-get-transforms image) newtrs))) (plist-put (cdr image) :transforms trlist) =20=20=20=20 ;; reset imagemagick properties=20 (image-tr--delete-properties image '(:width :height :rotation :backgrou= nd)) ;; reset convert specs if any (when (plist-get (cdr image) :ofile) (image-tr--delete-properties (cdr image) '(:data)) (plist-put (cdr image) :file (plist-get (cdr image) :ofile))) =20=20=20=20 ;; now apply the transforms (cl-loop for s on (cdr trlist) by 'cddr do ;; fixme: image might have been transformed by convert before? (when (assoc (car s) image-transform-features:native) (pcase (cons (car s) (cadr s)) (`(:resize . ,resize) (pcase (image-transform-parse:geometry resize) (`(,scale nil "%") (image-tr--rescale image scale)) (`(,sW ,sH "%") (image-tr--rescale image sW sH)) (`(,area "@") (error "Area geometry is not implemented = yet")) (`(,W nil nil) (plist-put (cdr image) :width W) (image-tr--delete-properties image '(:height))) (`(nil ,H nil) (plist-put (cdr image) :height H) (image-tr--delete-properties image '(:width))) ;; fixme: collapse following cases into one?=20=20 (`(,W ,H nil) ;; Maximum values of height and width given, aspect ra= tio preserved. (let ((osize (image-tr--osize image))) (if (> (/ (float (car osize)) (cdr osize)) (/ (float W) H)) (progn (plist-put (cdr image) :width W) (image-tr--delete-properties image '(:hei= ght))) (plist-put (cdr image) :height H) (image-tr--delete-properties image '(:width))))) (`(,W ,H "^") ;; Minimum values of width and height given, ;; aspect ratio preserved. fixme: is this ;; correct computation? (let ((osize (image-tr--osize image))) (if (< (/ (float (car osize)) (cdr osize)) (/ (float W) H)) (progn (plist-put (cdr image) :width W) (image-tr--delete-properties image '(:hei= ght))) (plist-put (cdr image) :height H) (image-tr--delete-properties image '(:width))))) (`(,W ,H ">") (error "> operator is not implemented yet= ")) (`(,W ,H "<") (error "< operator is not implemented yet= ")) (`(,W ,H "!") (if W (plist-put (cdr image) :width W) (image-tr--delete-properties image '(:width))) (if H (plist-put (cdr image) :height H) (image-tr--delete-properties image '(:height)))) (`(,W ,H ,x) ;; This should not happen, validity checks are ;; in the geometry reader. (error "Invalid geometry operator %s", x)))) (`(:rotate . ,rot) (plist-put (cdr image) :rotation (mod (+ (or (plist-get (cdr image) :rotation) = 0.0) (image-transform-parse:number rot)) 360))) (`(:scale . ,scale) (image-tr--rescale image (image-transform-parse:scale sca= le))) (`(:background . ,val) (plist-put (cdr image) :background val)) (`(:flatten . ,val)) ;; should never reach this place (_ (error "Incorrect specification in 'native' backend")))= )) (plist-put (cdr image) :transform-backend 'native) (plist-put (cdr image) :type 'imagemagick) image)) ;;;; Convert Backend (defvar image-transform-features:convert=20 '((:-- "Image Settings") ;; (:adjoin boolean "join images into a single multi-image file") ;; (:affine 'matrix "affine transform matrix") (:antialias "remove pixel-aliasing" boolean ) (:authenticate "decrypt image with this password" value ) (:background "background color" color ) (:bias "add bias when convolving an image" value ) (:black-point-compensation "use black point compensation" boolean ) (:blue-primary "chromaticity blue primary point" point ) (:bordercolor "border color" color ) (:caption "assign a caption to an image" string ) (:cdl "color correct with a color decision list" filename ) (:channel "apply option to select image channels" type ) (:colors "preferred number of colors in the image" value ) (:colorspace "alternate image colorspace" (choice CMY CMYK Gray HCL HCLp HSB HSI HSL HSV HWB Lab LCHab LCHuv LMS Log Luv OHTA Rec601YCbCr Rec709YCbCr RGB scRGB sRGB Transparent XYZ YCbCr YCC YDbDr YIQ YPbPr YUV)) (:comment "annotate image with comment" string ) (:compose "set image composite operator" operator ) (:compress "type of pixel compression when writing the image" (choice None BZip Fax Group4 JPEG JPEG2000 Lossless LZW RLE = or Zip)) (:decipher "convert cipher pixels to plain pixels" filename ) (:define "define one or more image format options" format-option ) (:delay "display the next image after pausing" value ) (:density "horizontal and vertical density of the image" geometry ) (:depth "image depth" value ) (:direction "render text right-to-left or left-to-right" type ) (:display "get image or font from this X server" server ) (:dispose "layer disposal method" method ) (:dither "apply error diffusion to image" method ) (:encipher "convert plain pixels to cipher pixels" filename ) (:encoding "text encoding type" (choice None BZip Fax Group4 JPEG JPEG2000 Lossless LZW RLE = or Zip)) (:endian "endianness (MSB or LSB) of the image" (choice MSB LSB)) (:family "render text with this font family" name ) (:features "analyze image features (e.g. contrast, correlation" distanc= e ) (:fill "color to use when filling a graphic primitive" color ) (:filter "use this filter when resizing an image" (choice Point Hermite Cubic Box Gaussian Catrom Triangle Quadratic Mitchell)) (:flatten "flatten a sequence of images" boolean ) (:font "render text with this font" name ) (:format "output formatted image characteristics" string ) (:fuzz "colors within this distance are considered equal" distance ) (:gravity "horizontal and vertical text placement" (choice Point Hermite Cubic Box Gaussian Catrom Triangle Quadratic Mitchell)) (:green-primary "chromaticity green primary point" point ) (:intent "type of rendering intent when managing the image color" (choice Absolute Perceptual Relative Saturation)) (:interlace "type of image interlacing scheme" (choice none line plane partition JPEG GIF PNG)) (:interpolate "pixel color interpolation method" (choice integer nearest-neighbor average bilinear mesh bicubic spline filter )) (:kerning "set the space between two letters" value ) (:label "assign a label to an image" string ) (:limit "pixel cache resource limit" type-value ) (:loop "add Netscape loop extension to your GIF animation" iterations ) (:mask "associate a mask with the image" filename ) (:matte "store matte channel if the image has one" boolean ) (:mattecolor "frame color" color ) (:monitor "monitor progress" boolean ) (:orient "image orientation" (choice bottom-left bottom-right left-bottom left-top right-bottom right-top top-left top-right undefined)) (:origin "image origin" geometry ) (:page "size and location of an image canvas (setting)" geometry ) (:ping "efficiently determine image attributes" boolean ) (:pointsize "font point size" value ) (:preview "image preview type" (choice Rotate Shear Roll Hue Saturation Brightness Gamma Spiff Dull Grayscale Quantize Despeckle ReduceNoise Add Noise Sharpen Blur Threshold EdgeDetect Spread Shade Raise Segment Solarize Swirl Implode Wave OilPaint CharcoalDrawing JPEG)) (:quality "JPEG/MIFF/PNG compression level" value ) (:quiet "suppress all warning messages" boolean ) (:red-primary "chromaticity red primary point" point ) (:regard-warnings "pay attention to warning messages" boolean ) (:sampling-factor "horizontal and vertical sampling factor" geometry ) (:scene "image scene number" value ) (:seed "seed a new sequence of pseudo-random numbers" value ) (:size "width and height of image" geometry ) (:statistic "replace each pixel with corresponding statistic from the n= eighborhood" (choice Gradient Maximum Minimum Mean Median Mode Nonpeak )) (:stretch "render text with this font stretch" (choice Any Condensed Expanded ExtraCondensed ExtraExpanded Normal SemiCondensed SemiExpanded UltraCondensed UltraExpanded)) (:stroke "graphic primitive stroke color" color ) (:strokewidth "graphic primitive stroke width" value ) (:style "render text with this font style" (choice Any Italic Normal Oblique)) (:support "resize support: > 1.0 is blurry, < 1.0 is sharp" factor ) (:synchronize "synchronize image to storage device" boolean ) (:taint "declare the image as modified" boolean ) (:texture "name of texture to tile onto the image background" filename ) (:tile-offset "tile offset" geometry ) (:treedepth "color tree depth" value ) (:transparent-color "transparent color" color ) (:undercolor "annotation bounding box color" color ) (:units "the units of image resolution" (choice Undefined PixelsPerInch PixelsPerCentimeter) ) (:verbose "print detailed information about the image" boolean ) (:view "FlashPix viewing transforms" boolean ) (:virtual-pixel "virtual pixel access method" method ) (:weight "render text with this font weight" (choice Undefined PixelsPerInch PixelsPerCentimeter)) (:white-point "chromaticity white point" point ) (:-- "Image Operators") (:adaptive-blur "adaptively blur pixels, decrease effect near edges" ge= ometry ) (:adaptive-resize "adaptively resize image with data dependent triangul= ation" geometry ) (:adaptive-sharpen "adaptively sharpen pixels, increase effect near edg= es" geometry ) (:annotate "annotate the image with text" geometry-text ) ;;?? (:auto-orient "automatically orient image" boolean ) (:black-threshold "force all pixels below the threshold into black" val= ue ) (:blur "reduce image noise and reduce detail levels" geometry ) (:border "surround image with a border of color" geometry ) (:charcoal "simulate a charcoal drawing" radius ) (:chop "remove pixels from the image interior" geometry ) (:clip "clip along the first path from the 8BIM profile" boolean ) (:clip-mask "associate a clip mask with the image" filename ) (:clip-path "clip along a named path from the 8BIM profile" id ) (:colorize "colorize the image with the fill color" value ) (:color-matrix "apply color correction to the image" matrix ) (:contrast "enhance the image contrast" boolean) (:+contrast "reduce the image contrast" boolean) (:contrast-stretch "improve contrast by `stretching the intensity range= " geometry ) (:convolve "apply a convolution kernel to the image" coefficients ) (:cycle "cycle the image colormap" amount ) (:despeckle "reduce the speckles within an image" boolean ) (:draw "annotate the image with a graphic primitive" string ) (:edge "apply a filter to detect edges in the image" radius ) (:emboss "emboss an image" radius ) (:enhance "apply a digital filter to enhance a noisy image" boolean ) (:equalize "perform histogram equalization to an image" boolean ) (:evaluate "evaluate an arithmetic, relational, or logical expression" = value-operator ) ;;?? (:extent "set the image size" geometry ) (:extract "extract area from image" geometry ) (:fft "implements the discrete Fourier transform (DFT)" boolean ) (:flip "flip image vertically" boolean ) (:floodfill "floodfill the image with color" geometry-color ) ;?? (:flop "flop image horizontally" boolean ) (:frame "surround image with an ornamental border" geometry ) (:function "apply a function to the image" name ) (:gamma "level of gamma correction" value ) (:gaussian-blur "reduce image noise and reduce detail levels" geometry ) (:geometry "preferred size or location of the image" geometry ) (:identify "identify the format and characteristics of the image" boole= an ) (:ift "implements the inverse discrete Fourier transform (DFT)" boolean= ) (:implode "implode image pixels about the center" amount ) (:lat "local adaptive thresholding" geometry ) (:layers "optimize or compare image layers" method ) (:level "adjust the level of image contrast" value ) (:linear-stretch "improve contrast by `stretching with saturation the i= ntensity range" geometry ) (:median "apply a median filter to the image" geometry ) (:mode "make each pixel the predominant color of the neighborhood" geom= etry ) (:modulate "vary the brightness, saturation, and hue" value ) (:monochrome "transform image to black and white" boolean ) (:morphology "apply a morphology method to the image" method-kernel ) ;= ;?? (:motion-blur "simulate motion blur" geometry ) (:negate "replace each pixel with its complementary color" boolean ) (:noise "add or reduce noise in an image" geometry ) (:normalize "transform image to span the full range of colors" boolean ) (:opaque "change this color to the fill color" color ) (:ordered-dither "add a noise pattern to the image with specific amplit= udes" NxN ) (:paint "simulate an oil painting" radius ) (:polaroid "simulate a Polaroid picture" angle ) (:posterize "reduce the image to a limited number of color levels" leve= ls ) (:print "interpret string and print to console" string ) (:profile "add, delete, or apply an image profile" filename ) (:quantize "reduce colors in this colorspace" colorspace ) (:radial-blur "radial blur the image" angle ) (:raise "lighten/darken image edges to create a 3-D effect" value ) (:random-threshold "random threshold the image" low,high ) (:region "apply options to a portion of the image" geometry ) (:render "render vector graphics" boolean ) (:repage "size and location of an image canvas" geometry ) (:resample "change the resolution of an image" geometry ) (:resize "resize the image" geometry ) (:roll "roll an image vertically or horizontally" geometry ) (:rotate "apply Paeth rotation to the image" degrees ) (:sample "scale image with pixel sampling" geometry ) (:scale "scale the image" scale) (:segment "segment an image" values ) (:selective-blur "selectively blur pixels within a contrast threshold" = geometry ) (:sepia-tone "simulate a sepia-toned photo" threshold ) (:set "set an image property" property-value ) ;?? (:shade "shade the image using a distant light source" degrees ) (:shadow "simulate an image shadow" geometry ) (:sharpen "sharpen the image" geometry ) (:shave "shave pixels from the image edges" geometry ) (:shear "slide one edge of the image along the X or Y axis" geometry ) (:sigmoidal-contrast "lightness rescaling using sigmoidal contrast enha= ncement" geometry ) (:sketch "simulate a pencil sketch" geometry ) (:solarize "negate all pixels above the threshold level" threshold ) (:splice "splice the background color into the image" geometry ) (:spread "displace image pixels by a random amount" amount ) (:strip "strip image of all profiles and comments" boolean ) (:swirl "swirl image pixels about the center" degrees ) (:threshold "threshold the image" value ) (:thumbnail "create a thumbnail of the image" geometry ) (:tile "tile image when filling a graphic primitive" filename ) (:tint "tint the image with the fill color" value ) (:transform "affine transform image" boolean ) (:transparent "make this color transparent within the image" color ) (:transpose "flip image vertically and rotate 90 degrees" boolean ) (:transverse "flop image horizontally and rotate 270 degrees" boolean ) (:trim "trim image edges" boolean ) ;; (:type "image type" type ) ; tothink: put this back? (:unique-colors "discard all but one of any pixel color" boolean ) (:unsharp "sharpen the image" geometry ) (:vignette "soften the edges of the image in vignette style" geometry ) (:wave "alter an image along a sine wave" geometry ) (:white-threshold "force all pixels above the threshold into white" val= ue ) (:-- "Image Sequence Operators") (:affinity "transform image colors to match this set of colors" filenam= e ) (:append "append an image sequence top to bottom (use +append for left = to right)" boolean ) (:clut "apply a color lookup table to the image" boolean ) (:coalesce "merge a sequence of images" boolean ) (:combine "combine a sequence of images" boolean ) (:composite "composite image" boolean ) (:crop "cut out a rectangular region of the image" geometry ) (:deconstruct "break down an image sequence into constituent parts" boo= lean ) (:evaluate-sequence "evaluate an arithmetic, relational, or logical exp= ression" operator ) (:flatten "flatten a sequence of images" boolean ) (:fx "apply mathematical expression to an image channel(s)" expression ) (:hald-clut "apply a Hald color lookup table to the image" boolean ) (:morph "morph an image sequence" value ) (:mosaic "create a mosaic from an image sequence" boolean ) (:process "process the image with a custom image filter" arguments ) (:separate "separate an image channel into a grayscale image" boolean ) (:smush "smush an image sequence together" geometry ) (:write "write images to this file" filename ) (:-- "Image Stack Operators") (:clone "clone an image" indexes ) (:delete "delete the image from the image sequence" indexes ) (:duplicate "duplicate an image one or more times" count,indexes ) (:insert "insert last image into the image sequence" index ) (:swap "swap two images in the image sequence" indexes ) ;; (:-- "Miscellaneous Options") ;; (:debug "display copious debugging information" events ) ;; (:help "print program options" boolean ) ;; (:log "format of debugging information" format ) ;; (:list "print a list of supported option arguments" type ) ;; (:version "print version information" boolean ) ) "Alist of supported features by \"convert\" backend. Each element is a list of the form (FEATURE DOC READ-TYPE) See `image-transform-backends' for a full description. http://www.imagemagick.org/script/command-line-processing.php") (defun image-tr--convert-args (&optional image concat) "Get from IMAGE a list of transform arguments suitable for `call-process'. If CONCAT is non-nil, also concatenate arguments and return a string instead of a list." (setq image (or image (image-at-point))) (let* ((transforms (cdr (plist-get (cdr image) :transforms))) args) (setq args (append (cl-loop for s on transforms by 'cddr append (let ((type (nth 2 (assoc (car s) image-transform-featu= res:convert))) (opt (symbol-name (car s)))) (list (concat (if (string-match-p "^:\\+" opt) "" "-") (substring opt 1)) (unless (eq 'boolean type) ;; could be symbol, number etc (format "%s" (cadr s)))))) '("-"))) =20=20=20=20 (setq args (delq nil args)) (if concat (mapconcat 'identity args " ") args))) (defun image-tr--process-convert-transforms (image) "Call \"convert\" on IMAGE and insert transformed data as :data image spe= c. IMAGE is modified destructively. Currently, only images loaded from a file are handled by this backend." ;; fixme: shell quoting is likely necessary for some convert specs (let* ((specs (cdr image)) (buf (get-buffer-create "*image-tr-output*")) (file (plist-get specs :file)) (ofile (or (plist-get specs :ofile) file (signal 'next-backend "Image is not associated with a file"))) (type (plist-get specs :type)) (log-file (expand-file-name ".image-transform.log")) ; debug only (args (image-tr--convert-args image))) (when (or (eq type 'imagemagick) (null type)) (setq type (if file (image-type ofile) (image-type (plist-get (cdr image) :data) nil t)))) =20=20=20=20 (plist-put specs :ofile ofile) =20=20=20=20 (plist-put specs :data (with-current-buffer buf (erase-buffer) (set-buffer-multibyte nil) (when (/=3D 0 (apply 'process-file image-transform-convert= -program nil (list t log-file) nil (expand-file-= name ofile) args)) (erase-buffer) (insert (format "COMMAND: %s %s %s\n\n" image-transform-convert-program (expand-file-name ofile) (combine-and-quote-strings args))) (insert-file-contents log-file) (signal 'next-backend (list (format "convert error: %s" = (buffer-string))))) (buffer-string))) (message "command: %s %s %s\n\n" image-transform-convert-program (expand-file-name ofile) (combine-and-quote-strings args)) =20=20=20=20 ;; (delete-file log-file) (image-tr--delete-properties image '(:file)) (plist-put specs :type type) =20=20=20=20 image)) (defun image-transform:convert (image &rest specs) "ImageMagick Convert backend. Convert IMAGE through a call to \"convert\" program and pass transforms in SPECS. SPECS are as in `image-transform'. See `image-transform-features:convert' for transforms accepted by this backend." (let* ((image-transform-accept-unparsed t) ; pass directly to convert (newtrs (image-tr--normalize-specs specs 'convert)) (trlist (image-tr--add-transforms (image-get-transforms image) newtrs))) (plist-put (cdr image) :transforms trlist) (plist-put (cdr image) :transform-backend 'convert) (image-tr--process-convert-transforms image))) (defvar image-tr--describe-hist nil) (defun image-transform-describe-convert-option (&optional option) "Display an online documentation of \"convert\" OPTION." (interactive) (let* ((opts (delete "--" (mapcar (lambda (x) (substring (symbol-name (car x)) 1)) image-transform-features:convert))) (O (completing-read "Convert option: " (append '("*ALL*") opts) nil t nil 'image-tr--describe-hist))) (browse-url (if (equal O "*ALL*") "http://www.imagemagick.org/script/convert.php" (format "http://www.imagemagick.org/script/command-line-o= ptions.php#%s" O))))) ;;; Transform UI (defvar image-tr--add-transform-hist nil) ;;;###autoload (defun image-add-transform (&optional image) "Interactively add transform to IMAGE. IMAGE defaults to `image-at-point'. Don't use this function in programs, use `image-transform' instead." (interactive) (let* ((allopts (delete ":--" (mapcan (lambda (b) (let ((b (intern (format "image-transfo= rm-features:%s" b)))) (mapcar (lambda (x) (let ((x (symbol-name (car = x)))) (propertize x 'backend b)= )) (symbol-value b)))) image-transform-backends))) (tr (completing-read "Transform: " allopts nil t nil 'image-tr--ad= d-transform-hist)) (tr-symb (intern tr)) (type (nth 2 (assoc tr-symb (symbol-value (get-text-property 1 'backend tr= ))))) (prompt (format "%s: " tr)) (value (pcase type (`boolean t) (`(choice . ,opts) (completing-read prompt opts)) (`number (read-number prompt)) (`filename (read-file-name prompt)) (_ (read-string prompt))))) (image-transform-interactive image tr-symb value))) ;;;###autoload (defun image-list-transforms (&optional image) "Print all transforms associated with IMAGE. IMAGE defaults to `image-at-point'." (interactive) (message "%s" (cdr (image-get-transforms image)))) ;;;###autoload (defun image-delete-transform (&optional image transform) "Remove from IMAGE the TRANSFORM. IMAGE defaults to `image-at-point'. Don't use this function in programs, use `image-tr--delete-transforms' instead." (interactive) (setq image (or image (image-at-point))) (let* ((trs (cl-loop for el in (image-get-transforms image) if (keywordp el) collect (symbol-name el))) (tr (if trs (completing-read "Delete transform: " (append '("*ALL*") t= rs) nil t) (message "No transforms for current image") nil))) (when tr (if (equal tr "*ALL*") (plist-put (cdr image) :transforms '(tr)) (image-tr--delete-transforms image (list (intern tr))))) (image-transform image))) (provide 'image-transform) (provide 'image-transform) ;;; image-transform.el ends here --=-=-=--