image-dired.el 104 KB
Newer Older
1
;;; image-dired.el --- use dired to browse and manipulate your images -*- lexical-binding: t -*-
2
;;
Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2005-2020 Free Software Foundation, Inc.
4 5 6 7 8 9 10
;;
;; Version: 0.4.11
;; Keywords: multimedia
;; Author: Mathias Dahl <mathias.rem0veth1s.dahl@gmail.com>

;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
15 16 17 18 19 20 21

;; 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
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

;;; Commentary:
;;
;; BACKGROUND
;; ==========
;;
;;  I needed a program to browse, organize and tag my pictures.  I got
;; tired of the old gallery program I used as it did not allow
;; multi-file operations easily.  Also, it put things out of my
;; control.  Image viewing programs I tested did not allow multi-file
;; operations or did not do what I wanted it to.
;;
;;  So, I got the idea to use the wonderful functionality of Emacs and
;; `dired' to do it.  It would allow me to do almost anything I wanted,
;; which is basically just to browse all my pictures in an easy way,
;; letting me manipulate and tag them in various ways.  `dired' already
;; provide all the file handling and navigation facilities; I only
;; needed to add some functions to display the images.
;;
;;  I briefly tried out thumbs.el, and although it seemed more
;; powerful than this package, it did not work the way I wanted to.  It
;; was too slow to created thumbnails of all files in a directory (I
;; currently keep all my 2000+ images in the same directory) and
;; browsing the thumbnail buffer was slow too.  image-dired.el will not
;; create thumbnails until they are needed and the browsing is done
;; quickly and easily in dired.  I copied a great deal of ideas and
;; code from there though... :)
;;
;;  `image-dired' stores the thumbnail files in `image-dired-dir'
;; using the file name format ORIGNAME.thumb.ORIGEXT.  For example
;; ~/.emacs.d/image-dired/myimage01.thumb.jpg.  The "database" is for
;; now just a plain text file with the following format:
;;
;; file-name-non-directory;comment:comment-text;tag1;tag2;tag3;...;tagN
;;
;;
;; PREREQUISITES
;; =============
;;
;; * The ImageMagick package.  Currently, `convert' and `mogrify' are
63
;; used.  Find it here: https://www.imagemagick.org.
64 65 66 67
;;
;; * For non-lossy rotation of JPEG images, the JpegTRAN program is
;; needed.
;;
68
;; * For `image-dired-get-exif-data' and `image-dired-set-exif-data' to work,
69 70 71 72 73 74 75 76 77 78 79 80 81
;; the command line tool `exiftool' is needed.  It can be found here:
;; http://www.sno.phy.queensu.ca/~phil/exiftool/.  These two functions
;; are, among other things, used for writing comments to image files
;; using `image-dired-thumbnail-set-image-description' and to create
;; "unique" file names using `image-dired-get-exif-file-name' (used by
;; `image-dired-copy-with-exif-file-name').
;;
;;
;; USAGE
;; =====
;;
;; This information has been moved to the manual.  Type `C-h r' to open
;; the Emacs manual and go to the node Thumbnails by typing `g
Mark Oteiza's avatar
Mark Oteiza committed
82
;; Image-Dired RET'.
83 84 85 86 87 88 89 90 91 92 93 94 95 96
;;
;; Quickstart: M-x image-dired RET DIRNAME RET
;;
;; where DIRNAME is a directory containing image files.
;;
;; LIMITATIONS
;; ===========
;;
;; * Supports all image formats that Emacs and convert supports, but
;; the thumbnails are hard-coded to JPEG format.
;;
;; * WARNING: The "database" format used might be changed so keep a
;; backup of `image-dired-db-file' when testing new versions.
;;
97
;; * `image-dired-display-image-mode' does not support animation
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
;;
;; TODO
;; ====
;;
;; * Support gallery creation when using per-directory thumbnail
;; storage.
;;
;; * Some sort of auto-rotate function based on rotate info in the
;; EXIF data.
;;
;; * Investigate if it is possible to also write the tags to the image
;; files.
;;
;; * From thumbs.el: Add an option for clean-up/max-size functionality
;;   for thumbnail directory.
;;
;; * From thumbs.el: Add setroot function.
;;
;; * From thumbs.el: Add image resizing, if useful (image-dired's automatic
;;  "image fit" might be enough)
;;
;; * From thumbs.el: Add the "modify" commands (emboss, negate,
;;   monochrome etc).
;;
;; * Add `image-dired-display-thumbs-ring' and functions to cycle that.  Find
;; out which is best, saving old batch just before inserting new, or
;; saving the current batch in the ring when inserting it.  Adding it
;; probably needs rewriting `image-dired-display-thumbs' to be more general.
;;
;; * Find some way of toggling on and off really nice keybindings in
;; dired (for example, using C-n or <down> instead of C-S-n).  Richard
;; suggested that we could keep C-t as prefix for image-dired commands
;; as it is currently not used in dired.  He also suggested that
;; `dired-next-line' and `dired-previous-line' figure out if
;; image-dired is enabled in the current buffer and, if it is, call
;; `image-dired-dired-next-line' and
;; `image-dired-dired-previous-line', respectively.  Update: This is
;; partly done; some bindings have now been added to dired.
;;
;; * Enhanced gallery creation with basic CSS-support and pagination
;; of tag pages with many pictures.
;;
;; * Rewrite `image-dired-modify-mark-on-thumb-original-file' to be
;; less ugly.
;;
;; * In some way keep track of buffers and windows and stuff so that
;; it works as the user expects.
;;
;; * More/better documentation
;;
;;
;;; Code:

(require 'dired)
152
(require 'image-mode)
153 154 155
(require 'widget)

(eval-when-compile
156
  (require 'cl-lib)
157 158 159 160 161
  (require 'wid-edit))

(defgroup image-dired nil
  "Use dired to browse your images as thumbnails, and more."
  :prefix "image-dired-"
162
  :link '(info-link "(emacs) Image-Dired")
163 164
  :group 'multimedia)

165
(defcustom image-dired-dir (locate-user-emacs-file "image-dired/")
166
  "Directory where thumbnail images are stored."
167
  :type 'directory
168 169 170 171 172 173 174 175 176 177 178 179 180 181
  :group 'image-dired)

(defcustom image-dired-thumbnail-storage 'use-image-dired-dir
  "How to store image-dired's thumbnail files.
Image-Dired can store thumbnail files in one of two ways and this is
controlled by this variable.  \"Use image-dired dir\" means that the
thumbnails are stored in a central directory.  \"Per directory\"
means that each thumbnail is stored in a subdirectory called
\".image-dired\" in the same directory where the image file is.
\"Thumbnail Managing Standard\" means that the thumbnails are
stored and generated according to the Thumbnail Managing Standard
that allows sharing of thumbnails across different programs."
  :type '(choice :tag "How to store thumbnail files"
                 (const :tag "Use image-dired-dir" use-image-dired-dir)
182 183
                 (const :tag "Thumbnail Managing Standard (normal 128x128)" standard)
                 (const :tag "Thumbnail Managing Standard (large 256x256)" standard-large)
184 185 186
                 (const :tag "Per-directory" per-directory))
  :group 'image-dired)

187
(defcustom image-dired-db-file
188
  (expand-file-name ".image-dired_db" image-dired-dir)
189
  "Database file where file names and their associated tags are stored."
190
  :type 'file
191 192
  :group 'image-dired)

193
(defcustom image-dired-temp-image-file
194
  (expand-file-name ".image-dired_temp" image-dired-dir)
195
  "Name of temporary image file used by various commands."
196
  :type 'file
197 198
  :group 'image-dired)

199
(defcustom image-dired-gallery-dir
200
  (expand-file-name ".image-dired_gallery" image-dired-dir)
201 202 203
  "Directory to store generated gallery html pages.
This path needs to be \"shared\" to the public so that it can access
the index.html page that image-dired creates."
204
  :type 'directory
205 206 207
  :group 'image-dired)

(defcustom image-dired-gallery-image-root-url
208
"https://your.own.server/image-diredpics"
209 210 211 212 213 214 215
  "URL where the full size images are to be found.
Note that this path has to be configured in your web server.  Image-Dired
expects to find pictures in this directory."
  :type 'string
  :group 'image-dired)

(defcustom image-dired-gallery-thumb-image-root-url
216
"https://your.own.server/image-diredthumbs"
217 218 219 220 221 222 223
  "URL where the thumbnail images are to be found.
Note that this path has to be configured in your web server.  Image-Dired
expects to find pictures in this directory."
  :type 'string
  :group 'image-dired)

(defcustom image-dired-cmd-create-thumbnail-program
224
  "convert"
225 226
  "Executable used to create thumbnail.
Used together with `image-dired-cmd-create-thumbnail-options'."
227
  :type 'file
228 229 230
  :group 'image-dired)

(defcustom image-dired-cmd-create-thumbnail-options
231
  '("-size" "%wx%h" "%f[0]" "-resize" "%wx%h>" "-strip" "jpeg:%t")
232 233 234
  "Options of command used to create thumbnail image.
Used with `image-dired-cmd-create-thumbnail-program'.
Available format specifiers are: %w which is replaced by
235 236 237
`image-dired-thumb-width', %h which is replaced by `image-dired-thumb-height',
%f which is replaced by the file name of the original image and %t
which is replaced by the file name of the thumbnail file."
238 239
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
240 241
  :group 'image-dired)

242
(defcustom image-dired-cmd-create-temp-image-program "convert"
243 244
  "Executable used to create temporary image.
Used together with `image-dired-cmd-create-temp-image-options'."
245
  :type 'file
246 247 248
  :group 'image-dired)

(defcustom image-dired-cmd-create-temp-image-options
249
  '("-size" "%wx%h" "%f[0]" "-resize" "%wx%h>" "-strip" "jpeg:%t")
250 251 252
  "Options of command used to create temporary image for display window.
Used together with `image-dired-cmd-create-temp-image-program',
Available format specifiers are: %w and %h which are replaced by
253 254 255
the calculated max size for width and height in the image display window,
%f which is replaced by the file name of the original image and %t which
is replaced by the file name of the temporary file."
256 257
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
258 259
  :group 'image-dired)

Mark Oteiza's avatar
Mark Oteiza committed
260 261 262
(defcustom image-dired-cmd-pngnq-program
  (or (executable-find "pngnq")
      (executable-find "pngnq-s9"))
263
  "The file name of the `pngnq' program.
Mark Oteiza's avatar
Mark Oteiza committed
264
It quantizes colors of PNG images down to 256 colors or fewer
Paul Eggert's avatar
Paul Eggert committed
265
using the NeuQuant algorithm."
Mark Oteiza's avatar
Mark Oteiza committed
266
  :version "26.1"
267 268 269 270 271 272 273 274 275 276
  :type '(choice (const :tag "Not Set" nil) file)
  :group 'image-dired)

(defcustom image-dired-cmd-pngnq-options
  '("-f" "%t")
  "Arguments to pass `image-dired-cmd-pngnq-program'.
Available format specifiers are the same as in
`image-dired-cmd-create-thumbnail-options'."
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
277 278 279 280 281 282
  :group 'image-dired)

(defcustom image-dired-cmd-pngcrush-program (executable-find "pngcrush")
  "The file name of the `pngcrush' program.
It optimizes the compression of PNG images.  Also it adds PNG textual chunks
with the information required by the Thumbnail Managing Standard."
283
  :type '(choice (const :tag "Not Set" nil) file)
284 285
  :group 'image-dired)

286 287 288 289 290 291 292 293 294 295 296 297 298 299
(defcustom image-dired-cmd-pngcrush-options
  `("-q"
    "-text" "b" "Description" "Thumbnail of file://%f"
    "-text" "b" "Software" ,(emacs-version)
    ;; "-text b \"Thumb::Image::Height\" \"%oh\" "
    ;; "-text b \"Thumb::Image::Mimetype\" \"%mime\" "
    ;; "-text b \"Thumb::Image::Width\" \"%ow\" "
    "-text" "b" "Thumb::MTime" "%m"
    ;; "-text b \"Thumb::Size\" \"%b\" "
    "-text" "b" "Thumb::URI" "file://%f"
    "%q" "%t")
  "Arguments for `image-dired-cmd-pngcrush-program'.
Available format specifiers are the same as in
`image-dired-cmd-create-thumbnail-options', with %q for a
300
temporary file name (typically generated by pnqnq)."
Mark Oteiza's avatar
Mark Oteiza committed
301
  :version "26.1"
302 303 304 305 306
  :type '(repeat (string :tag "Argument"))
  :group 'image-dired)

(defcustom image-dired-cmd-optipng-program (executable-find "optipng")
  "The file name of the `optipng' program."
307
  :version "26.1"
308 309 310 311
  :type '(choice (const :tag "Not Set" nil) file)
  :group 'image-dired)

(defcustom image-dired-cmd-optipng-options '("-o5" "%t")
312
  "Arguments passed to `image-dired-cmd-optipng-program'.
313 314
Available format specifiers are described in
`image-dired-cmd-create-thumbnail-options'."
315
  :version "26.1"
316 317 318 319 320
  :type '(repeat (string :tag "Argument"))
  :link '(url-link "man:optipng(1)")
  :group 'image-dired)

(defcustom image-dired-cmd-create-standard-thumbnail-options
321
  (append '("-size" "%wx%h" "%f[0]")
322 323 324 325 326 327 328 329
          (unless (or image-dired-cmd-pngcrush-program
                      image-dired-cmd-pngnq-program)
            (list
             "-set" "Thumb::MTime" "%m"
             "-set" "Thumb::URI" "file://%f"
             "-set" "Description" "Thumbnail of file://%f"
             "-set" "Software" (emacs-version)))
          '("-thumbnail" "%wx%h>" "png:%t"))
330 331 332 333 334
  "Options for creating thumbnails according to the Thumbnail Managing Standard.
Available format specifiers are the same as in
`image-dired-cmd-create-thumbnail-options', with %m for file modification time."
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
335 336 337
  :group 'image-dired)

(defcustom image-dired-cmd-rotate-thumbnail-program
338
  "mogrify"
339 340
  "Executable used to rotate thumbnail.
Used together with `image-dired-cmd-rotate-thumbnail-options'."
341
  :type 'file
342 343 344
  :group 'image-dired)

(defcustom image-dired-cmd-rotate-thumbnail-options
345
  '("-rotate" "%d" "%t")
346 347 348
  "Arguments of command used to rotate thumbnail image.
Used with `image-dired-cmd-rotate-thumbnail-program'.
Available format specifiers are: %d which is replaced by the
349 350 351
number of (positive) degrees to rotate the image, normally 90 or 270
\(for 90 degrees right and left), %t which is replaced by the file name
of the thumbnail file."
352 353
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
354 355 356
  :group 'image-dired)

(defcustom image-dired-cmd-rotate-original-program
357
  "jpegtran"
358 359
  "Executable used to rotate original image.
Used together with `image-dired-cmd-rotate-original-options'."
360
  :type 'file
361 362 363
  :group 'image-dired)

(defcustom image-dired-cmd-rotate-original-options
364 365 366 367
  '("-rotate" "%d" "-copy" "all" "-outfile" "%t" "%o")
  "Arguments of command used to rotate original image.
Used with `image-dired-cmd-rotate-original-program'.
Available format specifiers are: %d which is replaced by the
368 369 370 371
number of (positive) degrees to rotate the image, normally 90 or
270 \(for 90 degrees right and left), %o which is replaced by the
original image file name and %t which is replaced by
`image-dired-temp-image-file'."
372 373
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
374 375 376
  :group 'image-dired)

(defcustom image-dired-temp-rotate-image-file
377
  (expand-file-name ".image-dired_rotate_temp" image-dired-dir)
378
  "Temporary file for rotate operations."
379
  :type 'file
380 381 382 383 384 385 386 387 388 389
  :group 'image-dired)

(defcustom image-dired-rotate-original-ask-before-overwrite t
  "Confirm overwrite of original file after rotate operation.
If non-nil, ask user for confirmation before overwriting the
original file with `image-dired-temp-rotate-image-file'."
  :type 'boolean
  :group 'image-dired)

(defcustom image-dired-cmd-write-exif-data-program
390
  "exiftool"
391 392
  "Program used to write EXIF data to image.
Used together with `image-dired-cmd-write-exif-data-options'."
393
  :type 'file
394 395 396
  :group 'image-dired)

(defcustom image-dired-cmd-write-exif-data-options
397 398 399 400
  '("-%t=%v" "%f")
  "Arguments of command used to write EXIF data.
Used with `image-dired-cmd-write-exif-data-program'.
Available format specifiers are: %f which is replaced by
401
the image file name, %t which is replaced by the tag name and %v
402
which is replaced by the tag value."
403 404
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
405 406 407
  :group 'image-dired)

(defcustom image-dired-cmd-read-exif-data-program
408
  "exiftool"
409
  "Program used to read EXIF data to image.
410 411
Used together with `image-dired-cmd-read-exif-data-options'."
  :type 'file
412 413 414
  :group 'image-dired)

(defcustom image-dired-cmd-read-exif-data-options
415 416 417 418
  '("-s" "-s" "-s" "-%t" "%f")
  "Arguments of command used to read EXIF data.
Used with `image-dired-cmd-read-exif-data-program'.
Available format specifiers are: %f which is replaced
419
by the image file name and %t which is replaced by the tag name."
420 421
  :version "26.1"
  :type '(repeat (string :tag "Argument"))
422 423 424 425 426 427 428 429 430
  :group 'image-dired)

(defcustom image-dired-gallery-hidden-tags
  (list "private" "hidden" "pending")
  "List of \"hidden\" tags.
Used by `image-dired-gallery-generate' to leave out \"hidden\" images."
  :type '(repeat string)
  :group 'image-dired)

431
(defcustom image-dired-thumb-size
432 433 434 435
  (cond
   ((eq 'standard image-dired-thumbnail-storage) 128)
   ((eq 'standard-large image-dired-thumbnail-storage) 256)
   (t 100))
436
  "Size of thumbnails, in pixels.
437 438
This is the default size for both `image-dired-thumb-width'
and `image-dired-thumb-height'."
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-thumb-width image-dired-thumb-size
  "Width of thumbnails, in pixels."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-thumb-height image-dired-thumb-size
  "Height of thumbnails, in pixels."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-thumb-relief 2
  "Size of button-like border around thumbnails."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-thumb-margin 2
  "Size of the margin around thumbnails.
This is where you see the cursor."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-line-up-method 'dynamic
  "Default method for line-up of thumbnails in thumbnail buffer.
465 466 467 468 469
Used by `image-dired-display-thumbs' and other functions that needs
to line-up thumbnails.  Dynamic means to use the available width of
the window containing the thumbnail buffer, Fixed means to use
`image-dired-thumbs-per-row', Interactive is for asking the user,
and No line-up means that no automatic line-up will be done."
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
  :type '(choice :tag "Default line-up method"
                 (const :tag "Dynamic" dynamic)
		 (const :tag "Fixed" fixed)
		 (const :tag "Interactive" interactive)
                 (const :tag "No line-up" none))
  :group 'image-dired)

(defcustom image-dired-thumbs-per-row 3
  "Number of thumbnails to display per row in thumb buffer."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-display-window-width-correction 1
  "Number to be used to correct image display window width.
Change if the default (1) does not work (i.e. if the image does not
completely fit)."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-display-window-height-correction 0
  "Number to be used to correct image display window height.
Change if the default (0) does not work (i.e. if the image does not
completely fit)."
  :type 'integer
  :group 'image-dired)

(defcustom image-dired-track-movement t
  "The current state of the tracking and mirroring.
For more information, see the documentation for
`image-dired-toggle-movement-tracking'."
  :type 'boolean
  :group 'image-dired)

(defcustom image-dired-append-when-browsing nil
  "Append thumbnails in thumbnail buffer when browsing.
If non-nil, using `image-dired-next-line-and-display' and
`image-dired-previous-line-and-display' will leave a trail of thumbnail
images in the thumbnail buffer.  If you enable this and want to clean
Paul Eggert's avatar
Paul Eggert committed
508
the thumbnail buffer because it is filled with too many thumbnails,
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
just call `image-dired-display-thumb' to display only the image at point.
This value can be toggled using `image-dired-toggle-append-browsing'."
  :type 'boolean
  :group 'image-dired)

(defcustom image-dired-dired-disp-props t
  "If non-nil, display properties for dired file when browsing.
Used by `image-dired-next-line-and-display',
`image-dired-previous-line-and-display' and `image-dired-mark-and-display-next'.
If the database file is large, this can slow down image browsing in
dired and you might want to turn it off."
  :type 'boolean
  :group 'image-dired)

(defcustom image-dired-display-properties-format "%b: %f (%t): %c"
  "Display format for thumbnail properties.
%b is replaced with associated dired buffer name, %f with file name
\(without path) of original image file, %t with the list of tags and %c
with the comment."
  :type 'string
  :group 'image-dired)

(defcustom image-dired-external-viewer
  ;; TODO: Use mailcap, dired-guess-shell-alist-default,
  ;; dired-view-command-alist.
  (cond ((executable-find "display"))
        ((executable-find "xli"))
        ((executable-find "qiv") "qiv -t"))
  "Name of external viewer.
Including parameters.  Used when displaying original image from
`image-dired-thumbnail-mode'."
540 541 542
  :version "27.1"
  :type '(choice string
                 (const :tag "Not Set" nil))
543 544 545 546 547 548 549 550 551
  :group 'image-dired)

(defcustom image-dired-main-image-directory "~/pics/"
  "Name of main image directory, if any.
Used by `image-dired-copy-with-exif-file-name'."
  :type 'string
  :group 'image-dired)

(defcustom image-dired-show-all-from-dir-max-files 50
552
  "Maximum number of files to show using `image-dired-show-all-from-dir'
553 554 555 556
before warning the user."
  :type 'integer
  :group 'image-dired)

557 558 559
(defmacro image-dired--with-db-file (&rest body)
  "Run BODY in a temp buffer containing `image-dired-db-file'.
Return the last form in BODY."
Mark Oteiza's avatar
Mark Oteiza committed
560
  (declare (indent 0) (debug t))
561 562 563 564 565
  `(with-temp-buffer
     (if (file-exists-p image-dired-db-file)
	 (insert-file-contents image-dired-db-file))
     ,@body))

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
(defun image-dired-dir ()
  "Return the current thumbnails directory (from variable `image-dired-dir').
Create the thumbnails directory if it does not exist."
  (let ((image-dired-dir (file-name-as-directory
                    (expand-file-name image-dired-dir))))
    (unless (file-directory-p image-dired-dir)
      (make-directory image-dired-dir t)
      (message "Creating thumbnails directory"))
    image-dired-dir))

(defun image-dired-insert-image (file type relief margin)
  "Insert image FILE of image TYPE, using RELIEF and MARGIN, at point."
  (let ((i `(image :type ,type
                   :file ,file
                   :relief ,relief
                   :margin ,margin)))
    (insert-image i)))

(defun image-dired-get-thumbnail-image (file)
  "Return the image descriptor for a thumbnail of image file FILE."
  (unless (string-match (image-file-name-regexp) file)
    (error "%s is not a valid image file" file))
588 589 590
  (let* ((thumb-file (image-dired-thumb-name file))
	 (thumb-attr (file-attributes thumb-file)))
    (when (or (not thumb-attr)
Paul Eggert's avatar
Paul Eggert committed
591 592 593
	      (time-less-p (file-attribute-modification-time thumb-attr)
			   (file-attribute-modification-time
			    (file-attributes file))))
594 595 596 597 598 599 600 601
      (image-dired-create-thumb file thumb-file))
    (create-image thumb-file)
;;     (list 'image :type 'jpeg
;;           :file thumb-file
;; 	  :relief image-dired-thumb-relief :margin image-dired-thumb-margin)
    ))

(defun image-dired-insert-thumbnail (file original-file-name
602
                                     associated-dired-buffer)
603 604 605 606 607 608
  "Insert thumbnail image FILE.
Add text properties ORIGINAL-FILE-NAME and ASSOCIATED-DIRED-BUFFER."
  (let (beg end)
    (setq beg (point))
    (image-dired-insert-image file
                        ;; TODO: this should depend on the real file type
609 610
                        (if (memq image-dired-thumbnail-storage
                                  '(standard standard-large))
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
                            'png 'jpeg)
                        image-dired-thumb-relief
                        image-dired-thumb-margin)
    (setq end (point))
    (add-text-properties
     beg end
     (list 'image-dired-thumbnail t
           'original-file-name original-file-name
           'associated-dired-buffer associated-dired-buffer
           'tags (image-dired-list-tags original-file-name)
           'mouse-face 'highlight
           'comment (image-dired-get-comment original-file-name)))))

(defun image-dired-thumb-name (file)
  "Return thumbnail file name for FILE.
Depending on the value of `image-dired-thumbnail-storage', the file
name will vary.  For central thumbnail file storage, make a
MD5-hash of the image file's directory name and add that to make
the thumbnail file name unique.  For per-directory storage, just
add a subdirectory.  For standard storage, produce the file name
according to the Thumbnail Managing Standard."
632
  (cond ((memq image-dired-thumbnail-storage '(standard standard-large))
633 634
         (let* ((xdg (getenv "XDG_CACHE_HOME"))
                (dir (if (and xdg (file-name-absolute-p xdg))
635 636 637 638
                         xdg "~/.cache"))
                (thumbdir (cl-case image-dired-thumbnail-storage
                            (standard "thumbnails/normal")
                            (standard-large "thumbnails/large"))))
639 640
           (expand-file-name
            (concat (md5 (concat "file://" (expand-file-name file))) ".png")
641
            (expand-file-name thumbdir dir))))
642 643 644 645 646 647 648 649 650 651
        ((eq 'use-image-dired-dir image-dired-thumbnail-storage)
         (let* ((f (expand-file-name file))
                (md5-hash
                 ;; Is MD5 hashes fast enough? The checksum of a
                 ;; thumbnail file name need not be that
                 ;; "cryptographically" good so a faster one could
                 ;; be used here.
                 (md5 (file-name-as-directory (file-name-directory f)))))
           (format "%s%s%s.thumb.%s"
                   (file-name-as-directory (expand-file-name (image-dired-dir)))
652
                   (file-name-base f)
653 654 655 656 657 658
                   (if md5-hash (concat "_" md5-hash) "")
                   (file-name-extension f))))
        ((eq 'per-directory image-dired-thumbnail-storage)
         (let ((f (expand-file-name file)))
           (format "%s.image-dired/%s.thumb.%s"
                   (file-name-directory f)
659
                   (file-name-base f)
660 661
                   (file-name-extension f))))))

662 663 664 665
(defun image-dired--check-executable-exists (executable)
  (unless (executable-find (symbol-value executable))
    (error "Executable %S not found" executable)))

666 667
(defun image-dired-thumb-size (dimension)
  "Return thumb size depending on `image-dired-thumbnail-storage'.
668
DIMENSION should be either the symbol `width' or `height'."
669 670 671 672 673 674 675
  (cond
   ((eq 'standard image-dired-thumbnail-storage) 128)
   ((eq 'standard-large image-dired-thumbnail-storage) 256)
   (t (cl-ecase dimension
        (width image-dired-thumb-width)
        (height image-dired-thumb-height)))))

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
(defvar image-dired-queue nil
  "List of items in the queue.
Each item has the form (ORIGINAL-FILE TARGET-FILE).")

(defvar image-dired-queue-active-jobs 0
  "Number of active jobs in `image-dired-queue'.")

(defvar image-dired-queue-active-limit 2
  "Maximum number of concurrent jobs permitted for generating images.
Increase at own risk.")

(defun image-dired-pngnq-thumb (spec)
  "Quantize thumbnail described by format SPEC with pngnq(1)."
  (let ((process
         (apply #'start-process "image-dired-pngnq" nil
                image-dired-cmd-pngnq-program
                (mapcar (lambda (arg) (format-spec arg spec))
                        image-dired-cmd-pngnq-options))))
    (setf (process-sentinel process)
          (lambda (process status)
            (if (and (eq (process-status process) 'exit)
                     (zerop (process-exit-status process)))
                ;; Pass off to pngcrush, or just rename the
                ;; THUMB-nq8.png file back to THUMB.png
                (if (and image-dired-cmd-pngcrush-program
                         (executable-find image-dired-cmd-pngcrush-program))
                    (image-dired-pngcrush-thumb spec)
                  (let ((nq8 (cdr (assq ?q spec)))
                        (thumb (cdr (assq ?t spec))))
                    (rename-file nq8 thumb t)))
              (message "command %S %s" (process-command process)
                       (replace-regexp-in-string "\n" "" status)))))
    process))

(defun image-dired-pngcrush-thumb (spec)
Paul Eggert's avatar
Paul Eggert committed
711
  "Optimize thumbnail described by format SPEC with pngcrush(1)."
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  ;; If pngnq wasn't run, then the THUMB-nq8.png file does not exist.
  ;; pngcrush needs an infile and outfile, so we just copy THUMB to
  ;; THUMB-nq8.png and use the latter as a temp file.
  (when (not image-dired-cmd-pngnq-program)
    (let ((temp (cdr (assq ?q spec)))
          (thumb (cdr (assq ?t spec))))
      (copy-file thumb temp)))
  (let ((process
         (apply #'start-process "image-dired-pngcrush" nil
                image-dired-cmd-pngcrush-program
                (mapcar (lambda (arg) (format-spec arg spec))
                        image-dired-cmd-pngcrush-options))))
    (setf (process-sentinel process)
          (lambda (process status)
            (unless (and (eq (process-status process) 'exit)
                         (zerop (process-exit-status process)))
              (message "command %S %s" (process-command process)
                       (replace-regexp-in-string "\n" "" status)))
            (when (memq (process-status process) '(exit signal))
              (let ((temp (cdr (assq ?q spec))))
                (delete-file temp)))))
    process))

(defun image-dired-optipng-thumb (spec)
Paul Eggert's avatar
Paul Eggert committed
736
  "Optimize thumbnail described by format SPEC with optipng(1)."
737 738 739 740 741 742 743 744 745 746 747 748 749 750
  (let ((process
         (apply #'start-process "image-dired-optipng" nil
                image-dired-cmd-optipng-program
                (mapcar (lambda (arg) (format-spec arg spec))
                        image-dired-cmd-optipng-options))))
    (setf (process-sentinel process)
          (lambda (process status)
            (unless (and (eq (process-status process) 'exit)
                         (zerop (process-exit-status process)))
              (message "command %S %s" (process-command process)
                       (replace-regexp-in-string "\n" "" status)))))
    process))

(defun image-dired-create-thumb-1 (original-file thumbnail-file)
751
  "For ORIGINAL-FILE, create thumbnail image named THUMBNAIL-FILE."
752 753
  (image-dired--check-executable-exists
   'image-dired-cmd-create-thumbnail-program)
754 755
  (let* ((width (int-to-string (image-dired-thumb-size 'width)))
         (height (int-to-string (image-dired-thumb-size 'height)))
756
	 (modif-time (format-time-string
Paul Eggert's avatar
Paul Eggert committed
757 758
		      "%s" (file-attribute-modification-time
			    (file-attributes original-file))))
759 760
         (thumbnail-nq8-file (replace-regexp-in-string ".png\\'" "-nq8.png"
                                                       thumbnail-file))
761 762 763 764 765 766 767 768 769 770 771 772
         (spec
          (list
           (cons ?w width)
           (cons ?h height)
           (cons ?m modif-time)
           (cons ?f original-file)
           (cons ?q thumbnail-nq8-file)
           (cons ?t thumbnail-file)))
         (thumbnail-dir (file-name-directory thumbnail-file))
         process)
    (when (not (file-exists-p thumbnail-dir))
      (message "Creating thumbnail directory")
Paul Eggert's avatar
Paul Eggert committed
773 774
      (with-file-modes #o700
	(make-directory thumbnail-dir t)))
775

Paul Eggert's avatar
Paul Eggert committed
776
    ;; Thumbnail file creation processes begin here and are marshaled
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    ;; in a queue by `image-dired-create-thumb'.
    (setq process
          (apply #'start-process "image-dired-create-thumbnail" nil
                 image-dired-cmd-create-thumbnail-program
                 (mapcar
                  (lambda (arg) (format-spec arg spec))
                  (if (memq image-dired-thumbnail-storage
                            '(standard standard-large))
                      image-dired-cmd-create-standard-thumbnail-options
                    image-dired-cmd-create-thumbnail-options))))

    (setf (process-sentinel process)
          (lambda (process status)
            ;; Trigger next in queue once a thumbnail has been created
            (cl-decf image-dired-queue-active-jobs)
            (image-dired-thumb-queue-run)
            (if (not (and (eq (process-status process) 'exit)
                          (zerop (process-exit-status process))))
                (message "Thumb could not be created for %s: %s"
                         (abbreviate-file-name original-file)
                         (replace-regexp-in-string "\n" "" status))
              (set-file-modes thumbnail-file #o600)
              (clear-image-cache thumbnail-file)
              ;; PNG thumbnail has been created since we are
              ;; following the XDG thumbnail spec, so try to optimize
              (when (memq image-dired-thumbnail-storage
                          '(standard standard-large))
                (cond
                 ((and image-dired-cmd-pngnq-program
                       (executable-find image-dired-cmd-pngnq-program))
                  (image-dired-pngnq-thumb spec))
                 ((and image-dired-cmd-pngcrush-program
                       (executable-find image-dired-cmd-pngcrush-program))
                  (image-dired-pngcrush-thumb spec))
                 ((and image-dired-cmd-optipng-program
                       (executable-find image-dired-cmd-optipng-program))
                  (image-dired-optipng-thumb spec)))))))
    process))

(defun image-dired-thumb-queue-run ()
  "Run a queued job if one exists and not too many jobs are running.
Queued items live in `image-dired-queue'."
  (while (and image-dired-queue
              (< image-dired-queue-active-jobs
                 image-dired-queue-active-limit))
    (cl-incf image-dired-queue-active-jobs)
    (apply #'image-dired-create-thumb-1 (pop image-dired-queue))))

(defun image-dired-create-thumb (original-file thumbnail-file)
  "Add a job for generating thumbnail to `image-dired-queue'."
  (setq image-dired-queue
        (nconc image-dired-queue
               (list (list original-file thumbnail-file))))
  (run-at-time 0 nil #'image-dired-thumb-queue-run))
831 832

;;;###autoload
833 834 835 836 837 838 839
(defun image-dired-dired-toggle-marked-thumbs (&optional arg)
  "Toggle thumbnails in front of file names in the dired buffer.
If no marked file could be found, insert or hide thumbnails on the
current line.  ARG, if non-nil, specifies the files to use instead
of the marked files.  If ARG is an integer, use the next ARG (or
previous -ARG, if ARG<0) files."
  (interactive "P")
840
  (dired-map-over-marks
841 842 843 844
   (let ((image-pos  (dired-move-to-filename))
         (image-file (dired-get-filename nil t))
         thumb-file
         overlay)
845 846
     (when (and image-file
                (string-match-p (image-file-name-regexp) image-file))
847 848
       (setq thumb-file (image-dired-get-thumbnail-image image-file))
       ;; If image is not already added, then add it.
849 850
       (let ((thumb-ov (cl-loop for ov in (overlays-in (point) (1+ (point)))
                                if (overlay-get ov 'thumb-file) return ov)))
851 852
         (if thumb-ov
             (delete-overlay thumb-ov)
853
	   (put-image thumb-file image-pos)
854
	   (setq overlay
855 856
                 (cl-loop for ov in (overlays-in (point) (1+ (point)))
                          if (overlay-get ov 'put-image) return ov))
857 858 859 860
	   (overlay-put overlay 'image-file image-file)
	   (overlay-put overlay 'thumb-file thumb-file)))))
   arg             ; Show or hide image on ARG next files.
   'show-progress) ; Update dired display after each image is updated.
861 862
  (add-hook 'dired-after-readin-hook
            'image-dired-dired-after-readin-hook nil t))
863 864 865

(defun image-dired-dired-after-readin-hook ()
  "Relocate existing thumbnail overlays in dired buffer after reverting.
866
Move them to their corresponding files if they still exist.
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
Otherwise, delete overlays."
  (mapc (lambda (overlay)
          (when (overlay-get overlay 'put-image)
            (let* ((image-file (overlay-get overlay 'image-file))
                   (image-pos (dired-goto-file image-file)))
              (if image-pos
                  (move-overlay overlay image-pos image-pos)
                (delete-overlay overlay)))))
        (overlays-in (point-min) (point-max))))

(defun image-dired-next-line-and-display ()
  "Move to next dired line and display thumbnail image."
  (interactive)
  (dired-next-line 1)
  (image-dired-display-thumbs
   t (or image-dired-append-when-browsing nil) t)
  (if image-dired-dired-disp-props
      (image-dired-dired-display-properties)))

(defun image-dired-previous-line-and-display ()
  "Move to previous dired line and display thumbnail image."
  (interactive)
  (dired-previous-line 1)
  (image-dired-display-thumbs
   t (or image-dired-append-when-browsing nil) t)
  (if image-dired-dired-disp-props
      (image-dired-dired-display-properties)))

(defun image-dired-toggle-append-browsing ()
  "Toggle `image-dired-append-when-browsing'."
  (interactive)
  (setq image-dired-append-when-browsing
        (not image-dired-append-when-browsing))
  (message "Append browsing %s."
           (if image-dired-append-when-browsing
               "on"
             "off")))

(defun image-dired-mark-and-display-next ()
  "Mark current file in dired and display next thumbnail image."
  (interactive)
  (dired-mark 1)
  (image-dired-display-thumbs
   t (or image-dired-append-when-browsing nil) t)
  (if image-dired-dired-disp-props
      (image-dired-dired-display-properties)))

(defun image-dired-toggle-dired-display-properties ()
  "Toggle `image-dired-dired-disp-props'."
  (interactive)
  (setq image-dired-dired-disp-props
        (not image-dired-dired-disp-props))
  (message "Dired display properties %s."
           (if image-dired-dired-disp-props
               "on"
             "off")))

(defvar image-dired-thumbnail-buffer "*image-dired*"
  "Image-Dired's thumbnail buffer.")

(defun image-dired-create-thumbnail-buffer ()
  "Create thumb buffer and set `image-dired-thumbnail-mode'."
  (let ((buf (get-buffer-create image-dired-thumbnail-buffer)))
    (with-current-buffer buf
      (setq buffer-read-only t)
      (if (not (eq major-mode 'image-dired-thumbnail-mode))
          (image-dired-thumbnail-mode)))
    buf))

(defvar image-dired-display-image-buffer "*image-dired-display-image*"
  "Where larger versions of the images are display.")

(defun image-dired-create-display-image-buffer ()
  "Create image display buffer and set `image-dired-display-image-mode'."
  (let ((buf (get-buffer-create image-dired-display-image-buffer)))
    (with-current-buffer buf
      (setq buffer-read-only t)
      (if (not (eq major-mode 'image-dired-display-image-mode))
          (image-dired-display-image-mode)))
    buf))

(defvar image-dired-saved-window-configuration nil
  "Saved window configuration.")

;;;###autoload
(defun image-dired-dired-with-window-configuration (dir &optional arg)
  "Open directory DIR and create a default window configuration.

Convenience command that:

 - Opens dired in folder DIR
 - Splits windows in most useful (?) way
 - Set `truncate-lines' to t

After the command has finished, you would typically mark some
image files in dired and type
\\[image-dired-display-thumbs] (`image-dired-display-thumbs').

If called with prefix argument ARG, skip splitting of windows.

The current window configuration is saved and can be restored by
calling `image-dired-restore-window-configuration'."
  (interactive "DDirectory: \nP")
  (let ((buf (image-dired-create-thumbnail-buffer))
        (buf2 (image-dired-create-display-image-buffer)))
    (setq image-dired-saved-window-configuration
          (current-window-configuration))
    (dired dir)
    (delete-other-windows)
    (when (not arg)
977
      (split-window-right)
978 979 980
      (setq truncate-lines t)
      (save-excursion
        (other-window 1)
Mark Oteiza's avatar
Mark Oteiza committed
981
        (pop-to-buffer-same-window buf)
982
        (select-window (split-window-below))
Mark Oteiza's avatar
Mark Oteiza committed
983
        (pop-to-buffer-same-window buf2)
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        (other-window -2)))))

(defun image-dired-restore-window-configuration ()
  "Restore window configuration.
Restore any changes to the window configuration made by calling
`image-dired-dired-with-window-configuration'."
  (interactive)
  (if image-dired-saved-window-configuration
      (set-window-configuration image-dired-saved-window-configuration)
    (message "No saved window configuration")))

;;;###autoload
(defun image-dired-display-thumbs (&optional arg append do-not-pop)
  "Display thumbnails of all marked files, in `image-dired-thumbnail-buffer'.
If a thumbnail image does not exist for a file, it is created on the
fly.  With prefix argument ARG, display only thumbnail for file at
point (this is useful if you have marked some files but want to show
another one).

Recommended usage is to split the current frame horizontally so that
you have the dired buffer in the left window and the
`image-dired-thumbnail-buffer' buffer in the right window.

With optional argument APPEND, append thumbnail to thumbnail buffer
instead of erasing it first.

Juanma Barranquero's avatar
Juanma Barranquero committed
1010
Optional argument DO-NOT-POP controls if `pop-to-buffer' should be
1011 1012 1013 1014 1015 1016 1017
used or not.  If non-nil, use `display-buffer' instead of
`pop-to-buffer'.  This is used from functions like
`image-dired-next-line-and-display' and
`image-dired-previous-line-and-display' where we do not want the
thumbnail buffer to be selected."
  (interactive "P")
  (let ((buf (image-dired-create-thumbnail-buffer))
1018
        thumb-name files dired-buf)
1019 1020 1021 1022 1023 1024 1025 1026 1027
    (if arg
        (setq files (list (dired-get-filename)))
      (setq files (dired-get-marked-files)))
    (setq dired-buf (current-buffer))
    (with-current-buffer buf
      (let ((inhibit-read-only t))
        (if (not append)
            (erase-buffer)
          (goto-char (point-max)))
Mark Oteiza's avatar
Mark Oteiza committed
1028 1029
        (dolist (curr-file files)
          (setq thumb-name (image-dired-thumb-name curr-file))
1030 1031 1032
          (when (not (file-exists-p thumb-name))
            (image-dired-create-thumb curr-file thumb-name))
          (image-dired-insert-thumbnail thumb-name curr-file dired-buf)))
1033 1034 1035
      (if do-not-pop
          (display-buffer buf)
        (pop-to-buffer buf))
1036 1037 1038 1039 1040 1041 1042 1043 1044
      (cond ((eq 'dynamic image-dired-line-up-method)
             (image-dired-line-up-dynamic))
            ((eq 'fixed image-dired-line-up-method)
             (image-dired-line-up))
            ((eq 'interactive image-dired-line-up-method)
             (image-dired-line-up-interactive))
            ((eq 'none image-dired-line-up-method)
             nil)
            (t
1045
             (image-dired-line-up-dynamic))))))
1046 1047 1048 1049 1050 1051 1052

;;;###autoload
(defun image-dired-show-all-from-dir (dir)
  "Make a preview buffer for all images in DIR and display it.
If the number of files in DIR matching `image-file-name-regexp'
exceeds `image-dired-show-all-from-dir-max-files', a warning will be
displayed."
1053
  (interactive "DImage Dired: ")
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  (dired dir)
  (dired-mark-files-regexp (image-file-name-regexp))
  (let ((files (dired-get-marked-files)))
    (if (or (<= (length files) image-dired-show-all-from-dir-max-files)
            (and (> (length files) image-dired-show-all-from-dir-max-files)
                 (y-or-n-p
                  (format
                   "Directory contains more than %d image files.  Proceed? "
                   image-dired-show-all-from-dir-max-files))))
        (progn
          (image-dired-display-thumbs)
          (pop-to-buffer image-dired-thumbnail-buffer))
Paul Eggert's avatar
Paul Eggert committed
1066
      (message "Canceled."))))
1067 1068 1069 1070 1071

;;;###autoload
(defalias 'image-dired 'image-dired-show-all-from-dir)

;;;###autoload
1072
(define-obsolete-function-alias 'tumme 'image-dired "24.4")
1073

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
(defun image-dired-sane-db-file ()
  "Check if `image-dired-db-file' exists.
If not, try to create it (including any parent directories).
Signal error if there are problems creating it."
  (or (file-exists-p image-dired-db-file)
      (let (dir buf)
        (unless (file-directory-p (setq dir (file-name-directory
                                             image-dired-db-file)))
          (make-directory dir t))
        (with-current-buffer (setq buf (create-file-buffer
                                        image-dired-db-file))
          (write-file image-dired-db-file))
        (kill-buffer buf)
        (file-exists-p image-dired-db-file))
      (error "Could not create %s" image-dired-db-file)))

1090 1091
(defun image-dired-write-tags (file-tags)
  "Write file tags to database.
1092 1093
Write each file and tag in FILE-TAGS to the database.
FILE-TAGS is an alist in the following form:
1094
 ((FILE . TAG) ... )"
1095
  (image-dired-sane-db-file)
1096
  (let (end file tag)
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    (image-dired--with-db-file
     (setq buffer-file-name image-dired-db-file)
     (dolist (elt file-tags)
       (setq file (car elt)
	     tag (cdr elt))
       (goto-char (point-min))
       (if (search-forward-regexp (format "^%s.*$" file) nil t)
	   (progn
	     (setq end (point))
	     (beginning-of-line)
	     (when (not (search-forward (format ";%s" tag) end t))
	       (end-of-line)
	       (insert (format ";%s" tag))))
	 (goto-char (point-max))
	 (insert (format "\n%s;%s" file tag))))
     (save-buffer))))
1113 1114 1115

(defun image-dired-remove-tag (files tag)
  "For all FILES, remove TAG from the image database."
1116
  (image-dired-sane-db-file)
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
  (image-dired--with-db-file
   (setq buffer-file-name image-dired-db-file)
   (let (end)
     (unless (listp files)
       (if (stringp files)
	   (setq files (list files))
	 (error "Files must be a string or a list of strings!")))
     (dolist (file files)
       (goto-char (point-min))
       (when (search-forward-regexp (format "^%s" file) nil t)
	 (end-of-line)
	 (setq end (point))
	 (beginning-of-line)
	 (when (search-forward-regexp (format "\\(;%s\\)" tag) end t)
	   (delete-region (match-beginning 1) (match-end 1))
	   ;; Check if file should still be in the database. If
	   ;; it has no tags or comments, it will be removed.
	   (end-of-line)
	   (setq end (point))
	   (beginning-of-line)
	   (when (not (search-forward ";" end t))
	     (kill-line 1)
	     ;; If on empty line at end of buffer
	     (and (eobp)
		  (looking-at "^$")
		  (delete-char -1)))))))
   (save-buffer)))
1144 1145 1146

(defun image-dired-list-tags (file)
  "Read all tags for image FILE from the image database."
1147
  (image-dired-sane-db-file)
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  (image-dired--with-db-file
   (let (end (tags ""))
     (when (search-forward-regexp (format "^%s" file) nil t)
       (end-of-line)
       (setq end (point))
       (beginning-of-line)
       (if (search-forward ";" end t)
	   (if (search-forward "comment:" end t)
	       (if (search-forward ";" end t)
		   (setq tags (buffer-substring (point) end)))
	     (setq tags (buffer-substring (point) end)))))
     (split-string tags ";"))))
1160 1161 1162 1163 1164 1165

;;;###autoload
(defun image-dired-tag-files (arg)
  "Tag marked file(s) in dired.  With prefix ARG, tag file at point."
  (interactive "P")
  (let ((tag (read-string "Tags to add (separate tags with a semicolon): "))
1166
        files)
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    (if arg
        (setq files (list (dired-get-filename)))
      (setq files (dired-get-marked-files)))
    (image-dired-write-tags
     (mapcar
      (lambda (x)
        (cons x tag))
      files))))

(defun image-dired-tag-thumbnail ()
  "Tag current thumbnail."
  (interactive)
  (let ((tag (read-string "Tags to add (separate tags with a semicolon): ")))
    (image-dired-write-tags (list (cons (image-dired-original-file-name) tag))))
  (image-dired-update-property
   'tags (image-dired-list-tags (image-dired-original-file-name))))

;;;###autoload
(defun image-dired-delete-tag (arg)
  "Remove tag for selected file(s).
With prefix argument ARG, remove tag from file at point."
  (interactive "P")
  (let ((tag (read-string "Tag to remove: "))
        files)
    (if arg
        (setq files (list (dired-get-filename)))
      (setq files (dired-get-marked-files)))
    (image-dired-remove-tag files tag)))

(defun image-dired-tag-thumbnail-remove ()
  "Remove tag from thumbnail."
  (interactive)
  (let ((tag (read-string "Tag to remove: ")))
    (image-dired-remove-tag (image-dired-original-file-name) tag))
  (image-dired-update-property
   'tags (image-dired-list-tags (image-dired-original-file-name))))

(defun image-dired-original-file-name ()
  "Get original file name for thumbnail or display image at point."
  (get-text-property (point) 'original-file-name))

Mark Oteiza's avatar
Mark Oteiza committed
1208 1209 1210 1211 1212 1213
(defun image-dired-file-name-at-point ()
  "Get abbreviated file name for thumbnail or display image at point."
  (let ((f (image-dired-original-file-name)))
    (when f
      (abbreviate-file-name f))))

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
(defun image-dired-associated-dired-buffer ()
  "Get associated dired buffer at point."
  (get-text-property (point) 'associated-dired-buffer))

(defun image-dired-get-buffer-window (buf)
  "Return window where buffer BUF is."
  (get-window-with-predicate
   (lambda (window)
     (equal (window-buffer window) buf))
   nil t))

(defun image-dired-track-original-file ()
  "Track the original file in the associated dired buffer.
1227 1228
See documentation for `image-dired-toggle-movement-tracking'.
Interactive use only useful if `image-dired-track-movement' is nil."
1229
  (interactive)
1230
  (let* ((dired-buf (image-dired-associated-dired-buffer))
1231 1232
         (file-name (image-dired-original-file-name))
         (window (image-dired-get-buffer-window dired-buf)))
1233 1234 1235 1236 1237
    (and (buffer-live-p dired-buf) file-name
         (with-current-buffer dired-buf
           (if (not (dired-goto-file file-name))
               (message "Could not track file")
             (if window (set-window-point window (point))))))))
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

(defun image-dired-toggle-movement-tracking ()
  "Turn on and off `image-dired-track-movement'.
Tracking of the movements between thumbnail and dired buffer so that
they are \"mirrored\" in the dired buffer.  When this is on, moving
around in the thumbnail or dired buffer will find the matching
position in the other buffer."
  (interactive)
  (setq image-dired-track-movement (not image-dired-track-movement))
  (message "Tracking %s" (if image-dired-track-movement "on" "off")))

(defun image-dired-track-thumbnail ()
  "Track current dired file's thumb in `image-dired-thumbnail-buffer'.
1251 1252
This is almost the same as what `image-dired-track-original-file' does,
but the other way around."
1253
  (let ((file (dired-get-filename))
1254
        prop-val found window)
1255
    (when (get-buffer image-dired-thumbnail-buffer)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
      (with-current-buffer image-dired-thumbnail-buffer
        (goto-char (point-min))
        (while (and (not (eobp))
                    (not found))
          (if (and (setq prop-val
                         (get-text-property (point) 'original-file-name))
                   (string= prop-val file))
              (setq found t))
          (if (not found)
              (forward-char 1)))
        (when found
          (if (setq window (image-dired-thumbnail-window))
              (set-window-point window (point)))
          (image-dired-display-thumb-properties))))))
1270 1271 1272

(defun image-dired-dired-next-line (&optional arg)
  "Call `dired-next-line', then track thumbnail.
1273 1274
This can safely replace `dired-next-line'.
With prefix argument, move ARG lines."
1275 1276 1277 1278 1279 1280 1281
  (interactive "P")
  (dired-next-line (or arg 1))
  (if image-dired-track-movement
      (image-dired-track-thumbnail)))

(defun image-dired-dired-previous-line (&optional arg)
  "Call `dired-previous-line', then track thumbnail.
1282 1283
This can safely replace `dired-previous-line'.
With prefix argument, move ARG lines."
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  (interactive "P")
  (dired-previous-line (or arg 1))
  (if image-dired-track-movement
      (image-dired-track-thumbnail)))

(defun image-dired-forward-image (&optional arg)
  "Move to next image and display properties.
Optional prefix ARG says how many images to move; default is one
image."
  (interactive "p")
  (let (pos (steps (or arg 1)))
Mark Oteiza's avatar
Mark Oteiza committed
1295
    (dotimes (_ steps)
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
      (if (and (not (eobp))
               (save-excursion
                 (forward-char)
                 (while (and (not (eobp))
                             (not (image-dired-image-at-point-p)))
                   (forward-char))
                 (setq pos (point))
                 (image-dired-image-at-point-p)))
          (goto-char pos)
        (error "At last image"))))
  (when image-dired-track-movement
    (image-dired-track-original-file))
  (image-dired-display-thumb-properties))

(defun image-dired-backward-image (&optional arg)
  "Move to previous image and display properties.
Optional prefix ARG says how many images to move; default is one
image."
  (interactive "p")
  (let (pos (steps (or arg 1)))
Mark Oteiza's avatar
Mark Oteiza committed
1316
    (dotimes (_ steps)
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
      (if (and (not (bobp))
               (save-excursion
                 (backward-char)
                 (while (and (not (bobp))
                             (not (image-dired-image-at-point-p)))
                   (backward-char))
                 (setq pos (point))
                 (image-dired-image-at-point-p)))
          (goto-char pos)
        (error "At first image"))))
  (when image-dired-track-movement
    (image-dired-track-original-file))
  (image-dired-display-thumb-properties))

(defun image-dired-next-line ()
  "Move to next line and display properties."
  (interactive)
1334
  (let ((goal-column (current-column)))
1335 1336
    (forward-line 1)
    (move-to-column goal-column))
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  ;; If we end up in an empty spot, back up to the next thumbnail.
  (if (not (image-dired-image-at-point-p))
      (image-dired-backward-image))
  (if image-dired-track-movement
      (image-dired-track-original-file))
  (image-dired-display-thumb-properties))


(defun image-dired-previous-line ()
  "Move to previous line and display properties."
  (interactive)
1348
  (let ((goal-column (current-column)))
1349 1350
    (forward-line -1)
    (move-to-column goal-column))
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
  ;; If we end up in an empty spot, back up to the next
  ;; thumbnail. This should only happen if the user deleted a
  ;; thumbnail and did not refresh, so it is not very common. But we
  ;; can handle it in a good manner, so why not?
  (if (not (image-dired-image-at-point-p))
      (image-dired-backward-image))
  (if image-dired-track-movement
      (image-dired-track-original-file))
  (image-dired-display-thumb-properties))

(defun image-dired-format-properties-string (buf file props comment)
  "Format display properties.
BUF is the associated dired buffer, FILE is the original image file
1364
name, PROPS is a stringified list of tags and COMMENT is the image file's
1365 1366 1367 1368 1369 1370
comment."
  (format-spec
   image-dired-display-properties-format
   (list
    (cons ?b (or buf ""))
    (cons ?f file)
1371
    (cons ?t (or props ""))
1372 1373 1374 1375 1376 1377 1378
    (cons ?c (or comment "")))))

(defun image-dired-display-thumb-properties ()
  "Display thumbnail properties in the echo area."
  (if (not (eobp))
      (let ((file-name (file-name-nondirectory (image-dired-original-file-name)))
            (dired-buf (buffer-name (image-dired-associated-dired-buffer)))
1379 1380 1381
            (props (mapconcat #'identity (get-text-property (point) 'tags) ", "))
            (comment (get-text-property (point) 'comment))
            (message-log-max nil))
1382
        (if file-name
1383
             (message "%s"
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
             (image-dired-format-properties-string
              dired-buf
              file-name
              props
              comment))))))

(defun image-dired-dired-file-marked-p ()
  "Check whether file on current line is marked or not."
  (save-excursion
    (beginning-of-line)
    (not (looking-at "^ .*$"))))

(defun image-dired-modify-mark-on-thumb-original-file (command)
  "Modify mark in dired buffer.
1398 1399
COMMAND is one of `mark' for marking file in dired, `unmark' for
unmarking file in dired or `flag' for flagging file for delete in
1400 1401 1402 1403 1404 1405
dired."
  (let ((file-name (image-dired-original-file-name))
        (dired-buf (image-dired-associated-dired-buffer)))
    (if (not (and dired-buf file-name))
        (message "No image, or image with correct properties, at point.")
    (with-current-buffer dired-buf
1406
        (message "%s" file-name)
1407
        (if (dired-goto-file file-name)
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            (cond ((eq command 'mark) (dired-mark 1))
                  ((eq command 'unmark) (dired-unmark 1))
                  ((eq command 'toggle)
                   (if (image-dired-dired-file-marked-p)
                       (dired-unmark 1)
                     (dired-mark 1)))
                  ((eq command 'flag) (dired-flag-file-deletion 1))))))))

(defun image-dired-mark-thumb-original-file ()
  "Mark original image file in associated dired buffer."
  (interactive)
  (image-dired-modify-mark-on-thumb-original-file 'mark)
  (image-dired-forward-image))

(defun image-dired-unmark-thumb-original-file ()
  "Unmark original image file in associated dired buffer."
  (interactive)
  (image-dired-modify-mark-on-thumb-original-file 'unmark)
  (image-dired-forward-image))

(defun image-dired-flag-thumb-original-file ()
  "Flag original image file for deletion in associated dired buffer."
  (interactive)
  (image-dired-modify-mark-on-thumb-original-file 'flag)
  (image-dired-forward-image))

(defun image-dired-toggle-mark-thumb-original-file ()
  "Toggle mark on original image file in associated dired buffer."
  (interactive)
  (image-dired-modify-mark-on-thumb-original-file 'toggle))

(defun image-dired-jump-original-dired-buffer ()
  "Jump to the dired buffer associated with the current image file.
You probably want to use this together with
`image-dired-track-original-file'."
  (interactive)
  (let ((buf (image-dired-associated-dired-buffer))
        window frame)
    (setq window (image-dired-get-buffer-window buf))
    (if window
        (progn
          (if (not (equal (selected-frame) (setq frame (window-frame window))))
              (select-frame-set-input-focus frame))
          (select-window window))
      (message "Associated dired buffer not visible"))))

;;;###autoload
(defun image-dired-jump-thumbnail-buffer ()
  "Jump to thumbnail buffer."
  (interactive)
  (let ((window (image-dired-thumbnail-window))
        frame)
    (if window
        (progn
          (if (not (equal (selected-frame) (setq frame (window-frame window))))
              (select-frame-set-input-focus frame))
          (select-window window))
      (message "Thumbnail buffer not visible"))))

1467 1468 1469 1470 1471 1472 1473 1474 1475
(defvar image-dired-thumbnail-mode-line-up-map
  (let ((map (make-sparse-keymap)))
    ;; map it to "g" so that the user can press it more quickly
    (define-key map "g" 'image-dired-line-up-dynamic)
    ;; "f" for "fixed" number of thumbs per row
    (define-key map "f" 'image-dired-line-up)
    ;; "i" for "interactive"
    (define-key map "i" 'image-dired-line-up-interactive)
    map)
1476 1477
  "Keymap for line-up commands in `image-dired-thumbnail-mode'.")

1478 1479 1480 1481 1482 1483 1484
(defvar image-dired-thumbnail-mode-tag-map
  (let ((map (make-sparse-keymap)))
    ;; map it to "t" so that the user can press it more quickly
    (define-key map "t" 'image-dired-tag-thumbnail)
    ;; "r" for "remove"
    (define-key map "r" 'image-dired-tag-thumbnail-remove)
    map)
1485 1486
  "Keymap for tag commands in `image-dired-thumbnail-mode'.")

1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
(defvar image-dired-thumbnail-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map [right] 'image-dired-forward-image)
    (define-key map [left] 'image-dired-backward-image)
    (define-key map [up] 'image-dired-previous-line)
    (define-key map [down] 'image-dired-next-line)
    (define-key map "\C-f" 'image-dired-forward-image)
    (define-key map "\C-b" 'image-dired-backward-image)
    (define-key map "\C-p" 'image-dired-previous-line)
    (define-key map "\C-n" 'image-dired-next-line)

    (define-key map "d" 'image-dired-flag-thumb-original-file)
    (define-key map [delete] 'image-dired-flag-thumb-original-file)
    (define-key map "m" 'image-dired-mark-thumb-original-file)
    (define-key map "u" 'image-dired-unmark-thumb-original-file)
    (define-key map "." 'image-dired-track-original-file)
    (define-key map [tab] 'image-dired-jump-original-dired-buffer)

    ;; add line-up map
    (define-key map "g" image-dired-thumbnail-mode-line-up-map)
    ;; add tag map
    (define-key map "t" image-dired-thumbnail-mode-tag-map)

    (define-key map "\C-m" 'image-dired-display-thumbnail-original-image)
    (define-key map [C-return] 'image-dired-thumbnail-display-external)

    (define-key map "l" 'image-dired-rotate-thumbnail-left)
    (define-key map "r" 'image-dired-rotate-thumbnail-right)
    (define-key map "L" 'image-dired-rotate-original-left)
    (define-key map "R" 'image-dired-rotate-original-right)

    (define-key map "D" 'image-dired-thumbnail-set-image-description)
    (define-key map "\C-d" 'image-dired-delete-char)
    (define-key map " " 'image-dired-display-next-thumbnail-original)
    (define-key map (kbd "DEL") 'image-dired-display-previous-thumbnail-original)
    (define-key map "c" 'image-dired-comment-thumbnail)

    ;; Mouse
    (define-key map [mouse-2] 'image-dired-mouse-display-image)
    (define-key map [mouse-1] 'image-dired-mouse-select-thumbnail)
    ;; Seems I must first set C-down-mouse-1 to undefined, or else it
    ;; will trigger the buffer menu. If I try to instead bind
    ;; C-down-mouse-1 to `image-dired-mouse-toggle-mark', I get a message
    ;; about C-mouse-1 not being defined afterwards. Annoying, but I
    ;; probably do not completely understand mouse events.
    (define-key map [C-down-mouse-1] 'undefined)
    (define-key map [C-mouse-1] 'image-dired-mouse-toggle-mark)

    ;; Menu
    (easy-menu-define nil map
      "Menu for `image-dired-thumbnail-mode'."
      '("Image-Dired"
1539
        ["Quit" quit-window]
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
        ["Delete thumbnail from buffer" image-dired-delete-char]
        ["Remove tag from thumbnail" image-dired-tag-thumbnail-remove]
        ["Tag thumbnail" image-dired-tag-thumbnail]
        ["Comment thumbnail" image-dired-comment-thumbnail]
        ["Refresh thumb" image-dired-refresh-thumb]
        ["Dynamic line up" image-dired-line-up-dynamic]
        ["Line up thumbnails" image-dired-line-up]

        ["Rotate thumbnail left" image-dired-rotate-thumbnail-left]
        ["Rotate thumbnail right" image-dired-rotate-thumbnail-right]
        ["Rotate original left" image-dired-rotate-original-left]
        ["Rotate original right" image-dired-rotate-original-right]

        ["Toggle movement tracking on/off" image-dired-toggle-movement-tracking]

        ["Jump to dired buffer" image-dired-jump-original-dired-buffer]
        ["Track original" image-dired-track-original-file]

        ["Flag original for deletion" image-dired-flag-thumb-original-file]
        ["Unmark original" image-dired-unmark-thumb-original-file]
        ["Mark original" image-dired-mark-thumb-original-file]

        ["Display in external viewer" image-dired-thumbnail-display-external]
        ["Display image" image-dired-display-thumbnail-original-image]))
    map)
  "Keymap for `image-dired-thumbnail-mode'.")
1566

1567 1568
(defvar image-dired-display-image-mode-map
  (let ((map (make-sparse-keymap)))
1569 1570
    ;; `image-mode-map' has bindings that do not make sense in image-dired
    ;; (set-keymap-parent map image-mode-map)
1571 1572
    (define-key map "f" 'image-dired-display-current-image-full)
    (define-key map "s" 'image-dired-display-current-image-sized)
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    (define-key map "g" nil)

    ;; Useful bindings from `image-mode-map'
    (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)
    (define-key map [remap left-char] 'image-backward-hscroll)
    (define-key map [remap previous-line] 'image-previous-line)
    (define-key map [remap next-line] 'image-next-line)
    (define-key map [remap scroll-up] 'image-scroll-up)
    (define-key map [remap scroll-down] 'image-scroll-down)
    (define-key map [remap scroll-up-command] 'image-scroll-up)
    (define-key map [remap scroll-down-command] 'image-scroll-down)
1586 1587
    (define-key map [remap scroll-left] 'image-scroll-left)
    (define-key map [remap scroll-right] 'image-scroll-right)
1588 1589 1590 1591
    (define-key map [remap move-beginning-of-line] 'image-bol)
    (define-key map [remap move-end-of-line] 'image-eol)
    (define-key map [remap beginning-of-buffer] 'image-bob)
    (define-key map [remap end-of-buffer] 'image-eob)
1592 1593 1594 1595

    (easy-menu-define nil map
      "Menu for `image-dired-display-image-mode-map'."
      '("Image-Dired"
1596
        ["Quit" quit-window]
1597 1598 1599 1600
        ["Display original, sized to fit" image-dired-display-current-image-sized]
        ["Display original, full size" image-dired-display-current-image-full]))
    map)
  "Keymap for `image-dired-display-image-mode'.")
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618

(defun image-dired-display-current-image-full ()
  "Display current image in full size."
  (interactive)
  (let ((file (image-dired-original-file-name)))
    (if file
        (progn
          (image-dired-display-image file t)
          (message "Full size image displayed"))
      (error "No original file name at point"))))

(defun image-dired-display-current-image-sized ()
  "Display current image in sized to fit window dimensions."
  (interactive)
  (let ((file (image-dired-original-file-name)))
    (if file
        (progn
          (image-dired-display-image file)
1619
          (message "Fitted image displayed"))
1620 1621 1622
      (error "No original file name at point"))))

(define-derived-mode image-dired-thumbnail-mode
1623
  special-mode "image-dired-thumbnail"
1624
  "Browse and manipulate thumbnail images using dired.
1625
Use `image-dired-minor-mode' to get a nice setup."
Mark Oteiza's avatar
Mark Oteiza committed
1626
  :group 'image-dired
Mark Oteiza's avatar
Mark Oteiza committed
1627 1628
  (buffer-disable-undo)
  (add-hook 'file-name-at-point-functions 'image-dired-file-name-at-point nil t))
1629 1630

(define-derived-mode image-dired-display-image-mode
1631
  special-mode "image-dired-image-display"
1632 1633
  "Mode for displaying and manipulating original image.
Resized or in full-size."
Mark Oteiza's avatar
Mark Oteiza committed
1634
  :group 'image-dired
Mark Oteiza's avatar
Mark Oteiza committed
1635
  (buffer-disable-undo)
1636
  (image-mode-setup-winprops)
1637
  (setq cursor-type nil)
Mark Oteiza's avatar
Mark Oteiza committed
1638
  (add-hook 'file-name-at-point-functions 'image-dired-file-name-at-point nil t))
1639

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657