@kairotic/app 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,862 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 1 of 12: work
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (ns user (:require [clojure.string :as str] [clojure.set] [kairotic.score :as sc] [kairotic.canvas :as cv]
6
+ [kairotic.components :as comp] [kairotic.api :as api] [kairotic.code :as cbox] [kairotic.faust] [kairotic.library :as lib] [kairotic.help :as hlp] [kairotic.mt :as mt] [kairotic.quantize :as qz] [kairotic.tempo :as tm] [kairotic.spell :as sp] [kairotic.treecanvas :as tc] [kairotic.mtboxes :as mtb] [kairotic.hiccup :as hic] [kairotic.assistant :as ai] [kairotic.engine :as eng] [kairotic.presets :as pst] [kairotic.release :as rel] [kairotic.sounds :as snd] [kairotic.talk :as tk]
7
+ [kairotic.shapes :as shp] [kairotic.signal] [kairotic.links :as links] [clojure.edn]))
8
+
9
+ (def version "0.2.0-alpha")
10
+
11
+ ;; kairotic.code is aliased `cbox` (not `code`) because `code` is a REPL command defined below.
12
+
13
+ ;; ───────────────────────── model of the work ─────────────────────────
14
+
15
+ (def empty-patch {:boxes (sorted-map) :lines []})
16
+
17
+ ;; Box classes are components registered in kairotic.components: their ports, their view,
18
+ ;; their data with its own history, their behaviour with messages and their audio all come from there.
19
+
20
+ (declare open-work-file! view-instances inline-lines on-lines render-lines! line-name switch-line! check-ref-text! ref-badge ref-warning resolve-ref refs-in followed-fronts open-ref es? docs open-work! show-help! refresh-help! tsel-piece-id refill-data! forget-box! update-trust-bar! render-askbar! present-what! url-with copy-text!) ; the Help tab (Study 18), defined further down
21
+ (def klass comp/klass)
22
+ (defn box-def [b] (comp/lookup (klass (:text b))))
23
+ ;; how a box is shown: the view it chose among those of its class (a tree as a score or a roll, a freqt
24
+ ;; as a canvas or a score: discussion #30), or the :display of its class
25
+ (defn display-of "How a box is drawn (a tree's roll is drawn as a canvas)." [b] (comp/drawn-as b))
26
+ (defn view-of "The view a box is shown in, by its name (:score, :roll, :canvas…)." [b] (comp/shown-as b))
27
+ (def own-view? comp/own-view?)
28
+
29
+ (defn io
30
+ "Inlets and outlets of a box (or of a bare text)."
31
+ [b] (comp/io (if (string? b) {:text b} b)))
32
+
33
+ ;; boxes with a graphic buffer inside: score is another view of the same buffer
34
+ (def music-classes #{"canvas" "freqt"})
35
+ ;; boxes that act when pressed (they are moved by their left grip)
36
+ (def action-classes #{"number" "msg" "bang"})
37
+ (def kairos-classes #{"state" "transition" "instruction" "region"})
38
+
39
+ (defn prune-lines
40
+ "Removes the lines that no longer fit the ports of their boxes. Boxes with computed ports
41
+ (such as faust~, which depends on its compilation) are not pruned: so the history does not depend
42
+ on when each tab finished compiling."
43
+ [p]
44
+ (let [bx (:boxes p)
45
+ ok? (fn [[a o b i]]
46
+ (and (contains? bx a) (contains? bx b)
47
+ (or (comp/dynamic? (get bx a)) (< o (second (io (get bx a)))))
48
+ (or (comp/dynamic? (get bx b)) (< i (first (io (get bx b)))))))]
49
+ (update p :lines (fn [ls] (vec (filter ok? ls))))))
50
+
51
+ ;; ───── recipes (discussion #17) ─────
52
+ ;; A buffer filled from a tree with (keep! :bN) keeps, beside its :data, the recipe that made it:
53
+ ;; {:tree the tree as it arrived (measures, tuplets, dynamics…), :calls the boxes and lines upstream as
54
+ ;; code, :from the box it came from, :stale true once the buffer has been changed since}. The recipe is
55
+ ;; not part of the buffer: the buffer stays plain data, and the recipe says where it came from.
56
+
57
+ (defn sane-recipe [r]
58
+ (when (and (map? r) (or (vector? (:tree r)) (string? (:tree r))))
59
+ (cond-> {:tree (:tree r)}
60
+ (string? (:calls r)) (assoc :calls (:calls r))
61
+ (keyword? (:from r)) (assoc :from (:from r))
62
+ (true? (:stale r)) (assoc :stale true))))
63
+
64
+
65
+ ;; ───── layers: annotations and projections over or under the boxes (Study 26) ─────
66
+ ;; A patch can have layers, drawn over or under its boxes, in the patch view, in the presentation or in
67
+ ;; both. A layer holds marks — a line drawn by hand, an arrow, a text — whose points are anchored to a box
68
+ ;; ([:b4 dx dy], from its top-left corner: they follow it when it moves) or to the paper ([:patch x y]),
69
+ ;; and projections: the view of a box drawn again, at another size, somewhere on the paper.
70
+ ;; :layers {:notes {:z :over :show #{:patch :present}}}
71
+ ;; :marks {:a1 {:layer :notes :kind :line :pts [[:b4 -10 20] [:b7 0 -8] …]}
72
+ ;; :a2 {:layer :notes :kind :text :at [:patch 400 60] :txt "enters the clarinet"}}
73
+ ;; :projections {:b9 {:layer :viz :rect [x y w h]}}
74
+ ;; A mark anchored to a box that is deleted stays where it was, anchored to the paper.
75
+
76
+ (def layer-default {:z :over :show #{:patch :present}})
77
+
78
+ (defn sane-layer [l]
79
+ (let [l (if (map? l) l {})
80
+ show (set (filter #{:patch :present} (if (coll? (:show l)) (:show l) [])))]
81
+ {:z (if (= :under (:z l)) :under :over)
82
+ :show (if (and (coll? (:show l)) (contains? l :show)) show (:show layer-default))}))
83
+
84
+ (defn sane-anchor [a]
85
+ (when (and (sequential? a) (= 3 (count a)) (keyword? (first a)) (number? (second a)) (number? (nth a 2))
86
+ (js/isFinite (second a)) (js/isFinite (nth a 2)))
87
+ [(first a) (/ (js/Math.round (* 10 (second a))) 10) (/ (js/Math.round (* 10 (nth a 2))) 10)]))
88
+
89
+ (defn sane-mark [m]
90
+ (when (and (map? m) (keyword? (:layer m)))
91
+ (case (:kind m)
92
+ (:line :arrow) (let [ps (vec (keep sane-anchor (take 400 (:pts m))))]
93
+ (when (>= (count ps) 2) {:layer (:layer m) :kind (:kind m) :pts (if (= :arrow (:kind m)) [(first ps) (peek ps)] ps)}))
94
+ :text (when-let [a (sane-anchor (:at m))]
95
+ (let [t (str (:txt m))] (when (seq t) {:layer (:layer m) :kind :text :at a :txt (subs t 0 (min 200 (count t)))})))
96
+ ;; a small picture (a frame kept from a room's camera, #135): a data URL of an image, at most 48 KB
97
+ :image (when-let [a (sane-anchor (:at m))]
98
+ (let [src (str (:src m)) w (:w m) h (:h m)]
99
+ (when (and (re-matches #"data:image/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+" src) (<= (count src) 48000)
100
+ (number? w) (number? h) (< 0 w 1000) (< 0 h 1000))
101
+ {:layer (:layer m) :kind :image :at a :src src :w (js/Math.round w) :h (js/Math.round h)})))
102
+ nil)))
103
+
104
+ (defn sane-projection [pr]
105
+ (let [[x y w h] (:rect pr)]
106
+ (when (and (map? pr) (keyword? (:layer pr)) (every? number? [x y w h]))
107
+ {:layer (:layer pr) :rect [(js/Math.round x) (js/Math.round y) (max 40 (min 2400 (js/Math.round w))) (max 30 (min 2400 (js/Math.round h)))]})))
108
+
109
+ (defn with-layers
110
+ "The layers, marks and projections of x, normalized, into patch p (only those it has)."
111
+ [p x]
112
+ (let [ls (into {} (for [[k l] (:layers x) :when (keyword? k)] [k (sane-layer l)]))
113
+ ms (into (sorted-map) (for [[k m] (:marks x) :let [m (sane-mark m)] :when (and (keyword? k) m)] [k m]))
114
+ ps (into (sorted-map) (for [[k pr] (:projections x) :let [pr (sane-projection pr)] :when (and (keyword? k) pr)] [k pr]))]
115
+ (cond-> p (seq ls) (assoc :layers ls) (seq ms) (assoc :marks ms) (seq ps) (assoc :projections ps))))
116
+
117
+ (defn ensure-layer [p id] (if (get-in p [:layers id]) p (assoc-in p [:layers id] layer-default)))
118
+
119
+ (defn unanchor
120
+ "The marks anchored to box id, with those points on the paper where they were (the box is going)."
121
+ [p id]
122
+ (let [b (get-in p [:boxes id])
123
+ fix (fn [[a x y :as pt]] (if (and b (= a id)) [:patch (+ (:x b) x) (+ (:y b) y)] pt))]
124
+ (if-not (:marks p)
125
+ p
126
+ (update p :marks (fn [ms] (into (sorted-map) (for [[k m] ms]
127
+ [k (cond-> m (:pts m) (update :pts (fn [ps] (mapv fix ps)))
128
+ (:at m) (update :at fix))])))))))
129
+
130
+ (defn drop-empty [p k] (if (empty? (get p k)) (dissoc p k) p))
131
+
132
+ (defn shift-mark
133
+ "Mark m moved by dx dy: each point keeps its anchor (a box or the paper) and moves from it."
134
+ [m dx dy]
135
+ (let [f (fn [[a x y]] (sane-anchor [a (+ x dx) (+ y dy)]))]
136
+ (cond-> m (:pts m) (update :pts (fn [ps] (mapv f ps))) (:at m) (update :at f))))
137
+
138
+ (defn set-point
139
+ "Mark m with its point i (of a line or an arrow) anchored as a, now [anchor dx dy]."
140
+ [m i a]
141
+ (if (and (:pts m) (< -1 i (count (:pts m))) (sane-anchor a)) (assoc-in m [:pts i] (sane-anchor a)) m))
142
+
143
+ (defn sane-patch
144
+ "Events may come from other people: whatever arrives is normalized."
145
+ [x]
146
+ (if (map? x)
147
+ (with-layers
148
+ {:boxes (into (sorted-map)
149
+ (for [[k b0] (:boxes x) :when (and (keyword? k) (map? b0))
150
+ :let [b (comp/upgrade-box b0)]]
151
+ [k (cond-> {:text (str (:text b)) :x (or (:x b) 0) :y (or (:y b) 0)}
152
+ (and (vector? (:present b)) (= 2 (count (:present b))) (every? number? (:present b)))
153
+ (assoc :present (:present b))
154
+ (keyword? (:view b)) (assoc :view (:view b))
155
+ ;; a `patch @name` pinned to a point of its line (#117)
156
+ (and (vector? (:pin b)) (= 2 (count (:pin b))) (string? (first (:pin b))) (number? (second (:pin b))))
157
+ (assoc :pin (:pin b))
158
+ (and (vector? (:size b)) (= 2 (count (:size b))) (every? number? (:size b)))
159
+ (assoc :size (:size b))
160
+ (and (map? (:data b)) (comp/model-of b)) (assoc :data ((:load (comp/model-of b)) (:data b)))
161
+ (sane-recipe (:recipe b)) (assoc :recipe (sane-recipe (:recipe b))))]))
162
+ :lines (vec (filter (fn [l] (and (vector? l) (= 4 (count l)))) (:lines x)))}
163
+ x)
164
+ empty-patch))
165
+
166
+ (defn step [p [op & args]]
167
+ (case op
168
+ ;; a box written with the name of a class that became a view of another one (score → freqt) is read
169
+ ;; as that class, in that view: older works and histories keep working
170
+ :box (let [[id text x y] args] (if (keyword? id) (assoc-in p [:boxes id] (comp/upgrade-box {:text (str text) :x x :y y})) p))
171
+ :text (let [[id text] args]
172
+ (if (get-in p [:boxes id])
173
+ (prune-lines (update-in p [:boxes id] (fn [b] (comp/upgrade-box (assoc b :text (str text))))))
174
+ p))
175
+ :move (let [[id x y] args] (if (get-in p [:boxes id]) (update-in p [:boxes id] assoc :x x :y y) p))
176
+ ;; where a box appears in presentation (and in the panel of the sub-patch it is in), or nil
177
+ :present (let [[id x y] args]
178
+ (cond (not (get-in p [:boxes id])) p
179
+ (and (number? x) (number? y)) (assoc-in p [:boxes id :present] [x y])
180
+ :else (update-in p [:boxes id] dissoc :present)))
181
+ ;; how a box is shown, among the views of its class (discussion #30), or nil for its default
182
+ :view (let [[id k] args]
183
+ (cond (not (get-in p [:boxes id])) p
184
+ (keyword? k) (assoc-in p [:boxes id :view] k)
185
+ :else (update-in p [:boxes id] dissoc :view)))
186
+ ;; [:pin :b3 [node n]]: a `patch @name` reads its line at that point (#117); nil follows its front again
187
+ :pin (let [[id pos] args]
188
+ (cond (not (get-in p [:boxes id])) p
189
+ (and (vector? pos) (= 2 (count pos)) (string? (first pos)) (number? (second pos)))
190
+ (assoc-in p [:boxes id :pin] (vec pos))
191
+ :else (update-in p [:boxes id] dissoc :pin)))
192
+ ;; the size of a box drawn with a size of its own (a canvas, a freqt, a score: issue #40), or nil for its default
193
+ :size (let [[id w h] args]
194
+ (cond (not (get-in p [:boxes id])) p
195
+ (and (number? w) (number? h)) (assoc-in p [:boxes id :size] [w h])
196
+ :else (update-in p [:boxes id] dissoc :size)))
197
+ :connect (let [l (vec args)] (if (some #{l} (:lines p)) p (update p :lines conj l)))
198
+ :disconnect (let [l (vec args)] (update p :lines (fn [ls] (vec (remove #{l} ls)))))
199
+ :delete (let [[id] args]
200
+ (-> p (unanchor id)
201
+ (update :boxes dissoc id)
202
+ (update :lines (fn [ls] (vec (remove (fn [[a _ b _]] (or (= a id) (= b id))) ls))))
203
+ (update :projections dissoc id) (drop-empty :projections)))
204
+ ;; [:layer :notes {:z :under :show #{:present}}] · [:layer :notes nil] removes it with its marks and projections
205
+ :layer (let [[id l] args]
206
+ (cond (not (keyword? id)) p
207
+ (nil? l) (-> p (update :layers dissoc id)
208
+ (update :marks (fn [ms] (into (sorted-map) (remove (fn [[_ m]] (= id (:layer m))) ms))))
209
+ (update :projections (fn [ps] (into (sorted-map) (remove (fn [[_ pr]] (= id (:layer pr))) ps))))
210
+ (drop-empty :layers) (drop-empty :marks) (drop-empty :projections))
211
+ :else (assoc-in p [:layers id] (sane-layer l))))
212
+ ;; [:annot :a1 {:layer :notes :kind :line :pts […]}] (its layer is made if missing) · [:annot :a1 nil] erases it
213
+ ;; (not [:mark …]: that one is a point of the history, a snapshot or a take)
214
+ :annot (let [[id m] args]
215
+ (cond (not (keyword? id)) p
216
+ (nil? m) (-> p (update :marks dissoc id) (drop-empty :marks))
217
+ :else (if-let [m (sane-mark m)]
218
+ (-> p (ensure-layer (:layer m)) (update :marks (fnil assoc (sorted-map)) id m))
219
+ p)))
220
+ ;; [:project :b9 {:layer :viz :rect [x y w h]}] · [:project :b9 nil]
221
+ :project (let [[id pr] args]
222
+ (cond (not (get-in p [:boxes id])) (if (nil? pr) (-> p (update :projections dissoc id) (drop-empty :projections)) p)
223
+ (nil? pr) (-> p (update :projections dissoc id) (drop-empty :projections))
224
+ :else (if-let [pr (sane-projection pr)]
225
+ (-> p (ensure-layer (:layer pr)) (update :projections (fnil assoc (sorted-map)) id pr))
226
+ p)))
227
+ ;; event addressed to the data of a box, interpreted by its component:
228
+ ;; [:in :b2 [:stroke :t1 [[0 440] [1 440]]]] · [:in :b7 [:source "process = …;"]]
229
+ :in (let [[id ev] args dd (comp/model-of (get-in p [:boxes id]))]
230
+ (if (and dd (vector? ev))
231
+ (let [d0 (get-in p [:boxes id :data])
232
+ d1 ((:step dd) (or d0 (:empty dd)) ev)]
233
+ (cond-> (assoc-in p [:boxes id :data] d1)
234
+ ;; the buffer changed after it was kept: its recipe no longer made it
235
+ (and (get-in p [:boxes id :recipe]) (not= d0 d1)) (assoc-in [:boxes id :recipe :stale] true)))
236
+ p))
237
+ ;; [:kept :b5 data recipe]: a buffer written from a tree, with the recipe that made it, as one event
238
+ :kept (let [[id data r] args b (get-in p [:boxes id]) dd (comp/model-of b) r (sane-recipe r)]
239
+ (if (and dd (map? data) r)
240
+ (-> p (assoc-in [:boxes id :data] ((:load dd) data))
241
+ (assoc-in [:boxes id :recipe] (dissoc r :stale)))
242
+ p))
243
+ ;; [:recipe :b5 r] sets the recipe of a box (as the code of a work writes it); nil removes it
244
+ :recipe (let [[id r] args]
245
+ (cond (not (get-in p [:boxes id])) p
246
+ (sane-recipe r) (assoc-in p [:boxes id :recipe] (sane-recipe r))
247
+ :else (update-in p [:boxes id] dissoc :recipe)))
248
+ ;; [:data :b5 d]: the whole data of a box (a release, points forgotten: issue #45), nil to empty it
249
+ :data (let [[id d] args b (get-in p [:boxes id]) dd (comp/model-of b)]
250
+ (cond (not b) p
251
+ (and dd (map? d)) (assoc-in p [:boxes id :data] ((:load dd) d))
252
+ ;; a class not defined yet (a package still loading): its data as it was written
253
+ (map? d) (assoc-in p [:boxes id :data] d)
254
+ (nil? d) (update-in p [:boxes id] dissoc :data)
255
+ :else p))
256
+ ;; [:batch [ev …]]: several changes as one event of the history (a preset recalled: issue #35)
257
+ :batch (let [[evs] args] (if (sequential? evs) (reduce step p (filter vector? evs)) p))
258
+ :load (sane-patch (first args))
259
+ :clear empty-patch
260
+ p))
261
+
262
+ ;; ───────────────────────── EDN ⇄ JSON encoding ─────────────────────────
263
+ ;; db stores JSON; keywords, names (symbols) and maps are tagged so they come back as EDN without evaluating anything.
264
+
265
+ (defn enc [x]
266
+ (cond (keyword? x) {"k" (if (namespace x) (str (namespace x) "/" (name x)) (name x))}
267
+ ;; a name (a msg sends inc, e4, 6/5 as names): its whole text, tagged like a keyword
268
+ (symbol? x) {"y" (str x)}
269
+ (map? x) {"m" (mapv (fn [[k v]] [(enc k) (enc v)]) x)}
270
+ ;; a set (the views a layer is shown in) travels as a list: whoever reads it makes it a set again
271
+ (or (sequential? x) (set? x)) (mapv enc x)
272
+ :else x))
273
+
274
+ (defn dec* [x]
275
+ (cond (map? x) (cond (contains? x "k") (keyword (str (get x "k")))
276
+ (contains? x "y") (symbol (str (get x "y")))
277
+ (contains? x "m") (into {} (for [kv (get x "m") :when (and (sequential? kv) (= 2 (count kv)))]
278
+ [(dec* (first kv)) (dec* (second kv))]))
279
+ :else nil)
280
+ (sequential? x) (mapv dec* x)
281
+ :else x))
282
+
283
+ ;; ───────────────────────── history: a tree of segments ─────────────────────────
284
+ ;; node = segment of consecutive events by one person: {:id :parent :at :author :t :events}
285
+ ;; position = [node-id n] = after the first n events of that node.
286
+ ;;
287
+ ;; A work is a project of lines (discussion #117, phase 1): independent histories, each a whole tree of its
288
+ ;; own, shown as tabs above the patch. Their segments live in the same collection as always, each with the
289
+ ;; line it belongs to (:line, nil for the main line), so a work without lines is what it always was. :nodes
290
+ ;; holds the segments of the line on screen, and everything that reads the history reads only that line;
291
+ ;; :other holds the segments of the other lines, by line id, until their tab is chosen.
292
+
293
+ (def max-events 64)
294
+
295
+ (defonce hist (atom {:nodes {} :other {} :loaded false :mode :connecting :writable false}))
296
+
297
+ ;; the lines of the open work: their names (in <work>/lines, one document per line), which one is on screen,
298
+ ;; and where each one was left (its tab remembers its point of the history)
299
+ ;; {:active "main" :index {"main" {:name "main" :created 0} "Xk3…" {:name "sketch" :created … :archived false}}
300
+ ;; :pos {"Xk3…" [node n]}}
301
+ (def main-line "main")
302
+ (defonce line-state (atom {:active main-line :index {} :pos {}}))
303
+ (defn active-line [] (:active @line-state))
304
+ (defn on-main-line? [] (= main-line (active-line)))
305
+ (defonce world (atom {:pos nil :auto true :prev-pos nil :jumped-at 0}))
306
+ (defonce me (atom {:id nil}))
307
+ (defonce peers (atom []))
308
+ (defonce profiles (atom {}))
309
+ (defonce scratch (atom nil))
310
+ (defonce cache (atom {}))
311
+ (defonce dbref (atom nil))
312
+ (defonce roomref (atom nil))
313
+ (defonce userref (atom nil))
314
+ (defonce settings (atom {:simul-ms 1500}))
315
+
316
+ ;; a session = a tab; it survives reloads of that tab
317
+ (def session-id
318
+ (or (try (.getItem js/sessionStorage "kairotic-session") (catch :default _ nil))
319
+ (let [s (str "s" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36))]
320
+ (try (.setItem js/sessionStorage "kairotic-session" s) (catch :default _ nil))
321
+ s)))
322
+
323
+ (defn my-author [] (or (:id @me) "local"))
324
+ (defn node [nid] (get-in @hist [:nodes nid]))
325
+ (defn node-session [n] (or (:session n) (:author n)))
326
+
327
+ (defn norm
328
+ "A position at the start of a child node is the same as its branching point."
329
+ [pos]
330
+ (loop [[nid idx :as pos] pos guard 0]
331
+ (let [n (node nid)]
332
+ (cond (or (nil? pos) (nil? n) (> guard 512)) pos
333
+ (and (zero? idx) (:parent n) (node (:parent n))) (recur [(:parent n) (:at n)] (inc guard))
334
+ :else [nid (max 0 (min idx (count (:events n))))]))))
335
+
336
+ (defn patch-at
337
+ ([pos] (patch-at pos 0))
338
+ ([pos depth]
339
+ (if (or (nil? pos) (> depth 512))
340
+ empty-patch
341
+ (or (get @cache pos)
342
+ (let [[nid idx] pos n (node nid)]
343
+ (if (nil? n)
344
+ empty-patch
345
+ (let [base (if (and (:parent n) (node (:parent n))) (patch-at [(:parent n) (:at n)] (inc depth)) empty-patch)
346
+ p (reduce step base (take idx (:events n)))]
347
+ (swap! cache assoc pos p)
348
+ p)))))))
349
+
350
+ ;; ───── where the commands act: the work, or a sub-patch inside it ─────
351
+ ;; view-path is the sub-patch on screen ([] = the work, [:b5] = inside :b5 …); (inside :b5 …) adds to it
352
+ ;; while its body runs. Commands read (current) and their events are wrapped as [:in :b5 event].
353
+
354
+ ;; ───── Perform (issue #5): a time of its own to rehearse, try and improvise with the work ─────
355
+ ;; In Perform the changes do not go to the history: they make a take that starts from a point of it
356
+ ;; (:origin), and the patch on screen (and in the engine) is that take. Leaving it (compose) keeps the
357
+ ;; take as a new point or discards it. In a shared room, the takes of those who perform from the same
358
+ ;; point are one jam: everyone's changes, in time order. 13-perform.cljs has the rest.
359
+ ;; {:from pos :origin pos :base patch :patch patch :own [{:t :s :ev}] :others {session [{:t :s :ev}]}
360
+ ;; :redo [entry] :cut t :jam id-or-nil}
361
+
362
+ (declare jam-push!)
363
+
364
+ (defonce perf (atom nil))
365
+
366
+ (defn perf-events
367
+ "The changes of the take after its last snapshot (:cut), from everyone in the jam, in time order."
368
+ [{:keys [own others cut]}]
369
+ (sort-by (juxt :t :s) (filter (fn [e] (> (:t e) (or cut 0))) (concat own (apply concat (vals others))))))
370
+
371
+ (defn perf-recompute [st] (assoc st :patch (reduce step (:base st) (map :ev (perf-events st)))))
372
+
373
+ (defn perform-event!
374
+ "A change made in Perform: it goes to the take (and to the jam), not to the history."
375
+ [ev]
376
+ (swap! perf (fn [st] (-> st (update :own conj {:t (js/Date.now) :s session-id :ev ev}) (assoc :redo []) (update :patch step ev))))
377
+ (jam-push!))
378
+
379
+ (defn work-patch [] (or (:patch @perf) (patch-at (:pos @world))))
380
+
381
+ ;; ───── the line that plays (discussion #117, decision 6) ─────
382
+ ;; The engine plays the line where ▶ was pressed; the tab on screen is only what you see and edit, so
383
+ ;; changing tabs does not stop it. While another line plays, the one on screen still runs its messages
384
+ ;; (they travel without ▶), as a part of the engine's patch apart from the line that plays: its boxes are
385
+ ;; known by the prefix @<its line> (:@l3x.b1), so ids of two lines never meet. Its audio boxes stay out:
386
+ ;; only the line that plays sounds.
387
+
388
+ (defn playing-line [] (when (eng/running?) (:playing @line-state)))
389
+
390
+ (defn playing-elsewhere?
391
+ "Is the engine playing a line other than the one on screen?"
392
+ [] (let [p (playing-line)] (and p (not= p (active-line)))))
393
+
394
+ (defn view-prefix
395
+ "Where the engine knows the line on screen while another plays: inside the line that plays, where it uses
396
+ it (its first instance: what the tab shows), or, if it does not, under @<its line> (#117)."
397
+ []
398
+ (if (playing-elsewhere?)
399
+ (or (first (view-instances)) [(keyword (str "@" (active-line)))])
400
+ []))
401
+
402
+ (defn nodes-patch
403
+ "The patch at pos of a line whose segments are nodes (a line not on screen)."
404
+ [nodes pos]
405
+ (let [evs (loop [[nid idx] pos acc () guard 0]
406
+ (let [n (get nodes nid)]
407
+ (if (or (nil? n) (> guard 512))
408
+ acc
409
+ (let [acc (cons (take idx (:events n)) acc)]
410
+ (if (and (:parent n) (get nodes (:parent n)))
411
+ (recur [(:parent n) (:at n)] acc (inc guard))
412
+ acc)))))]
413
+ (reduce step empty-patch (apply concat evs))))
414
+
415
+ (defonce off-screen-cache (atom [nil nil nil]))
416
+
417
+ (defn off-screen-patch
418
+ "The patch of line lid, not on screen: where its tab was left (or its newest point)."
419
+ [lid]
420
+ (let [nodes (get-in @hist [:other lid] {})
421
+ saved (get-in @line-state [:pos lid])
422
+ pos (if (and saved (get nodes (first saved)))
423
+ saved
424
+ (when (seq nodes)
425
+ (let [n (apply max-key (fn [n] (or (:t n) 0)) (vals nodes))] [(:id n) (count (:events n))])))
426
+ [k1 k2 v] @off-screen-cache]
427
+ (if (and (identical? k1 nodes) (= k2 pos))
428
+ v
429
+ (let [p (if pos (nodes-patch nodes pos) empty-patch)] (reset! off-screen-cache [nodes pos p]) p))))
430
+
431
+ (defn silent
432
+ "Patch p without its audio boxes (nor the lines to and from them)."
433
+ [p]
434
+ (let [audio (set (keep (fn [[id b]] (when (:audio (comp/lookup (klass (:text b)))) id)) (:boxes p)))]
435
+ (if (empty? audio)
436
+ p
437
+ (-> p (update :boxes (fn [bx] (into (sorted-map) (remove (fn [[id _]] (audio id)) bx))))
438
+ (update :lines (fn [ls] (vec (remove (fn [[a _ b _]] (or (audio a) (audio b))) ls))))))))
439
+
440
+ (defonce engine-patch-cache (atom [nil nil nil nil]))
441
+
442
+ (defn engine-patch
443
+ "The patch the engine runs: the work on screen, or, while another line plays, that line — with the one on
444
+ screen beside it (silent, under its prefix) when it does not use it already. The same object while neither
445
+ changes (the engine flattens it again only when it is another)."
446
+ []
447
+ (if (and (playing-elsewhere?) (empty? (view-instances)))
448
+ (let [off (off-screen-patch (playing-line)) here (work-patch) k (first (view-prefix))
449
+ [a b c v] @engine-patch-cache]
450
+ (if (and (identical? a off) (identical? b here) (= c k))
451
+ v
452
+ (let [v (assoc-in off [:boxes k] {:text "patch" :x 0 :y 0 :data (silent here)})]
453
+ (reset! engine-patch-cache [off here k v])
454
+ v)))
455
+ (if (playing-elsewhere?) (off-screen-patch (playing-line)) (work-patch))))
456
+
457
+ (declare played!)
458
+
459
+ (defn inject-local!
460
+ "A message played here (a gesture, the REPL) into box f of the engine. In a jam it is also played to the
461
+ others (issue #11): messages are not events of the take, so they travel apart (13-perform.cljs)."
462
+ [f inlet v]
463
+ ;; from the tab of a line used more than once by the line that plays: to every instance of it (#117)
464
+ (let [ins (view-instances)
465
+ pre (when (next ins) (str (str/join "." (map name (first ins))) "."))
466
+ n (name f)]
467
+ (if (and pre (str/starts-with? n pre))
468
+ (doseq [path ins]
469
+ (eng/inject! engine-patch (keyword (str (str/join "." (map name path)) "." (subs n (count pre)))) inlet v))
470
+ (eng/inject! engine-patch f inlet v)))
471
+ (played! f inlet v))
472
+ (defn root-patch [] (or @scratch (work-patch)))
473
+
474
+ (defonce view-path (atom []))
475
+ (def ^:dynamic *inside* [])
476
+
477
+ (defn cmd-path [] (if @scratch *inside* (into @view-path *inside*)))
478
+
479
+ (defn line-ref? "A `patch @name` box: a line used as a sub-patch (#117)." [b] (boolean (and b (eng/line-ref b))))
480
+
481
+ ;; an embedded patch keeps its inside in the box; a `patch @name` reads a line, and is not entered
482
+ (defn embedded? [b] (and b (= "patch" (klass (:text b))) (not (line-ref? b))))
483
+
484
+ ;; a component box defines a class: it has no inlets nor outlets, so it is not drawn in the patch but kept
485
+ ;; in the Components tab (issue #8). It is still a box of the work: its history, its code and links.
486
+ (defn definition? [b] (and b (= "component" (klass (:text b)))))
487
+
488
+ (defn without-definitions [boxes] (into (or (empty boxes) (sorted-map)) (remove (fn [[_ b]] (definition? b)) boxes)))
489
+
490
+ (defn valid-prefix
491
+ "The longest part of `path` that still leads through embedded patches of p."
492
+ [p path]
493
+ (loop [q p acc [] ids (seq path)]
494
+ (if-let [id (first ids)]
495
+ (let [b (get-in q [:boxes id])]
496
+ (if (embedded? b) (recur (or (:data b) empty-patch) (conj acc id) (next ids)) acc))
497
+ acc)))
498
+
499
+ (defn patch-in [p path]
500
+ (reduce (fn [q id] (or (get-in q [:boxes id :data]) empty-patch)) p (valid-prefix p path)))
501
+
502
+ (defn current []
503
+ (let [r (root-patch)]
504
+ (when-not @scratch
505
+ (let [ok (valid-prefix r @view-path)]
506
+ (when (< (count ok) (count @view-path)) (reset! view-path ok))))
507
+ (patch-in r (cmd-path))))
508
+
509
+ (defn wrap-in [path ev] (reduce (fn [e id] [:in id e]) ev (reverse path)))
510
+
511
+ (defn engine-path
512
+ "Where the engine knows the sub-patch on screen: its path, after the prefix of its line while another plays."
513
+ [] (into (view-prefix) (cmd-path)))
514
+
515
+ (defn fid
516
+ "The id the engine knows a box of the current view by."
517
+ [id] (eng/flat-id (engine-path) id))
518
+
519
+ ;; ───── which box is drawn over which (issue #166) ─────
520
+ ;; Boxes are drawn in the order of the number of their ids (not as text, which put :b10–:b19 under :b2): a
521
+ ;; patch is drawn in the order its boxes were made, the newest on top. A box dragged here comes to the front,
522
+ ;; so that what is being moved is never hidden. That order is only for this tab, as the selection is: it is
523
+ ;; not part of the work, not in the history and not in its code.
524
+
525
+ (defonce dragged-front (atom [])) ; engine ids of the boxes dragged here, the last one on top
526
+
527
+ (defn id-z [id] (let [m (re-matches #"b(\d+)" (name id))] (if m (js/parseInt (second m) 10) 0)))
528
+
529
+ (defn to-front!
530
+ "Brings boxes of the current view to the front, in this tab only, keeping their order among themselves."
531
+ [ids]
532
+ (let [fs (map fid (sort-by id-z ids)) fs (sort-by (fn [f] (.indexOf (to-array @dragged-front) f)) fs)]
533
+ (swap! dragged-front (fn [v] (vec (take-last 400 (concat (remove (set fs) v) fs)))))))
534
+
535
+ (defn by-z
536
+ "The [id box] pairs of a map of boxes of the current view, from the bottom to the top: the ones dragged in
537
+ this tab on top, in the order they were dragged; the others in the order of the number of their ids."
538
+ [boxes]
539
+ (let [rank (into {} (map-indexed (fn [i f] [f i]) @dragged-front))]
540
+ (sort-by (fn [[id _]] [(get rank (fid id) -1) (id-z id) (name id)]) boxes)))
541
+
542
+ (defn target
543
+ "Where a message to inlet i of box id goes in the engine: a sub-patch receives it in its i-th inlet box."
544
+ [id inlet]
545
+ (let [b (get-in (current) [:boxes id])]
546
+ (if (and b (comp/subpatch? b))
547
+ (let [inner (eng/inner-patch b) x (get (:inlets (comp/patch-ports inner)) inlet)]
548
+ (if x [(eng/flat-id (conj (engine-path) id) x) 0] (throw (js/Error. (str id " has no inlet " inlet)))))
549
+ [(fid id) inlet])))
550
+
551
+ (defn local-id
552
+ "From an engine id back to an id of the current view (nil if it lives elsewhere)."
553
+ [fid*]
554
+ (let [path (engine-path) n (name fid*)]
555
+ (if (empty? path)
556
+ (when-not (str/includes? n ".") fid*)
557
+ (let [pre (str (str/join "." (map name path)) ".") rest-n (subs n (min (count n) (count pre)))]
558
+ (when (and (str/starts-with? n pre) (not (str/includes? rest-n "."))) (keyword rest-n))))))
559
+
560
+ (defn start-of
561
+ "Depth (number of events from the root) at which a node starts."
562
+ ([nid] (start-of nid 0))
563
+ ([nid depth]
564
+ (let [n (node nid)]
565
+ (if (and n (:parent n) (node (:parent n)) (< depth 512))
566
+ (+ (start-of (:parent n) (inc depth)) (:at n))
567
+ 0))))
568
+
569
+ (defn depth-of [[nid idx]] (+ (start-of nid) idx))
570
+
571
+ (defn tip-of [nid] [nid (count (:events (node nid)))])
572
+
573
+ (defn newest-tip []
574
+ (let [ns (vals (:nodes @hist))]
575
+ (when (seq ns) (tip-of (:id (apply max-key (fn [n] (or (:t n) 0)) ns))))))
576
+
577
+ ;; ───────────────────────── storage ─────────────────────────
578
+
579
+ (defonce queues (atom {}))
580
+
581
+ (defonce recent-errors (atom [])) ; the last errors the REPL showed (for the Feedback tab)
582
+
583
+ (defn print-line
584
+ "How the REPL writes what a print box received: its label (or print), then the value — a string as it is
585
+ (what format and str make), anything else as EDN."
586
+ [v label]
587
+ (str (if (seq label) label "print") ": " (if (string? v) v (pr-str v))))
588
+
589
+ (defn repl-print! [cls html]
590
+ (when (= cls "err")
591
+ (let [d (js/document.createElement "div")]
592
+ (set! (.-innerHTML d) html)
593
+ (swap! recent-errors (fn [es] (vec (take-last 10 (conj es (.-textContent d))))))))
594
+ (let [out (js/document.getElementById "repl-out") d (js/document.createElement "div")]
595
+ (set! (.-className d) cls)
596
+ (set! (.-innerHTML d) html)
597
+ (.appendChild out d)
598
+ (set! (.-scrollTop out) (.-scrollHeight out))))
599
+
600
+ (defn esc [s] (-> (str s) (str/replace "&" "&amp;") (str/replace "<" "&lt;") (str/replace ">" "&gt;") (str/replace "\"" "&quot;")))
601
+
602
+ (defn db-failed! [e]
603
+ (let [code (or (.-code e) "error")]
604
+ (when (#{"invalid_argument" "revoked" "not_granted"} code)
605
+ (swap! hist assoc :writable false :mode :readonly))
606
+ (repl-print! "err" (esc (str "Could not save to the shared history (" code "). Your gestures stay in this tab.")))))
607
+
608
+ (defn enqueue! [k f]
609
+ (let [prev (get @queues k (js/Promise.resolve nil))
610
+ p (-> prev (.then (fn [_] (f))) (.catch db-failed!))]
611
+ (swap! queues assoc k p)))
612
+
613
+ (defn node->js [n]
614
+ (clj->js (cond-> {:parent (:parent n) :at (:at n) :author (:author n) :session (:session n) :t (:t n)
615
+ :merge (:merge n) :events (mapv enc (:events n))}
616
+ (:line n) (assoc :line (:line n)))))
617
+
618
+ ;; ───────────────────────── works: shared rooms and solo work ─────────────────────────
619
+ ;; room: rooms/<id> (metadata) · rooms/<id>/history/<segment>
620
+ ;; solo: data/users/<uid>/<id> (private) · data/users/<uid>/<id>/history/<segment>
621
+
622
+ (defonce work (atom {:kind nil :id nil :name nil}))
623
+
624
+ (defn uid [] (:id @me))
625
+
626
+ (defn base-of [kind id]
627
+ (case kind
628
+ :room (str "rooms/" id)
629
+ :solo (when (uid) (str "data/users/" (uid) "/" id))
630
+ nil))
631
+
632
+ (defn work-base [] (base-of (:kind @work) (:id @work)))
633
+ (defn hist-path [] (when-let [b (work-base)] (str b "/history")))
634
+ ;; what belongs to one line besides its segments (its jams): the work's own place for the main line
635
+ (defn line-base [] (when-let [b (work-base)] (if (on-main-line?) b (str b "/lines/" (active-line)))))
636
+
637
+ (defn persist? []
638
+ (and @dbref (:writable @hist) (#{:room :solo} (:kind @work)) (hist-path)))
639
+
640
+ (defn new-id []
641
+ (if (persist?)
642
+ (.-id (.doc (.collection @dbref (hist-path))))
643
+ (str "local-" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36) (.toString (js/Date.now) 36))))
644
+
645
+ (defn new-node! [parent at evs merge]
646
+ (let [id (new-id)
647
+ n (cond-> {:id id :parent parent :at at :author (my-author) :session session-id :t (js/Date.now)
648
+ :merge merge :events (vec evs)}
649
+ (not (on-main-line?)) (assoc :line (active-line)))]
650
+ (swap! hist assoc-in [:nodes id] n)
651
+ (when (and (persist?) (not (str/starts-with? id "local-")))
652
+ (let [path (str (hist-path) "/" id) body (node->js n)]
653
+ (enqueue! path (fn [] (.set (.doc @dbref path) body)))))
654
+ id))
655
+
656
+ (defn append-event! [nid ev]
657
+ (swap! hist update-in [:nodes nid] (fn [n] (-> n (update :events conj ev) (assoc :t (js/Date.now)))))
658
+ (when (and (persist?) (not (str/starts-with? nid "local-")))
659
+ (let [n (node nid)
660
+ path (str (hist-path) "/" nid)
661
+ body (clj->js {:events (mapv enc (:events n)) :t (:t n)})]
662
+ (enqueue! path (fn [] (.update (.doc @dbref path) body))))))
663
+
664
+ (defn own-open-tip? [[nid idx]]
665
+ (let [n (node nid)]
666
+ (and n (= (node-session n) session-id) (= idx (count (:events n))) (< idx max-events))))
667
+
668
+ (defn commit!
669
+ "Adds an event where you are. If you have just moved forward over someone else's event less than the
670
+ simultaneity interval ago, your event is considered parallel and starts from where you were (a branch)."
671
+ [ev]
672
+ (let [{:keys [pos prev-pos jumped-at]} @world
673
+ parallel? (and prev-pos (< (- (js/Date.now) jumped-at) (:simul-ms @settings)))
674
+ base (if parallel? prev-pos pos)]
675
+ (if (and base (own-open-tip? base))
676
+ (do (append-event! (first base) ev)
677
+ (swap! world assoc :pos [(first base) (inc (second base))] :auto true :prev-pos nil))
678
+ (let [id (new-node! (first base) (if base (second base) 0) [ev] nil)]
679
+ (swap! world assoc :pos [id 1] :auto true :prev-pos nil)))))
680
+
681
+ ;; ───────────────────────── paths, front and merge ─────────────────────────
682
+
683
+ (defn segments
684
+ "Path from the root to a position, as [[segment n] ...]."
685
+ [pos]
686
+ (loop [[nid idx :as p] pos acc () guard 0]
687
+ (let [n (node nid)]
688
+ (if (and n (:parent n) (node (:parent n)) (< guard 512))
689
+ (recur [(:parent n) (:at n)] (cons p acc) (inc guard))
690
+ (vec (cons p acc))))))
691
+
692
+ (defn reaches?
693
+ "Is `tip` reached by moving forward from `pos`?"
694
+ [pos tip]
695
+ (let [[pn pi] pos]
696
+ (boolean (some (fn [[sn si]] (and (= sn pn) (>= si pi))) (segments tip)))))
697
+
698
+ (defn front-from
699
+ "The newest tip reached by moving forward from pos."
700
+ [pos]
701
+ (let [cands (filter (fn [t] (reaches? pos t)) (map (fn [n] (tip-of (:id n))) (vals (:nodes @hist))))]
702
+ (when (seq cands) (apply max-key (fn [[nid _]] (or (:t (node nid)) 0)) cands))))
703
+
704
+ (defn seg-events [[nid n] from]
705
+ (let [evs (vec (take n (:events (node nid))))]
706
+ (subvec evs (min from (count evs)))))
707
+
708
+ (defn diverge
709
+ "Common point of two paths and the events each one adds from there."
710
+ [ts ss]
711
+ (loop [i 0]
712
+ (let [t (nth ts i nil) s (nth ss i nil)]
713
+ (when (and t s (= (first t) (first s)))
714
+ (let [nt (nth ts (inc i) nil) nx (nth ss (inc i) nil)]
715
+ (if (and (= (second t) (second s)) nt nx (= (first nt) (first nx)))
716
+ (recur (inc i))
717
+ (let [k (min (second t) (second s))
718
+ extra (fn [segs] (vec (concat (seg-events (nth segs i) k) (mapcat (fn [g] (seg-events g 0)) (drop (inc i) segs)))))]
719
+ {:base [(first t) k] :t-extra (extra ts) :s-extra (extra ss)})))))))
720
+
721
+ (defn unbatch
722
+ "The events of a history with the changes of every [:batch …] in its place."
723
+ [evs]
724
+ (mapcat (fn [e] (if (and (vector? e) (= :batch (first e)) (sequential? (second e))) (unbatch (second e)) [e])) evs))
725
+
726
+ (defn summarize [evs]
727
+ (reduce (fn [acc [op & args]]
728
+ (case op
729
+ (:box :text :move :size) (update acc :mod conj (first args))
730
+ ;; each mark, layer and projection is its own unit; a mark refers to the boxes it is anchored to
731
+ :annot (-> acc (update :mod conj [:annot (first args)])
732
+ (update :ref into (let [m (second args)] (filter (fn [a] (and (keyword? a) (not= a :patch)))
733
+ (map first (concat (:pts m) (when (:at m) [(:at m)])))))))
734
+ :layer (update acc :mod conj [:layer (first args)])
735
+ :project (-> acc (update :mod conj [:project (first args)]) (update :ref conj (first args)))
736
+ :delete (-> acc (update :mod conj (first args)) (update :del conj (first args)))
737
+ (:connect :disconnect) (update acc :ref into [(first args) (nth args 2 nil)])
738
+ :load (assoc acc :load true)
739
+ ;; a kept buffer rewrites the whole box data; a recipe alone is its own unit
740
+ :data (-> acc (update :mod conj (first args)) (update :ref conj (first args)) (update :whole conj (first args)))
741
+ :kept (-> acc (update :mod conj (first args)) (update :ref conj (first args)) (update :whole conj (first args)))
742
+ :recipe (-> acc (update :mod conj [(first args) :recipe]) (update :ref conj (first args)))
743
+ :pin (-> acc (update :mod conj [(first args) :pin]) (update :ref conj (first args)))
744
+ ;; in a canvas, each stroke is its own unit of change, and so is each grid;
745
+ ;; clear or load affects the whole canvas
746
+ :in (let [[id [iop eid]] args]
747
+ (case iop
748
+ (:stroke :move :stretch :erase) (-> acc (update :mod conj [id eid]) (update :ref conj id))
749
+ :grid-x (-> acc (update :mod conj [id :grid-x]) (update :ref conj id))
750
+ :tuning (-> acc (update :mod conj [id :tuning]) (update :ref conj id))
751
+ :quantize (-> acc (update :mod conj [id :quant]) (update :ref conj id))
752
+ ;; in a tree, each edited node is its own unit; inserting or removing changes its container
753
+ ;; units: [box path kind] — :node (replaced), :kids (children added or removed, so their
754
+ ;; indices move), :attrs (only its attributes)
755
+ :edit (-> acc
756
+ (update :tree into (for [[op p] eid :let [p (vec p)]]
757
+ (case op
758
+ :attrs [id p :attrs]
759
+ (:insert :remove) [id (if (seq p) (pop p) p) :kids]
760
+ [id p :node])))
761
+ (update :ref conj id))
762
+ (-> acc (update :mod conj id) (update :ref conj id) (update :whole conj id))))
763
+ acc))
764
+ {:mod #{} :ref #{} :del #{} :whole #{} :tree #{} :load false} (unbatch evs)))
765
+
766
+ (defn remap-ev [m [op & args :as e]]
767
+ (let [f (fn [x] (get m x x))]
768
+ (case op
769
+ (:box :text :move :size :delete :kept :recipe :data :project :pin) (into [op (f (first args))] (rest args))
770
+ :annot (let [[id m] args fa (fn [[a x y]] [(f a) x y])]
771
+ [op id (cond-> m (:pts m) (update :pts (fn [ps] (mapv fa ps))) (:at m) (update :at fa))])
772
+ :in (let [[id inner] args]
773
+ [op (f id) (if-let [ne (get-in m [:stroke-ids [id (second inner)]])] (assoc inner 1 ne) inner)])
774
+ (:connect :disconnect) (let [[a o b i] args] [op (f a) o (f b) i])
775
+ :batch [op (mapv (fn [x] (remap-ev m x)) (first args))]
776
+ e)))
777
+
778
+ (defn free-box-id [used]
779
+ (loop [k 1] (let [id (keyword (str "b" k))] (if (used id) (recur (inc k)) id))))
780
+
781
+ (defn tree-units-clash?
782
+ "Whether two edits of one tree touch the same thing: a replaced node and anything inside it, children
783
+ added or removed and anything below them (their indices move), or the attributes of the same node."
784
+ [[p kp] [q kq]]
785
+ (let [prefix? (fn [a b] (and (<= (count a) (count b)) (= a (subvec b 0 (count a)))))
786
+ proper? (fn [a b] (and (< (count a) (count b)) (prefix? a b)))
787
+ one-way (fn [[a ka] [b kb]]
788
+ (case ka
789
+ :node (prefix? a b)
790
+ :kids (or (proper? a b) (and (= a b) (= kb :kids)))
791
+ :attrs (and (= a b) (= kb :attrs))))]
792
+ (or (one-way [p kp] [q kq]) (one-way [q kq] [p kp]))))
793
+
794
+ (defn tree-clash
795
+ "Edits of the same tree that touch the same thing in both branches: [[box path] …]."
796
+ [S T]
797
+ (concat
798
+ (for [[i p kp] (:tree S) [j q kq] (:tree T) :when (and (= i j) (tree-units-clash? [p kp] [q kq]))]
799
+ [i (if (<= (count p) (count q)) p q)])
800
+ (for [[i] (:tree S) :when (contains? (:whole T) i)] [i []])
801
+ (for [[i] (:tree T) :when (contains? (:whole S) i)] [i []])))
802
+
803
+ (defn plan-merge
804
+ "Which events of branch `src` must be brought to `tgt`, or why it cannot be done."
805
+ [tgt src]
806
+ (let [ts (segments tgt) ss (segments src)
807
+ ;; what was already brought by earlier merges is not brought again
808
+ merged (keep (fn [g] (:merge (node (first g)))) ts)
809
+ done (last (filter (fn [m] (and (vector? m) (node (first m)) (reaches? m src))) merged))
810
+ d (diverge ts ss)
811
+ s-extra (if done (or (:s-extra (diverge (segments done) ss)) []) (:s-extra d))]
812
+ (cond
813
+ (nil? d) {:error "Those two positions do not share an origin."}
814
+ (empty? s-extra) {:error "That branch has nothing new to bring here: it is already included."}
815
+ :else
816
+ (let [base (patch-at (:base d))
817
+ base-ids (set (keys (:boxes base)))
818
+ in-base? (fn [x] (if (vector? x)
819
+ (or (#{:grid-x :tuning :quant} (second x)) (get-in base [:boxes (first x) :data :strokes (second x)]))
820
+ (base-ids x)))
821
+ S (summarize s-extra) T (summarize (:t-extra d))
822
+ note-boxes (fn [X] (set (keep (fn [x] (when (vector? x) (first x))) (:mod X))))
823
+ clash (filter in-base? (concat (clojure.set/intersection (:mod S) (:mod T))
824
+ (clojure.set/intersection (:ref S) (:del T))
825
+ (clojure.set/intersection (:ref T) (:del S))
826
+ (clojure.set/intersection (:whole S) (note-boxes T))
827
+ (clojure.set/intersection (:whole T) (note-boxes S))))
828
+ clash-name (fn [x] (cond (not (vector? x)) (str x)
829
+ (#{:grid-x :tuning :quant} (second x)) (str "the " (name (second x)) " of " (first x))
830
+ :else (str "stroke " (second x) " of " (first x))))]
831
+ (cond
832
+ (or (and (:load S) (seq (:t-extra d))) (and (:load T) (seq s-extra)))
833
+ {:error "They are not compatible: one of the branches rebuilds the whole work (:load)."}
834
+ (seq (concat clash (tree-clash S T)))
835
+ {:error (str "They are not compatible: both branches change "
836
+ (str/join ", " (concat (map clash-name (distinct clash))
837
+ (map (fn [[id p]] (str "the tree of " id (when (seq p) (str " at " (pr-str p)))))
838
+ (distinct (tree-clash S T)))))
839
+ ".")}
840
+ :else
841
+ (let [target (patch-at tgt)
842
+ created (distinct (keep (fn [[op id]] (when (and (= op :box) (not (base-ids id))) id)) s-extra))
843
+ m (loop [[c & more] created used (into (set (keys (:boxes target))) created) m {}]
844
+ (cond (nil? c) m
845
+ (contains? (:boxes target) c) (let [nid (free-box-id used)] (recur more (conj used nid) (assoc m c nid)))
846
+ :else (recur more used m)))
847
+ ;; new strokes in both branches with the same id: the incoming ones are renamed
848
+ tbox (fn [id] (get-in target [:boxes (get m id id) :data :strokes]))
849
+ created-notes (distinct (keep (fn [[op id inner]]
850
+ (when (and (= op :in) (vector? inner) (= :stroke (first inner))
851
+ (not (get-in base [:boxes id :data :strokes (second inner)])))
852
+ [id (second inner)]))
853
+ s-extra))
854
+ nm (loop [[[id eid :as c] & more] created-notes used {} nm {}]
855
+ (cond (nil? c) nm
856
+ (contains? (tbox id) eid)
857
+ (let [taken (into (set (keys (tbox id))) (get used id))
858
+ ne (loop [k 1] (let [x (keyword (str "t" k))] (if (taken x) (recur (inc k)) x)))]
859
+ (recur more (update used id (fnil conj #{}) ne eid) (assoc nm c ne)))
860
+ :else (recur more (update used id (fnil conj #{}) eid) nm)))]
861
+ {:events (vec (cons [:merge-from (first src) (second src)] (map (fn [e] (remap-ev (assoc m :stroke-ids nm) e)) s-extra)))
862
+ :renamed (merge m (into {} (for [[[id eid] ne] nm] [(keyword (str (name id) "." (name eid))) ne])))}))))))