@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,1247 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 6 of 12: gestures
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (in-ns 'user)
6
+
7
+ ;; ───────────────────────── gestures in the patch ─────────────────────────
8
+
9
+ (def svg ($ "canvas"))
10
+
11
+ (defn pt
12
+ "Pointer position in patch coordinates (even when the patch is shown scaled)."
13
+ [e]
14
+ (let [p (.createSVGPoint svg)]
15
+ (set! (.-x p) (.-clientX e))
16
+ (set! (.-y p) (.-clientY e))
17
+ (let [q (.matrixTransform p (.inverse (.getScreenCTM svg)))]
18
+ [(.-x q) (.-y q)])))
19
+
20
+ (defn closest [e sel] (.closest (.-target e) sel))
21
+
22
+ ;; on touch screens the pointer is captured: look at what is under the finger
23
+ (defn under [e sel]
24
+ (when-let [el (.elementFromPoint js/document (.-clientX e) (.-clientY e))] (.closest el sel)))
25
+
26
+ (defn drop-target
27
+ "Where a wire would land: the box under the pointer (other than the source one) and its inlet nearest
28
+ to the cursor, or else an inlet within reach above a box."
29
+ [e wire]
30
+ (or (when-let [el (under e ".box")]
31
+ (let [id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])]
32
+ (when (and b (not= id (:from wire)))
33
+ (let [[ins _] (io b) [w _] (box-dims id b) [x _] (pt e)]
34
+ (when (pos? ins)
35
+ [id (apply min-key (fn [i] (js/Math.abs (- x (+ (:x b) (port-x w ins i) (/ pw 2))))) (range ins))])))))
36
+ (let [[x y] (pt e) t (port-near (current) :in x y)]
37
+ (when (and t (not= (first t) (:from wire))) t))))
38
+
39
+ (declare upgrade-repl-line! close-repl-line!)
40
+
41
+ (defn repl-line-run!
42
+ "Runs a line of the REPL written on the patch: in the REPL's history, printed in the REPL as usual, and what it
43
+ gave shown in element out (in red if it is an error)."
44
+ [code out]
45
+ (swap! ui (fn [u] (-> u (update :hist conj code) (assoc :hidx nil))))
46
+ (let [n (.-childElementCount ($ "repl-out"))]
47
+ (repl-eval! code :repl)
48
+ (let [new (drop n (array-seq (.-children ($ "repl-out"))))
49
+ last-el (last (filter (fn [k] (#{"out" "err"} (.-className k))) new))]
50
+ (set! (.-className out) (str "edit-out" (when (and last-el (= "err" (.-className last-el))) " err")))
51
+ (set! (.-textContent out) (if last-el (.-textContent last-el) "")))))
52
+
53
+ (defn open-editor!
54
+ "The field to write a box (a new one at x y, or the text of box id). What starts with ( is a line of the REPL
55
+ instead (issue #163): Enter evaluates it, shows what it gave under the field and leaves it open for the next
56
+ one (↑ ↓ go through the REPL's history); Esc, or Enter on an empty line, closes it."
57
+ [{:keys [id x y text]}]
58
+ (when-let [old ($ "box-edit")] (.remove old))
59
+ (when-let [old ($ "box-edit-out")] (.remove old))
60
+ (close-repl-line!)
61
+ (let [inp (js/document.createElement "input") done (atom false)
62
+ out (js/document.createElement "div")
63
+ repl? (atom false) hidx (atom nil)
64
+ ;; once: removing the field makes it lose the focus, and its blur closes it too
65
+ close! (fn [] (when-not @done (reset! done true) (.remove inp) (.remove out)))
66
+ set-repl! (fn [on]
67
+ (reset! repl? on)
68
+ (.toggle (.-classList inp) "as-repl" on)
69
+ (set! (.-placeholder inp) (if on "(command) · Enter runs it · Esc closes" "canvas, reader, ramp 0 8 4, number, msg 1, synth~… · ( for a command")))
70
+ ;; a line of the REPL: run, print in the REPL as usual, and show what it gave here
71
+ run! (fn [code] (reset! hidx nil) (repl-line-run! code out))
72
+ finish (fn [commit?]
73
+ (when-not @done
74
+ (let [v (str/trim (.-value inp))]
75
+ (cond
76
+ (and @repl? commit? (seq v)) (do (run! v) (set! (.-value inp) "") (.focus inp))
77
+ @repl? (close!)
78
+ :else
79
+ (do
80
+ (close!)
81
+ (when (and commit? (seq v) (not= v text))
82
+ (cond
83
+ ;; a component is defined in the Components tab, not drawn in the patch (issue #8)
84
+ (and (= "component" (klass v)) (nil? id)) (gesture! "(new-component!)")
85
+ id (do (gesture! (str "(text! " id " " (pr-str v) ")"))
86
+ (when (= "component" (klass v))
87
+ (select-tab! "comp")
88
+ (js/setTimeout (fn [] (open-code-editor-at! (cmd-path) id)) 0)))
89
+ :else (gesture! (str "(box " (pr-str v) " " (js/Math.round x) " " (js/Math.round y) ")")))))))))
90
+ recall! (fn [dir]
91
+ (let [h (:hist @ui) n (count h)]
92
+ (when (pos? n)
93
+ (let [i (case dir :up (max 0 (dec (or @hidx n))) :down (min n (inc (or @hidx n))))]
94
+ (reset! hidx i)
95
+ (set! (.-value inp) (if (< i n) (nth h i) ""))))))]
96
+ (set! (.-id inp) "box-edit")
97
+ (set! (.-className inp) "edit")
98
+ (.setAttribute inp "spellcheck" "false")
99
+ (set! (.-value inp) (or text ""))
100
+ (set! (.-id out) "box-edit-out")
101
+ (set! (.-className out) "edit-out")
102
+ (set-repl! (and (nil? id) (str/starts-with? (str text) "(")))
103
+ (let [[px py] (wrap-px x (- y 4))]
104
+ (set! (.. inp -style -left) (str px "px"))
105
+ (set! (.. inp -style -top) (str py "px"))
106
+ (set! (.. out -style -left) (str px "px"))
107
+ (set! (.. out -style -top) (str (+ py 32) "px")))
108
+ (.appendChild ($ "canvas-wrap") inp)
109
+ (.appendChild ($ "canvas-wrap") out)
110
+ (.focus inp)
111
+ (if @repl?
112
+ (let [n (count (.-value inp))] (.setSelectionRange inp n n))
113
+ (.select inp))
114
+ ;; a new box whose text starts with ( is a line of the REPL; once it is one, it stays one, and becomes the
115
+ ;; code editor of a line of the REPL (23-ids.cljs) as soon as that is loaded
116
+ (when @repl? (upgrade-repl-line! inp x y close!))
117
+ (.addEventListener inp "input"
118
+ (fn [_] (when (and (nil? id) (not @repl?) (str/starts-with? (str/triml (.-value inp)) "("))
119
+ (set-repl! true)
120
+ (upgrade-repl-line! inp x y close!))))
121
+ (.addEventListener inp "keydown"
122
+ (fn [e] (case (.-key e)
123
+ "Enter" (do (.preventDefault e) (finish true))
124
+ "Escape" (do (.preventDefault e) (finish false))
125
+ "ArrowUp" (when @repl? (.preventDefault e) (recall! :up))
126
+ "ArrowDown" (when @repl? (.preventDefault e) (recall! :down))
127
+ nil)))
128
+ ;; leaving it writes the box; a line of the REPL is closed without running it
129
+ (.addEventListener inp "blur" (fn [_] (if @repl? (close!) (finish true))))))
130
+
131
+ ;; ───── typing a number into a numeric control (issue #32) ─────
132
+ ;; A double-click on a number box, on a component whose :gesture gives numbers (a knob), on a parameter
133
+ ;; of a code box (its slider or its value) or on such a control presented in the panel of a sub-patch
134
+ ;; opens a small field with its value. Enter, or leaving the field, applies what is typed as the same
135
+ ;; gesture a drag leaves in the history; Esc closes it with no change.
136
+
137
+ (defn typed-number
138
+ "The number written in s, or nil: 440, -3.5, .25, 1e-3, a decimal comma (0,5) or a ratio (3/2)."
139
+ [s]
140
+ (let [t (str/replace (str/trim (str s)) #"\s+" "")
141
+ t (if (and (str/includes? t ",") (not (str/includes? t "."))) (str/replace t "," ".") t)
142
+ num (fn [u] (when (re-matches #"[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?" u)
143
+ (let [v (js/Number u)] (when (js/isFinite v) v))))]
144
+ (if-let [[_ a b] (re-matches #"([^/]+)/([^/]+)" t)]
145
+ (let [x (num a) y (num b)] (when (and x y (not (zero? y))) (/ x y)))
146
+ (num t))))
147
+
148
+ (defn typed-str
149
+ "A typed number as it is written in the field and in the code of the gesture: up to six decimals, so
150
+ it is kept as typed (a drag rounds what it sends to three) without the noise of a float."
151
+ [v] (let [r (cv/round-to v 6)] (if (= r (js/Math.round r)) (str (js/Math.round r)) (str r))))
152
+
153
+ (defn open-number-input!
154
+ "A small field over a numeric control at x y (patch coordinates), with its value. Enter, or leaving the
155
+ field, gives the number typed to commit!; Esc closes it and calls cancel!, if given (it undoes what
156
+ the first click of the double-click did). What is not a number is not applied: on Enter the field
157
+ stays open and says so; on leaving it, it closes as with Esc. The field opens after the click that
158
+ asked for it has ended, so that click does not take the focus away from it."
159
+ [{:keys [x y value commit! cancel!]}]
160
+ (js/setTimeout
161
+ (fn []
162
+ (when-let [old ($ "num-edit")] (.remove old))
163
+ (let [inp (js/document.createElement "input") done (atom false)
164
+ close! (fn [] (reset! done true) (.remove inp))
165
+ finish (fn [how]
166
+ (when-not @done
167
+ (let [v (typed-number (.-value inp))]
168
+ (cond
169
+ (and (not= how :cancel) (some? v)) (do (close!) (commit! v))
170
+ (= how :enter) (do (.add (.-classList inp) "bad")
171
+ (set! (.-title inp) "Not a number (440, -3.5, 0,5, 3/2) · Esc closes"))
172
+ :else (do (close!) (when cancel! (cancel!)))))))]
173
+ (set! (.-id inp) "num-edit")
174
+ (set! (.-className inp) "edit num")
175
+ (.setAttribute inp "inputmode" "decimal")
176
+ (.setAttribute inp "aria-label" "Value")
177
+ (set! (.-value inp) (if (number? value) (typed-str value) ""))
178
+ (let [[px py] (wrap-px x y)]
179
+ (set! (.. inp -style -left) (str px "px"))
180
+ (set! (.. inp -style -top) (str py "px")))
181
+ (.appendChild ($ "canvas-wrap") inp)
182
+ (.focus inp)
183
+ (.select inp)
184
+ (.addEventListener inp "input" (fn [_] (.remove (.-classList inp) "bad") (set! (.-title inp) "")))
185
+ (.addEventListener inp "keydown"
186
+ (fn [e] (case (.-key e)
187
+ "Enter" (do (.preventDefault e) (finish :enter))
188
+ "Escape" (do (.preventDefault e) (finish :cancel))
189
+ nil)))
190
+ (.addEventListener inp "blur" (fn [_] (finish :blur)))))
191
+ 0))
192
+
193
+ (defn double-click-on
194
+ "When this pointerdown is the second of a double-click on control k, the first click [k ms before];
195
+ otherwise nil, and this click is remembered (with `before`, the value the control had before it). The
196
+ first click redraws the box, so the browser's dblclick does not reach it: as for the code row, the
197
+ double-click is detected here."
198
+ [k before]
199
+ (let [now (js/Date.now) [lk lt :as first-click] (:num-click @ui)]
200
+ (if (and (= lk k) (< (- now lt) 450))
201
+ (do (swap! ui assoc :num-click nil) first-click)
202
+ (do (swap! ui assoc :num-click [k now before]) nil))))
203
+
204
+ (defn el-box [el]
205
+ (let [id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])] [id (when b (view-box b))]))
206
+
207
+ (defn pos-click!
208
+ "Ask a buffer for an exact position: the box sends it through its left outlet (and marks it)."
209
+ [id t]
210
+ (gesture! (str "(send! " id " " (cv/fmt (max 0 t)) ")")))
211
+
212
+ (defn pts-code [pts] (str "[" (str/join " " (map (fn [[t f]] (str "[" (cv/fmt t) " " (cv/fmt f) "]")) pts)) "]"))
213
+
214
+ ;; ───── editing a tree from its score (Study 20) ─────
215
+ ;; A score that shows a tree coming from a tree box knows, for every note it draws, where that note is
216
+ ;; written (kairotic.mt/expand-source). Click a note to select it; ↑ ↓ change its pitch (⇧ an octave),
217
+ ;; + − double or halve its duration, ← → select the previous or next one, Delete turns it into a rest.
218
+ ;; A rest can be selected too: Enter makes it a note (the pitch of the note before it), ↑ ↓ a note a step
219
+ ;; above or below that one (⇧ an octave), and a letter a…g the nearest note of that name; on a note, a
220
+ ;; letter changes its pitch to the nearest one of that name.
221
+ ;; Every change is one (tree-edit! …) of the tree box: a node edit in its history.
222
+
223
+ (defn tsel-piece-id
224
+ "The id, in the drawn score, of the selected note (it changes when the score is drawn again)."
225
+ [ts pieces]
226
+ (or (when (some (fn [pc] (= (:id pc) (:id ts))) pieces) (:id ts))
227
+ (:id (first (filter (fn [pc] (= (:src pc) (:src ts))) pieces)))))
228
+
229
+ (defn select-tree-note! [score-id piece from]
230
+ (swap! ui assoc :sel nil :nsel nil :tsel {:score score-id :from from :src (:src piece) :id (:id piece)})
231
+ (render-scene (current)))
232
+
233
+ (defn writable-target
234
+ "Edits that make a written note editable (a melody string becomes its nodes) and the path of the note:
235
+ [ops path], or nil if it comes from a fragment (:defs)."
236
+ [t {:keys [src sub use rtm]}]
237
+ (cond
238
+ (or use rtm (nil? src)) nil
239
+ (nil? sub) [[] src]
240
+ :else (let [s (mt/node-at t src) nodes (mt/melody s) parent (pop src) idx (peek src)]
241
+ [(into [[:remove src]] (map-indexed (fn [k n] [:insert (conj parent (+ idx k)) n]) nodes))
242
+ (into (conj parent (+ idx (first sub))) (rest sub))])))
243
+
244
+ (defn piece-midi
245
+ "The pitch (MIDI) of a piece of a score drawn from a tree, read from the written tree t; nil for a rest."
246
+ [t {:keys [src sub]}]
247
+ (let [n (mt/node-at t src)
248
+ n (if (and sub (string? n))
249
+ (let [x (nth (mt/melody n) (first sub) nil)] (if (next sub) (nth (mt/kids x) (second sub) nil) x))
250
+ n)
251
+ n (if (= :chord (mt/tag n)) (first (filter (fn [k] (= :note (mt/tag k))) (mt/kids n))) n)]
252
+ (when (= :note (mt/tag n)) (mt/midi-of (mt/attrs n)))))
253
+
254
+ (def letter-pcs {"c" 0 "d" 2 "e" 4 "f" 5 "g" 7 "a" 9 "b" 11})
255
+
256
+ (defn nearest-pc
257
+ "The pitch nearest m whose pitch class is pc."
258
+ [m pc]
259
+ (let [r (js/Math.round m)]
260
+ (first (sort-by (fn [x] (js/Math.abs (- x m))) (filter (fn [x] (= pc (mod x 12))) (range (- r 6) (+ r 7)))))))
261
+
262
+ (defn tree-key!
263
+ "A key on the selected note (or rest) of a score."
264
+ [k shift?]
265
+ (let [{:keys [score from] :as ts} (:tsel @ui)
266
+ pieces (get-in @score-cache [score :pieces])
267
+ cur (tsel-piece-id ts pieces)
268
+ order (vec (filter :src pieces))
269
+ i (first (keep-indexed (fn [i pc] (when (= (:id pc) cur) i)) order))]
270
+ (cond
271
+ (= k "Escape") (do (swap! ui assoc :tsel nil) (render-scene (current)))
272
+ (#{"ArrowLeft" "ArrowRight"} k)
273
+ (when i (let [j (max 0 (min (dec (count order)) (+ i (if (= k "ArrowLeft") -1 1))))]
274
+ (select-tree-note! score (nth order j) from)))
275
+ :else
276
+ (let [t (tree-data from)
277
+ [pre target] (or (writable-target t (:src ts))
278
+ (fail (if (:rtm (:src ts))
279
+ "That note comes from a proportional rhythm (:rtm): edit its :shares or :pitches"
280
+ "That note comes from a fragment (:defs): edit the fragment, or write it out")))
281
+ t1 (reduce mt/apply-op t pre)
282
+ n (mt/node-at t1 target)
283
+ parent (mt/node-at t1 (pop target))
284
+ in-chord? (= :chord (mt/tag parent))
285
+ dur-path (if in-chord? (pop target) target)
286
+ dn (mt/node-at t1 dur-path)
287
+ eff (or (:dur (mt/attrs dn)) (:dur (mt/attrs (mt/node-at (mt/explicit t1) dur-path))) 1)
288
+ nxt-path (conj (pop dur-path) (inc (peek dur-path)))
289
+ nxt (mt/node-at t1 nxt-path)
290
+ keep-next (when (and (mt/node? nxt) (#{:note :rest :chord} (mt/tag nxt)) (nil? (:dur (mt/attrs nxt))))
291
+ [[:attrs nxt-path (assoc (mt/attrs nxt) :dur eff)]])
292
+ ;; the pitch a rest becomes: from the note before it in the score (or after it), else B4
293
+ staff (:staff (nth order (or i 0) nil))
294
+ same (fn [pcs] (filter (fn [pc] (= staff (:staff pc))) pcs))
295
+ near (or (last (keep (fn [pc] (piece-midi t (:src pc))) (same (take (or i 0) order))))
296
+ (first (keep (fn [pc] (piece-midi t (:src pc))) (same (drop (inc (or i 0)) order))))
297
+ 71)
298
+ to-note (fn [m] [[:set dur-path (mt/make :note (assoc (dissoc (mt/attrs n) :dur) :pitch (mt/pitch-name (js/Math.round m)) :dur eff) [])]])
299
+ letter (get letter-pcs (str/lower-case k))
300
+ edits (case (if (and (= :rest (mt/tag n)) (#{"ArrowUp" "ArrowDown" "Enter"} k)) :rest->note (if letter :letter k))
301
+ :rest->note
302
+ (into (to-note (case k "ArrowUp" (+ near (if shift? 12 1)) "ArrowDown" (- near (if shift? 12 1)) near)) keep-next)
303
+ :letter
304
+ (case (mt/tag n)
305
+ :rest (into (to-note (nearest-pc near letter)) keep-next)
306
+ :note [[:attrs target (mt/set-midi (mt/attrs n) (nearest-pc (mt/midi-of (mt/attrs n)) letter))]]
307
+ nil)
308
+ ("ArrowUp" "ArrowDown")
309
+ (when (= :note (mt/tag n))
310
+ (let [m (mt/midi-of (mt/attrs n)) d (* (if shift? 12 1) (if (= k "ArrowUp") 1 -1))]
311
+ [[:attrs target (mt/set-midi (mt/attrs n) (+ m d))]]))
312
+ ;; another name for the same sound: c#4 → db4 → b##3 …
313
+ "#"
314
+ (when (= :note (mt/tag n))
315
+ (let [a (mt/attrs n) m (js/Math.round (mt/midi-of a))
316
+ names (mapv sp/->name (sp/spellings m))
317
+ cur (some-> (mt/spelling-of a) sp/->name)]
318
+ [[:attrs target (assoc a :pitch (get names (mod (inc (max -1 (.indexOf names cur))) (count names))))]]))
319
+ ("+" "=" "-")
320
+ (into [[:attrs dur-path (assoc (mt/attrs dn) :dur (* eff (if (= k "-") 0.5 2)))]] keep-next)
321
+ ("Delete" "Backspace")
322
+ (if (and in-chord? (> (count (filter mt/node? (mt/kids parent))) 1))
323
+ [[:remove target]]
324
+ (into [[:set dur-path [:rest {:dur eff}]]] keep-next))
325
+ nil)]
326
+ (when (seq edits)
327
+ (let [ops (into pre edits)]
328
+ (if (= score from)
329
+ ;; a tree box shown as a score (discussion #30): its notes edit its own tree, directly
330
+ (do (swap! ui assoc :tsel (assoc ts :src {:src (if (#{"Delete" "Backspace"} k) dur-path target)} :id nil))
331
+ (gesture! (str "(tree-edit! " from " " (str/join " " (map pr-str ops)) ")")))
332
+ ;; a score box: the edits leave it by its third outlet; connected back to the tree box, they
333
+ ;; change it, and the tree, changed, comes back to the score
334
+ (do (when-not (some (fn [[a o]] (and (= a score) (= o 2))) (:lines (current)))
335
+ (fail (str "To edit " from " from this score, connect the score's third outlet (edits) to " from
336
+ ", or show " from " itself as a score: (view " from " :score)")))
337
+ (swap! ui assoc :tsel (assoc ts :src {:src (if (#{"Delete" "Backspace"} k) dur-path target)} :id nil))
338
+ (eng/emit! engine-patch (fid score) 2 [:edit ops])))
339
+ (render-scene (current))))))))
340
+
341
+ (defn score-click!
342
+ "Click on a score: a note picks its stroke; elsewhere, the nearest position of that system is requested."
343
+ [e id b x y]
344
+ (let [gn (or (.closest (.-target e) "g.note") (.closest (.-target e) "g.rest"))
345
+ m (when gn (re-matches #"n-([^-]+)-([^-]+)-(\d+)" (str (.-id gn))))
346
+ tid (when m (keyword (nth m 2)))
347
+ c (get @score-cache id)
348
+ piece (when (and gn (:from c)) (first (filter (fn [pc] (= (:id pc) (.-id gn))) (:pieces c))))
349
+ ;; a note or rest of a freqt's own strokes, quantized: alt-click divides its beat another way
350
+ qpiece (when (and gn (.-altKey e) (not (:from c)) (not (live-tree id)) (not (kept-tree b)))
351
+ (first (filter (fn [pc] (= (:id pc) (.-id gn))) (:pieces c))))]
352
+ (cond
353
+ (and piece (:src piece))
354
+ (select-tree-note! id piece (:from c))
355
+ (and qpiece (.-shiftKey e) (:midi qpiece))
356
+ (let [nm (enharmonic! id (:t qpiece) (:midi qpiece))]
357
+ (repl-print! "out" (esc (str "; " id " · the note at " (cv/fmt (:t qpiece)) " written " nm " (shift-alt-click again: another name)"))))
358
+ qpiece
359
+ (let [ch (division! id (:t qpiece))]
360
+ (repl-print! "out" (esc (str "; " id " · the beat at " (cv/fmt (:t qpiece)) " divided " (pr-str ch) " (alt-click again: another way; (division! " id " " (cv/fmt (:t qpiece)) " nil): the quantizer's)"))))
361
+ (and tid (get-in b [:data :strokes tid]))
362
+ (swap! ui assoc :sel nil :nsel [id tid])
363
+ :else
364
+ (let [lx (- x (:x b) 4) ly (- y (:y b) hdr 4)
365
+ as (filter (fn [a] (<= (:y0 a) ly (:y1 a))) (get-in @score-cache [id :anchors]))]
366
+ (swap! ui assoc :sel nil :nsel nil :tsel nil)
367
+ (when (seq as)
368
+ (pos-click! id (:t (apply min-key (fn [a] (js/Math.abs (- (:x a) lx))) as))))))))
369
+
370
+ (defn snap-t [d t] (let [q (cv/quantize-t (:gx d) t)] (if (cv/generic? d) q (max 0 q))))
371
+ (defn snap-f [d f] (cv/quantize-f (:gy d) f))
372
+
373
+ (defn number-value [id b]
374
+ (let [v (or (second (last-shown id)) (get-in @eng/rt [:states (fid id)]) (eng/num-of (first (eng/args-of (:text b)))) 0)]
375
+ (if (number? v) v 0)))
376
+
377
+ ;; the code of a box opens in the editor window (14-editor.cljs)
378
+ (declare open-code-editor!)
379
+
380
+ (defn data-header?
381
+ "Is (x, y) on the right half of the header of a box whose data can be edited as text (not a code box,
382
+ whose code row opens it)? There a double-click opens its data in the code window (discussion #30)."
383
+ [id b x y]
384
+ (let [[w _] (box-dims id b)]
385
+ (boolean (and (comp/source-of b) (not= :code (display-of b))
386
+ (<= (:y b) y (+ (:y b) hdr)) (> x (+ (:x b) (/ w 2)))))))
387
+
388
+ (defn param-k
389
+ "How a parameter is named in a message: a keyword if possible (:cutoff), otherwise a string."
390
+ [label] (if (re-matches #"[A-Za-z][A-Za-z0-9_\-]*" (str label)) (keyword label) (str label)))
391
+
392
+ (defn param-of [b label] (first (filter (fn [p] (= (:label p) label)) (code-params b))))
393
+
394
+ (defn value-at-x [b p x]
395
+ (let [[w _] (box-dims nil b) tw (- w param-x0 64)
396
+ u (max 0 (min 1 (/ (- x (:x b) param-x0) tw)))
397
+ v (+ (:min p) (* u (- (:max p) (:min p))))
398
+ st (:step p)]
399
+ (cv/round-to (if (and (number? st) (pos? st)) (* st (js/Math.round (/ v st))) v) 4)))
400
+
401
+ (defn send-quiet! [id v]
402
+ (let [was-on (eng/running?)]
403
+ (inject-local! (fid id) 0 v)
404
+ (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))
405
+ (render-overlay!)))
406
+
407
+ (defn send-flat-quiet! [f v]
408
+ (let [was-on (eng/running?)]
409
+ (inject-local! f 0 v)
410
+ (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))
411
+ (render-overlay!)))
412
+
413
+ (defn ctl-gesture!
414
+ "Calls the :gesture of the box being dragged; if the value changes, sends it to its inlet 0."
415
+ [x y fine]
416
+ (when-let [{:keys [f b ox oy x0 y0 start hit] :as cd} (:ctldrag @ui)]
417
+ (let [v (try ((:gesture (box-def b))
418
+ (assoc (ctl-m* f b) :start start :x (- x ox) :y (- y oy) :dx (- x x0) :dy (- y y0) :fine (boolean fine) :hit hit))
419
+ (catch :default e (js/console.error "gesture" e) nil))]
420
+ (swap! ui update :ctldrag assoc :x x :y y :fine (boolean fine))
421
+ (when (and (some? v) (not= v (:v cd)))
422
+ (swap! ui assoc-in [:ctldrag :v] v)
423
+ (send-flat-quiet! f v)))))
424
+
425
+ (defn ctl-release-value
426
+ "On release, the :gesture of the box is asked once more with :up true; what it returns is the value
427
+ that stays in the history. A :gesture that ignores :up returns the last value, as before."
428
+ [{:keys [f b ox oy x0 y0 x y fine start v hit]}]
429
+ (let [x (or x x0) y (or y y0)
430
+ u (try ((:gesture (box-def b))
431
+ (assoc (ctl-m* f b) :start start :x (- x ox) :y (- y oy) :dx (- x x0) :dy (- y y0)
432
+ :fine (boolean fine) :up true :hit hit))
433
+ (catch :default e (js/console.error "gesture" e) v))]
434
+ (if (some? u) u v)))
435
+
436
+ (defn ctl-commit!
437
+ "Leaves the value v of a control in the history, as its drag does on release: a box whose class keeps
438
+ it (:persist, a knob) is rewritten with its new arguments (this tab already sent the value); any other
439
+ sends it as a gesture, whose code starts with `echo` ((send! :b3 … or (send-to! :b7.b4 …), the number
440
+ written by `fmt`."
441
+ [{:keys [f id echo]} v fmt]
442
+ (let [b (when id (get-in (current) [:boxes id])) d (when b (box-def b))]
443
+ (if (and b (:persist d))
444
+ (when (some? v)
445
+ (let [t (comp/args-text d (klass (:text b)) (merge (comp/args-for d (:text b)) ((:persist d) v)))]
446
+ ;; this tab already sent the value: the new text need not send it again
447
+ (swap! echoed assoc f t)
448
+ (when (not= t (:text b)) (gesture! (str "(text! " id " " (pr-str t) ")")))))
449
+ (gesture! (str echo (cond (number? v) (fmt v) (some? v) (pr-str v) :else ":bang") ")")))))
450
+
451
+ (defn send-to!
452
+ "Sends a message to inlet 0 of a box inside a sub-patch of this view: (send-to! :b7.b4 0.5)."
453
+ [rel v]
454
+ (let [was-on (eng/running?)]
455
+ (inject-local! (eng/flat-id (engine-path) rel) 0 v)
456
+ (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))
457
+ v))
458
+
459
+ (defn start-ctl-drag!
460
+ ([f b ox oy x y echo] (start-ctl-drag! f b ox oy x y echo false))
461
+ ([f b ox oy x y echo fine]
462
+ (swap! ui assoc :sel nil :nsel nil
463
+ :ctldrag {:f f :b b :ox ox :oy oy :x0 x :y0 y :start (second (shown-flat f)) :v nil :echo echo
464
+ ;; the part of its view pressed (a shape with :hit), worked out from the shapes themselves
465
+ :hit (try (shp/hit-near (ctl-shapes* (ctl-m* f b) b) [(- x ox) (- y oy)]) (catch :default _ nil))})
466
+ (ctl-gesture! x y fine)))
467
+
468
+ ;; ───── the number typed, for each kind of control (issue #32) ─────
469
+
470
+ (defn ctl-number
471
+ "The number a control with a :gesture (engine id f) holds now, or nil if its gesture does not give
472
+ numbers (a keyboard gives notes): what it last showed, its state, or what its gesture gives at rest."
473
+ [f b]
474
+ (let [g (:gesture (box-def b))]
475
+ (when (fn? g)
476
+ (let [m (ctl-m* f b)
477
+ at-rest (try (g (assoc m :start (:shown m) :x 0 :y 0 :dx 0 :dy 0 :fine false))
478
+ (catch :default _ nil))]
479
+ (when (number? at-rest)
480
+ (first (filter number? [(:shown m) (:state m) at-rest])))))))
481
+
482
+ (defn ctl-typed!
483
+ "A number typed into a control with a :gesture (cd as for a drag: :f :b :id :echo). One that keeps its
484
+ value in its text (a knob) gets it first, so the text keeps what its :receive made of it (a knob keeps
485
+ it between its min and max); any other is sent it by the gesture itself."
486
+ [{:keys [f b id] :as cd} v]
487
+ (if (and id (:persist (box-def b)))
488
+ (do (send-flat-quiet! f v)
489
+ (let [st (get-in @eng/rt [:states f])] (ctl-commit! cd (if (number? st) st v) typed-str)))
490
+ (ctl-commit! cd v typed-str)))
491
+
492
+ (defn type-ctl!
493
+ "Opens the field over a control with a :gesture whose top-left corner is at x y and size [w h]."
494
+ [cd x y [w h] v]
495
+ (open-number-input! {:x x :y (+ y (max 0 (- (/ h 2) 13))) :value v :commit! (fn [n] (ctl-typed! cd n))}))
496
+
497
+ (defn type-number-box!
498
+ "Opens the field over the number box id."
499
+ [id b]
500
+ (open-number-input! {:x (+ (:x b) grip) :y (- (:y b) 2) :value (number-value id b)
501
+ ;; like a knob's: sent, and kept in its text
502
+ :commit! (fn [n] (ctl-typed! {:f (fid id) :b b :id id :echo (str "(send! " id " ")} n))}))
503
+
504
+ (defn param-typed-value
505
+ "A typed value for parameter p of a code box, kept between its min and max (Faust clamps it too: so
506
+ the history keeps what sounds)."
507
+ [p v] (if (< (:min p) (:max p)) (max (:min p) (min (:max p) v)) v))
508
+
509
+ (defn send-param! [id label v]
510
+ (gesture! (str "(send! " id " [" (pr-str (param-k label)) " " (typed-str v) "])")))
511
+
512
+ (defn type-param!
513
+ "Opens the field over parameter `label` of code box id. `before` is the value it had before the first
514
+ click of the double-click (a click on the slider moves it there): Esc puts that back."
515
+ [id b label before]
516
+ (let [{:keys [y-par params]} (code-geom b)
517
+ i (or (first (keep-indexed (fn [i q] (when (= (:label q) label) i)) params)) 0)
518
+ p (nth params i nil)]
519
+ (when p
520
+ (open-number-input!
521
+ {:x (+ (:x b) param-x0) :y (+ (:y b) y-par (* i param-h) -4) :value before
522
+ :commit! (fn [n] (send-param! id label (param-typed-value p n)))
523
+ :cancel! (fn [] (when (and (number? before) (not= before (param-value id b p))) (send-param! id label before)))}))))
524
+
525
+ ;; ───── selection: one box, several (⇧+click or a frame drawn on the paper), moved or deleted together ─────
526
+ ;; A plain click selects a box and moves it; ⌘/Ctrl+click also opens its inspector (its arguments and text).
527
+
528
+ (defn scene-boxes
529
+ "The boxes on screen, where they are drawn (their presentation places, in presentation)."
530
+ [] (:boxes (scene-of (current))))
531
+
532
+ (defn group-drag
533
+ "Several boxes start moving together from the pointer at x y (nil if none of them is on screen)."
534
+ [ids x y]
535
+ (let [bs (scene-boxes)
536
+ from (into {} (for [id ids :let [b (get bs id)] :when b] [id [(:x b) (:y b)]]))]
537
+ (when (seq from) {:ids from :x0 x :y0 y :gx 0 :gy 0 :moved false})))
538
+
539
+ ;; In presentation (issue #57) the paper is for playing: no new boxes, no wires, no selection with the mouse
540
+ ;; (no frame, ⇧+click, ⌘/Ctrl+click, ⌘/Ctrl+A; a click does not select, so Delete cannot remove a box). In the
541
+ ;; editor's Present a box can still be dragged to a new place, one at a time; in a Release/Perform embed not.
542
+
543
+ (defn locked? "In presentation: the paper is for playing." [] (boolean @pres-mode))
544
+
545
+ ;; ⌥/Alt held at the last press: in presentation, only ⌥+drag moves a box (a plain drag plays it, or
546
+ ;; does nothing), so that a freqt, a canvas or a knob is not moved by its header or its grip by mistake
547
+ (defonce alt-press (atom false))
548
+
549
+ (defn pick-box!
550
+ "A plain click on a box: if it is one of several selected, they all start moving; otherwise it alone is
551
+ selected (its inspector closed) and starts moving. `extra` is merged into the ui state. In presentation
552
+ nothing is selected: in the editor ⌥+drag moves the box to a new place (a plain drag leaves it where it
553
+ is), in an embed it stays."
554
+ ([id b x y] (pick-box! id b x y nil))
555
+ ([id b x y extra]
556
+ (let [ids (sel-ids)]
557
+ (cond
558
+ (locked?)
559
+ (swap! ui merge {:sel nil :insp nil :nsel nil
560
+ :drag (when (and (not embed-mode) @alt-press)
561
+ {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false})}
562
+ extra)
563
+ (and (> (count ids) 1) (contains? ids id))
564
+ ;; released without moving, the click selects that box alone (see end-gesture!)
565
+ (swap! ui merge {:nsel nil :drag (some-> (group-drag ids x y) (assoc :clicked id))} extra)
566
+ :else
567
+ (swap! ui merge {:sel [:box id] :insp nil :nsel nil
568
+ :drag {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false}}
569
+ extra)))))
570
+
571
+ (defn inspect-box!
572
+ "⌘/Ctrl+click on a box: selects it, opens its inspector, and it can be moved."
573
+ [id b x y]
574
+ (swap! ui assoc :sel [:box id] :insp id :nsel nil :tsel nil
575
+ :drag {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false}))
576
+
577
+ (defn shift-pick
578
+ "The box a ⇧+click adds to (or takes out of) the selection; nil where ⇧ already means something else
579
+ (on the drawing area of a canvas or a freqt it draws a straight stroke; on the body of a box with a
580
+ :gesture it is part of the gesture, fine control or a chord: there the grip selects)."
581
+ [e]
582
+ (when (and (.-shiftKey e) (not (closest e ".port")) (not (locked?)))
583
+ (when-let [el (closest e ".box")]
584
+ (let [[id b] (el-box el)]
585
+ (when (and b (not (and (closest e ".mus-body") (= :canvas (display-of b))))
586
+ (not (and (closest e ".box.act") (not (closest e ".grip")) (fn? (:gesture (box-def b))))))
587
+ id)))))
588
+
589
+ (defn toggle-box!
590
+ "⇧+click: the box joins the selection, or leaves it; what stays selected can be dragged at once."
591
+ [id x y]
592
+ (let [ids (sel-ids) now (if (contains? ids id) (disj ids id) (conj ids id))]
593
+ (swap! ui assoc :sel (sel-of now) :insp nil :nsel nil :tsel nil
594
+ :drag (when (contains? now id) (group-drag now x y)))))
595
+
596
+ (defn group-offset
597
+ "The offset of a group being dragged, stopped so that no box goes past the top or the left edge."
598
+ [{:keys [ids x0 y0]} x y]
599
+ [(max (- x x0) (- (apply min (map first (vals ids)))))
600
+ (max (- y y0) (- (apply min (map second (vals ids)))))])
601
+
602
+ ;; the frame: drawn from an empty place of the paper, it selects every box it touches (⇧ adds to the selection)
603
+
604
+ (defn marquee-rect [{:keys [x0 y0 x y]}]
605
+ [(min x0 x) (min y0 y) (js/Math.abs (- x x0)) (js/Math.abs (- y y0))])
606
+
607
+ (defn marquee-hits
608
+ "The boxes on screen that the frame touches."
609
+ [m]
610
+ (let [[mx my mw mh] (marquee-rect m)]
611
+ (set (for [[id b] (scene-boxes)
612
+ :let [[w h] (box-dims id b)]
613
+ :when (and (< mx (+ (:x b) w)) (< (:x b) (+ mx mw)) (< my (+ (:y b) h)) (< (:y b) (+ my mh)))]
614
+ id))))
615
+
616
+ (defn mark-hits!
617
+ "Marks on screen the boxes the frame is touching (without drawing the whole patch again)."
618
+ [hits]
619
+ (doseq [el (array-seq (.querySelectorAll ($ "scene") ".box"))]
620
+ (.toggle (.-classList el) "hit" (contains? hits (keyword (.. el -dataset -box))))))
621
+
622
+ (defn draw-marquee! [m]
623
+ (let [r (or ($ "marquee")
624
+ (let [r (js/document.createElementNS "http://www.w3.org/2000/svg" "rect")]
625
+ (.setAttribute r "id" "marquee")
626
+ (.setAttribute r "class" "marquee")
627
+ (.appendChild svg r)
628
+ r))
629
+ [x y w h] (marquee-rect m)]
630
+ (.setAttribute r "x" x)
631
+ (.setAttribute r "y" y)
632
+ (.setAttribute r "width" w)
633
+ (.setAttribute r "height" h)
634
+ (mark-hits! (marquee-hits m))))
635
+
636
+ (defn end-marquee! [m]
637
+ (when-let [r ($ "marquee")] (.remove r))
638
+ (mark-hits! #{})
639
+ (let [hits (if (:moved m) (marquee-hits m) #{})]
640
+ (swap! ui assoc :marquee nil :insp nil :sel (sel-of (if (:add m) (into (:base m) hits) hits)))))
641
+
642
+ ;; on a Mac, Ctrl+click is also a right click: on a box it opens the inspector, not the browser's menu
643
+ ;; ───── annotating (Study 26): marks drawn on a layer, anchored to the box nearest each point ─────
644
+ ;; (:annot @ui) = {:tool :draw|:arrow|:text|:move|:erase :layer :notes} while the Annotate bar is open;
645
+ ;; (:adraw @ui) the mark being drawn. What is drawn stays in the history as (mark …).
646
+
647
+ (defn drawn-boxes
648
+ "The boxes on screen now, with their place and size: [[id [x y w h]] …]."
649
+ []
650
+ (let [p (scene-of (current))]
651
+ (for [[id b] (:boxes p)] (let [[x y] (box-pos id b) [w h] (box-dims id b)] [id [x y w h]]))))
652
+
653
+ (defn anchor-of
654
+ "Where a point of a mark is anchored: to the box nearest it (within 150 px), from its top-left corner, or to the paper."
655
+ [[x y]]
656
+ (let [d (fn [[bx by bw bh]] (js/Math.hypot (max 0 (- bx x) (- x (+ bx bw))) (max 0 (- by y) (- y (+ by bh)))))
657
+ [id [bx by] :as best] (first (sort-by (fn [[_ r]] (d r)) (drawn-boxes)))
658
+ r1 (fn [v] (/ (js/Math.round (* 10 v)) 10))]
659
+ (if (and best (< (d (second best)) 150))
660
+ [id (r1 (- x bx)) (r1 (- y by))]
661
+ [:patch (r1 x) (r1 y)])))
662
+
663
+ (defn annot-layer [] (or (:layer (:annot @ui)) (first (keys (:layers (current)))) :notes))
664
+
665
+ (defn mark-hit
666
+ "The mark of a shown layer under [x y], or nil."
667
+ [[x y :as q]]
668
+ (let [p (current)
669
+ sd (fn [[px py] [ax ay] [bx by]]
670
+ (let [dx (- bx ax) dy (- by ay) L2 (+ (* dx dx) (* dy dy))
671
+ u (if (zero? L2) 0 (max 0 (min 1 (/ (+ (* (- px ax) dx) (* (- py ay) dy)) L2))))]
672
+ (js/Math.hypot (- px (+ ax (* u dx))) (- py (+ ay (* u dy))))))]
673
+ (->> (:marks p)
674
+ (filter (fn [[_ m]] (layer-shown? p (:layer m))))
675
+ (keep (fn [[id m]]
676
+ (when-let [ps (mark-points p m)]
677
+ (let [dist (if (= :text (:kind m))
678
+ (let [[[tx ty]] ps] (if (and (<= (- tx 4) x (+ tx (* 8 (count (:txt m))))) (<= (- ty 16) y (+ ty 5))) 0 99))
679
+ (apply min 99 (map (fn [a b] (sd q a b)) ps (rest ps))))]
680
+ (when (< dist 8) [dist id])))))
681
+ (sort-by first) first second)))
682
+
683
+ (defn annot-preview []
684
+ (when-let [{:keys [kind px]} (:adraw @ui)]
685
+ (let [pts (str/join " " (map (fn [[x y]] (str (js/Math.round x) "," (js/Math.round y))) px))]
686
+ (case kind
687
+ :draw (str "<polyline class=\"amark new\" points=\"" pts "\"></polyline>")
688
+ :arrow (str "<polyline class=\"amark new\" points=\"" pts "\"></polyline>")
689
+ ""))))
690
+
691
+ (defn annot-down! [x y]
692
+ (let [{:keys [tool]} (:annot @ui) lid (annot-layer)]
693
+ (case tool
694
+ :draw (swap! ui assoc :adraw {:kind :draw :px [[x y]]})
695
+ :arrow (swap! ui assoc :adraw {:kind :arrow :px [[x y] [x y]]})
696
+ :text (let [t (str/trim (str (some-> ($ "annot-text") .-value)))]
697
+ (if (seq t)
698
+ (gesture! (str "(mark " lid " " (next-mark-id) " " (pr-str {:kind :text :at (anchor-of [x y]) :txt t}) ")"))
699
+ (some-> ($ "annot-text") .focus)))
700
+ :erase (do (swap! ui assoc :adraw {:kind :erase})
701
+ (when-let [id (mark-hit [x y])] (gesture! (str "(unmark " id ")"))))
702
+ ;; moving a mark: pressed near one end of a line or an arrow, only that end (it is anchored again where
703
+ ;; it is let go); anywhere else on the mark, all of it (each point keeps its anchor)
704
+ :move (when-let [id (mark-hit [x y])]
705
+ (let [p (current) m (get-in p [:marks id]) ps (when (:pts m) (mark-points p m))
706
+ near (fn [i] (when-let [[px py] (and ps (nth ps i nil))] (< (js/Math.hypot (- x px) (- y py)) 9)))
707
+ end (cond (not ps) nil (near 0) 0 (near (dec (count ps))) (dec (count ps)) :else nil)]
708
+ (swap! ui assoc :adraw {:kind :move :id id :x0 x :y0 y :x x :y y :end end})))
709
+ nil)
710
+ (render-layers!)))
711
+
712
+ (defn annot-move! [x y]
713
+ (when-let [{:keys [kind px]} (:adraw @ui)]
714
+ (case kind
715
+ :draw (let [[lx ly] (peek px)]
716
+ (when (> (js/Math.hypot (- x lx) (- y ly)) 3)
717
+ (swap! ui update-in [:adraw :px] conj [x y])
718
+ (render-layers!)))
719
+ :arrow (do (swap! ui assoc-in [:adraw :px 1] [x y]) (render-layers!))
720
+ :move (do (swap! ui update :adraw assoc :x x :y y) (render-layers!))
721
+ :erase (when-let [id (mark-hit [x y])] (gesture! (str "(unmark " id ")")))
722
+ nil)))
723
+
724
+ (defn annot-up! []
725
+ (when-let [{:keys [kind px id x0 y0 x y end]} (:adraw @ui)]
726
+ (swap! ui assoc :adraw nil)
727
+ (let [lid (annot-layer)]
728
+ (case kind
729
+ :draw (when (> (count px) 1)
730
+ (let [ps (cv/simplify (vec px) 1.2)]
731
+ (gesture! (str "(mark " lid " " (next-mark-id) " " (pr-str {:kind :line :pts (mapv anchor-of ps)}) ")"))))
732
+ :arrow (let [[a b] px]
733
+ (when (> (js/Math.hypot (- (first b) (first a)) (- (second b) (second a))) 8)
734
+ (gesture! (str "(mark " lid " " (next-mark-id) " " (pr-str {:kind :arrow :pts [(anchor-of a) (anchor-of b)]}) ")"))))
735
+ :move (let [r1 (fn [v] (/ (js/Math.round (* 10 v)) 10)) dx (r1 (- x x0)) dy (r1 (- y y0))
736
+ p (current) m (get-in p [:marks id])]
737
+ (when (and m (> (+ (js/Math.abs dx) (js/Math.abs dy)) 2))
738
+ (if (some? end)
739
+ ;; one end: anchored again where it was let go (to the box nearest it, or to the paper)
740
+ (let [[ex ey] (nth (mark-points p m) end)]
741
+ (gesture! (str "(mark " (:layer m) " " id " " (pr-str (dissoc (set-point m end (anchor-of [(+ ex dx) (+ ey dy)])) :layer)) ")")))
742
+ (gesture! (str "(move-mark " id " " dx " " dy ")")))))
743
+ nil))
744
+ (render-layers!)))
745
+
746
+ (defn render-annot-bar!
747
+ "The Annotate bar: its tool, its layer and how that layer is shown."
748
+ []
749
+ (let [bar ($ "annot-bar") a (:annot @ui)]
750
+ (when bar
751
+ (set! (.-hidden bar) (nil? a))
752
+ (.toggle (.-classList ($ "annot-toggle")) "on" (some? a))
753
+ (.toggle (.-classList js/document.body) "annotating" (some? (:tool a)))
754
+ (.toggle (.-classList js/document.body) "annot-move" (= :move (:tool a)))
755
+ (when a
756
+ (let [p (current) lid (annot-layer) l (or (get-in p [:layers lid]) layer-default)
757
+ inp ($ "annot-layer")]
758
+ (doseq [btn (array-seq (.querySelectorAll bar "[data-atool]"))]
759
+ (.setAttribute btn "aria-pressed" (str (= (name (or (:tool a) "")) (.. btn -dataset -atool)))))
760
+ (when-not (= inp (.-activeElement js/document)) (set! (.-value inp) (name lid)))
761
+ (set! (.-innerHTML ($ "annot-layers")) (apply str (for [k (sort (map name (keys (:layers p))))] (str "<option value=\"" (esc k) "\"></option>"))))
762
+ (set! (.-textContent ($ "annot-z")) (name (:z l)))
763
+ (set! (.-checked ($ "annot-show-patch")) (contains? (:show l) :patch))
764
+ (set! (.-checked ($ "annot-show-present")) (contains? (:show l) :present)))))))
765
+
766
+ (defn annotate
767
+ "Opens the Annotate bar (with a tool: :draw :arrow :text :erase), or closes it: (annotate) · (annotate :arrow) · (annotate false)."
768
+ ([] (annotate (if (:annot @ui) false :draw)))
769
+ ([tool]
770
+ (if (false? tool)
771
+ (swap! ui assoc :annot nil :adraw nil)
772
+ (swap! ui assoc :annot {:tool (keyword tool) :layer (annot-layer)} :sel nil))
773
+ (render-layers!)
774
+ (boolean (:annot @ui))))
775
+
776
+ (.addEventListener ($ "annot-toggle") "click" (fn [_] (annotate)))
777
+ (.addEventListener ($ "annot-done") "click" (fn [_] (annotate false)))
778
+ (.addEventListener ($ "annot-bar") "click"
779
+ (fn [e] (when-let [b (.closest (.-target e) "[data-atool]")] (annotate (.. b -dataset -atool)))))
780
+ (.addEventListener ($ "annot-layer") "change"
781
+ (fn [e] (let [v (str/trim (.. e -target -value))]
782
+ (when (re-matches #"[A-Za-z][A-Za-z0-9_-]*" v) (swap! ui assoc-in [:annot :layer] (keyword v)))
783
+ (render-layers!))))
784
+ (.addEventListener ($ "annot-z") "click"
785
+ (fn [_] (let [lid (annot-layer) l (or (get-in (current) [:layers lid]) layer-default)]
786
+ (gesture! (str "(layer " lid " {:z " (if (= :over (:z l)) ":under" ":over") "})")))))
787
+ (doseq [[el k] [["annot-show-patch" :patch] ["annot-show-present" :present]]]
788
+ (.addEventListener ($ el) "change"
789
+ (fn [e] (let [lid (annot-layer) l (or (get-in (current) [:layers lid]) layer-default)
790
+ show ((if (.. e -target -checked) conj disj) (:show l) k)]
791
+ (gesture! (str "(layer " lid " {:show " (pr-str show) "})"))))))
792
+
793
+ (.addEventListener svg "contextmenu"
794
+ (fn [e] (when (and (.-ctrlKey e) (closest e ".box")) (.preventDefault e))))
795
+
796
+ (defonce corner-click (atom nil)) ; the last press on the corner of a box: {:id :t} (a double-click resets it)
797
+
798
+ (.addEventListener svg "pointerdown"
799
+ (fn [e]
800
+ (reset! alt-press (boolean (.-altKey e)))
801
+ (let [[x y] (pt e) mod? (or (.-metaKey e) (.-ctrlKey e))
802
+ ;; an outlet within reach of the pointer (not only right on it) starts a wire
803
+ out (when-not (or (locked?) (:annot @ui)) (port-near (current) :out x y))]
804
+ (cond
805
+ ;; annotating: the pointer draws marks (the Annotate bar is open)
806
+ (and (:annot @ui) (:tool (:annot @ui)))
807
+ (do (.preventDefault e) (annot-down! x y))
808
+
809
+ out
810
+ (do (.preventDefault e)
811
+ (.add (.-classList svg) "wiring")
812
+ (swap! ui assoc :wire {:from (first out) :out (second out) :x x :y y}))
813
+
814
+ ;; the corner of a canvas, freqt or score: drag to resize it (issue #40)
815
+ (closest e ".resize-corner")
816
+ (let [[id b] (el-box (closest e ".resize-corner"))]
817
+ (when b
818
+ (.preventDefault e)
819
+ (let [[w h] (box-size id b) now (js/Date.now) {pid :id pt :t} @corner-click]
820
+ (reset! corner-click {:id id :t now})
821
+ (if (and (= pid id) (< (- now pt) 400))
822
+ ;; a double-click on the corner: back to its default size
823
+ (do (reset! corner-click nil)
824
+ (when (:size b) (gesture! (str "(resize " id ")"))))
825
+ (swap! ui assoc :sel nil :nsel nil :drag nil
826
+ :resize {:id id :x0 x :y0 y :w0 w :h0 h :w w :h h :moved false})))))
827
+
828
+ ;; ⌘/Ctrl+click anywhere on a box: select it and open its inspector
829
+ (and mod? (closest e ".box") (not (closest e ".port")) (not (locked?)))
830
+ (let [[id b] (el-box (closest e ".box"))]
831
+ (when b
832
+ (.preventDefault e)
833
+ (inspect-box! id b x y)))
834
+
835
+ ;; ⇧+click: add the box to the selection, or take it out
836
+ (shift-pick e)
837
+ (do (.preventDefault e)
838
+ (toggle-box! (shift-pick e) x y))
839
+
840
+ ;; the chips of a header (discussion #30): ⇄ shows the box in its next view, { } opens its data as text
841
+ (closest e ".hchip")
842
+ (let [el (closest e ".hchip") [id b] (el-box el)]
843
+ (when b
844
+ (.preventDefault e)
845
+ (swap! ui assoc :drag nil)
846
+ (case (.. el -dataset -chip)
847
+ "view" (gesture! (str "(view " id " " (next-view b) ")"))
848
+ "code" (js/setTimeout (fn [] (open-code-editor! id)) 0)
849
+ nil)))
850
+
851
+ ;; a control presented in the panel of a sub-patch
852
+ (closest e ".pres-area")
853
+ (let [el (closest e ".pres-area") [id b] (el-box el) kid (keyword (.. el -dataset -kid))
854
+ k (when b (first (filter (fn [k] (= (:id k) kid)) (:kids (panel-layout b)))))]
855
+ (when (and k (fn? (:gesture (box-def (:b k)))))
856
+ (.preventDefault e)
857
+ (let [[kx ky] (kid-origin (:x b) (:y b) k)
858
+ f (eng/flat-id (conj (engine-path) id) kid)
859
+ echo (str "(send-to! " (eng/flat-id [id] kid) " ")
860
+ v (ctl-number f (:b k))]
861
+ ;; a double-click on a numeric control: its value is typed (issue #32)
862
+ (if (and (number? v) (double-click-on [:kid f] v))
863
+ (type-ctl! {:f f :b (:b k) :echo echo} kx ky [(:w k) (:h k)] v)
864
+ (start-ctl-drag! f (:b k) kx ky x y echo (.-shiftKey e))))))
865
+
866
+ ;; action boxes: the grip selects and moves them (⌘/Ctrl+click opens the inspector), the body only plays
867
+ (and (closest e ".box.act") (not (closest e ".grip")) (not (closest e ".port")))
868
+ (let [[id b] (el-box (closest e ".box.act"))]
869
+ (when b
870
+ (.preventDefault e)
871
+ (swap! ui (fn [u] (assoc u :nsel nil :sel (when-not (= (:sel u) [:box id]) (:sel u)))))
872
+ (let [num-box? (= "number" (klass (:text b)))
873
+ ctl? (fn? (:gesture (box-def b)))
874
+ cval (when (and ctl? (not num-box?)) (ctl-number (fid id) b))
875
+ ;; a double-click on a number box, or on a control whose gesture gives numbers:
876
+ ;; its value is typed (issue #32); the first click did what a click does
877
+ again? (and (or num-box? (some? cval)) (some? (double-click-on [:box id] nil)))]
878
+ (cond
879
+ (and again? num-box?) (type-number-box! id b)
880
+ again? (type-ctl! {:f (fid id) :b b :id id :echo (str "(send! " id " ")}
881
+ (+ (:x b) grip) (:y b) (comp/size-of b) cval)
882
+ num-box? (swap! ui assoc :numdrag {:id id :y0 y :v0 (number-value id b) :v nil})
883
+ ctl? (do (start-ctl-drag! (fid id) b (+ (:x b) grip) (:y b) x y (str "(send! " id " ") (.-shiftKey e))
884
+ (swap! ui assoc-in [:ctldrag :id] id))
885
+ :else (gesture! (str "(send! " id " :bang)"))))))
886
+
887
+ ;; the first click selects the box and redraws it, so the double click is detected here
888
+ (closest e ".code-area")
889
+ (let [[id b] (el-box (closest e ".code-area")) now-ms (js/Date.now) [lid lt] (:last-click @ui)]
890
+ (when b
891
+ (if (and (= lid id) (< (- now-ms lt) 450))
892
+ (do (.preventDefault e)
893
+ (swap! ui assoc :last-click nil :drag nil)
894
+ (js/setTimeout (fn [] (open-code-editor! id)) 0))
895
+ (pick-box! id b x y {:last-click [id now-ms]}))))
896
+
897
+ (closest e ".param")
898
+ (let [el (closest e ".param") [id b] (el-box el) label (.. el -dataset -param) p (param-of b label)]
899
+ (when p
900
+ (.preventDefault e)
901
+ (swap! ui assoc :sel nil :nsel nil)
902
+ (case (:type p)
903
+ "button" (do (send-quiet! id [(param-k label) 1])
904
+ (swap! ui assoc :paramdrag {:id id :label label :button true}))
905
+ "checkbox" (let [v (if (pos? (param-value id b p)) 0 1)]
906
+ (gesture! (str "(send! " id " [" (pr-str (param-k label)) " " v "])")))
907
+ ;; a slider: a double-click types its value (issue #32), the one it had before the first click
908
+ (if-let [[_ _ before] (double-click-on [:param id label] (param-value id b p))]
909
+ (type-param! id b label before)
910
+ (let [v (value-at-x b p x)]
911
+ (send-quiet! id [(param-k label) v])
912
+ (swap! ui assoc :paramdrag {:id id :label label :p p :v v}))))))
913
+
914
+ ;; the value written beside a slider: a click is a click on the box, a double-click types the value
915
+ (closest e ".pval-hit")
916
+ (let [el (closest e ".pval-hit") [id b] (el-box el) label (.. el -dataset -param) p (param-of b label)]
917
+ (when b
918
+ (if-let [[_ _ before] (when p (double-click-on [:param id label] (param-value id b p)))]
919
+ (do (.preventDefault e)
920
+ (swap! ui assoc :drag nil)
921
+ (type-param! id b label before))
922
+ (pick-box! id b x y))))
923
+
924
+ (closest e ".stroke-hit")
925
+ (let [el (closest e ".stroke-hit") [id b] (el-box el) tid (keyword (.. el -dataset -stroke))
926
+ d (canvas-data b) tr (get-in d [:strokes tid])]
927
+ (when tr
928
+ (.preventDefault e)
929
+ (swap! ui assoc :sel nil :nsel [id tid]
930
+ :ldrag {:kind :move :box id :tid tid :g (canvas-geom d id b) :d d :x0 x :y0 y :alt (.-altKey e)
931
+ :pts0 (:pts tr) :pts (:pts tr) :dt 0 :dc 0 :moved false})))
932
+
933
+ (closest e ".score-slot")
934
+ (let [[id b] (el-box (closest e ".score-slot"))]
935
+ (when b (score-click! e id b x y)))
936
+
937
+ (closest e ".mus-body")
938
+ (let [[id b] (el-box (closest e ".mus-body"))]
939
+ (when b
940
+ (case (display-of b)
941
+ :canvas (let [d (canvas-data b) g (canvas-geom d id b)
942
+ lx (- x (:x b)) ly (- y (:y b))
943
+ t0 (snap-t d (cv/x->t g lx)) f0 (snap-f d (cv/y->f g ly))
944
+ mode (cond (.-altKey e) :free (.-shiftKey e) :line :else :note)]
945
+ (.preventDefault e)
946
+ (swap! ui assoc :sel nil :nsel nil
947
+ :ldrag {:kind :draw :mode mode :box id :g g :d d :x0 x :y0 y :bx (:x b) :by (:y b)
948
+ :t0 t0 :f0 f0 :click-t (cv/x->t g lx) :raw [[lx ly]] :pts nil :moved false}))
949
+ :score (score-click! e id b x y)
950
+ nil)))
951
+
952
+ (closest e ".box")
953
+ (let [el (closest e ".box") id (keyword (.. el -dataset -box)) b (some-> (get-in (current) [:boxes id]) view-box)]
954
+ (when b
955
+ ;; the first click redraws the box, so a double click on a patch box is detected here
956
+ (let [now (js/Date.now) [lid lt] (:last-box-click @ui) again? (and (= lid id) (< (- now lt) 450))]
957
+ (cond
958
+ ;; a patch @name: its line, in its tab (#117)
959
+ (and again? (line-ref? b) (not (.-altKey e)))
960
+ (do (.preventDefault e)
961
+ (swap! ui assoc :last-box-click nil :drag nil)
962
+ (js/setTimeout (fn [] (gesture! (str "(open-ref " id ")"))) 0))
963
+ (and again? (embedded? b) (not (.-altKey e)))
964
+ (do (.preventDefault e)
965
+ (swap! ui assoc :last-box-click nil :drag nil)
966
+ (js/setTimeout (fn [] (gesture! (str "(enter " id ")"))) 0))
967
+ ;; a double-click on the right of the header of a box with data opens it as text
968
+ (and again? (data-header? id b x y))
969
+ (do (.preventDefault e)
970
+ (swap! ui assoc :last-box-click nil :drag nil)
971
+ (js/setTimeout (fn [] (open-code-editor! id)) 0))
972
+ :else (pick-box! id b x y {:last-box-click [id now]})))))
973
+
974
+ (closest e ".wire-hit")
975
+ (let [idx (js/parseInt (.. (closest e ".wire-hit") -dataset -line) 10)]
976
+ (swap! ui assoc :sel [:line (nth (:lines (current)) idx)] :nsel nil))
977
+
978
+ ;; an empty place of the paper: a frame starts (a plain click there deselects); in presentation, nothing
979
+ (locked?) (swap! ui assoc :sel nil :nsel nil :tsel nil :insp nil)
980
+ :else (let [add? (.-shiftKey e)]
981
+ (swap! ui assoc :nsel nil :tsel nil :insp nil
982
+ :sel (when add? (:sel @ui))
983
+ :marquee {:x0 x :y0 y :x x :y y :moved false :add add? :base (if add? (sel-ids) #{})}))))))
984
+
985
+ (defn move-ldrag [ld x y]
986
+ (let [{:keys [g d x0 y0 pts0]} ld
987
+ [t0 f0] (first pts0)
988
+ dt (cv/round-to (- (snap-t d (cv/x->t g (+ (cv/t->x g t0) (- x x0)))) t0) 4)
989
+ ft (snap-f d (cv/y->f g (+ (cv/f->y g f0) (- y y0))))
990
+ dc (cv/round-to (cv/delta-y d ft f0) 3)]
991
+ (assoc ld :moved true :dt dt :dc dc :pts (mapv (fn [[t f]] [(+ t dt) (cv/shift-y d f dc)]) pts0))))
992
+
993
+ (defn draw-ldrag [ld x y]
994
+ (let [{:keys [g d mode t0 f0 bx by raw]} ld
995
+ lx (- x bx) ly (- y by)]
996
+ (case mode
997
+ :note (assoc ld :pts [[t0 f0] [(snap-t d (cv/x->t g lx)) f0]])
998
+ :line (assoc ld :pts [[t0 f0] [(snap-t d (cv/x->t g lx)) (snap-f d (cv/y->f g ly))]])
999
+ :free (let [[px py] (peek raw)
1000
+ far? (if (cv/generic? d) (> (js/Math.hypot (- lx px) (- ly py)) 2) (> lx (+ px 1)))
1001
+ raw (if far? (conj raw [lx ly]) raw)]
1002
+ (assoc ld :raw raw :pts (mapv (fn [[px py]] [(cv/x->t g px) (cv/y->f g py)]) raw))))))
1003
+
1004
+ (defn hover-hit!
1005
+ "The part of a component's view (a shape with :hit) the pointer is over or near, highlighted."
1006
+ [e x y]
1007
+ (let [el (closest e ".box.act")
1008
+ [id b] (when el (el-box el))
1009
+ h (when (and b (fn? (:gesture (box-def b))) (not (closest e ".grip")))
1010
+ (let [f (fid id)
1011
+ k (try (shp/hit-near (ctl-shapes* (ctl-m* f b) b) [(- x (:x b) grip) (- y (:y b))]) (catch :default _ nil))]
1012
+ (when (some? k) [id k])))]
1013
+ (when (not= h (:hover-hit @ui))
1014
+ (swap! ui assoc :hover-hit h)
1015
+ (render-overlay!))))
1016
+
1017
+ (defn hover-out!
1018
+ "The outlet within reach of the pointer lights up, and the pointer becomes a cross: press there to wire."
1019
+ [x y]
1020
+ (let [h (when-not (or (locked?) (:annot @ui)) (port-near (current) :out x y))]
1021
+ (when (not= h (:hover-out @ui))
1022
+ (let [el-of (fn [[id o]] (.querySelector svg (str ".port.out[data-box=\"" (name id) "\"][data-out=\"" o "\"]")))]
1023
+ (some-> (:hover-out @ui) el-of .-classList (.remove "hot"))
1024
+ (some-> h el-of .-classList (.add "hot"))
1025
+ (.toggle (.-classList svg) "near-out" (some? h))
1026
+ (swap! ui assoc :hover-out h)))))
1027
+
1028
+ (.addEventListener svg "pointermove"
1029
+ (fn [e]
1030
+ (let [[x y] (pt e) {:keys [drag wire ldrag numdrag paramdrag ctldrag marquee resize adraw]} @ui]
1031
+ (cond
1032
+ adraw (annot-move! x y)
1033
+ resize (let [[w0 h0] size-min [w1 h1] size-max
1034
+ w (js/Math.round (max w0 (min w1 (+ (:w0 resize) (- x (:x0 resize))))))
1035
+ h (js/Math.round (max h0 (min h1 (+ (:h0 resize) (- y (:y0 resize))))))]
1036
+ (when (or (not= w (:w resize)) (not= h (:h resize)))
1037
+ (swap! ui assoc :resize (assoc resize :w w :h h :moved true))
1038
+ (render-scene (current))))
1039
+ marquee (let [far (> (+ (js/Math.abs (- x (:x0 marquee))) (js/Math.abs (- y (:y0 marquee)))) 3)
1040
+ m (assoc marquee :x x :y y :moved (or (:moved marquee) far))]
1041
+ (swap! ui assoc :marquee m)
1042
+ (when (:moved m) (draw-marquee! m)))
1043
+ (and drag (:ids drag))
1044
+ (let [[gx gy] (group-offset drag x y)]
1045
+ (when (or (:moved drag) (> (+ (js/Math.abs gx) (js/Math.abs gy)) 2))
1046
+ ;; what is being moved comes to the front, here (issue #166)
1047
+ (when-not (:moved drag) (to-front! (keys (:ids drag))))
1048
+ (swap! ui assoc :drag (assoc drag :gx gx :gy gy :moved true))))
1049
+ ctldrag (ctl-gesture! x y (.-shiftKey e))
1050
+ paramdrag (when-not (:button paramdrag)
1051
+ (let [b (get-in (current) [:boxes (:id paramdrag)]) v (value-at-x b (:p paramdrag) x)]
1052
+ (when (not= v (:v paramdrag))
1053
+ (swap! ui assoc :paramdrag (assoc paramdrag :v v))
1054
+ (send-quiet! (:id paramdrag) [(param-k (:label paramdrag)) v]))))
1055
+ numdrag (let [inc-size (if (.-shiftKey e) 0.01 0.1)
1056
+ v (cv/round-to (+ (:v0 numdrag) (* inc-size (js/Math.round (- (:y0 numdrag) y)))) 4)]
1057
+ (when (not= v (or (:v numdrag) (:v0 numdrag)))
1058
+ (swap! ui assoc :numdrag (assoc numdrag :v v))
1059
+ (let [was-on (eng/running?)]
1060
+ (inject-local! (fid (:id numdrag)) 0 v)
1061
+ (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!)))))
1062
+ (render-overlay!)))
1063
+ ldrag (let [far (> (+ (js/Math.abs (- x (:x0 ldrag))) (js/Math.abs (- y (:y0 ldrag)))) 3)]
1064
+ (when (or (:moved ldrag) far)
1065
+ (swap! ui assoc :ldrag
1066
+ (if (= :move (:kind ldrag))
1067
+ (move-ldrag ldrag x y)
1068
+ (assoc (draw-ldrag ldrag x y) :moved true)))))
1069
+ drag (let [nx (max 0 (- x (:dx drag))) ny (max 0 (- y (:dy drag)))]
1070
+ (when (or (:moved drag) (> (+ (js/Math.abs (- nx (:x drag))) (js/Math.abs (- ny (:y drag)))) 2))
1071
+ (when-not (:moved drag) (to-front! [(:id drag)]))
1072
+ (swap! ui assoc :drag (assoc drag :x nx :y ny :moved true))))
1073
+ wire (swap! ui assoc :wire (assoc wire :x x :y y) :hover-in (drop-target e wire))
1074
+ :else (do (hover-out! x y) (hover-hit! e x y))))))
1075
+
1076
+ (defn finish-drawing! [{:keys [box mode d g pts raw moved click-t]}]
1077
+ (if-not moved
1078
+ (pos-click! box click-t)
1079
+ (let [generic? (cv/generic? d)
1080
+ min-dur (if (:gx d) (cv/step-x (:gx d)) 0.05)
1081
+ pts (case mode
1082
+ :free (let [px (cv/simplify raw 1.5)]
1083
+ (mapv (fn [[px py]] [(cv/round-to (cv/x->t g px) 4) (cv/round-to (cv/y->f g py) 4)]) px))
1084
+ (if generic? pts (sort-by first pts)))
1085
+ ps (cv/sane-pts-for d pts)]
1086
+ (when (and ps (or generic? (>= (- (first (peek ps)) (ffirst ps)) (* 0.99 min-dur))))
1087
+ ;; drawn freehand (⌥): in a measured tree, the note goes to its free voice
1088
+ (gesture! (if (= mode :free)
1089
+ (str "(stroke " box " " (cv/next-id d) " " (pts-code ps) " true)")
1090
+ (str "(stroke " box " " (pts-code ps) ")")))))))
1091
+
1092
+ (defn end-gesture! [e]
1093
+ (let [{:keys [drag wire ldrag numdrag paramdrag ctldrag marquee resize adraw]} @ui]
1094
+ (cond
1095
+ adraw (annot-up!)
1096
+ resize (do (swap! ui assoc :resize nil)
1097
+ (if (:moved resize)
1098
+ (gesture! (str "(resize " (:id resize) " " (:w resize) " " (:h resize) ")"))
1099
+ (render-scene (current))))
1100
+ marquee (end-marquee! marquee)
1101
+ (and drag (:ids drag) (:moved drag))
1102
+ (let [{:keys [ids gx gy]} drag ks (sort-by box-num (keys ids)) r (fn [v] (js/Math.round v))]
1103
+ (swap! ui assoc :drag nil)
1104
+ (if (= 1 (count ks))
1105
+ (let [[x0 y0] (get ids (first ks))]
1106
+ (gesture! (str (if @pres-mode "(present " "(move ") (first ks) " " (r (+ x0 gx)) " " (r (+ y0 gy)) ")")))
1107
+ (gesture! (str (if @pres-mode "(present-by [" "(move-by [") (str/join " " ks) "] " (r gx) " " (r gy) ")"))))
1108
+ (and drag (:clicked drag))
1109
+ (swap! ui assoc :drag nil :sel [:box (:clicked drag)])
1110
+ ctldrag
1111
+ (let [v (ctl-release-value ctldrag)]
1112
+ (swap! ui assoc :ctldrag nil)
1113
+ ;; the change stays in the work (a knob is rewritten with its new arguments), or is sent as a gesture
1114
+ (ctl-commit! ctldrag v cv/fmt))
1115
+ paramdrag
1116
+ (do (swap! ui assoc :paramdrag nil)
1117
+ (if (:button paramdrag)
1118
+ (do (send-quiet! (:id paramdrag) [(param-k (:label paramdrag)) 0])
1119
+ (repl-print! "in from-patch" (str "<span class=\"p\">⟵</span>" (esc (str "(send! " (:id paramdrag) " [" (pr-str (param-k (:label paramdrag))) " 1]) … [" (pr-str (param-k (:label paramdrag))) " 0]")))))
1120
+ (gesture! (str "(send! " (:id paramdrag) " [" (pr-str (param-k (:label paramdrag))) " " (cv/fmt (:v paramdrag)) "])"))))
1121
+ numdrag
1122
+ (do (swap! ui assoc :numdrag nil)
1123
+ ;; let go after a drag: its value stays in its text, as a knob's (this tab already sent it); a click sends it again
1124
+ (if (:v numdrag)
1125
+ (ctl-commit! {:f (fid (:id numdrag)) :id (:id numdrag) :echo (str "(send! " (:id numdrag) " ")} (:v numdrag) cv/fmt)
1126
+ (gesture! (str "(send! " (:id numdrag) " :bang)"))))
1127
+ ldrag
1128
+ (do (swap! ui assoc :ldrag nil)
1129
+ (if (= :move (:kind ldrag))
1130
+ (when (and (:moved ldrag) (or (not (zero? (:dt ldrag))) (not (zero? (:dc ldrag)))))
1131
+ (gesture! (str "(move-stroke " (:box ldrag) " " (:tid ldrag) " " (cv/fmt (:dt ldrag)) " " (cv/fmt (:dc ldrag))
1132
+ ;; ⌥: a note of a measured tree leaves its measures
1133
+ (when (:alt ldrag) " :free") ")")))
1134
+ (finish-drawing! ldrag)))
1135
+ (and drag (:moved drag))
1136
+ (do (swap! ui assoc :drag nil)
1137
+ (gesture! (str (if @pres-mode "(present " "(move ") (:id drag) " " (js/Math.round (:x drag)) " " (js/Math.round (:y drag)) ")")))
1138
+ drag (swap! ui assoc :drag nil)
1139
+ wire
1140
+ (let [[to in] (when e (drop-target e wire))]
1141
+ (.remove (.-classList svg) "wiring")
1142
+ (swap! ui assoc :wire nil :hover-in nil)
1143
+ (when to
1144
+ (gesture! (str "(connect " (:from wire) " " (:out wire) " " to " " in ")"))
1145
+ ;; a tree into a freqt shown as a score: the edits made on the score come back to the tree (a dashed line)
1146
+ (let [p (current) from (:from wire)]
1147
+ (when (and (= "tree" (klass (get-in p [:boxes from :text]))) (= "freqt" (klass (get-in p [:boxes to :text])))
1148
+ (= :score (display-of (get-in p [:boxes to])))
1149
+ (zero? in)
1150
+ (not (some (fn [[a o b]] (and (= a to) (= o 2) (= b from))) (:lines p))))
1151
+ (gesture! (str "(connect " to " 2 " from " 0)"))
1152
+ (repl-print! "out" (esc (str "; and back: the edits made on " to " go to " from " (the dashed line)"))))))))))
1153
+
1154
+ (.addEventListener svg "pointerup" end-gesture!)
1155
+ (.addEventListener svg "pointerleave" (fn [_] (when (:hover-out @ui) (hover-out! -1e6 -1e6)) (when (:hover-hit @ui) (swap! ui assoc :hover-hit nil) (render-overlay!)) (when (or (:adraw @ui) (:drag @ui) (:wire @ui) (:ldrag @ui) (:numdrag @ui) (:paramdrag @ui) (:ctldrag @ui) (:marquee @ui) (:resize @ui)) (end-gesture! nil))))
1156
+
1157
+ (.addEventListener svg "dblclick"
1158
+ (fn [e]
1159
+ (let [[x y] (pt e)]
1160
+ (cond
1161
+ ;; in presentation no box is written or created
1162
+ (locked?) nil
1163
+ (closest e ".resize-corner") nil
1164
+ (closest e ".code-area") nil
1165
+ (or (closest e ".param") (closest e ".pval-hit") (closest e ".pres-area")
1166
+ (closest e ".stroke-hit") (closest e ".score-slot") (closest e ".mus-body")) nil
1167
+ (and (closest e ".box.act") (not (closest e ".grip"))) nil
1168
+ (closest e ".hchip") nil
1169
+ (closest e ".box")
1170
+ (let [el (closest e ".box") id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])]
1171
+ (when b
1172
+ (if (or (and (or (embedded? b) (line-ref? b)) (not (.-altKey e))) (data-header? id (view-box b) x y))
1173
+ nil
1174
+ (open-editor! {:id id :x (:x b) :y (:y b) :text (:text b)}))))
1175
+ :else (open-editor! {:x x :y y})))))
1176
+
1177
+ (defn stroke-key!
1178
+ "Arrows, + − and Delete on the chosen stroke, respecting the grids of the canvas."
1179
+ [e k [id tid]]
1180
+ (let [b (get-in (current) [:boxes id]) d (:data b) tr (get-in d [:strokes tid]) sh (.-shiftKey e)]
1181
+ (if (nil? tr)
1182
+ (swap! ui assoc :nsel nil)
1183
+ (let [pts (:pts tr) [t0 f0] (first pts) dur (- (first (peek pts)) t0)
1184
+ gy (:gy d) stp (cv/step-x (:gx d)) cyc (cv/cycle (:gx d))
1185
+ g (canvas-geom d id b)
1186
+ dc (fn [dir] (cond
1187
+ (cv/generic? d) (* dir (if sh 5 1) (or (:step gy) (cv/nice-step (- (:yb g) (:ya g)) 20)))
1188
+ (:cents gy)
1189
+ (cv/round-to (cv/hz->cents (cv/degree->hz gy (+ (cv/hz->degree gy f0) (* dir (if sh (count (cv/degrees gy)) 1)))) f0) 3)
1190
+ :else (* dir (if sh 1200 100))))
1191
+ move-by (fn [dt c] (gesture! (str "(move-stroke " id " " tid " " (cv/fmt dt) " " (cv/fmt c) ")")))
1192
+ stretch-to (fn [nd] (gesture! (str "(stretch " id " " tid " " (cv/fmt (/ nd dur)) ")")))]
1193
+ (case k
1194
+ "ArrowUp" (move-by 0 (dc 1))
1195
+ "ArrowDown" (move-by 0 (dc -1))
1196
+ "ArrowLeft" (when (or (cv/generic? d) (pos? t0)) (move-by (- (if (cv/generic? d) (if sh cyc stp) (min t0 (if sh cyc stp)))) 0))
1197
+ "ArrowRight" (move-by (if sh cyc stp) 0)
1198
+ ("+" "=") (stretch-to (+ dur stp))
1199
+ "-" (when (> dur stp) (stretch-to (- dur stp)))
1200
+ ("Delete" "Backspace") (do (swap! ui assoc :nsel nil) (gesture! (str "(erase-stroke " id " " tid ")")))
1201
+ "Escape" (swap! ui assoc :nsel nil)
1202
+ nil)))))
1203
+
1204
+ (.addEventListener js/document "keydown"
1205
+ (fn [e]
1206
+ (let [tag (.. js/document -activeElement -tagName) k (.-key e) mod? (or (.-ctrlKey e) (.-metaKey e))]
1207
+ (when (and (= k "Escape") (:merge-pick @ui))
1208
+ (swap! ui assoc :merge-pick false)
1209
+ (.remove (.-classList ($ "hist-wrap")) "picking"))
1210
+ (when-not (#{"INPUT" "TEXTAREA"} tag)
1211
+ (cond
1212
+ (and (or (= k "?") (= k "F1")) (not mod?))
1213
+ (let [[kind v] (:sel @ui) b (when (= kind :box) (get-in (current) [:boxes v]))]
1214
+ (.preventDefault e)
1215
+ (show-help! (when b (klass (:text b)))))
1216
+ (and (:tsel @ui) (not mod?)
1217
+ (or (#{"ArrowUp" "ArrowDown" "ArrowLeft" "ArrowRight" "+" "=" "-" "#" "Delete" "Backspace" "Escape" "Enter"} k)
1218
+ (letter-pcs (str/lower-case k))))
1219
+ (do (.preventDefault e)
1220
+ (try (tree-key! k (.-shiftKey e))
1221
+ (catch :default ex (repl-print! "err" (esc (or (.-message ex) (str ex)))))))
1222
+ (and (:nsel @ui) (not mod?)
1223
+ (#{"ArrowUp" "ArrowDown" "ArrowLeft" "ArrowRight" "+" "=" "-" "Delete" "Backspace" "Escape"} k))
1224
+ (do (.preventDefault e) (stroke-key! e k (:nsel @ui)))
1225
+ (and (= k " ") (not= tag "BUTTON") (.-hidden ($ "manager")))
1226
+ (do (.preventDefault e) (gesture! (if (eng/running?) "(stop)" "(play)")))
1227
+ (and (#{"Delete" "Backspace"} k) (:sel @ui) (not (locked?)))
1228
+ (let [[kind v] (:sel @ui)]
1229
+ (.preventDefault e)
1230
+ (swap! ui assoc :sel nil :insp nil)
1231
+ (case kind
1232
+ :box (gesture! (str "(delete " v ")"))
1233
+ :boxes (gesture! (str "(delete " (str/join " " (sort-by box-num v)) ")"))
1234
+ (gesture! (str "(disconnect " (str/join " " v) ")"))))
1235
+ (and (= k "Escape") (or (:sel @ui) (:insp @ui)))
1236
+ (swap! ui assoc :sel nil :insp nil)
1237
+ ;; ⌘/Ctrl+A: every box on screen
1238
+ ;; (in presentation it selects nothing, and the browser does not select the page either)
1239
+ (and mod? (= (str/lower-case k) "a") (.-hidden ($ "manager")))
1240
+ (do (.preventDefault e)
1241
+ (when-not (locked?) (swap! ui assoc :sel (sel-of (keys (scene-boxes))) :insp nil :nsel nil :tsel nil)))
1242
+ (and mod? (= (str/lower-case k) "z") (.-shiftKey e))
1243
+ (do (.preventDefault e) (gesture! "(forward)"))
1244
+ (and mod? (= (str/lower-case k) "z"))
1245
+ (do (.preventDefault e) (gesture! "(rewind)"))
1246
+ (and mod? (= (str/lower-case k) "y"))
1247
+ (do (.preventDefault e) (gesture! "(forward)")))))))