Skip to content

Instantly share code, notes, and snippets.

@schuster-rainer
Created July 12, 2012 22:16
Show Gist options
  • Save schuster-rainer/3101452 to your computer and use it in GitHub Desktop.
Save schuster-rainer/3101452 to your computer and use it in GitHub Desktop.
Clojure.Compile a ClojureCLR script with gen-class and a WPF UI into an executable console app
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="My WPF UI" Height="300" Width="300">
<StackPanel Margin="5">
<StackPanel>
<Label Content="Prename:" />
<TextBox x:Name="preName" MinWidth="50"/>
</StackPanel>
<StackPanel>
<Label Content="Surename:" />
<TextBlock x:Name="sureName" />
</StackPanel>
</StackPanel>
</Window>
; ClojureCLR 1.4
; to compile the wpfapp.clj into an executable run: "Clojure.Compile.exe wpfapp"
; see also: http://clojureclr.blogspot.de/2012/01/compiling-and-loading-in-clojureclr.html
; be aware of the namespace and the filename! atm it should stick to exactly the same name
(assembly-load-with-partial-name "PresentationFramework")
(assembly-load-with-partial-name "PresentationCore")
(assembly-load-with-partial-name "WindowsBase")
(assembly-load-with-partial-name "System.Xml")
(ns wpfapp
(:import (System.Windows Application Window))
(:import (System.Windows.Threading Dispatcher DispatcherPriority))
(:import (System.Threading ApartmentState ThreadStart Thread AutoResetEvent))
(:import (System.IO File))
(:import (System.Xml XmlReader))
(:import (System.Windows.Markup XamlReader))
(:import (System))
(:gen-class))
(defn run[& args]
(let [app (new Application)
win (-> "MyWpfUI.xaml"
File/OpenText
XmlReader/Create
XamlReader/Load)]
(pr "running app!")
(.Run app win)))
; STAThreadAttribute should instrcut the compiler to run the main thread
; as STA. WPF and COM interop needs STA. For further details read
; STAThreadAttribute: http://msdn.microsoft.com/en-us/library/ms680112(v=vs.85).aspx
; STA: http://msdn.microsoft.com/en-us/library/ms680112(v=vs.85).aspx
; For Clojure.Compile.exe it doesn't work with gen-class and -main.
; therefore I'm creating a new thread setting it to STA as workaround
; atm we're only able to run a console app!
; To be a first class .NET citizen the Clojure.Compile.exe
; should have options like C#:
; - Console Application
; - Class Library
; - Windows Application
(defn sta-thread [func]
(let [delegate (gen-delegate ThreadStart [] (func))
thread (doto (new Thread delegate)
(.SetApartmentState ApartmentState/STA)
(.Start))]
thread))
(defn -main [& args]
(let [uithread (sta-thread (partial run args))]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment