Hello Stephen,

maybe this is worth another addition to c.c.swing-utils?

(import 'javax.swing.JFileChooser)
(use [clojure.contrib.def :only (defvar-)])

(defvar- file-chooser-last-directory
  (atom nil))

(defn with-chosen-file*
"Creates a file chooser with the given Ok button label. If a directory is
  supplied the chooser starts showing the directory. If no directory is
provided the chooser shows the last directory which was opened in the last
  call to the chooser."
  ([thunk label]
   (with-chosen-file*
     (fn [f]
       (reset! file-chooser-last-directory (.getParentFile f))
       (thunk f))
     @file-chooser-last-directory
     label))
  ([thunk directory label]
   (let [chooser (JFileChooser. directory)]
     (when (= (.showDialog chooser nil label)
              JFileChooser/APPROVE_OPTION)
       (thunk (.getSelectedFile chooser))))))

(defmacro with-chosen-file
  "Opens a file chooser, binds the result the user chose to the given
  variable name and executes the body. In front of the body there might
  be two options given:

    :directory is the initial directory shown in the chooser
    :label is the label shown on the Ok button of the dialog

  If no directory is given, the dialog will show the parent directory
  of the last chosen file. If no label is given Choose will be used.
  If given, directory must be specified first."
  [file & body]
  (let [directory (when (= (first body) :directory)
                    (second body))
        body      (if directory
                    (nnext body)
                    body)
        label     (if (= (first body) :label)
                    (second body)
                    "Choose")
        body      (if (= (first body) :label)
                    (nnext body)
                    body)]
    (if directory
      `(with-chosen-file* (fn [~file] ~...@body) ~directory ~label)
      `(with-chosen-file* (fn [~file] ~...@body) ~label))))

Any thoughts? I'm not totally happy with the current form, so discussion appreciated.

Sincerely
Meikel

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to