@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,838 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · components
3
+ ;; Every box class is a component: a map of data and functions, registered by name.
4
+ ;; The patch, the engine and the projection to code only consult this registry, so adding
5
+ ;; a class (from the core, from a library or written by whoever uses the system) touches nothing else.
6
+ ;;
7
+ ;; {:class "ramp" the first word of the box text
8
+ ;; :doc "…" :usage "ramp from to seconds [loop]"
9
+ ;; :license "MPL-2.0" SPDX id
10
+ ;; :args [[:min 0] [:max 1] [:initial :min] [:log false] [:name nil]]
11
+ ;; declared arguments, in order. The kind of the default decides how
12
+ ;; the words of the box text fill them: a number (or the key of an
13
+ ;; earlier argument) takes the next number; true/false is a flag that is
14
+ ;; on when its own name is written ("log"); anything else (nil, a
15
+ ;; string) takes the next free word, as a keyword. With :args, the m
16
+ ;; of :receive, :derive, :draw and :gesture gets :args as that map
17
+ ;; (without it, :args is the raw vector of words and numbers).
18
+ ;; :io [2 1] | (fn [box] [inlets outlets]) box = {:text :args :data}
19
+ ;; :dynamic-io true its ports depend on something computed (lines are not pruned)
20
+ ;; :receive (fn [m] result) messages; pure. m = {:id :state :args :inlet :value :at :data
21
+ ;; :buffer :buffer-id}
22
+ ;; result = {:state :out [[o v]] :later [[at i v]] :effects [[k x]] :show v}
23
+ ;; The same value again must change nothing that is going on: data
24
+ ;; boxes send what they hold again after ■, when a line or a box
25
+ ;; before it is new, or in a room. A player does not start over, a
26
+ ;; learner does not learn it twice (compare with what :state keeps).
27
+ ;; What its audio node finds in the sound (api/report!) arrives here
28
+ ;; too, with :inlet :audio: a level, a block of samples, an error.
29
+ ;; What one of its :tasks found arrives with :inlet :task:
30
+ ;; {:task k :arg x :value v} or {:task k :arg x :error "…"}.
31
+ ;; :tasks {k (fn [x box] promise)} what the box asks of the world (the network, a file…), outside
32
+ ;; its pure logic: :receive returns the effect [k x], the engine
33
+ ;; runs the task, with or without ▶, and its outcome comes back on
34
+ ;; inlet :task. box = {:text :args :data :id :state}. The effect
35
+ ;; [:keep d] then writes d as the data of the box (its :model :load
36
+ ;; reads it), as a gesture: in the history, the same for everyone.
37
+ ;; :audio {:create (fn [ac box env] node) box = {:text :args (raw) :data :id :state}, env = {:master …}
38
+ ;; node = {:inlets [[AudioNode i]] :outlets [[AudioNode o]] …}
39
+ ;; (an inlet can be an AudioParam: a signal is added to it)
40
+ ;; :effects {k (fn [node x at])}
41
+ ;; :key (fn [box] x) if it changes, the node is rebuilt
42
+ ;; :update (fn [node box at]) with it, a new text does not rebuild the node: it gets the
43
+ ;; new box (:text :args …) instead (and its state is forgotten)
44
+ ;; :wired (fn [node inlets]) after wiring: the set of inlets that receive a signal
45
+ ;; :feed (fn [node data]) the buffer at its right inlet, whenever it changes (:reads-buffer)
46
+ ;; :dispose (fn [node])}
47
+ ;; :sends (fn [box] value) a data box: the page sends this value out of its outlet 0 whenever
48
+ ;; the text or data of the box changes (and again toward a new line or
49
+ ;; a box after it that changed), as a tree box sends its tree. box =
50
+ ;; {:id :text :args :data}; nil while the value is not ready yet
51
+ ;; :model {:empty x :step (fn [d ev]) :load (fn [x]) :code (fn [id d] lines)} box data with its own history
52
+ ;; With :source (fn [d] text), :read (fn [d text] d2) and :diff (fn [d d2] events) its data can
53
+ ;; also be read and edited as text, in the code window (discussion #30): read throws on bad
54
+ ;; text, and what diff returns is applied as one [:batch events] of the history.
55
+ ;; :display :text | :canvas | :score | :code | :number | :msg | :bang how the patch shows built-in boxes
56
+ ;; :views [:code :score] the displays a box of this class can switch between, the first
57
+ ;; one its default: each box keeps its choice, (view :bN :score),
58
+ ;; and its data stays the same (discussion #30)
59
+ ;; :view-as {:roll :canvas} a view drawn as another display (a tree's roll is drawn as a canvas)
60
+ ;; :view-aliases {:canvas :roll} older names of its views, still read (in works and in (view …))
61
+ ;; :language "edn" with a :display that is not :code: its [:data :source] is still
62
+ ;; its text, opened in the code window from { } (a tree box)
63
+ ;; :size [width height] | (fn [box] [w h]) a box with its own view (drawing and gestures), handle not counted
64
+ ;; :view shapes a shapes template (kairotic.shapes) whose values can be holes,
65
+ ;; keywords starting with $ (:$angle). Plain data: preferred over :draw
66
+ ;; :derive (fn [m] {key value}) pure; the values for the holes of :view. Same m as :draw.
67
+ ;; Holes can also name an argument (:$min) or :shown, :w, :h
68
+ ;; :draw (fn [m] shapes) escape hatch; pure; m = {:shown :state :args :text :data :w :h};
69
+ ;; :shown is the last thing the box returned as :show
70
+ ;; :gesture (fn [m] value) dragging over the box; m = the one of :draw plus {:start :x :y :dx :dy :fine :hit}
71
+ ;; (:start = what was shown on press; x, y local; dx, dy since the press;
72
+ ;; :fine with ⇧; :hit = the :hit of the shape pressed, kairotic.shapes). The value reaches inlet 0 of the box itself while
73
+ ;; dragging. On release it is called once more with :up true, and
74
+ ;; what it returns stays in the history as (send :bN value) (a
75
+ ;; :gesture that ignores :up repeats its last value: knob, sliders)
76
+ ;; :persist (fn [value] {arg value}) with :args: what a gesture leaves in the box text. On release, instead of
77
+ ;; (send! :bN value) the patch writes (text! :bN "class …") with these
78
+ ;; arguments, so the change stays in the work
79
+ ;; :parse (fn [text] args) instead of :args: reads the arguments from the whole box text (the
80
+ ;; functions of clojure.core as boxes read theirs as EDN)
81
+ ;; :language "faust" for code boxes
82
+ ;; :template "…" initial source of a code box
83
+ ;; :params … parameters
84
+ ;; :reads-buffer true receives in m the canvas connected to its right inlet
85
+ ;; :patch {:boxes … :lines …} an abstraction: the class is a patch. Its inlet/inlet~ and
86
+ ;; outlet/outlet~ boxes, ordered left to right, are its ports, and
87
+ ;; $1 $2 … in the texts of its boxes take the words of the box text.
88
+ ;; The engine expands it in place (kairotic.engine/flatten-patch)
89
+ ;; :origin :core | :work | :user
90
+ ;; :from :bN} the box that defines a work class
91
+
92
+ (ns kairotic.components
93
+ (:require [clojure.string :as str]
94
+ [clojure.edn :as edn]
95
+ [kairotic.score :as sc]
96
+ [kairotic.canvas :as cv]
97
+ [kairotic.span :as span]))
98
+
99
+ (defonce registry (atom {}))
100
+ ;; how a musical tree becomes a buffer of strokes (set by kairotic.mtboxes; kairotic.mt is not required here)
101
+ (defonce tree-buffer (atom nil))
102
+ ;; how an audio node gives its own box something found in the sound: (fn [id value at]) (set by
103
+ ;; kairotic.engine, which is loaded after this; components reach it through kairotic.api/report!)
104
+ (defonce audio-report (atom nil))
105
+ ;; how an audio node asks the page for an effect of its box ([:sample …]): (fn [id effect]) (kairotic.engine)
106
+ (defonce audio-effect (atom nil))
107
+ ;; what runs after the audio nodes are fitted and fed, every tick (kairotic.ringaudio folds faust~ loops there)
108
+ (defonce after-feed (atom nil))
109
+
110
+ (declare patch-io)
111
+
112
+ (defn define!
113
+ "Registers (or replaces) a component. Returns its name. An abstraction (:patch) gets its ports
114
+ from its inlet and outlet boxes."
115
+ [klass-name d]
116
+ (let [d (if (map? (:patch d))
117
+ (assoc d :io (fn [_] (patch-io (:patch d))) :dynamic-io true :abstraction true)
118
+ d)]
119
+ (swap! registry assoc klass-name (merge {:display :text :origin :core :io [1 1]} d {:class klass-name})))
120
+ klass-name)
121
+
122
+ ;; classes that are not registered but can be made when a box asks for them (kairotic.corefns: the
123
+ ;; functions of clojure.core): each is (fn [class-name] definition-or-nil). A registered class comes first.
124
+ (defonce fallbacks (atom []))
125
+
126
+ (defn lookup [klass-name]
127
+ (or (get @registry klass-name)
128
+ (some (fn [f] (f klass-name)) @fallbacks)))
129
+
130
+ ;; ───────── text of a box ─────────
131
+
132
+ ;; A box can start with flags written as Clojure metadata, before its class: ^:hot vector % 0 0
133
+ ;; (the hot mode of Clojure boxes). They are not part of the class nor of its arguments.
134
+ (def ^:private meta-re #"^(?:\^:[^\s\^]+\s+)+")
135
+
136
+ (defn meta-flags
137
+ "The flags written before the class (^:hot → #{:hot})."
138
+ [text]
139
+ (let [m (re-find meta-re (str/trim (str text)))]
140
+ (if m (set (map (fn [[_ k]] (keyword k)) (re-seq #"\^:([^\s\^]+)" m))) #{})))
141
+
142
+ (defn strip-meta "The text without the flags written before the class." [text]
143
+ (str/replace (str/trim (str text)) meta-re ""))
144
+
145
+ (defn- form-end
146
+ "Where the bracketed form at the start of s ends (its length), strings and escapes skipped; the
147
+ whole length when it never closes."
148
+ [s]
149
+ (loop [i 0 depth 0 in-str false]
150
+ (if (>= i (count s))
151
+ (count s)
152
+ (let [c (.charAt s i)]
153
+ (cond
154
+ in-str (cond (= c "\\") (recur (+ i 2) depth true)
155
+ (= c "\"") (recur (inc i) depth false)
156
+ :else (recur (inc i) depth true))
157
+ (= c "\"") (recur (inc i) depth true)
158
+ (#{"{" "[" "("} c) (recur (inc i) (inc depth) false)
159
+ (#{"}" "]" ")"} c) (if (= depth 1) (inc i) (recur (inc i) (dec depth) false))
160
+ :else (recur (inc i) depth false))))))
161
+
162
+ (defn klass
163
+ "The class of a box: its first word, after any ^:flags. A map or a set written first ({60 :c 64 :e},
164
+ #{60 64 67}) is the class as a whole, as a function in Clojure."
165
+ [text]
166
+ (let [t (strip-meta text)]
167
+ (if (re-find #"^#?\{" t)
168
+ (subs t 0 (form-end t))
169
+ (first (str/split t #"\s+")))))
170
+
171
+ (defn token [s]
172
+ (if (re-matches #"-?(\d+\.?\d*|\.\d+)(e-?\d+)?" s) (js/parseFloat s) (keyword s)))
173
+
174
+ (defn args-of [text]
175
+ (let [t (strip-meta text)]
176
+ (mapv token (remove str/blank? (str/split (str/trim (subs t (count (klass t)))) #"\s+")))))
177
+
178
+ (defn box-info [b] {:text (:text b) :args (args-of (:text b)) :data (:data b)})
179
+
180
+ (defn io
181
+ "Inlets and outlets of a box (a map with :text and, if it has it, :data)."
182
+ [b]
183
+ (let [d (lookup (klass (:text b))) x (:io d)]
184
+ (cond (fn? x) (x (box-info b)) (vector? x) x :else [1 1])))
185
+
186
+ (defn dynamic?
187
+ "Ports that must not be pruned: computed ones (a compilation) and those of classes defined by the
188
+ work itself or that do not exist yet, because they depend on when their definition is evaluated."
189
+ [b]
190
+ (let [d (lookup (klass (:text b)))]
191
+ (boolean (or (nil? d) (:dynamic-io d) (= :work (:origin d))))))
192
+
193
+ (defn model-of [b] (:model (lookup (klass (:text b)))))
194
+
195
+ ;; classes that became a view of another one: a box written with the old name is read as the new
196
+ ;; class, in that view (discussion #30: a score box is a freqt shown as a score)
197
+ (def renamed {"score" ["freqt" :score]})
198
+
199
+ (defn upgrade-box
200
+ "A box of a renamed class, as its new class in the matching view (its arguments kept); others unchanged."
201
+ [b]
202
+ (let [t (str/trim (str (:text b))) k (klass t)]
203
+ (if-let [[nk v] (get renamed k)]
204
+ (let [b (assoc b :text (str nk (subs t (count k))))]
205
+ ;; the view it showed: its old default becomes v; another view it could show stays, if the new
206
+ ;; class has it and it is not that class's default
207
+ (if (or (nil? (:view b)) (= (:view b) v))
208
+ (assoc b :view v)
209
+ (let [vs (:views (lookup nk))]
210
+ (if (and (some #{(:view b)} vs) (not= (:view b) (first vs))) b (dissoc b :view)))))
211
+ b)))
212
+
213
+ (defn views-of "The displays a box can switch between (none, or one, if its class has no :views)." [b]
214
+ (:views (lookup (klass (:text b)))))
215
+
216
+ (defn view-name
217
+ "A view as its class names it now: an older name ((:view-aliases of the class) becomes the current one."
218
+ [b v] (get (:view-aliases (lookup (klass (:text b)))) v v))
219
+
220
+ (defn shown-as
221
+ "The view a box is shown in: the view it chose, if its class offers it (by its current name or an older
222
+ one), or the :display of its class."
223
+ [b]
224
+ (let [d (lookup (klass (:text b))) v (view-name b (:view b))]
225
+ (if (and (keyword? v) (some #{v} (:views d))) v (or (:display d) :text))))
226
+
227
+ (defn drawn-as
228
+ "How a box is drawn: the display of the view it is shown in (a tree's :roll is drawn as a :canvas)."
229
+ [b]
230
+ (let [v (shown-as b)] (get (:view-as (lookup (klass (:text b)))) v v)))
231
+
232
+ (defn source-of
233
+ "The data of a box as text, to edit (a code box's source, or what its model's :source writes), or nil."
234
+ [b]
235
+ (let [m (model-of b)]
236
+ (cond (fn? (:source m)) ((:source m) (or (:data b) (:empty m)))
237
+ (let [d (lookup (klass (:text b)))] (or (= :code (:display d)) (string? (:language d))))
238
+ (str (get-in b [:data :source]))
239
+ :else nil)))
240
+
241
+ (defn own-view?
242
+ "Does the box have its own view (a :draw or a :view)?"
243
+ [b]
244
+ (let [d (lookup (klass (:text b)))]
245
+ (boolean (or (fn? (:draw d)) (some? (:view d))))))
246
+
247
+ (defn size-of
248
+ "Size of a box's own view, bounded to something reasonable."
249
+ [b]
250
+ (let [s (:size (lookup (klass (:text b))))
251
+ s (if (fn? s) (try (s (box-info b)) (catch :default _ nil)) s)]
252
+ (if (and (sequential? s) (= 2 (count s)) (every? number? s))
253
+ [(max 24 (min 480 (first s))) (max 16 (min 480 (second s)))]
254
+ [64 64])))
255
+
256
+ ;; ───────── patches inside patches ─────────
257
+ ;; A sub-patch (an embedded `patch` box, or an instance of an abstraction) talks to the outside
258
+ ;; through its inlet/outlet boxes: message ones (inlet, outlet) and audio ones (inlet~, outlet~)
259
+ ;; share the numbering, ordered by their position from left to right, as in Max.
260
+
261
+ (def inlet-classes #{"inlet" "inlet~"})
262
+ (def outlet-classes #{"outlet" "outlet~"})
263
+
264
+ (defn patch-ports
265
+ "The ids of a patch's inlet and outlet boxes, in port order: {:inlets [...] :outlets [...]}."
266
+ [p]
267
+ (let [of (fn [classes]
268
+ (->> (:boxes p)
269
+ (filter (fn [[_ b]] (contains? classes (klass (:text b)))))
270
+ (sort-by (fn [[id b]] [(or (:x b) 0) (or (:y b) 0) (name id)]))
271
+ (mapv first)))]
272
+ {:inlets (of inlet-classes) :outlets (of outlet-classes)}))
273
+
274
+ (defn patch-io [p] (let [{:keys [inlets outlets]} (patch-ports p)] [(count inlets) (count outlets)]))
275
+
276
+ (defn subpatch?
277
+ "Is the box a sub-patch (embedded or an abstraction)?"
278
+ [b]
279
+ (let [k (klass (:text b))]
280
+ (or (= k "patch") (map? (:patch (lookup k))))))
281
+
282
+ ;; ───────── utilities for writing components ─────────
283
+
284
+ (defn parse-args
285
+ "Fills a declared :args spec from the raw words and numbers of a box text (see the header)."
286
+ [spec raw]
287
+ (let [words (filter keyword? raw)
288
+ flag-names (set (keep (fn [[k d]] (when (boolean? d) (name k))) spec))
289
+ written (set (map name words))]
290
+ (loop [[[k d :as item] & more] spec
291
+ nums (filter number? raw)
292
+ free (remove (fn [w] (flag-names (name w))) words)
293
+ acc {}]
294
+ (if-not item
295
+ acc
296
+ (cond
297
+ (boolean? d) (recur more nums free (assoc acc k (if (contains? written (name k)) true d)))
298
+ (or (number? d) (and (keyword? d) (contains? acc d)))
299
+ (recur more (rest nums) free (assoc acc k (cond (seq nums) (first nums) (keyword? d) (get acc d) :else d)))
300
+ :else (recur more nums (rest free) (assoc acc k (if (seq free) (first free) d))))))))
301
+
302
+ (defn num-text [x] (if (== x (js/Math.round x)) (str (js/Math.round x)) (str (/ (js/Math.round (* x 10000)) 10000))))
303
+
304
+ (defn args-text
305
+ "The text of a box of class k whose arguments are `vals` (a map), written in the order of the :args
306
+ spec of d: the numbers (those still at their default at the end are left out), then flags and words."
307
+ [d k vals]
308
+ (let [spec (:args d)
309
+ dflt (fn [x] (if (keyword? x) (get vals x) x))
310
+ nums (for [[a v] spec :when (or (number? v) (and (keyword? v) (not (boolean? v))))]
311
+ [(get vals a (dflt v)) (dflt v)])
312
+ nums (reverse (drop-while (fn [[v d0]] (= v d0)) (reverse nums)))
313
+ flags (for [[a v] spec :when (and (boolean? v) (get vals a))] (name a))
314
+ words (for [[a v] spec :when (not (or (number? v) (keyword? v) (boolean? v)))
315
+ :let [w (get vals a)] :when w] (if (keyword? w) (name w) (str w)))]
316
+ (str/join " " (concat [k] (map (comp num-text first) nums) flags words))))
317
+
318
+ (defn args-for
319
+ "The :args a component receives: the parsed map if it declares :args, else the raw vector."
320
+ [d text]
321
+ (let [raw (args-of text) spec (:args d)]
322
+ (cond
323
+ (fn? (:parse d)) ((:parse d) text)
324
+ (and (sequential? spec) (every? (fn [x] (and (vector? x) (keyword? (first x)))) spec)) (parse-args spec raw)
325
+ :else raw)))
326
+
327
+ (defn clamp
328
+ "x between a and b (in either order)."
329
+ [x a b] (max (min a b) (min (max a b) x)))
330
+
331
+ (defn nice
332
+ "A value rounded to a sensible precision for display and sending."
333
+ [v]
334
+ (let [a (js/Math.abs v)
335
+ e (cond (>= a 100) 1 (>= a 10) 10 (>= a 1) 100 :else 1000)]
336
+ (/ (js/Math.round (* v e)) e)))
337
+
338
+ (defn to-unit
339
+ "Where v lies between lo and hi, as 0…1 (logarithmically if log? and both are positive)."
340
+ [v lo hi log?]
341
+ (let [u (cond (= lo hi) 0
342
+ (and log? (pos? lo) (pos? hi) (pos? v)) (/ (js/Math.log (/ v lo)) (js/Math.log (/ hi lo)))
343
+ :else (/ (- v lo) (- hi lo)))]
344
+ (if (js/isFinite u) (clamp u 0 1) 0)))
345
+
346
+ (defn from-unit
347
+ "The value at u (0…1) between lo and hi, rounded with `nice`."
348
+ [u lo hi log?]
349
+ (let [u (clamp u 0 1)]
350
+ (nice (if (and log? (pos? lo) (pos? hi)) (* lo (js/Math.pow (/ hi lo) u)) (+ lo (* u (- hi lo)))))))
351
+
352
+ (defn num-of [v] (cond (number? v) v (and (sequential? v) (number? (first v))) (first v) :else nil))
353
+ (defn map-num [f v] (cond (number? v) (f v) (sequential? v) (mapv (fn [x] (if (number? x) (f x) x)) v) :else v))
354
+ (defn r6 [x] (/ (js/Math.round (* x 1e6)) 1e6))
355
+ (defn tick? [v g] (and (vector? v) (= :tick (first v)) (or (nil? g) (= g (second v)))))
356
+ (def grain 0.01)
357
+
358
+ ;; ───────── core: messages ─────────
359
+
360
+ (defn arit [op]
361
+ (fn [{:keys [state args inlet value]}]
362
+ (let [b (if (some? state) state (or (num-of (first args)) 0))]
363
+ (cond (= inlet 1) {:state (or (num-of value) b)}
364
+ (or (number? value) (sequential? value)) {:state b :out [[0 (map-num (fn [x] (op x b)) value)]]}
365
+ :else {:state b}))))
366
+
367
+ (defn ramp [{:keys [state args inlet value at]}]
368
+ (let [[a b s lp] args
369
+ st (or state {:gen 0 :a (or (num-of a) 0) :b (or (num-of b) 1) :s (max 0.01 (or (num-of s) 1))
370
+ :loop (= lp :loop) :on false})
371
+ start (fn [st a b s]
372
+ (let [g (inc (:gen st))]
373
+ {:state (assoc st :gen g :a a :b b :s s :t0 at :on true)
374
+ :out [[0 a]] :show a :later [[(+ at grain) 0 [:tick g]]]}))]
375
+ (cond
376
+ (tick? value nil)
377
+ (if (and (:on st) (tick? value (:gen st)))
378
+ (let [u (/ (- at (:t0 st)) (:s st))]
379
+ (cond
380
+ (and (>= u 1) (:loop st)) (start st (:a st) (:b st) (:s st))
381
+ (>= u 1) {:state (assoc st :on false) :out [[0 (:b st)]] :show (:b st)}
382
+ :else (let [v (r6 (+ (:a st) (* u (- (:b st) (:a st)))))]
383
+ {:state st :out [[0 v]] :show v :later [[(+ at grain) 0 [:tick (:gen st)]]]})))
384
+ {:state st})
385
+ (= inlet 1) {:state (assoc st :loop (boolean (and (num-of value) (not (zero? (num-of value))))))}
386
+ (= value :bang) (start st (:a st) (:b st) (:s st))
387
+ (= value :stop) {:state (assoc st :on false :gen (inc (:gen st)))}
388
+ (and (sequential? value) (= 3 (count value)) (every? number? value))
389
+ (let [[a b s] value] (start st a b (max 0.01 s)))
390
+ (number? value) {:state (assoc st :on false :gen (inc (:gen st))) :out [[0 value]] :show value}
391
+ :else {:state st})))
392
+
393
+ (defn metro [{:keys [state args inlet value at]}]
394
+ (let [st (or state {:on false :ms (max 5 (or (num-of (first args)) 500)) :gen 0})
395
+ next-tick (fn [st] [[(+ at (/ (:ms st) 1000)) 0 [:tick (:gen st)]]])]
396
+ (cond
397
+ (tick? value nil) (if (and (:on st) (tick? value (:gen st)))
398
+ {:state st :out [[0 :bang]] :show :bang :later (next-tick st)}
399
+ {:state st})
400
+ (= inlet 1) {:state (assoc st :ms (max 5 (or (num-of value) (:ms st))))}
401
+ (or (= value 0) (= value :stop)) {:state (assoc st :on false :gen (inc (:gen st)))}
402
+ (or (= value :bang) (number? value) (= value :start))
403
+ (let [st (assoc st :on true :gen (inc (:gen st)))]
404
+ {:state st :out [[0 :bang]] :show :bang :later (next-tick st)})
405
+ :else {:state st})))
406
+
407
+ (defn counter [{:keys [state args inlet value]}]
408
+ (let [[step mx mn] args
409
+ step (or (num-of step) 1) mn (or (num-of mn) 0) mx (num-of mx)
410
+ v (if (some? state) state mn)]
411
+ (cond
412
+ (= inlet 1) {:state (or (num-of value) v)}
413
+ (= value :reset) {:state mn}
414
+ (or (= value :bang) (number? value))
415
+ (let [nv (r6 (+ v step)) nv (if (and mx (>= nv mx)) mn nv)]
416
+ {:state nv :out [[0 v]] :show v})
417
+ :else {:state v})))
418
+
419
+ (defn number-box [{:keys [state args value]}]
420
+ (let [init (if (map? args) (:initial args) (num-of (first args)))
421
+ cur (if (some? state) state (or (num-of init) 0))]
422
+ (cond (= value :bang) {:state cur :out [[0 cur]] :show cur}
423
+ (num-of value) (let [v (num-of value)] {:state v :out [[0 v]] :show v})
424
+ :else {:state cur})))
425
+
426
+ ;; ───── a reader on a ring (kairotic.span): two ways, as a head of Study 47 ─────
427
+ ;; · it follows: d behind the ring's head, then its speed (msg :d 1, msg :speed 0.5, or reader d 1 [speed 0.5]),
428
+ ;; moving on its own: every tick it looks a tick ahead and sends what it will cross, each at the instant it meets
429
+ ;; it (so a d shorter than a tick may miss what is written meanwhile); it starts when the ring's time does
430
+ ;; (:start on its buffer wire) or when it gets a d; :stop stops it
431
+ ;; · it is moved: a number on the left is a position of the ring (seconds, or 0…1 with norm), from any source; it
432
+ ;; sends what it crosses since the last one, either way; a move larger than its jump is a seek
433
+ ;; What it sends: each value as it was written, on the left.
434
+
435
+ (def ring-tick 0.05)
436
+
437
+ (defn- word-num [args k] (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))
438
+
439
+ (defn reader-on-ring [{:keys [inlet value buffer state args at]}]
440
+ (let [r buffer st (or state {})
441
+ speed0 (or (word-num args :speed) 1)
442
+ jump (or (:jump st) (word-num args :jump) 0.5)
443
+ drift (fn [st T] (+ (or (:drift0 st) 0) (* (- 1 (:speed st)) (- T (:since st)))))
444
+ follow (fn [st d]
445
+ (let [g (inc (:gen st 0))]
446
+ {:state (assoc st :mode :follow :d d :speed (or (:speed st) speed0) :drift0 0 :since at :gen g)
447
+ :later [[at 0 [:tick g]]]}))
448
+ cmd (fn [k] (when (and (vector? value) (= k (first value)) (number? (second value))) (second value)))]
449
+ (cond
450
+ ;; the ring's time starts: a reader given a d begins to follow
451
+ (= inlet 1)
452
+ (let [d (or (:d st) (word-num args :d))]
453
+ (if (and (= value :start) d (not= :pos (:mode st))) (follow st d) {}))
454
+ (cmd :d) (follow st (cmd :d))
455
+ (cmd :speed)
456
+ (let [s (cmd :speed)]
457
+ {:state (if (= :follow (:mode st)) (assoc st :drift0 (drift st at) :since at :speed s) (assoc st :speed s))})
458
+ (cmd :jump) {:state (assoc st :jump (cmd :jump))}
459
+ (= value :stop) {:state (-> st (dissoc :mode) (update :gen (fnil inc 0)))}
460
+ ;; what it meets, at the instant it meets it
461
+ (and (vector? value) (= :reader/at (first value))) {:out [[0 (second value)]]}
462
+ (tick? value nil)
463
+ (if (and (= :follow (:mode st)) (= (second value) (:gen st)))
464
+ (let [now-p (span/follow-at r st at)
465
+ next-tick [(+ at ring-tick) 0 [:tick (:gen st)]]]
466
+ (if (nil? now-p)
467
+ {:state (dissoc st :p) :later [next-tick]} ; the ring has not started (or was cleared)
468
+ (let [end-p (span/follow-at r st (+ at ring-tick))
469
+ from (let [p (:p st)] (if (or (nil? p) (> (js/Math.abs (- now-p p)) jump)) now-p p))]
470
+ {:state (assoc st :p end-p) :show {:ring true :p (span/wrap r now-p)}
471
+ :later (conj (mapv (fn [[x e]] [(span/when-met now-p at (:speed st) x) 0 [:reader/at (:v e)]])
472
+ (span/crossings r at from end-p))
473
+ next-tick)})))
474
+ {})
475
+ (num-of value)
476
+ (let [u (num-of value) l (:dur r)
477
+ q (if (some #{:norm} args) (* u l) u)
478
+ prev (when (= :pos (:mode st)) (:p st))
479
+ p (if prev (+ prev (span/shortest l (span/wrap r prev) q)) q)
480
+ seek (or (nil? prev) (> (js/Math.abs (- p prev)) jump))]
481
+ {:state (-> st (assoc :mode :pos :p p) (update :gen (fnil inc 0)))
482
+ :show {:ring true :p (span/wrap r p)}
483
+ :out (if seek [] (mapv (fn [[_ e]] [0 (:v e)]) (span/crossings r at prev p)))})
484
+ :else {})))
485
+
486
+ (defn reader [{:keys [inlet value buffer buffer-id args] :as m}]
487
+ (cond
488
+ (span/ring? buffer) (reader-on-ring m)
489
+ ;; reader path [stroke]: a position from 0 to 1 along a stroke, in the order it was drawn → [x y]
490
+ (and (zero? inlet) (num-of value) (some #{:path} args))
491
+ (let [sid (first (remove #{:path :norm :d :speed :jump} (filter keyword? args)))
492
+ u (clamp (num-of value) 0 1)
493
+ pts (when buffer (cv/stroke-for buffer sid))
494
+ pt (when pts (cv/point-along buffer pts u))]
495
+ (if pt
496
+ {:out [[0 pt]] :show {:t u :from buffer-id :axis :path :pt pt}}
497
+ {}))
498
+ (and (zero? inlet) (num-of value))
499
+ (let [axis (if (some #{:y} args) :y :x)
500
+ ;; with norm, 0…1 covers the axis (as a reader~ reads it): its range, along a log axis too
501
+ t (if (and buffer (some #{:norm} args))
502
+ (let [[lo hi log] (if (= axis :y) (cv/y-range buffer) (cv/x-range buffer)) u (num-of value)]
503
+ (if (and log (pos? lo) (pos? hi)) (* lo (js/Math.pow (/ hi lo) u)) (+ lo (* u (- hi lo)))))
504
+ (num-of value))
505
+ r (if buffer (cv/read-along buffer axis t) [])]
506
+ ;; as in Max, first the right outlet (ids) and then the left one (values)
507
+ {:out [[1 (mapv first r)] [0 (mapv second r)]] :show {:t t :from buffer-id :n (count r) :axis axis}})
508
+ :else
509
+ {}))
510
+
511
+ ;; ───── what a canvas, freqt or score takes on its left inlet (issue #26) ─────
512
+ ;; · a number: comes out on the left and moves the cursor (as a click does)
513
+ ;; · a musical tree ([:voice …]): shown live over the buffer; (keep! :bN) writes it in, with its recipe
514
+ ;; · an edit: changes the buffer, as one event of the history (the same as the commands of the REPL)
515
+ ;; [:stroke [[x y] …]] · [:stroke :t3 [[x y] …]] · [:note t pitch dur] (pitch: MIDI or "c4")
516
+ ;; [:move :t1 dx dy] · [:stretch :t1 k] · [:erase :t1] · [:clear] · [:cut t] (everything from t on)
517
+ ;; · [:cut t1 t2] (what is between t1 and t2)
518
+ ;; [:axis :x lo hi] · [:axis :y lo hi :log] · [:grid-x step cycles] · [:grid-y step] · [:tuning "19-tet" ref]
519
+ ;; [:quantize {:meter "6/8" …}] (a freqt: how its score is quantized; nil: the defaults)
520
+ ;; [:batch [edit …]]: several at once, one event
521
+ ;; · a question: the answer comes out on the left, nothing changes
522
+ ;; [:read x] (or [:read :y v]) → [[stroke value] …] · [:strokes] → [:t1 …] · [:get :t1] → its points
523
+ ;; [:count] · [:end] (where the last stroke ends) · [:range] / [:range :y] → [lo hi] · [:data] → the buffer
524
+
525
+ (def canvas-edits #{:stroke :note :move :stretch :erase :clear :cut :axis :grid-x :grid-y :tuning :quantize :batch})
526
+ (def canvas-questions #{:read :strokes :get :count :end :range :data})
527
+
528
+ (defn canvas-edit?
529
+ "An edit for a canvas (and not a musical tree: [:note {…}] is a node of a tree, [:note 0 \"c4\" 1] an edit)."
530
+ [v]
531
+ (and (vector? v) (contains? canvas-edits (first v))
532
+ (or (not= :note (first v)) (cv/num? (second v)))))
533
+
534
+ (defn canvas-question? [v] (and (vector? v) (contains? canvas-questions (first v))))
535
+
536
+ (defn canvas-event
537
+ "One message as an event of the buffer d (ids given to new strokes), or nil if it does not read."
538
+ [d [op & args]]
539
+ (case op
540
+ :stroke (let [[a b c] args [id pts look] (if (keyword? a) [a b c] [(cv/next-id d) a b])]
541
+ (if (cv/sane-look look) [:stroke id pts look] [:stroke id pts]))
542
+ :note (let [[t p dur] args
543
+ hz (cond (cv/num? p) (if (cv/generic? d) p (cv/midi->hz p))
544
+ (string? p) (some-> (sc/pitch p) cv/midi->hz))]
545
+ (when (and (cv/num? t) (cv/num? dur) (pos? dur) hz)
546
+ [:stroke (cv/next-id d) [[t (cv/round-to hz 3)] [(+ t dur) (cv/round-to hz 3)]]]))
547
+ (:move :stretch :erase :clear) (into [op] args)
548
+ :axis (let [[k lo hi lg] args]
549
+ (cond (map? k) [:axis k]
550
+ (#{:x :y} k) [:axis (assoc (or (:ax d) cv/default-ax) k {:lo lo :hi hi :log (= lg :log)})]))
551
+ :grid-x (let [[s cs] args] [:grid-x (if (map? s) s (when (cv/num? s) {:step s :cycles (or cs [])}))])
552
+ :grid-y (let [[s] args] [:grid-y (if (map? s) s (when (cv/num? s) {:step s}))])
553
+ :quantize (let [[q] args] (when (or (nil? q) (map? q)) [:quantize q]))
554
+ :tuning (let [[x ref] args
555
+ base (cond (map? x) x
556
+ (string? x) (or (get cv/tunings (str/lower-case x)) (cv/parse-scl x)))]
557
+ (when base [:tuning (cond-> base (cv/num? ref) (assoc :ref ref) (not (cv/num? ref)) (update :ref #(or % cv/default-ref)))]))
558
+ nil))
559
+
560
+ (defn canvas-events
561
+ "The messages (an edit, or [:batch [edits]]) as events of the buffer d, each one applied before the next
562
+ is read (so new strokes get new ids); those that change nothing are left out."
563
+ [d msg]
564
+ (let [msgs (if (= :batch (first msg)) (filter vector? (second msg)) [msg])
565
+ ;; [:cut t] removes everything from t on, [:cut t1 t2] what is between t1 and t2 (as the erases,
566
+ ;; shortened and split strokes it takes)
567
+ msgs (mapcat (fn [m] (if (and (= :cut (first m)) (cv/num? (second m)))
568
+ [[:cut-now (second m) (let [t2 (get m 2)] (when (and (cv/num? t2) (> t2 (second m))) t2))]]
569
+ [m]))
570
+ msgs)]
571
+ (first (reduce (fn [[evs d] m]
572
+ (if (= :cut-now (first m))
573
+ (let [es (cv/cut-events d (second m) (get m 2))]
574
+ [(into evs es) (reduce cv/step d es)])
575
+ (let [e (canvas-event d m) d2 (when e (cv/step d e))]
576
+ (if (and e (not= d2 d)) [(conj evs e) d2] [evs d]))))
577
+ [[] d] msgs))))
578
+
579
+ (defn canvas-answer
580
+ "The answer to a question about the buffer d."
581
+ [d [q & args]]
582
+ (case q
583
+ :read (let [[a b] args] (if (#{:x :y} a) (cv/read-along d a b) (cv/read-along d :x a)))
584
+ :strokes (mapv first (cv/sorted-strokes d))
585
+ :get (get-in d [:strokes (first args) :pts])
586
+ :count (count (:strokes d))
587
+ :end (cv/end-t d)
588
+ :range (vec (take 2 (if (= :y (first args)) (cv/y-range d) (cv/x-range d))))
589
+ :data d
590
+ nil))
591
+
592
+ (defn canvas-receiver
593
+ "The left inlet of a canvas (empty: its buffer before anything is drawn)."
594
+ [empty]
595
+ (fn [{:keys [inlet value state data]}]
596
+ (let [d (or data empty)]
597
+ (cond
598
+ (not (zero? inlet)) {:state state}
599
+ (canvas-edit? value)
600
+ (let [evs (canvas-events d value)]
601
+ (if (seq evs)
602
+ {:state state :effects [[:canvas-edit evs]]}
603
+ {:state state :effects [[:print (str "canvas: " (pr-str value) " changes nothing (an id that is not there, or points it cannot take)")]]}))
604
+ (canvas-question? value)
605
+ (let [a (canvas-answer d value)] {:state state :out (if (some? a) [[0 a]] [])})
606
+ (and (vector? value) (keyword? (first value)))
607
+ {:state (assoc state :tree value) :show {:tree value}}
608
+ (num-of value)
609
+ {:state state :out [[0 (num-of value)]] :show (cond-> {:t (num-of value)} (:tree state) (assoc :tree (:tree state)))}
610
+ :else {:state state}))))
611
+
612
+ (def canvas-box (canvas-receiver cv/empty))
613
+
614
+ (def canvas-model {:empty cv/generic-empty :step cv/step :load (fn [x] (cv/step cv/generic-empty [:load x])) :code cv/->code
615
+ :source cv/->source :read cv/read-source :diff cv/diff})
616
+ (def freqt-model {:empty cv/empty :step cv/step :load (fn [x] (cv/step cv/empty [:load x])) :code cv/->code
617
+ :source cv/->source :read cv/read-source :diff cv/diff})
618
+
619
+ (define! "loadbang" {:doc "Sends a bang when the engine starts (▶)." :io [0 1] :receive (fn [_] {:out [[0 :bang]]})})
620
+ (define! "bang" {:doc "A button: when pressed (or on receiving anything) it sends a bang." :io [1 1] :display :bang
621
+ :receive (fn [_] {:out [[0 :bang]] :show :bang})})
622
+ (defn msg-word
623
+ "A word of a msg box, read as Clojure reads it: a number, :x a keyword, true false nil, and any other
624
+ word a name (a symbol) — inc, but also free text such as e4, 6/5, +7, https://…, /osc/address, whose
625
+ whole text is (str x)."
626
+ [w]
627
+ (cond (re-matches #"-?(\d+\.?\d*|\.\d+)(e-?\d+)?" w) (js/parseFloat w)
628
+ (and (str/starts-with? w ":") (> (count w) 1)) (keyword (subs w 1))
629
+ (= w "true") true
630
+ (= w "false") false
631
+ (= w "nil") nil
632
+ :else (symbol w)))
633
+
634
+ (defn msg-words
635
+ "The content of a msg box, after its class, read as in Clojure: numbers, keywords with their colon
636
+ (:stop, :rec), names (inc, e4, https://…), true false nil, text between quotes as strings —
637
+ \"https://…\", \"two words\", with \\\" and \\\\ inside (an unclosed quote takes the rest) — and EDN forms
638
+ ([0 4 7], {:freq 440}, #{60 64})."
639
+ [text]
640
+ (let [t (str/trim (str text))
641
+ t (subs t (count (klass t)))
642
+ n (count t)]
643
+ (loop [i 0 out [] word nil quoted nil]
644
+ (if (>= i n)
645
+ (cond quoted (conj out quoted)
646
+ word (conj out (msg-word word))
647
+ :else out)
648
+ (let [c (nth t i)]
649
+ (cond
650
+ (some? quoted) (cond (and (= c "\\") (< (inc i) n)) (recur (+ i 2) out word (str quoted (nth t (inc i))))
651
+ (= c "\"") (recur (inc i) (conj out quoted) nil nil)
652
+ :else (recur (inc i) out word (str quoted c)))
653
+ (re-matches #"\s" c) (recur (inc i) (if word (conj out (msg-word word)) out) nil nil)
654
+ (and (= c "\"") (nil? word)) (recur (inc i) out nil "")
655
+ ;; a form: [..], {..}, #{..}, (..) as EDN, whole
656
+ (and (nil? word) (or (#{"[" "{" "("} c) (and (= c "#") (= "{" (get t (inc i))))))
657
+ (let [rest-t (subs t i)
658
+ len (form-end (if (= c "#") (subs rest-t 1) rest-t))
659
+ len (if (= c "#") (inc len) len)
660
+ src (subs rest-t 0 len)]
661
+ (recur (+ i len) (conj out (try (edn/read-string src) (catch :default _ (symbol src)))) nil nil))
662
+ :else (recur (inc i) out (str word c) nil)))))))
663
+
664
+ (define! "msg" {:doc "Message: when pressed it sends its content, read as in Clojure: numbers, keywords with their colon (:stop, :rec 4), names (any other word: inc, e4, 6/5, https://…), true false nil, text between quotes (\"two words\") as a string and EDN forms ([0 4 7], {:freq 440}); several make a list. A word without its colon is a name, not a keyword: msg stop does not stop a metro, msg :stop does." :usage "msg :stop · msg 0 8 4 · msg inc"
665
+ :io [1 1] :display :msg
666
+ :parse msg-words
667
+ :receive (fn [{:keys [args]}] {:out [[0 (case (count args) 0 :bang 1 (first args) (vec args))]] :show :bang})})
668
+ (define! "number" {:doc "A draggable number; sends it when it changes or on receiving a bang. Let go (or typed), its value stays in its text, as a knob's does: it travels with the work, and going back in the history brings back the number it had." :usage "number [initial]"
669
+ :io [1 1] :display :number :receive number-box
670
+ ;; like a knob (issue #146): on release the value is written in the box text
671
+ :args [[:initial 0]] :persist (fn [v] {:initial v})})
672
+ (defn print-label
673
+ "The label of a print box: everything written after print (print out0 · print the left hand), or nil."
674
+ [text]
675
+ (let [t (strip-meta text) l (str/trim (subs t (count (klass t))))] (when (seq l) l)))
676
+
677
+ (define! "print" {:doc "Writes to the REPL whatever it receives, after its label: print out0 writes out0: 60 (without one, print: 60). A string is written as it is, anything else as EDN; to shape what it writes, a format or str before it (format \"%.1f Hz\")."
678
+ :usage "print [label]"
679
+ :io [1 0] :parse print-label
680
+ :receive (fn [{:keys [value args]}] {:effects [(if (string? args) [:print value args] [:print value])]})})
681
+
682
+ ;; ───── draw: a view made of the messages that arrive (kairotic.shapes) ─────
683
+ ;; Shapes arrive as data and are drawn as the shapes of any component: SVG, in the theme's colours,
684
+ ;; without markup of their own. A shape with :hit k, pressed, sends k out.
685
+
686
+ (def draw-kinds #{:rect :circle :line :arc :needle :path :text :curve :group})
687
+ (def draw-max 600)
688
+
689
+ (defn draw-shape? [x] (and (vector? x) (contains? draw-kinds (first x)) (or (nil? (second x)) (map? (second x)))))
690
+
691
+ (def draw-palette #{:ink :soft :accent :kairos :bg :grid})
692
+
693
+ (defn draw-positional
694
+ "A shape written as a msg can write it, its numbers in order: circle cx cy r · rect x y w h ·
695
+ line x1 y1 x2 y2 · arc cx cy r from to · text x y \"words\" — then, in any order, a colour of the
696
+ palette (accent, kairos…) and hit name. [:circle 60 50 18 :accent :hit :sun] → the shape, or nil."
697
+ [v]
698
+ (when (and (vector? v) (#{:circle :rect :line :arc :text} (first v)) (number? (second v)))
699
+ (let [[kind & more] v
700
+ nums (vec (take-while number? more)) words (drop (count nums) more)
701
+ colour (first (filter draw-palette words))
702
+ hit (second (drop-while (fn [w] (not= :hit w)) words))
703
+ txt (first (filter string? words))
704
+ o (fn [ks] (zipmap ks nums))]
705
+ (case kind
706
+ :circle (when (= 3 (count nums)) [:circle (cond-> (assoc (o [:cx :cy :r]) :fill (or colour :accent) :stroke nil) hit (assoc :hit hit))])
707
+ :rect (when (= 4 (count nums)) [:rect (cond-> (assoc (o [:x :y :w :h]) :fill (or colour :accent) :stroke nil) hit (assoc :hit hit))])
708
+ :line (when (= 4 (count nums)) [:line (cond-> (assoc (o [:x1 :y1 :x2 :y2]) :stroke (or colour :ink) :weight 2) hit (assoc :hit hit))])
709
+ :arc (when (= 5 (count nums)) [:arc (cond-> (assoc (o [:cx :cy :r :from :to]) :stroke (or colour :ink) :weight 2) hit (assoc :hit hit))])
710
+ :text (when (= 2 (count nums)) [:text (cond-> (assoc (o [:x :y]) :fill (or colour :ink) :size 12) hit (assoc :hit hit)) (or txt "")])))))
711
+
712
+ (defn as-shape [x] (if (draw-shape? x) x (draw-positional x)))
713
+
714
+ (defn draw-size [args]
715
+ (let [[w h] (filter number? args)]
716
+ [(clamp (or w 240) 40 480) (clamp (or h 160) 30 480)]))
717
+
718
+ (defn draw-receive [{:keys [value state]}]
719
+ (let [st (or state {:named {} :order [] :n 0})
720
+ put (fn [st k f] (-> st (assoc-in [:named k] f) (update :order (fn [o] (if (some #{k} o) o (conj o k))))))
721
+ trim (fn [st] (if (> (count (:order st)) draw-max)
722
+ (let [drop (take (- (count (:order st)) draw-max) (:order st))]
723
+ (-> st (update :named (fn [m] (apply dissoc m drop))) (update :order (fn [o] (vec (drop-while (set drop) o))))))
724
+ st))
725
+ shown (fn [st] (mapv (fn [k] (get-in st [:named k])) (:order st)))
726
+ done (fn [st] {:state st :show (shown st)})]
727
+ (cond
728
+ ;; a part of the view pressed (its own gesture): what that part is called goes out
729
+ (and (vector? value) (= :pressed (first value)) (some? (second value))) {:out [[0 (second value)]]}
730
+ (as-shape value) (let [k (keyword (str "s" (inc (:n st))))] (done (trim (put (assoc st :n (inc (:n st))) k (as-shape value)))))
731
+ (and (sequential? value) (seq value) (every? draw-shape? value))
732
+ (done (trim (reduce (fn [st [i f]] (put st (keyword (str "s" (inc i))) f))
733
+ {:named {} :order [] :n (count value)} (map-indexed vector value))))
734
+ ;; [:set k shape], or as a msg writes it: set k circle 10 10 4 kairos
735
+ (and (vector? value) (= :set (first value)) (some? (second value))
736
+ (or (as-shape (nth value 2 nil)) (as-shape (vec (drop 2 value)))))
737
+ (done (trim (put st (second value) (or (as-shape (nth value 2 nil)) (as-shape (vec (drop 2 value)))))))
738
+ (and (vector? value) (#{:unset :remove} (first value)))
739
+ (done (-> st (update :named dissoc (second value)) (update :order (fn [o] (vec (remove #{(second value)} o))))))
740
+ (#{:clear} value) (done {:named {} :order [] :n 0})
741
+ :else {})))
742
+
743
+ (define! "draw" {:doc "A view drawn from the messages that arrive: each shape of kairotic.shapes ([:circle {:cx 40 :cy 40 :r 10 :fill :accent}], [:line …], [:path {:points [[x y] …]}], [:text {:x :y} \"…\"], [:curve …], [:group {:x :y :rotate} [shapes]]) is added — or as a msg writes it: :circle 40 40 10 :accent, :rect x y w h, :line x1 y1 x2 y2, :arc cx cy r from to, :text x y \"words\", with a colour and :hit name; a list of shapes replaces them all; [:set k shape] (:set k :circle …) adds or replaces the shape called k (to move a cursor), [:unset k] removes it, :clear empties it. A shape with :hit k, pressed, sends k out."
744
+ :usage "draw [width height]"
745
+ :io [1 1]
746
+ :size (fn [b] (draw-size (:args b)))
747
+ :receive draw-receive
748
+ :draw (fn [{:keys [shown w h]}]
749
+ (into [[:rect {:x 0.5 :y 0.5 :w (- w 1) :h (- h 1) :r 3 :stroke :grid :fill nil}]]
750
+ (if (sequential? shown) shown [])))
751
+ ;; a press on a shape with :hit: sent once, on release, as [:pressed k]
752
+ :gesture (fn [{:keys [up hit]}] (when (and up (some? hit)) [:pressed hit]))})
753
+ (define! "mtof" {:doc "MIDI pitch → Hz (lists too)." :receive (fn [{:keys [value]}] (if (or (number? value) (sequential? value)) {:out [[0 (map-num cv/midi->hz value)]]} {}))})
754
+ (define! "ftom" {:doc "Hz → MIDI pitch (lists too)." :receive (fn [{:keys [value]}] (if (or (number? value) (sequential? value)) {:out [[0 (map-num cv/hz->midi value)]]} {}))})
755
+ (doseq [[op-name op] [["+" +] ["-" -] ["*" *] ["/" (fn [a b] (if (zero? b) 0 (/ a b)))]]]
756
+ (define! op-name {:doc (str "Arithmetic: left inlet " op-name " argument (or the last thing that came in on the right); lists too.")
757
+ :usage (str op-name " n") :io [2 1] :receive (arit op)}))
758
+ ;; the other way round, as in Max and Pd: !/ 1 turns a length in seconds into a frequency in Hz
759
+ (doseq [[op-name op] [["!-" (fn [a b] (- b a))] ["!/" (fn [a b] (if (zero? a) 0 (/ b a)))]]]
760
+ (define! op-name {:doc (str "Arithmetic the other way round: argument " (subs op-name 1) " left inlet (" op-name " 1 turns seconds into Hz); lists too.")
761
+ :usage (str op-name " n") :io [2 1] :receive (arit op)}))
762
+ (define! "metro" {:doc "Sends periodic bangs: 1 or bang starts it, 0 or :stop stops it." :usage "metro ms" :io [2 1] :receive metro})
763
+ (define! "counter" {:doc "Each bang sends the value and advances one step; goes back to the minimum on reaching the maximum." :usage "counter step [max] [min]" :io [2 1] :receive counter})
764
+ (define! "ramp" {:doc "Linear motion: a bang (or [a b s]) goes from a to b in s seconds; a number jumps there." :usage "ramp a b s [loop]" :io [2 1] :receive ramp})
765
+ (define! "canvas" {:doc "Graphic buffer for any numeric data: strokes in a plane with axes of any range, linear or log ((axis :b1 :y -1 1)). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read x], [:strokes], [:get :t1], [:data]) are answered on the left. The right outlet is the buffer for a reader, which can read it along X or Y."
766
+ :io [1 2] :display :canvas :receive (canvas-receiver cv/generic-empty) :model canvas-model})
767
+ (define! "freqt" {:doc "Graphic buffer of frequency over time: Hz on a log scale, time from 0, tunings (Scala) and bar grids, drawn as a canvas or as a score ((view :b1 :score), ⇄ in its header). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:note t \"c4\" dur], [:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read t], [:strokes], [:end], [:data]) are answered on the left. The second outlet is the buffer for a reader. A musical tree on the inlet is shown over it, measured; shown as a score, the edits you make on that tree's notes leave by the third outlet ([:edit …]): connect it back to the tree box."
768
+ :io [1 3] :display :canvas :views [:canvas :score] :receive canvas-box :model freqt-model})
769
+ (define! "reader" {:doc "Reads the buffer connected to its right inlet (canvas, freqt, ring) at the position that comes in on the left, in the buffer's own units — the X axis of a canvas (Y with `reader y`), the time of a freqt, the seconds of a ring — or, with `norm`, from 0 to 1, as reader~ does at audio rate. On a canvas or freqt: ids on the right and the values on the left (every crossing); with `reader path [stroke]` a position from 0 to 1 travels along a stroke in the order it was drawn and gives [x y]. On a ring: what it crosses, each value as it was written, either way (a move larger than its jump is a seek); or, without positions, it follows the ring's head d behind, then a speed (reader d 1 speed 0.5; msg :d, :speed, :jump, :stop)."
770
+ :usage "reader [x|y|path [stroke]] [norm] [d s] [speed x] [jump s]"
771
+ :io [2 2] :receive reader :reads-buffer true})
772
+ (doseq [[n io] [["state" [1 1]] ["transition" [2 1]] ["instruction" [1 0]] ["region" [1 1]]]]
773
+ (define! n {:doc "Kairotic class with no semantics yet." :io io}))
774
+
775
+ ;; ───────── core: audio ─────────
776
+
777
+ ;; synth~ moved to the package @kairotic/synth (Study 14)
778
+
779
+ (define! "osc~" {:doc "Sine oscillator. A number on the left changes its frequency; a signal on the left (from reader~, sig~…) is its frequency in Hz."
780
+ :usage "osc~ [hz]" :io [2 1]
781
+ :receive (fn [{:keys [inlet value]}] (if (and (zero? inlet) (num-of value)) {:effects [[:freq (num-of value)]]} {}))
782
+ :audio {:create (fn [ac c _] (let [o (.createOscillator ac) g (.createGain ac)
783
+ base (atom (or (num-of (first (:args c))) 440))]
784
+ (set! (.. o -frequency -value) @base)
785
+ (set! (.. g -gain -value) 0.15)
786
+ (.connect o g) (.start o)
787
+ {:osc o :base base :inlets [[(.-frequency o) 0]] :outlets [[g 0]]}))
788
+ :effects {:freq (fn [node x at] (reset! (:base node) x) (.linearRampToValueAtTime (.-frequency (:osc node)) x at))}
789
+ ;; with a signal on the left the frequency is only that signal
790
+ :wired (fn [node ins] (set! (.. (:osc node) -frequency -value) (if (contains? ins 0) 0 @(:base node))))
791
+ :dispose (fn [node] (try (.stop (:osc node)) (catch :default _ nil)))}})
792
+ (define! "gain~" {:doc "Gain: signal on the left, factor on the right — a number, or a signal (an envelope, a reader~) that then is the factor."
793
+ :usage "gain~ [factor]" :io [2 1]
794
+ :receive (fn [{:keys [inlet value]}] (if (and (= 1 inlet) (num-of value)) {:effects [[:gain (num-of value)]]} {}))
795
+ :audio {:create (fn [ac c _] (let [g (.createGain ac) base (atom (or (num-of (first (:args c))) 0.5))]
796
+ (set! (.. g -gain -value) @base)
797
+ {:g g :base base :inlets [[g 0] [(.-gain g) 0]] :outlets [[g 0]]}))
798
+ :effects {:gain (fn [node x at] (reset! (:base node) x) (.setTargetAtTime (.-gain (:g node)) x at 0.01))}
799
+ :wired (fn [node ins] (set! (.. (:g node) -gain -value) (if (contains? ins 1) 0 @(:base node))))}})
800
+ (defn dac-channels
801
+ "The output channels of a dac~ (1-based): its numbers, or 1 2."
802
+ [b] (let [cs (filterv (fn [x] (and (number? x) (>= x 1))) (:args b))] (if (seq cs) cs [1 2])))
803
+
804
+ (define! "dac~" {:doc "Audio output: each inlet is an output channel, the ones written after it (dac~ 1 2 by default; dac~ 1 2 3 4 … if the sound card has them)."
805
+ :usage "dac~ [channel …]"
806
+ :io (fn [b] [(count (dac-channels b)) 0]) :dynamic-io true
807
+ :receive (fn [_] {})
808
+ :audio {:create (fn [_ b env]
809
+ {:inlets (vec (for [c (dac-channels b)]
810
+ [(or ((:channel env) (dec c)) (:silent env)) 0]))
811
+ :outlets []})
812
+ :key (fn [b] (dac-channels b))}})
813
+
814
+ ;; ───────── space ─────────
815
+ ;; pan~ and space~ moved to the package @kairotic/spatial (Study 14)
816
+
817
+ ;; ───────── core: ports of a sub-patch ─────────
818
+ ;; Seen from inside, an inlet only has an outlet and an outlet only has an inlet; seen from
819
+ ;; the parent patch they are the ports of the sub-patch box. They just pass on what arrives.
820
+
821
+ (defn pass-on [{:keys [value]}] {:out [[0 value]]})
822
+
823
+ (defn pass-audio [ac _ _]
824
+ (let [g (.createGain ac)] {:inlets [[g 0]] :outlets [[g 0]] :g g}))
825
+
826
+ (define! "inlet" {:doc "An inlet of the sub-patch it is in (inlets are numbered left to right). Passes on the messages that arrive at it."
827
+ :io [0 1] :receive pass-on})
828
+ (define! "outlet" {:doc "An outlet of the sub-patch it is in (numbered left to right). Sends out of the sub-patch what arrives at it."
829
+ :io [1 0] :receive pass-on})
830
+ (define! "inlet~" {:doc "An audio inlet of the sub-patch it is in (numbered left to right, together with the message inlets)."
831
+ :io [0 1] :receive (fn [_] {}) :audio {:create pass-audio}})
832
+ (define! "outlet~" {:doc "An audio outlet of the sub-patch it is in (numbered left to right, together with the message outlets)."
833
+ :io [1 0] :receive (fn [_] {}) :audio {:create pass-audio}})
834
+
835
+ (defn listing
836
+ "The registered components: [[class doc usage origin] …]."
837
+ []
838
+ (vec (for [[k d] (sort-by key @registry)] [k (:doc d) (:usage d) (:origin d)])))