Skip to content

Instantly share code, notes, and snippets.

@jkk
Created September 10, 2010 01:32
Show Gist options
  • Select an option

  • Save jkk/572906 to your computer and use it in GitHub Desktop.

Select an option

Save jkk/572906 to your computer and use it in GitHub Desktop.
(ns user
(:use [clojure.java [io :only [file]] [shell :only [sh]]]))
(defn- os []
"Returns :win, :mac, :unix, or nil"
(condp
#(<= 0 (.indexOf %2 %1))
(.toLowerCase (System/getProperty "os.name"))
"win" :win
"mac" :mac
"nix" :unix
"nux" :unix
nil))
(defn open
"Open the given file (a string, File, or file URI) in the default
application for the current desktop environment. Returns nil"
[f]
(let [f (file f)]
;; There's an 'open' method in java.awt.Desktop but it hangs on Windows
;; using Clojure Box and turns the process into a GUI process on Max OS X.
;; Maybe it's ok for Linux?
(do
(condp = (os)
:mac (sh "open" (str f))
:win (sh "cmd" (str "/c start " (-> f .toURI .toURL str)))
:else (sh "xdg-open" (str f)))
nil)))
(defn open-data
"Write the given data (string or bytes) to a temporary file with the
given extension (string or keyword, with or without the dot) and then open
it in the default application for that extension in the current desktop
environment. Returns nil"
[data ext]
(let [ext (name ext)
ext (if (= \. (first ext)) ext (str \. ext))
tmp (java.io.File/createTempFile (subs ext 1) ext)]
(with-open [w (if (string? data)
(java.io.FileWriter. tmp)
(java.io.FileOutputStream. tmp))]
(.write w data))
(open tmp)))
;;;
(comment
;; Text -- opens in text editor
(open-data "Hello, World" :txt)
;; HTML -- browser, probably
(open-data "Hello, <b>World</b>" :html)
;; Image -- image viewer
(let [img (java.awt.image.BufferedImage.
100 100 java.awt.image.BufferedImage/TYPE_INT_RGB)
png-bytes (let [out (java.io.ByteArrayOutputStream.)]
(.drawString (.getGraphics img) "OMG LOL" 20 55)
(javax.imageio.ImageIO/write img "png" out)
(.toByteArray out))]
(open-data png-bytes :png))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment