1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
(ns glimmer-cosmic.core
"The libcosmic backend for glimmer. Requiring this namespace installs it:
(ns myapp
(:require [glimmer.core :as ui]
[glimmer-cosmic.core])) ; installs this backend
(defn -main [& _] (ui/run my-app :title \"myapp\"))
The tree half is glimmer-vidya's: node handles in a Rust arena, props written
across, handlers kept here and found by node id when an event comes back.
The loop half is inverted. libcosmic will not be driven a frame at a time —
it takes the main thread and keeps it until the window closes — so `run`
blocks the main thread there and the reconciler lives on a worker. The worker
is \"the UI thread\" as far as glimmer is concerned: `schedule` queues onto it,
handlers run on it, and at the end of each pass it commits, which is the only
moment libcosmic sees what changed."
(:require [glimmer.backend :as b]
[glimmer-cosmic.ffi :as ffi]))
;; Node id -> the :on-* props that node was last rendered with.
(defonce ^:private handlers (atom {}))
;; Work posted from other threads, run on the worker at the top of a pass.
(defonce ^:private pending (atom []))
(defonce ^:private quit-requested (atom false))
;; --- props -------------------------------------------------------------------
(def ^:private tag-orientation {:hbox "horizontal" :vbox "vertical"})
(defn- handler-key? [k]
(let [s (name k)]
(and (> (count s) 3) (= "on-" (subs s 0 3)))))
(defn- set-prop! [node k v]
(let [key (name k)]
(cond
(nil? v) nil
(true? v) (ffi/node-set-bool! node key true)
(false? v) (ffi/node-set-bool! node key false)
(number? v) (ffi/node-set-num! node key (double v))
(string? v) (ffi/node-set-str! node key v)
(keyword? v) (ffi/node-set-str! node key (name v))
:else (ffi/node-set-str! node key (str v)))))
(defn- write-props!
"Replace a node's props with `props`, cleared first so a prop a re-render
stops setting is gone — and so the value libcosmic wrote back when someone
typed is overwritten by the component's own state."
[node tag props]
(ffi/node-clear-props! node)
(when-let [orientation (tag-orientation tag)]
(when-not (contains? props :orientation)
(ffi/node-set-str! node "orientation" orientation)))
(doseq [[k v] props]
(when-not (handler-key? k)
(set-prop! node k v)))
(swap! handlers assoc node
(reduce (fn [acc [k v]]
(if (and (handler-key? k) (fn? v)) (assoc acc k v) acc))
{}
props))
nil)
(defn- forget-dead-handlers! []
(swap! handlers
(fn [m]
(reduce (fn [acc [id hs]]
(if (ffi/node-exists? id) (assoc acc id hs) acc))
{}
m)))
nil)
;; --- the backend operations --------------------------------------------------
(defn- create! [tag props]
(let [node (ffi/node-new (name tag))]
(when (zero? node)
(throw (ex-info "jolt-cosmic could not allocate a node" {:tag tag})))
(write-props! node tag props)
node))
(defn- apply-props! [tag node props] (write-props! node tag props))
(defn- append-child! [_parent-tag parent child]
(ffi/node-append! parent child)
nil)
(defn- remove-child! [_parent-tag parent child]
(ffi/node-remove! parent child)
(forget-dead-handlers!)
nil)
(defn- replace-child! [_parent-tag parent old-child new-child]
(ffi/node-replace! parent old-child new-child)
(forget-dead-handlers!)
nil)
(defn- reorder-child! [_parent-tag parent child sibling]
(ffi/node-insert-after! parent child (or sibling 0))
nil)
;; --- the worker --------------------------------------------------------------
(defn- schedule
"glimmer.backend's :schedule. Queues `work` for the worker and wakes it, so a
`swap!` from anywhere re-renders on the next pass rather than the next
timeout."
[work]
(swap! pending conj work)
(ffi/wake!)
nil)
(defn- drain! []
(loop []
(let [q @pending]
(when (seq q)
(if (compare-and-set! pending q [])
(doseq [f q] (f))
(recur))))))
;; --- timers ------------------------------------------------------------------
(defonce ^:private timers (atom {:next-id 0 :entries {}}))
(defn- now-ms [] (System/currentTimeMillis))
(defn- add-timer! [ms every? f]
(let [id (:next-id (swap! timers update :next-id inc))]
(swap! timers assoc-in [:entries id]
{:due (+ (now-ms) ms) :every (when every? ms) :f f})
(ffi/wake!)
id))
(defn after!
"Run `f` on the worker in about `ms` milliseconds. Returns an id for
`cancel!`."
[ms f] (add-timer! ms false f))
(defn every!
"Run `f` on the worker about every `ms` milliseconds until cancelled."
[ms f] (add-timer! ms true f))
(defn cancel! [id] (swap! timers update :entries dissoc id) nil)
(defn cancel-all! [] (swap! timers assoc :entries {}) nil)
(defn- pump-timers! []
(let [t (now-ms)
due (reduce (fn [acc [id e]] (if (<= (:due e) t) (conj acc [id e]) acc))
[]
(:entries @timers))]
(doseq [[id e] due]
(if-let [period (:every e)]
(swap! timers assoc-in [:entries id :due] (+ t period))
(swap! timers update :entries dissoc id))
((:f e)))
nil))
(defn- next-timeout
"How long the worker may sleep: until the nearest timer, capped so a quit or
an auto-quit deadline is noticed within a quarter second."
[]
(let [dues (map :due (vals (:entries @timers)))]
(if (seq dues)
(max 0 (min 250 (- (apply min dues) (now-ms))))
250)))
;; --- events ------------------------------------------------------------------
(defn- dispatch-events! []
(loop []
(when (ffi/poll-event!)
(let [node (ffi/event-node)
kind (ffi/event-name)
hs (get @handlers node)]
(case kind
"click" (when-let [f (:on-click hs)] (f))
"toggled" (when-let [f (:on-toggled hs)] (f))
"change" (when-let [f (:on-change hs)] (f (ffi/event-text)))
"activate" (when-let [f (:on-activate hs)] (f))
;; The two edges of a hover, as glimmer-vidya sends them: once when
;; the pointer comes onto the widget and once when it leaves.
"hover" (when-let [f (:on-hover hs)] (f))
"unhover" (when-let [f (:on-unhover hs)] (f))
;; Ctrl+V on a clipboard with no text on it. What is on it instead is
;; the caller's to find out, with `clipboard-image-png!`.
"paste-empty" (when-let [f (:on-paste-empty hs)] (f))
nil))
(recur))))
;; --- running -----------------------------------------------------------------
(defn- clear-children! [node]
(loop []
(when (pos? (ffi/node-child-count node))
(ffi/node-remove! node (ffi/node-child-at node 0))
(recur)))
(forget-dead-handlers!)
nil)
(defn quit!
"Close the window; `run` returns once libcosmic has."
[]
(reset! quit-requested true)
(ffi/quit!)
nil)
(defn- work-loop
"The worker: sleep until something happens, then run queued work, handlers
and timers, and publish whatever they changed in one commit."
[started auto-quit-ms]
(try
(loop []
(ffi/wait! (next-timeout))
(drain!)
(dispatch-events!)
(pump-timers!)
(ffi/commit!)
(when (and auto-quit-ms (>= (- (now-ms) started) auto-quit-ms))
(quit!))
(when-not (ffi/should-close?)
(recur)))
(finally
;; A handler that throws takes the window with it, rather than leaving
;; one on screen that nothing is listening to.
(ffi/quit!))))
(defn- run!
"glimmer.backend's :run. Mounts the root component, starts the worker, and
blocks the calling thread — which must be the main thread — in libcosmic
until the window closes or `quit!` is called.
Options (on top of glimmer's own :title :width :height :auto-quit-ms):
:mode :system (default), :dark or :light"
[opts mount-root!]
(let [{:keys [title width height mode auto-quit-ms]
:or {title "glimmer" width 900 height 640}} opts
root (ffi/tree-root)
started (now-ms)]
(reset! quit-requested false)
;; Mounted here, before the loop, so it reconciles inline; the first commit
;; is what libcosmic opens with.
(clear-children! root)
(mount-root! root :window)
(ffi/commit!)
(reset! b/loop-running? true)
(let [worker (future (work-loop started auto-quit-ms))
status (ffi/run! width height title
(case mode
:dark ffi/dark-mode
:light ffi/light-mode
ffi/system-mode))]
(try
;; Rethrows whatever ended the worker, on the thread that called run.
@worker
(finally
(reset! b/loop-running? false)
(cancel-all!)
(reset! handlers {})))
(when-not (zero? status)
(throw (ex-info "jolt-cosmic's window did not run cleanly"
{:status status}))))))
;; --- looking at what was rendered --------------------------------------------
(defn dump-str
"The tree as it is in the arena — after the reconciler, before any commit —
as hiccup text."
([] (dump-str 0))
([node] (ffi/tree-dump node)))
(defn dump
([] (dump 0))
([node] (read-string (dump-str node))))
(defn dump!
([] (dump! 0))
([node] (println (dump-str node)) nil))
;; --- the backend -------------------------------------------------------------
;; --- the window and the desktop ------------------------------------------------
(defn window-size
"The window's size in points, [width height]: the size asked for until it
has opened, and what libcosmic reports after that."
[]
[(ffi/window-width) (ffi/window-height)])
(defn pick-image!
"Open the desktop's picture chooser. True when it was asked for; the choice
is collected with `picked-image!`, since the chooser answers when the person
using it does."
[]
(ffi/pick-image!))
(defn picked-image!
"Write the chosen picture to `path` as PNG. True once, when one was chosen."
[path]
(ffi/picked-image! path))
(defn clipboard-image-png!
"Write the picture on the clipboard to `path` as PNG. True when there was
one — as found by the Ctrl+V that fired the `:entry`'s `:on-paste-empty`,
since libcosmic reads its clipboard on its own thread, not on demand."
[path]
(ffi/clipboard-image-png! path))
(def backend
{:name :cosmic
:create! create!
:apply-props! apply-props!
:append-child! append-child!
:remove-child! remove-child!
:replace-child! replace-child!
:reorder-child! reorder-child!
:schedule schedule
:run run!})
(defn install! [] (b/register! backend) nil)
(defonce ^:private installed (do (install!) true))
|