An introduction of the core features of the Groovy Light Table Plugin.
You may find the video on youtube or vimeo
Welcome ! I'm a software developer doing most of my work on the JVM platform. This blog is a channel for small discoveries and insights percolating from my day to day work. I hope that you will find some of it useful !
// from the evalGroovy method
def evalResult = scriptExecutor.execute(data.code, clientSessions.get(currentClientId))
clientSessions.put(currentClientId, evalResult.bindings)
;; Behavior for clearing bindings
(behavior ::on-clear-bindings
:desc "Clear cached bindings for this editor"
:triggers #{:on.clear.bindings}
:reaction (fn [editor]
(let [info (:info @editor)
cl (eval/get-client! {:command :editor.clear.groovy
:origin editor
:info info
:create try-connect})]
(clients/send cl
:editor.clear.groovy info
:only editor))))
;; Command that allows a new keyboard bindable action for invoking the behaviour above
(cmd/command {:command :clear-bindings
:desc "Groovy: Clear bindings for current editor"
:exec (fn []
(when-let [ed (pool/last-active)]
(object/raise ed :on.clear.bindings)))})
// Wiring up the behaviour in groovy.behaviors
:editor.groovy [:lt.plugins.groovy/on-eval
:lt.plugins.groovy/on-eval.one
:lt.plugins.groovy/on-clear-bindings
:lt.plugins.groovy/groovy-res
:lt.plugins.groovy/groovy-err
[:lt.object/add-tag :watchable]]
// The command dispatch got a new command
case "editor.clear.groovy":
clientSessions.clear(currentClientId)
break;
(behavior ::on-eval
:desc "Groovy: Eval current editor"
:triggers #{:eval}
:reaction (fn [editor]
(object/raise groovy :eval! {:origin editor
:info (assoc (@editor :info)
:code (ed/->val editor)
:meta {:start 0, :end (ed/last-line editor)})})))
(behavior ::on-eval.one
:desc "Groovy: Eval current selection"
:triggers #{:eval.one}
:reaction (fn [editor]
(let [pos (ed/->cursor editor)
info (conj (:info @editor)
(if (ed/selection? editor)
{:code (ed/selection editor) :meta {:start (-> (ed/->cursor editor "start") :line)
:end (-> (ed/->cursor editor "end") :line)}}
{:pos pos :code (ed/line editor (:line pos)) :meta {:start (:line pos) :end (:line pos)}}))]
(object/raise groovy :eval! {:origin editor :info info}))))
(behavior ::eval!
:triggers #{:eval!}
:reaction (fn [this event]
(let [{:keys [info origin]} event
client (-> @origin :client :default)]
(notifos/working "Evaluating groovy...")
(clients/send (eval/get-client! {:command :editor.eval.groovy
:origin origin
:info info
:create try-connect})
:editor.eval.groovy info
:only origin))))
[89,
"editor.eval.groovy",
{"line-ending":"\n",
"name":"sample.groovy",
"type-name":"Groovy",
"path":"/Users/mrundberget/Library/Application Support/LightTable/plugins/Groovy/sample.groovy",
"mime":"text/x-groovy",
"tags":["editor.groovy"],
"code":"println \"hello\"",
"meta":{"start":22,"end":22}}]
ltClient.withStreams { input, output ->
try {
input.eachLine { line ->
def (currentClientId, command, data) = new JsonSlurper().parseText(line)
switch (command) {
case "client.close":
stop()
break
case "editor.eval.groovy":
evalGroovy(data, currentClientId)
break
default:
log "Invalid command: $command"
}
// ...
private void evalGroovy(data, currentClientId) {
def evalResult = scriptExecutor.execute(data.code)
def resultParams = [meta: data.meta]
if (evalResult.out) {
resultParams << [out: evalResult.out]
}
if(evalResult.exprValues) {
resultParams << [result: convertToClientVals(evalResult.exprValues)]
}
if (!evalResult.err) {
data = [currentClientId?.toInteger(), "groovy.res", resultParams]
} else {
data = [currentClientId?.toInteger(), "groovy.err", [ex: evalResult.err] + resultParams]
}
sendData data
}
[89,
"groovy.res",
{"meta":{"start":22,"end":23},"out":"hello\nmama\n","result":[{"line":1,"values":["null"]},{"line":2,"values":["null"]}]}]
(defn notify-of-results [editor res]
(doseq [ln (:result res)]
(let [lineNo (+ (:line ln) (-> res :meta :start) -1)]
(object/raise editor :editor.result (clojure.string/join " " (:values ln)) {:line lineNo :start-line lineNo}))))
(behavior ::groovy-res
:triggers #{:groovy.res}
:reaction (fn [editor res]
(notifos/done-working)
(when-let [o (:out res)] (.log js/console o))
(notify-of-results editor res)))
(defn notify-of-error [editor res]
(let [lineNo (+ (-> res :ex :line) (-> res :meta :start) -1)]
(object/raise editor :editor.exception (:ex res) {:line lineNo :start-line lineNo'})))
(behavior ::groovy-err
:triggers #{:groovy.err}
:reaction (fn [editor res]
(object/raise editor :groovy.res res)
(notify-of-error editor res)))
{:+ {:app [(:lt.objs.plugins/load-js ["codemirror/groovy.js", "groovy_compiled.js"])]
:clients []
:editor.groovy [:lt.plugins.groovy/on-eval
:lt.plugins.groovy/on-eval.one
:lt.plugins.groovy/groovy-res
:lt.plugins.groovy/groovy-err
[:lt.object/add-tag :watchable]]
:files [(:lt.objs.files/file-types
[{:name "Groovy" :exts [:groovy] :mime "text/x-groovy" :tags [:editor.groovy]}])]
:groovy.lang [:lt.plugins.groovy/eval!
:lt.plugins.groovy/connect]}}
(defn run-groovy[{:keys [path name client] :as info}]
(let [obj (object/create ::connecting-notifier info)
client-id (clients/->id client)
project-dir (files/parent path)]
(object/merge! client {:port tcp/port
:proc obj})
(notifos/working "Connecting..")
(proc/exec {:command binary-path
:args [tcp/port client-id project-dir]
:cwd plugin-dir
:env {"GROOVY_PATH" (files/join (files/parent path))}
:obj obj})))
(defn check-groovy[obj]
(assoc obj :groovy (or (::groovy-exe @groovy)
(.which shell "groovy"))))
(defn check-server[obj]
(assoc obj :groovy-server (files/exists? server-path)))
(defn handle-no-groovy [client]
(clients/rem! client)
(notifos/done-working)
(popup/popup! {:header "We couldn't find Groovy."
:body "In order to evaluate in Groovy files, Groovy must be installed and on your system PATH."
:buttons [{:label "Download Groovy"
:action (fn []
(platform/open "http://gvmtool.net/"))}
{:label "ok"}]}))
(defn notify [obj]
(let [{:keys [groovy path groovy-server client]} obj]
(cond
(or (not groovy) (empty? groovy)) (do (handle-no-groovy client))
:else (run-groovy obj))
obj))
(defn check-all [obj]
(-> obj
(check-groovy)
(check-server)
(notify)))
(defn try-connect [{:keys [info]}]
(.log js/console (str "try connect" info))
(let [path (:path info)
client (clients/client! :groovy.client)]
(check-all {:path path
:client client})
client))
(object/object* ::groovy-lang
:tags #{:groovy.lang})
(def groovy (object/create ::groovy-lang))
(scl/add-connector {:name "Groovy"
:desc "Select a directory to serve as the root of your groovy project... then again it might not be relevant..."
:connect (fn []
(dialogs/dir groovy :connect))})
(behavior ::connect
:triggers #{:connect}
:reaction (fn [this path]
(try-connect {:info {:path path}})))
import groovy.json.*
params = [
ltPort: args[0].toInteger(),
clientId: args[1].toInteger() // light table generated id for the client (connection)
]
logFile = new File("server.log")
def log(msg) {
logFile << "${new Date().format('dd.MM.yyyy mm:hh:sss')} - $msg\n"
}
client = null
try {
client = new Socket("127.0.0.1", params.ltPort)
} catch (Exception e) {
log "Could not connect to port: ${params.ltPort}"
throw e
}
def sendData(data) {
client << new JsonBuilder(data).toString() + "\n"
}
// ack to Light Table
sendData (
[
name: "Groovy",
"client-id": params.clientId,
dir: new File("").absolutePath,
commands: ["editor.eval.groovy"],
type: "groovy"
]
)
println "Connected" // tells lighttable we're good
client.withStreams {input, output ->
while(true) {
// insert code to listen for events from light table and respond to those (eval code etc)
}
}
(behavior ::on-out
:triggers #{:proc.out}
:reaction (fn [this data]
(let [out (.toString data)]
(object/update! this [:buffer] str out)
(if (> (.indexOf out "Connected") -1)
(do
(notifos/done-working)
(object/merge! this {:connected true}))
(object/update! this [:buffer] str data)))))
(behavior ::on-error
:triggers #{:proc.error}
:reaction (fn [this data]
(let [out (.toString data)]
(when-not (> (.indexOf (:buffer @this) "Connected") -1)
(object/update! this [:buffer] str data)
))
))
(behavior ::on-exit
:triggers #{:proc.exit}
:reaction (fn [this data]
;(object/update! this [:buffer] str data)
(when-not (:connected @this)
(notifos/done-working)
(popup/popup! {:header "We couldn't connect."
:body [:span "Looks like there was an issue trying to connect
to the project. Here's what we got:" [:pre (:buffer @this)]]
:buttons [{:label "close"}]})
(clients/rem! (:client @this)))
(proc/kill-all (:procs @this))
(object/destroy! this)
))
(object/object* ::connecting-notifier
:triggers []
:behaviors [::on-exit ::on-error ::on-out]
:init (fn [this client]
(object/merge! this {:client client :buffer ""})
nil))
{:+ {:app [(:lt.objs.plugins/load-js ["codemirror/groovy.js", "groovy_compiled.js"])]
:clients []
:editor.groovy []
:files [(:lt.objs.files/file-types
[{:name "Groovy" :exts [:groovy] :mime "text/x-groovy" :tags [:editor.groovy]}])]
:groovy.lang [:lt.plugins.groovy/connect]}}
{:+ {:app {
"ctrl-shift-t" [:tabset.new]
"ctrl-shift-left" [:tabs.prev]
;; etc
}
:editor {"alt-w" [:editor.watch.watch-selection]
"alt-shift-w" [:editor.watch.unwatch]
"ctrl-k" [:editor.kill-line]
;; etc
}}}
(ns repl
(:require [mycompany-com.web :refer [app]]
[ring.adapter.jetty]))
(defn start-server []
(defonce server (ring.adapter.jetty/run-jetty #'app {:port 3000 :join? false}))
(.start server))
(defn stop-server []
(.stop server))