trackwright 0.3.0__py3-none-any.whl

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 (46) hide show
  1. trackwright/__init__.py +13 -0
  2. trackwright/__main__.py +7 -0
  3. trackwright/bridge.py +323 -0
  4. trackwright/cli.py +203 -0
  5. trackwright/commands.py +397 -0
  6. trackwright/config.py +149 -0
  7. trackwright/core/__init__.py +1 -0
  8. trackwright/core/automation.py +410 -0
  9. trackwright/core/base.py +313 -0
  10. trackwright/core/commanding.py +300 -0
  11. trackwright/core/exporting.py +143 -0
  12. trackwright/core/importing.py +127 -0
  13. trackwright/core/lifecycle.py +74 -0
  14. trackwright/core/models.py +467 -0
  15. trackwright/core/policy.py +58 -0
  16. trackwright/core/presets.py +88 -0
  17. trackwright/core/project.py +221 -0
  18. trackwright/core/ranges.py +355 -0
  19. trackwright/core/reading.py +229 -0
  20. trackwright/core/refs.py +88 -0
  21. trackwright/core/saving.py +72 -0
  22. trackwright/core/service.py +27 -0
  23. trackwright/core/settings.py +80 -0
  24. trackwright/core/writing.py +390 -0
  25. trackwright/coremidi.py +307 -0
  26. trackwright/cubase/Trackwright_Bridge.js +1130 -0
  27. trackwright/cubase/__init__.py +83 -0
  28. trackwright/doctor.py +69 -0
  29. trackwright/errors.py +120 -0
  30. trackwright/exports.py +54 -0
  31. trackwright/fake.py +1112 -0
  32. trackwright/host.py +238 -0
  33. trackwright/hostport.py +74 -0
  34. trackwright/installer.py +305 -0
  35. trackwright/launcher.py +150 -0
  36. trackwright/logs.py +50 -0
  37. trackwright/ops.py +46 -0
  38. trackwright/protocol.py +182 -0
  39. trackwright/py.typed +0 -0
  40. trackwright/server.py +472 -0
  41. trackwright/transport.py +130 -0
  42. trackwright-0.3.0.dist-info/METADATA +190 -0
  43. trackwright-0.3.0.dist-info/RECORD +46 -0
  44. trackwright-0.3.0.dist-info/WHEEL +4 -0
  45. trackwright-0.3.0.dist-info/entry_points.txt +3 -0
  46. trackwright-0.3.0.dist-info/licenses/LICENSE +661 -0
trackwright/fake.py ADDED
@@ -0,0 +1,1112 @@
1
+ """FakeCubase: an in-memory simulator of the Trackwright script and of Cubase.
2
+
3
+ It answers the same operations with the same result shapes as ``Trackwright_Bridge.js`` and
4
+ reproduces the behaviours verified against Cubase Elements 15.0.30 in the POC:
5
+
6
+ - the mixer's last child duplicates the last channel (same id);
7
+ - removed objects return sentinels and ``INVALID_OBJECT``;
8
+ - process writes outside [0, 1] are refused; routing values (e.g. 22) cannot be written back;
9
+ - selection is single; ``da.base`` follows it and is ``-1`` on tracks without a mixer channel;
10
+ - after a script reload the session changes and old ids point at *different* objects;
11
+ - commands: ``dialog`` ones leave a pending dialog, ``confirm`` ones may wait for confirmation;
12
+ - "Locate Next Marker" without a next marker moves to the end of the last event (``last_event_end``).
13
+
14
+ It is used by the unit and contract tests and by ``trackwright serve --simulate``. Everything it
15
+ reports is flagged ``simulated``: it is never evidence about real Cubase behaviour.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import itertools
21
+ import secrets
22
+ from collections.abc import Callable
23
+ from dataclasses import dataclass, field
24
+ from typing import Any
25
+
26
+ from trackwright.commands import COMMANDS
27
+ from trackwright.cubase import SCRIPT_VERSION
28
+ from trackwright.errors import HostError, RequestTimeoutError, StaleSessionError, TrackwrightError
29
+ from trackwright.ops import SESSIONLESS_OPS
30
+
31
+ JsonObject = dict[str, Any]
32
+ BARS = "Compases+Tiempos"
33
+ SECONDS = "Segundos"
34
+
35
+ PLUGINS: tuple[JsonObject, ...] = (
36
+ {
37
+ "name": "StudioEQ",
38
+ "vendor": "Steinberg Media Technologies",
39
+ "version": "1.0.0",
40
+ "format": "VST3",
41
+ "subCategories": "Fx|EQ",
42
+ "uid": "946051208E29496E804F64A825C8A047",
43
+ "path": "",
44
+ },
45
+ {
46
+ "name": "Compressor",
47
+ "vendor": "Steinberg Media Technologies",
48
+ "version": "1.0.0",
49
+ "format": "VST3",
50
+ "subCategories": "Fx|Dynamics",
51
+ "uid": "5B38F28281144FFE80285FF7CCF20483",
52
+ "path": "",
53
+ },
54
+ )
55
+
56
+
57
+ @dataclass
58
+ class Param:
59
+ title: str
60
+ kind: str # "continuous" | "discrete" | "text"
61
+ value: float
62
+ text: str | None = None
63
+ automatable: bool = False
64
+
65
+
66
+ @dataclass
67
+ class Obj:
68
+ id: int
69
+ type: str
70
+ title: str
71
+ unique_name: str
72
+ uid: str
73
+ children: list[int] = field(default_factory=list)
74
+ params: dict[int, Param] = field(default_factory=dict)
75
+ removed: bool = False
76
+ has_events: bool = False
77
+
78
+
79
+ class FakeCubase:
80
+ """In-memory host. Use the helper methods (``remove``, ``reload_script``...) to drive scenarios."""
81
+
82
+ simulated = True
83
+
84
+ def __init__(
85
+ self, *, tracks: tuple[tuple[str, str], ...] = (("Synth", "POC-INSTR"), ("AudioChannel", "POC-TEST"))
86
+ ) -> None:
87
+ self._ids = itertools.count(100)
88
+ self.objects: dict[int, Obj] = {}
89
+ self.session = self._new_session()
90
+ self.mixer = self._obj("VST Mixer", "VST Mixer")
91
+ self._studio()
92
+ self.channels: list[int] = [self._channel("OutputChannel", "Stereo Out").id]
93
+ for kind, title in tracks:
94
+ self.channels.append(self._channel(kind, title).id)
95
+ self.selected: int = self.channels[-1]
96
+ self.objects[self.selected].params[4000].value = 1
97
+ self.non_mixer_tracks: list[str] = []
98
+ self.transport = {
99
+ "locator": "1. 1. 1. 0",
100
+ "cycleLeft": "1. 1. 1. 0",
101
+ "cycleRight": "1. 1. 1. 0",
102
+ }
103
+ self.tempo = 120.0
104
+ self.online = True # False simulates Cubase closed or still starting (TW-1201)
105
+ # Range editing (TW-1211): audio events per channel in seconds, the active tool, the range selection
106
+ # and an undo history, as observed in Cubase 15 (experiments/tw1211).
107
+ self.track_events: dict[int, list[tuple[float, float]]] = {
108
+ self.channel_by_title(title).id: list(events)
109
+ for title, events in (
110
+ ("POC-TEST", [(0.0, 2.4), (2.0, 6.8), (6.0, 18.0), (18.0, 22.0), (22.0, 139.976)]),
111
+ ("POC-INSTR", [(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]),
112
+ )
113
+ if any(self.objects[c].title == title for c in self.channels)
114
+ }
115
+ self.tool = "select"
116
+ self.range: tuple[float, float] | None = None
117
+ self.history: list[dict[int, list[tuple[float, float]]]] = []
118
+ self.clipboard_seconds = 0.0
119
+ self.selected_events: list[tuple[int, tuple[float, float]]] = [] # object selection (TW-1212)
120
+ self.editor_focused = True
121
+ """The user has clicked on the plugin window once (Preset Next/Previous need it, TW-1205)."""
122
+ self.preset_loaded = True
123
+ """The plugin shows a preset (Preset Next/Previous do nothing without one, TW-1205)."""
124
+ self.auto_select_under_cursor = True
125
+ """Cubase preference seen on the user's system (TW-1212): moving the cursor selects the events under it."""
126
+ # Automation simulation (TW-1207): playback advances the cursor on every transport.get.
127
+ self.automation_controls = True
128
+ self.playing = False
129
+ self.position = 0.0 # beats from the project start
130
+ self.beats_per_poll = 0.25
131
+ self.auto_values: dict[tuple[int, str], float] = {}
132
+ self.auto_touched: set[str] = set()
133
+ self.automation: dict[tuple[int, str], list[tuple[float, float]]] = {}
134
+ self.markers: list[str] = []
135
+ self.last_event_end: str | None = "9. 1. 1. 0"
136
+ """End of the last event in the project (``None`` = no events). Used by "Locate Next Marker"."""
137
+ self.fired: list[str] = []
138
+ self.pending_dialog: str | None = None
139
+ self.pending_removal: int | None = None
140
+ self.events: list[JsonObject] = []
141
+ self.event_seq = 0
142
+ self.calls: list[tuple[str, JsonObject]] = []
143
+ self.fail_next: dict[str, TrackwrightError] = {}
144
+ self.can_perform_false: set[str] = {"edit.undo", "edit.redo", "edit.paste"}
145
+
146
+ # ------------------------------------------------------------------ model building
147
+ @staticmethod
148
+ def _new_session() -> str:
149
+ return secrets.token_hex(6)
150
+
151
+ def _obj(self, kind: str, title: str, **extra: Any) -> Obj:
152
+ oid = next(self._ids)
153
+ obj = Obj(
154
+ id=oid, type=kind, title=title, unique_name=extra.pop("unique_name", kind), uid=f"UID{oid:06d}", **extra
155
+ )
156
+ self.objects[oid] = obj
157
+ return obj
158
+
159
+ def _studio(self) -> None:
160
+ """Device Root with the Transport and Metronome objects (TW-1209), as in Cubase 15."""
161
+ root = self._obj("Device Root", "Device Root")
162
+ del self.objects[root.id] # id 1, as in Cubase 15
163
+ root.id = 1
164
+ self.objects[1] = root
165
+ transport = self._obj("Transport", "Transporte")
166
+ on_off = ("start", "record", "cycle", "punchIn", "punchOut", "usePreRoll", "usePostRoll", "metronomeOn",
167
+ "precountOn", "returnOnStop") # fmt: skip
168
+ tags = {
169
+ "start": 4015,
170
+ "record": 4019,
171
+ "cycle": 4022,
172
+ "punchIn": 4020,
173
+ "punchOut": 4021,
174
+ "usePreRoll": 4037,
175
+ "usePostRoll": 4038,
176
+ "metronomeOn": 4099,
177
+ "precountOn": 4100,
178
+ "returnOnStop": 4150,
179
+ } # as in Cubase 15
180
+ transport.params = {tags[title]: Param(title, "discrete", 0) for title in on_off}
181
+ transport.params[4016] = Param("stop", "discrete", 1)
182
+ texts = {"signature": "4/4", "cycleLeftTime": "1. 1. 1. 0", "cycleRightTime": "1. 1. 1. 0",
183
+ "punchInTime": "1. 1. 1. 0", "punchOutTime": "1. 1. 1. 0", "preRoll": "0. 0. 0. 0",
184
+ "postRoll": "0. 0. 0. 0", "timeFormat": "Compases+Tiempos", "timeFormat2": "Segundos",
185
+ "recordButtonMode": "Punch in/out", "audioRecordMode": "Mantener historial",
186
+ "midiRecordMode": "Nuevas partes", "midiCycleRecordMode": "Mix",
187
+ "recordStartMode": "Iniciar en cursor", "startPlayModes": "Inicio desde posición"} # fmt: skip
188
+ for i, (title, value) in enumerate(texts.items()):
189
+ transport.params[4027 if title == "signature" else 4200 + i] = Param(title, "text", 0, value)
190
+ metronome = self._obj("Metronome", "Metronome")
191
+ metronome.params = {1: Param("clickLevel", "continuous", 1.0), 2: Param("tickInRecord", "discrete", 0),
192
+ 3: Param("tickInPlayback", "discrete", 0)} # fmt: skip
193
+ root.children = [self._obj("MIDI System", "CoreMIDI").id, transport.id, metronome.id]
194
+ self.studio = {"root": root, "transport": transport, "metronome": metronome}
195
+
196
+ @property
197
+ def meter(self) -> tuple[int, int]:
198
+ numerator, denominator = (self.studio["transport"].params[4027].text or "4/4").split("/")
199
+ return int(numerator), int(denominator)
200
+
201
+ def studio_param(self, kind: str, title: str) -> Param:
202
+ return next(p for p in self.studio[kind].params.values() if p.title == title)
203
+
204
+ def _channel(self, kind: str, title: str) -> Obj:
205
+ ch = self._obj(kind, title)
206
+ ch.params = {
207
+ 1024: Param("Nombre", "text", 1, title),
208
+ 4000: Param("Seleccionado", "discrete", 0),
209
+ 1025: Param("Volumen", "continuous", 0.7890865802764893, automatable=True),
210
+ 1027: Param("Enmudecer", "discrete", 0, automatable=True),
211
+ 1028: Param("Solo", "discrete", 0),
212
+ 4002: Param("Habilitar grabación", "discrete", 0),
213
+ 4013: Param("Escribir automatización", "discrete", 0),
214
+ 4014: Param("Leer automatización", "discrete", 0),
215
+ 4101: Param(
216
+ "Entrada",
217
+ "discrete",
218
+ 19 if kind == "AudioChannel" else 0,
219
+ "Stereo In" if kind == "AudioChannel" else "Sin bus",
220
+ ),
221
+ 4102: Param(
222
+ "Salida",
223
+ "discrete",
224
+ 0 if kind == "OutputChannel" else 22,
225
+ "Sin bus" if kind == "OutputChannel" else "Stereo Out",
226
+ ),
227
+ }
228
+ inserts = self._obj("Inserts", "Inserciones")
229
+ for i in range(1, 9):
230
+ slot = self._obj("Slot", str(i), unique_name="Slot")
231
+ slot.params[4125] = Param("Tipo de efecto", "discrete", 0, "Ningún efecto")
232
+ slot.params[4101] = Param("Edición", "discrete", 0) # opens the plugin editor (verified, TW-1205)
233
+ inserts.children.append(slot.id)
234
+ strips = self._obj("Strips", "Strip")
235
+ for i in range(1, 7):
236
+ slot = self._obj("Slot", str(i), unique_name="Slot")
237
+ if i == 3:
238
+ eq = self._obj("EQ", "EQ")
239
+ eq.params[4232] = Param("EQ 1 Gain", "continuous", 0.5, automatable=True)
240
+ for band in range(1, 5): # remaining EQ parameters, titled as in Cubase 15
241
+ for offset, name in enumerate(("Gain", "Freq", "Q")):
242
+ tag = 4300 + band * 10 + offset
243
+ if not (band == 1 and name == "Gain"):
244
+ eq.params[tag] = Param(f"EQ {band} {name}", "continuous", 0.5, automatable=True)
245
+ slot.children.append(eq.id)
246
+ strips.children.append(slot.id)
247
+ sends = self._obj("Sends", "Envíos")
248
+ for i in range(1, 9):
249
+ send = self._obj("Slot", str(i), unique_name="Slot")
250
+ send.params[4097] = Param("Nivel", "continuous", 0.7890865802764893, automatable=True)
251
+ sends.children.append(send.id)
252
+ panner = self._obj("Panner", "Panner")
253
+ panner.params[4201] = Param("Izquierda-derecha", "continuous", 0.5, automatable=True)
254
+ input_filter = self._obj("InputFilter", "Input Filter")
255
+ input_filter.params = {
256
+ 4201: Param("PreGain", "continuous", 0.5, automatable=True),
257
+ 4204: Param("LC-Freq", "continuous", 0.0, automatable=True),
258
+ 4206: Param("HC-Freq", "continuous", 1.0, automatable=True),
259
+ }
260
+ ch.children = [input_filter.id, panner.id, inserts.id, strips.id, sends.id]
261
+ return ch
262
+
263
+ # ------------------------------------------------------------------ scenario helpers
264
+ def channel_by_title(self, title: str) -> Obj:
265
+ return next(self.objects[c] for c in self.channels if self.objects[c].title == title)
266
+
267
+ def remove(self, oid: int) -> None:
268
+ """Delete an object as if the user removed it in Cubase."""
269
+ self.objects[oid].removed = True
270
+ for parent in self.objects.values():
271
+ if oid in parent.children:
272
+ parent.children.remove(oid)
273
+ if oid in self.channels:
274
+ self.channels.remove(oid)
275
+ self._event("mix.removed", oid)
276
+
277
+ def reload_script(self) -> None:
278
+ """Restart Cubase / reload the script: new session, and ids are reassigned so old ids are reused."""
279
+ self.session = self._new_session()
280
+ remapped: dict[int, int] = {}
281
+ live = sorted(self.objects)
282
+ rotated = live[1:] + live[:1] # every id now names a different object
283
+ for old, new in zip(live, rotated, strict=True):
284
+ remapped[old] = new
285
+ objects = {}
286
+ for old, obj in self.objects.items():
287
+ obj.id = remapped[old]
288
+ obj.children = [remapped[c] for c in obj.children]
289
+ objects[obj.id] = obj
290
+ self.objects = objects
291
+ self.mixer = self.objects[remapped[self.mixer.id]]
292
+ self.channels = [remapped[c] for c in self.channels]
293
+ self.selected = remapped.get(self.selected, -1)
294
+
295
+ def finish_import(self, duration: float | None) -> None:
296
+ """The user picks a file in the import selector (``None`` = cancels): it lands on the selected track
297
+ at the cursor, as verified in Cubase."""
298
+ self.pending_dialog = None
299
+ if duration is not None:
300
+ self._snapshot()
301
+ start = self._seconds(self.transport["locator"])
302
+ self.track_events.setdefault(self.selected, []).append((start, start + duration))
303
+
304
+ def complete_dialog(self, name: str) -> None:
305
+ """The user fills in and accepts the pending Add Track dialog."""
306
+ kind = {"addtrack.audio": "AudioChannel", "addtrack.group": "GroupChannel"}.get(self.pending_dialog or "")
307
+ if self.pending_dialog == "addtrack.folder":
308
+ self.non_mixer_tracks.append(name)
309
+ elif kind:
310
+ ch = self._channel(kind, name)
311
+ self.channels.append(ch.id)
312
+ self._select(ch.id)
313
+ self.pending_dialog = None
314
+
315
+ def confirm_pending_removal(self) -> None:
316
+ if self.pending_removal is not None:
317
+ self.remove(self.pending_removal)
318
+ self.pending_removal = None
319
+ self.selected = -1
320
+
321
+ def _event(self, kind: str, oid: int, tag: int = -1) -> None:
322
+ self.event_seq += 1
323
+ self.events.append({"n": self.event_seq, "k": kind, "id": oid, "t": tag, "i": 0, "ms": 0})
324
+
325
+ # ------------------------------------------------------------------ HostPort
326
+ @property
327
+ def session_id(self) -> str | None:
328
+ return self.session
329
+
330
+ def call(self, op: str, params: JsonObject | None = None) -> JsonObject:
331
+ p = dict(params or {})
332
+ self.calls.append((op, p))
333
+ if not self.online or self.pending_dialog == "file.import_audio":
334
+ # Cubase closed, or blocked by the macOS file selector (verified, TW-1203): the bridge times out.
335
+ raise RequestTimeoutError(f"no answer from Cubase for {op}", outcome_unknown=op not in SESSIONLESS_OPS)
336
+ if op in self.fail_next:
337
+ raise self.fail_next.pop(op)
338
+ handler = getattr(self, "_op_" + op.replace(".", "_"), None)
339
+ if handler is None:
340
+ raise HostError(f"unknown op {op}", code="UNKNOWN_OP")
341
+ result: JsonObject = handler(p)
342
+ return result
343
+
344
+ def request_with_session(self, op: str, sid: str, params: JsonObject | None = None) -> JsonObject:
345
+ """Like the script: refuse a foreign session id (used to test stale sessions)."""
346
+ if op not in SESSIONLESS_OPS and sid != self.session:
347
+ raise StaleSessionError(f"expected session {self.session}")
348
+ return self.call(op, params)
349
+
350
+ # ------------------------------------------------------------------ helpers mirroring the script
351
+ def _live(self, oid: Any) -> Obj:
352
+ obj = self.objects.get(oid) if isinstance(oid, int) else None
353
+ if obj is None or obj.removed:
354
+ raise HostError(f"object {oid} is not valid (removed or unknown)", code="INVALID_OBJECT")
355
+ return obj
356
+
357
+ @staticmethod
358
+ def _num(p: JsonObject, name: str, default: float | None = None) -> float:
359
+ value = p.get(name, default)
360
+ if value is None:
361
+ raise HostError(f"missing {name}", code="BAD_REQUEST")
362
+ if isinstance(value, bool) or not isinstance(value, int | float):
363
+ raise HostError(f"{name} must be a number", code="BAD_REQUEST")
364
+ return value
365
+
366
+ def _base(self, p: JsonObject) -> int:
367
+ return self.mixer.id if p.get("scope") == "mixer" else self.selected
368
+
369
+ def _describe(self, obj: Obj) -> JsonObject:
370
+ return {
371
+ "id": obj.id,
372
+ "title": obj.title,
373
+ "type": obj.type,
374
+ "uniqueName": obj.unique_name,
375
+ "uid": obj.uid,
376
+ "children": len(obj.children),
377
+ "params": len(obj.params),
378
+ }
379
+
380
+ @staticmethod
381
+ def _display(param: Param) -> str:
382
+ if param.kind == "text" or (param.text is not None and param.value > 1):
383
+ return param.text or ""
384
+ if param.text is not None and param.kind == "discrete" and param.value == 0:
385
+ return param.text
386
+ if param.kind == "discrete":
387
+ return "Activ." if param.value >= 0.5 else "Desact."
388
+ return f"{param.value:.2f}"
389
+
390
+ def _describe_param(self, obj: Obj, tag: int) -> JsonObject:
391
+ if obj is self.studio["transport"]: # cursor position, live (verified: time and time2 follow the cursor)
392
+ try:
393
+ seconds_text = _format_seconds(self._seconds(self.transport["locator"]))
394
+ except ValueError:
395
+ seconds_text = ""
396
+ obj.params[4023] = Param("time", "text", 0, self.transport["locator"])
397
+ obj.params[4101] = Param("time2", "text", 0, seconds_text)
398
+ param = obj.params.get(tag)
399
+ if param is None:
400
+ return {
401
+ "tag": tag,
402
+ "title": "",
403
+ "process": -1,
404
+ "display": "",
405
+ "units": "",
406
+ "valueType": "",
407
+ "automatable": False,
408
+ "editLock": False,
409
+ "defaultProcess": -1,
410
+ "plain": -1,
411
+ }
412
+ plain = param.value * 48 - 24 if param.kind == "continuous" else param.value
413
+ return {
414
+ "tag": tag,
415
+ "title": param.title,
416
+ "process": param.value,
417
+ "display": self._display(param),
418
+ "units": "",
419
+ "valueType": param.kind,
420
+ "automatable": param.automatable,
421
+ "editLock": False,
422
+ "defaultProcess": -1,
423
+ "plain": plain,
424
+ }
425
+
426
+ def _guard(self, p: JsonObject) -> JsonObject:
427
+ base = self.objects.get(self.selected)
428
+ title = base.title if base else None
429
+ expected = p.get("expectChannelTitle")
430
+ if isinstance(expected, str) and title != expected:
431
+ raise HostError(f'base channel title is "{title}", expected "{expected}"', code="PRECONDITION_FAILED")
432
+ return {"base": self.selected, "baseTitle": title, "policy": "open"}
433
+
434
+ def _select(self, oid: int) -> None:
435
+ for cid in self.channels:
436
+ self.objects[cid].params[4000].value = 0
437
+ self.objects[oid].params[4000].value = 1
438
+ self.selected = oid
439
+
440
+ # ------------------------------------------------------------------ direct ops
441
+ def _host(self) -> JsonObject:
442
+ return {"appName": "Cubase", "appVersion": "15.0.30 (simulated)", "insertSlots": 8}
443
+
444
+ def _op_hello(self, _p: JsonObject) -> JsonObject:
445
+ return {
446
+ "scriptVersion": SCRIPT_VERSION,
447
+ "protocol": 1,
448
+ "sessionId": self.session,
449
+ "loadedAt": 0,
450
+ "host": self._host(),
451
+ }
452
+
453
+ def _op_ping(self, p: JsonObject) -> JsonObject:
454
+ return {"pong": True, "scriptVersion": SCRIPT_VERSION, "protocol": 1, "echo": p.get("echo")}
455
+
456
+ def _op_status(self, _p: JsonObject) -> JsonObject:
457
+ return {
458
+ "deviceActive": True,
459
+ "pageActive": True,
460
+ "daActive": True,
461
+ "daMixActive": True,
462
+ "queue": 0,
463
+ "dupInFlightDropped": 0,
464
+ "lastError": "",
465
+ "simulated": True,
466
+ }
467
+
468
+ def _op_capabilities(self, _p: JsonObject) -> JsonObject:
469
+ caps = {
470
+ "json": True,
471
+ "directAccessCreated": True,
472
+ "mixerDirectAccessCreated": True,
473
+ "mixerDirectAccessActive": True,
474
+ "transportTimeDisplay": True,
475
+ "commandsBound": len(COMMANDS),
476
+ "commandErrors": 0,
477
+ "writePolicy": "open",
478
+ "simulated": True,
479
+ }
480
+ return {"capabilities": caps, "host": self._host()}
481
+
482
+ def _op_events(self, _p: JsonObject) -> JsonObject:
483
+ events, self.events = self.events, []
484
+ return {"events": events, "dropped": 0, "lastSeq": self.event_seq, "idleTicks": 0, "ms": 0}
485
+
486
+ def _time(self, value: str, display: str) -> JsonObject:
487
+ return {"time": value, "format": BARS if display == "primary" else SECONDS, "ms": 0}
488
+
489
+ def _op_transport_get(self, _p: JsonObject) -> JsonObject:
490
+ if self.playing: # verified: the cursor position is reported while playing
491
+ self.position += self.beats_per_poll
492
+ self.transport["locator"] = _beats_to_bars(self.position, self.meter)
493
+ # Verified quirk: the secondary display reports bar strings while declaring "Segundos".
494
+ out: JsonObject = {"available": True, "tempoBPM": self.tempo, "updates": 1}
495
+ for display in ("primary", "secondary"):
496
+ out[display] = {k: self._time(v, display) for k, v in self.transport.items()}
497
+ return out
498
+
499
+ def _op_cmd_list(self, _p: JsonObject) -> JsonObject:
500
+ commands = [
501
+ {"key": s.key, "category": s.category, "name": s.name, "fired": self.fired.count(s.key)}
502
+ for s in COMMANDS.values()
503
+ ]
504
+ return {"commands": commands, "errors": []}
505
+
506
+ # ------------------------------------------------------------------ DirectAccess reads
507
+ def _op_da_base(self, p: JsonObject) -> JsonObject:
508
+ base = self._base(p)
509
+ if base < 0:
510
+ return {"base": base}
511
+ return {"base": base, "object": self._describe(self.objects[base])}
512
+
513
+ def _op_da_object(self, p: JsonObject) -> JsonObject:
514
+ return self._describe(self._live(int(self._num(p, "id"))))
515
+
516
+ def _op_da_children(self, p: JsonObject) -> JsonObject:
517
+ obj = self._live(int(self._num(p, "id")))
518
+ offset = int(self._num(p, "offset", 0))
519
+ limit = min(int(self._num(p, "limit", 20)), 50)
520
+ items = [self._describe(self.objects[c]) | {"index": i} for i, c in enumerate(obj.children) if i >= offset][
521
+ :limit
522
+ ]
523
+ return {"id": obj.id, "total": len(obj.children), "offset": offset, "items": items}
524
+
525
+ def _op_da_params(self, p: JsonObject) -> JsonObject:
526
+ obj = self._live(int(self._num(p, "id")))
527
+ offset = int(self._num(p, "offset", 0))
528
+ limit = min(int(self._num(p, "limit", 10)), 25)
529
+ tags = list(obj.params)
530
+ items = [self._describe_param(obj, t) | {"index": i} for i, t in enumerate(tags) if i >= offset][:limit]
531
+ return {"id": obj.id, "total": len(tags), "offset": offset, "items": items}
532
+
533
+ def _op_da_param_get(self, p: JsonObject) -> JsonObject:
534
+ return self._describe_param(self._live(int(self._num(p, "id"))), int(self._num(p, "tag")))
535
+
536
+ def _op_da_convert(self, p: JsonObject) -> JsonObject:
537
+ obj = self._live(int(self._num(p, "id")))
538
+ out: JsonObject = {"id": obj.id, "tag": int(self._num(p, "tag"))}
539
+ if "process" in p:
540
+ out["plainFromProcess"] = self._num(p, "process") * 48 - 24
541
+ if "plain" in p:
542
+ out["processFromPlain"] = (self._num(p, "plain") + 24) / 48
543
+ return out
544
+
545
+ def _op_da_channels(self, p: JsonObject) -> JsonObject:
546
+ base = self._base(p)
547
+ if base < 0:
548
+ return {"base": base, "total": 0, "items": [], "duplicates": []}
549
+ offset = int(self._num(p, "offset", 0))
550
+ limit = min(int(self._num(p, "limit", 16)), 32)
551
+ tags = p.get("tags") or [1024, 4000, 1025, 1027, 1028, 4101, 4102]
552
+ children = [*self.channels, self.channels[-1]] if base == self.mixer.id else self.objects[base].children
553
+ items: list[JsonObject] = []
554
+ duplicates: list[JsonObject] = []
555
+ seen: set[int] = set()
556
+ for index, cid in enumerate(children):
557
+ if index < offset or len(items) >= limit:
558
+ continue
559
+ if cid in seen:
560
+ duplicates.append({"index": index, "id": cid})
561
+ continue
562
+ seen.add(cid)
563
+ obj = self.objects[cid]
564
+ values = {
565
+ str(t): {
566
+ "title": obj.params[t].title,
567
+ "display": self._display(obj.params[t]),
568
+ "process": obj.params[t].value,
569
+ }
570
+ if t in obj.params
571
+ else None
572
+ for t in tags
573
+ }
574
+ items.append(
575
+ self._describe(obj)
576
+ | {
577
+ "index": index,
578
+ "mixerVisible": True,
579
+ "mixerIndex": index - 1 if index else -1,
580
+ "mixerZone": 0,
581
+ "values": values,
582
+ }
583
+ )
584
+ return {
585
+ "base": base,
586
+ "baseObject": self._describe(self.objects[base]),
587
+ "total": len(children),
588
+ "offset": offset,
589
+ "items": items,
590
+ "duplicates": duplicates,
591
+ }
592
+
593
+ def _op_pm_collections(self, p: JsonObject) -> JsonObject:
594
+ slot = self._live(int(self._num(p, "slot")))
595
+ total = 1 if slot.type == "Slot" and slot.params.get(4125) else 0
596
+ items = [{"index": 0, "name": "Por defecto", "entries": len(PLUGINS)}] if total else []
597
+ return {"slot": slot.id, "total": total, "items": items, "defaultIndex": 0, "activeIndex": 0 if total else -1}
598
+
599
+ def _op_pm_entries(self, p: JsonObject) -> JsonObject:
600
+ slot = self._live(int(self._num(p, "slot")))
601
+ if int(self._num(p, "collection")) != 0 or not slot.params.get(4125):
602
+ raise HostError("collection not found", code="NOT_FOUND")
603
+ offset = int(self._num(p, "offset", 0))
604
+ limit = min(int(self._num(p, "limit", 20)), 40)
605
+ needle = str(p.get("filter") or "").lower()
606
+ matched = [
607
+ e | {"index": i}
608
+ for i, e in enumerate(PLUGINS)
609
+ if needle in f"{e['name']} {e['vendor']} {e['subCategories']}".lower()
610
+ ]
611
+ return {
612
+ "slot": slot.id,
613
+ "collection": 0,
614
+ "collectionName": "Por defecto",
615
+ "total": len(PLUGINS),
616
+ "matched": len(matched),
617
+ "offset": offset,
618
+ "items": matched[offset : offset + limit],
619
+ }
620
+
621
+ def _op_cmd_canPerform(self, p: JsonObject) -> JsonObject: # noqa: N802 - mirrors the op name
622
+ keys = [p["key"]] if p.get("key") else list(COMMANDS)
623
+ return {"canPerform": {k: self._can(k) for k in keys if k in COMMANDS}}
624
+
625
+ RANGE_ACTIONS = ("edit.delete", "edit.delete_time", "edit.cut_time", "edit.insert_silence", "edit.crop_range")
626
+
627
+ def _can(self, key: str) -> bool:
628
+ """canPerform as observed (TW-1211/1212): undo needs history and no open dialog, range actions a
629
+ range, object actions a selection, Select Events under Cursor an event under the cursor."""
630
+ rules: dict[str, Callable[[], bool]] = {
631
+ "edit.undo": lambda: bool(self.history) and self.pending_dialog is None,
632
+ "edit.delete": lambda: self.range is not None if self.tool == "range" else bool(self.selected_events),
633
+ "edit.select_events_under_cursor": lambda: bool(self._under_cursor()),
634
+ "edit.split_at_cursor": lambda: bool(self.selected_events),
635
+ "edit.select_in_loop": lambda: (
636
+ self._seconds(self.transport["cycleLeft"]) < self._seconds(self.transport["cycleRight"])
637
+ ),
638
+ }
639
+ rules.update({k: lambda: self.range is not None for k in self.RANGE_ACTIONS if k != "edit.delete"})
640
+ rule = rules.get(key)
641
+ return rule() if rule is not None else key not in self.can_perform_false
642
+
643
+ # ------------------------------------------------------------------ writes
644
+ def _op_da_param_set(self, p: JsonObject) -> JsonObject:
645
+ obj = self._live(int(self._num(p, "id")))
646
+ tag = int(self._num(p, "tag"))
647
+ value = self._num(p, "value")
648
+ guard = self._guard(p)
649
+ before = self._describe_param(obj, tag)
650
+ if value < 0 or value > 1:
651
+ raise HostError("process value must be in [0,1]", code="BAD_REQUEST")
652
+ expected = p.get("expectTitle")
653
+ if isinstance(expected, str) and before["title"] != expected:
654
+ raise HostError(
655
+ f'parameter title is "{before["title"]}", expected "{expected}"', code="PRECONDITION_FAILED"
656
+ )
657
+ param = obj.params.get(tag)
658
+ if param is not None:
659
+ if tag == 4000 and value >= 0.5:
660
+ self._select(obj.id)
661
+ else:
662
+ param.value = round(value, 6) if param.kind == "continuous" else (1 if value >= 0.5 else 0)
663
+ if tag in (4101, 4102):
664
+ param.text = "Sin bus" # verified: writing routing ends on 'Sin bus'
665
+ self._event("param", obj.id, tag)
666
+ return {"guard": guard, "before": before, "after": self._describe_param(obj, tag), "requested": value}
667
+
668
+ def _op_da_param_setDisplay(self, p: JsonObject) -> JsonObject: # noqa: N802 - mirrors the op name
669
+ obj = self._live(int(self._num(p, "id")))
670
+ tag = int(self._num(p, "tag"))
671
+ text = p.get("value")
672
+ if not isinstance(text, str):
673
+ raise HostError("value must be a string", code="BAD_REQUEST")
674
+ guard = self._guard(p)
675
+ before = self._describe_param(obj, tag)
676
+ param = obj.params.get(tag)
677
+ if param is not None and param.kind == "text": # verified: routing ignores display writes
678
+ param.text = text
679
+ if tag == 1024:
680
+ obj.title = text
681
+ return {"guard": guard, "before": before, "after": self._describe_param(obj, tag), "requested": text}
682
+
683
+ def _op_pm_set(self, p: JsonObject) -> JsonObject:
684
+ slot = self._live(int(self._num(p, "slot")))
685
+ uid = p.get("uid")
686
+ if not isinstance(uid, str) or not uid:
687
+ raise HostError("uid required", code="BAD_REQUEST")
688
+ guard = self._guard(p)
689
+ before = self._describe(slot)
690
+ if slot.type != "Slot":
691
+ raise HostError(f"target is not a Slot (type={slot.type})", code="PRECONDITION_FAILED")
692
+ if slot.children:
693
+ raise HostError(f"slot has {len(slot.children)} child object(s)", code="SLOT_NOT_EMPTY")
694
+ entry = next((e for e in PLUGINS if e["uid"] == uid), None)
695
+ if entry is not None:
696
+ plugin = self._obj("Plugin", entry["name"], unique_name=f"{uid}-0")
697
+ plugin.params[4207] = Param("GainP1L", "continuous", 0.5, automatable=True)
698
+ for n in range(1, 9): # bank parameters, titled like the automation controls report them
699
+ plugin.params[4300 + n] = Param(f"Param {n}", "continuous", 0.5, automatable=True)
700
+ slot.children.append(plugin.id)
701
+ slot.params[4125] = Param("Tipo de efecto", "discrete", 1, entry["name"])
702
+ return {"guard": guard, "result": entry is not None, "before": before, "after": self._describe(slot)}
703
+
704
+ # ------------------------------------------------------------------ automation controls (TW-1207)
705
+ AUTO_KEYS: tuple[str, ...] = (
706
+ "volume",
707
+ "pan",
708
+ *(f"send{i}.level" for i in range(1, 5)),
709
+ *(f"eq{b}.{p}" for b in range(1, 5) for p in ("gain", "freq", "q")),
710
+ "prefilter.gain",
711
+ "prefilter.lowcut",
712
+ "prefilter.highcut",
713
+ *(f"qc{i}" for i in range(1, 9)),
714
+ *(f"insert{s}.p{n}" for s in (1, 2) for n in range(1, 9)),
715
+ )
716
+
717
+ def _auto_title(self, key: str) -> str:
718
+ """Title of the parameter bound to a control on the selected track (' / ' when nothing is bound)."""
719
+ if key.startswith("qc"):
720
+ return " / "
721
+ if key.startswith("insert"):
722
+ slot_index, param_index = int(key[6]) - 1, int(key.split(".p")[1])
723
+ inserts = next(
724
+ self.objects[c] for c in self.objects[self.selected].children if self.objects[c].type == "Inserts"
725
+ )
726
+ slot = self.objects[inserts.children[slot_index]]
727
+ if not slot.children:
728
+ return " / "
729
+ return f"{self.objects[slot.children[0]].title} / Param {param_index}"
730
+ return {"volume": f"{self.objects[self.selected].title} / Volumen", "pan": "Panner / Izquierda-derecha"}.get(
731
+ key, f"Channel / {key}"
732
+ )
733
+
734
+ def _auto_value(self, key: str) -> float:
735
+ recorded = self.automation.get((self.selected, key))
736
+ reading = self.objects[self.selected].params[4014].value >= 0.5
737
+ if self.playing and reading and recorded and key not in self.auto_touched:
738
+ earlier = [value for beat, value in recorded if beat <= self.position]
739
+ if earlier:
740
+ return earlier[-1]
741
+ if key == "volume":
742
+ return self.objects[self.selected].params[1025].value
743
+ return self.auto_values.get((self.selected, key), 0.5)
744
+
745
+ def _require_controls(self) -> None:
746
+ if not self.automation_controls:
747
+ raise HostError("automation controls are not enabled in this script build", code="UNSUPPORTED")
748
+ if self.selected < 0:
749
+ raise HostError("no selected channel", code="NO_BASE_OBJECT")
750
+
751
+ def _describe_control(self, key: str) -> JsonObject:
752
+ value = self._auto_value(key)
753
+ bound = self._auto_title(key).strip(" /") != ""
754
+ return {"key": key, "value": value if bound else None, "display": f"{value:.2f}" if bound else "",
755
+ "title": self._auto_title(key), "touched": key in self.auto_touched, "errors": []} # fmt: skip
756
+
757
+ def _op_auto_control(self, p: JsonObject) -> JsonObject:
758
+ self._require_controls()
759
+ key = p.get("key")
760
+ if key not in self.AUTO_KEYS:
761
+ raise HostError(f"unknown automation control {key}", code="NOT_FOUND")
762
+ touched_before = key in self.auto_touched
763
+ if p.get("touch") is True:
764
+ self.auto_touched.add(key)
765
+ if "value" in p:
766
+ value = self._num(p, "value")
767
+ if not 0 <= value <= 1:
768
+ raise HostError("value must be in [0,1]", code="BAD_REQUEST")
769
+ if key == "volume":
770
+ self.objects[self.selected].params[1025].value = value
771
+ else:
772
+ self.auto_values[(self.selected, key)] = value
773
+ writing = self.objects[self.selected].params[4013].value >= 0.5
774
+ if writing and self.playing and key in self.auto_touched: # verified: touched + W + playing records
775
+ self.automation.setdefault((self.selected, key), []).append((self.position, value))
776
+ if p.get("touch") is False:
777
+ self.auto_touched.discard(key)
778
+ return self._describe_control(key) | {"touchedBefore": touched_before}
779
+
780
+ def _op_auto_list(self, _p: JsonObject) -> JsonObject:
781
+ if not self.automation_controls:
782
+ return {"enabled": False, "controls": []}
783
+ if self.selected < 0:
784
+ return {"enabled": True, "controls": [], "errors": ["no selected channel"]}
785
+ return {"enabled": True, "controls": [self._describe_control(k) for k in self.AUTO_KEYS], "errors": []}
786
+
787
+ def _op_sel_step(self, p: JsonObject) -> JsonObject:
788
+ direction = p.get("direction")
789
+ if direction not in ("next", "prev"):
790
+ raise HostError("direction must be next|prev", code="BAD_REQUEST")
791
+ tracks = self.channels[1:]
792
+ if self.selected in tracks:
793
+ i = tracks.index(self.selected) + (1 if direction == "next" else -1)
794
+ if 0 <= i < len(tracks):
795
+ self._select(tracks[i])
796
+ return {"triggered": direction}
797
+
798
+ def _op_transport_setTime(self, p: JsonObject) -> JsonObject: # noqa: N802 - mirrors the op name
799
+ which = p.get("which", "locator")
800
+ display = p.get("display", "secondary")
801
+ time = p.get("time")
802
+ if which not in self.transport:
803
+ raise HostError("which must be locator|cycleLeft|cycleRight", code="BAD_REQUEST")
804
+ if display not in ("primary", "secondary"):
805
+ raise HostError("display must be primary|secondary", code="BAD_REQUEST")
806
+ if not isinstance(time, str) or not 0 < len(time) <= 32:
807
+ raise HostError("time must be a non-empty string", code="BAD_REQUEST")
808
+ before = self._time(self.transport[which], display)
809
+ if display == "primary":
810
+ self.transport[which] = time
811
+ elif which == "locator":
812
+ self.transport[which] = self._bars_at(_parse_seconds(time))
813
+ self._cursor_moved()
814
+ else: # verified bug (TW-1211): locators set through the seconds display land elsewhere
815
+ self.transport[which] = "1. 1. 1. 0"
816
+ return {"which": which, "display": display, "requested": time, "before": before}
817
+
818
+ def _op_transport_setTempo(self, p: JsonObject) -> JsonObject: # noqa: N802 - mirrors the op name
819
+ bpm = self._num(p, "bpm")
820
+ if not 20 <= bpm <= 300:
821
+ raise HostError("bpm must be in [20,300]", code="BAD_REQUEST")
822
+ before, self.tempo = self.tempo, float(bpm)
823
+ return {"requested": bpm, "before": before}
824
+
825
+ def _op_cmd_run(self, p: JsonObject) -> JsonObject:
826
+ key = p.get("key")
827
+ spec = COMMANDS.get(str(key))
828
+ if spec is None:
829
+ raise HostError(f"unknown command key {key}", code="NOT_FOUND")
830
+ can = self._can(spec.key)
831
+ if not can and p.get("force") is not True:
832
+ raise HostError(f"canPerform=false for {spec.category}/{spec.name}", code="CANNOT_PERFORM")
833
+ self.fired.append(spec.key)
834
+ self._apply_command(spec.key)
835
+ return {
836
+ "key": spec.key,
837
+ "category": spec.category,
838
+ "name": spec.name,
839
+ "canPerform": can,
840
+ "fired": self.fired.count(spec.key),
841
+ }
842
+
843
+ def _apply_command(self, key: str) -> None:
844
+ if COMMANDS[key].command_class == "dialog" and key != "audio.detect_silence":
845
+ self.pending_dialog = key
846
+ elif key.startswith("transport."):
847
+ self._apply_transport(key)
848
+ elif key.startswith(("tool.", "edit.")) and self._apply_edit(key):
849
+ return
850
+ else:
851
+ self._apply_project(key)
852
+
853
+ # ------------------------------------------------------------------ range editing (TW-1211)
854
+ def _seconds(self, bars: str) -> float:
855
+ return _bars_to_beats(bars, self.meter) * 60 / self.tempo
856
+
857
+ def _bars_at(self, seconds: float) -> str:
858
+ return _beats_to_bars(seconds * self.tempo / 60, self.meter)
859
+
860
+ def _apply_selection(self, key: str) -> bool:
861
+ if key in ("tool.range", "tool.select"):
862
+ self.tool = key.split(".")[1]
863
+ self.range = None
864
+ elif key == "edit.select_in_loop":
865
+ start, end = self._seconds(self.transport["cycleLeft"]), self._seconds(self.transport["cycleRight"])
866
+ self.range = (start, end) if self.tool == "range" and start < end else None
867
+ elif key == "edit.select_none":
868
+ self.range = None
869
+ self.selected_events = []
870
+ elif key == "edit.select_all":
871
+ self.selected_events = [(tid, e) for tid, events in self.track_events.items() for e in events]
872
+ elif key == "edit.select_events_under_cursor": # verified: only the selected tracks
873
+ self.selected_events = self._under_cursor()
874
+ else:
875
+ return False
876
+ return True
877
+
878
+ def _apply_edit(self, key: str) -> bool:
879
+ """Tool, selection and range commands; ``False`` lets other edit commands fall through."""
880
+ if self._apply_selection(key):
881
+ return True
882
+ if key == "edit.split_at_cursor" and self.selected_events:
883
+ self._split_selected(self._seconds(self.transport["locator"]))
884
+ elif key == "edit.delete" and self.tool == "select" and self.selected_events:
885
+ self._snapshot()
886
+ for tid, event in self.selected_events:
887
+ self.track_events[tid].remove(event)
888
+ self.selected_events = []
889
+ elif key in self.RANGE_ACTIONS and self.range is not None:
890
+ self.history.append({tid: list(events) for tid, events in self.track_events.items()})
891
+ for tid, events in self.track_events.items():
892
+ self.track_events[tid] = _edit_events(events, key, *self.range)
893
+ if key == "edit.cut_time":
894
+ self.clipboard_seconds = self.range[1] - self.range[0]
895
+ elif key == "edit.undo" and self.history:
896
+ self.track_events = self.history.pop()
897
+ self.selected_events = []
898
+ else:
899
+ return False
900
+ return True
901
+
902
+ def _snapshot(self) -> None:
903
+ self.history.append({tid: list(events) for tid, events in self.track_events.items()})
904
+
905
+ def _under_cursor(self) -> list[tuple[int, tuple[float, float]]]:
906
+ here = self._seconds(self.transport["locator"])
907
+ return [(self.selected, e) for e in self.track_events.get(self.selected, []) if e[0] - 1e-6 <= here < e[1]]
908
+
909
+ def _split_selected(self, at: float) -> None:
910
+ self._snapshot()
911
+ for tid, (a, b) in self.selected_events:
912
+ if a + 1e-6 < at < b - 1e-6:
913
+ events = self.track_events[tid]
914
+ events[events.index((a, b))] = (a, at)
915
+ events.append((at, b))
916
+ self.selected_events = []
917
+
918
+ def selection_bounds(self) -> tuple[float, float] | None:
919
+ if self.tool == "range":
920
+ return self.range
921
+ if not self.selected_events:
922
+ return None
923
+ return min(e[0] for _, e in self.selected_events), max(e[1] for _, e in self.selected_events)
924
+
925
+ def edges(self, track_id: int) -> list[float]:
926
+ return sorted({round(edge, 3) for event in self.track_events.get(track_id, []) for edge in event})
927
+
928
+ def _apply_preset(self, key: str) -> bool:
929
+ """Preset Next/Previous: act on the plugin whose editor is open, only when a preset is loaded."""
930
+ if key not in ("preset.next", "preset.previous"):
931
+ return False
932
+ open_slots = [o for o in self.objects.values() if o.type == "Slot" and 4101 in o.params
933
+ and o.params[4101].value >= 0.5 and o.children] # fmt: skip
934
+ if len(open_slots) == 1 and self.preset_loaded and self.editor_focused:
935
+ step = 0.1 if key == "preset.next" else -0.1
936
+ for param in self.objects[open_slots[0].children[0]].params.values():
937
+ param.value = round((param.value + step) % 1.0, 6)
938
+ return True
939
+
940
+ def _apply_project(self, key: str) -> None:
941
+ if self._apply_preset(key):
942
+ return
943
+ tracks = self.channels[1:]
944
+ if key == "addtrack.marker":
945
+ self.non_mixer_tracks.append("Marker")
946
+ self.selected = -1
947
+ elif key == "marker.insert":
948
+ self.markers.append(self.transport["locator"])
949
+ elif key in ("project.select_track_next", "project.select_track_prev") and self.selected in tracks:
950
+ i = tracks.index(self.selected) + (1 if key.endswith("next") else -1)
951
+ if 0 <= i < len(tracks):
952
+ self._select(tracks[i])
953
+ elif key == "project.remove_selected_tracks" and self.selected in tracks:
954
+ if self.objects[self.selected].has_events:
955
+ self.pending_removal = self.selected # Cubase asks for confirmation
956
+ else:
957
+ self.remove(self.selected)
958
+ self.selected = -1
959
+
960
+ def _apply_transport(self, key: str) -> None:
961
+ self._apply_transport_move(key)
962
+ self._cursor_moved()
963
+
964
+ def _cursor_moved(self) -> None:
965
+ if self.auto_select_under_cursor and self.tool == "select" and self.track_events:
966
+ self.selected_events = self._under_cursor()
967
+
968
+ def _apply_locators(self, key: str) -> bool:
969
+ bounds = self.selection_bounds()
970
+ if key == "transport.locators_to_selection" and bounds:
971
+ self.transport["cycleLeft"], self.transport["cycleRight"] = (self._bars_at(b) for b in bounds)
972
+ elif key in ("transport.set_left_locator", "transport.set_right_locator"):
973
+ self.transport["cycleLeft" if "left" in key else "cycleRight"] = self.transport["locator"]
974
+ else:
975
+ return False
976
+ return True
977
+
978
+ def _apply_transport_move(self, key: str) -> None:
979
+ cursor = self.transport["locator"]
980
+ if self._apply_locators(key):
981
+ return
982
+ if key == "transport.locate_next_event":
983
+ here = self._seconds(cursor)
984
+ following = [edge for edge in self.edges(self.selected) if edge > here + 1e-6]
985
+ if following:
986
+ self.transport["locator"] = self._bars_at(following[0])
987
+ elif key in ("transport.locate_selection", "transport.locate_selection_end") and self.selection_bounds():
988
+ bounds = self.selection_bounds()
989
+ assert bounds is not None
990
+ self.transport["locator"] = self._bars_at(bounds[0 if key.endswith("selection") else 1])
991
+ elif key == "transport.start":
992
+ self.playing = True
993
+ self.position = _bars_to_beats(cursor, self.meter)
994
+ elif key == "transport.stop":
995
+ self.playing = False
996
+ elif key == "transport.locate_prev_marker":
997
+ earlier = [m for m in self.markers if _bars(m) < _bars(cursor)]
998
+ self.transport["locator"] = max(earlier, key=_bars) if earlier else "1. 1. 1. 0"
999
+ elif key == "transport.locate_next_marker":
1000
+ later = [m for m in self.markers if _bars(m) > _bars(cursor)]
1001
+ if later:
1002
+ self.transport["locator"] = min(later, key=_bars)
1003
+ elif self.last_event_end is not None and _bars(self.last_event_end) > _bars(cursor):
1004
+ # Verified on Cubase 15 (2026-11-12): without a next marker the cursor goes to the end of the
1005
+ # last event of the project (the POC had seen it stay put).
1006
+ self.transport["locator"] = self.last_event_end
1007
+
1008
+
1009
+ def _bars_to_beats(time: str, meter: tuple[int, int]) -> float:
1010
+ bar, beat, sixteenth, ticks = (int(part) for part in time.replace(".", " ").split())
1011
+ beat_length = 4 / meter[1]
1012
+ return (bar - 1) * meter[0] * beat_length + (beat - 1) * beat_length + (sixteenth - 1) / 4 + ticks / 480
1013
+
1014
+
1015
+ def _beats_to_bars(beats: float, meter: tuple[int, int]) -> str:
1016
+ beat_length = 4 / meter[1]
1017
+ bar, rest = divmod(beats, meter[0] * beat_length)
1018
+ beat, rest = divmod(rest, beat_length)
1019
+ sixteenth, rest = divmod(rest, 0.25)
1020
+ return f"{int(bar) + 1}. {int(beat) + 1}. {int(sixteenth) + 1}.{round(rest * 480):>3}"
1021
+
1022
+
1023
+ def _bars(time: str) -> tuple[int, ...]:
1024
+ return tuple(int(part) for part in time.replace(".", " ").split())
1025
+
1026
+
1027
+ def _parse_seconds(time: str) -> float:
1028
+ hours, minutes, seconds = time.split(":")
1029
+ return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
1030
+
1031
+
1032
+ def _format_seconds(seconds: float) -> str:
1033
+ millis = round(seconds * 1000)
1034
+ hours, rest = divmod(millis, 3_600_000)
1035
+ minutes, rest = divmod(rest, 60_000)
1036
+ return f"{hours}:{minutes:02d}:{rest // 1000:02d}.{rest % 1000:03d}"
1037
+
1038
+
1039
+ def _edit_events(events: list[tuple[float, float]], key: str, start: float, end: float) -> list[tuple[float, float]]:
1040
+ """What each range command does to one track's events (verified in Cubase, TW-1211)."""
1041
+ gap = end - start
1042
+ out: list[tuple[float, float]] = []
1043
+ for a, b in events:
1044
+ if key == "edit.crop_range":
1045
+ if b > start and a < end:
1046
+ out.append((max(a, start), min(b, end)))
1047
+ elif key == "edit.insert_silence":
1048
+ if b <= start:
1049
+ out.append((a, b))
1050
+ elif a >= start:
1051
+ out.append((a + gap, b + gap))
1052
+ else:
1053
+ out += [(a, start), (start + gap, b + gap)]
1054
+ else: # delete keeps a hole; delete_time / cut_time close it
1055
+ shift = gap if key != "edit.delete" else 0.0
1056
+ if a < start:
1057
+ out.append((a, min(b, start)))
1058
+ if b > end:
1059
+ out.append((max(a, end) - shift, b - shift))
1060
+ return out
1061
+
1062
+
1063
+ class FakeLauncher:
1064
+ """Opens the simulated Cubase: ``launch`` brings the script online after ``answers_after`` polls."""
1065
+
1066
+ app = "Cubase 15 (simulated)"
1067
+ launch_timeout = 5.0
1068
+
1069
+ def __init__(self, cubase: FakeCubase, *, running: bool = True, answers_after: int = 1) -> None:
1070
+ self.cubase = cubase
1071
+ self.running = running
1072
+ self.answers_after = answers_after
1073
+ self.launched: list[object] = []
1074
+
1075
+ def is_running(self) -> bool:
1076
+ return self.running
1077
+
1078
+ def project_folders(self) -> list[str]:
1079
+ return ["/Projects/Demo"] if self.running else []
1080
+
1081
+ def launch(self, project: object = None) -> None:
1082
+ self.launched.append(project)
1083
+ self.running = True
1084
+ if self.answers_after >= 0:
1085
+ self.cubase.online = True
1086
+
1087
+
1088
+ class FakeExports:
1089
+ """Export folder for the simulator: ``files`` are returned by ``find`` (no disk access)."""
1090
+
1091
+ def __init__(self) -> None:
1092
+ from trackwright.exports import ExportedFile # noqa: PLC0415
1093
+
1094
+ self.files: list[ExportedFile] = []
1095
+ self._file = ExportedFile
1096
+ self.searched: list[tuple[object, float]] = []
1097
+ self.durations: dict[str, float] = {}
1098
+
1099
+ def add(self, path: str, duration: float | None, *, modified: float = 2e9, size: int = 1000) -> None:
1100
+ self.files.append(self._file(path, size, modified, duration))
1101
+
1102
+ def duration(self, path: object) -> float | None:
1103
+ return self.durations.get(str(path))
1104
+
1105
+ def find(self, folder: object, since: float, suffixes: frozenset[str] | None = None) -> list[object]:
1106
+ self.searched.append((folder, since))
1107
+ return sorted(
1108
+ (f for f in self.files
1109
+ if f.modified >= since - 1.0 and (suffixes is None or any(f.path.lower().endswith(x) for x in suffixes))),
1110
+ key=lambda f: f.modified, # type: ignore[attr-defined]
1111
+ reverse=True,
1112
+ ) # fmt: skip