omnipython-applibs 0.1.2.dev16__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 (143) hide show
  1. appkit/__init__.py +52 -0
  2. appkit/__init__.pyi +17 -0
  3. appkit/data.py +149 -0
  4. appkit/data.pyi +25 -0
  5. appkit/foreground.py +357 -0
  6. appkit/foreground.pyi +45 -0
  7. appkit/home.py +19 -0
  8. appkit/home.pyi +8 -0
  9. appkit/hover.py +59 -0
  10. appkit/hover.pyi +13 -0
  11. appkit/index.py +199 -0
  12. appkit/index.pyi +30 -0
  13. appkit/launcher.py +1075 -0
  14. appkit/launcher.pyi +96 -0
  15. appkit/manifest.py +75 -0
  16. appkit/manifest.pyi +8 -0
  17. appkit/net.py +167 -0
  18. appkit/net.pyi +34 -0
  19. appkit/places.py +202 -0
  20. appkit/places.pyi +39 -0
  21. appkit/py.typed +0 -0
  22. appkit/scope.py +636 -0
  23. appkit/scope.pyi +110 -0
  24. appkit/shell.py +121 -0
  25. appkit/shell.pyi +32 -0
  26. appkit/worker.py +409 -0
  27. appkit/worker.pyi +83 -0
  28. controlkit/__init__.py +19 -0
  29. controlkit/__init__.pyi +10 -0
  30. controlkit/_draw.py +88 -0
  31. controlkit/_safe.py +29 -0
  32. controlkit/dotmatrix.py +101 -0
  33. controlkit/dotmatrix.pyi +23 -0
  34. controlkit/encoder.py +297 -0
  35. controlkit/encoder.pyi +55 -0
  36. controlkit/font5x7.py +22 -0
  37. controlkit/font5x7.pyi +11 -0
  38. controlkit/lamp_button.py +92 -0
  39. controlkit/lamp_button.pyi +40 -0
  40. controlkit/meter.py +86 -0
  41. controlkit/meter.pyi +30 -0
  42. controlkit/mock.py +116 -0
  43. controlkit/mock.pyi +35 -0
  44. controlkit/pad_grid.py +113 -0
  45. controlkit/pad_grid.pyi +41 -0
  46. controlkit/py.typed +0 -0
  47. controlkit/slider.py +185 -0
  48. controlkit/slider.pyi +49 -0
  49. controlkit/sprites.py +279 -0
  50. controlkit/sprites.pyi +22 -0
  51. controlkit/theme.py +120 -0
  52. controlkit/theme.pyi +15 -0
  53. deskkit/__init__.py +74 -0
  54. deskkit/__init__.pyi +18 -0
  55. deskkit/forecast.py +261 -0
  56. deskkit/forecast.pyi +40 -0
  57. deskkit/localtime.py +215 -0
  58. deskkit/localtime.pyi +33 -0
  59. deskkit/py.typed +0 -0
  60. deskkit/shell.py +113 -0
  61. deskkit/shell.pyi +33 -0
  62. omnipython_applibs-0.1.2.dev16.dist-info/METADATA +90 -0
  63. omnipython_applibs-0.1.2.dev16.dist-info/RECORD +143 -0
  64. omnipython_applibs-0.1.2.dev16.dist-info/WHEEL +5 -0
  65. omnipython_applibs-0.1.2.dev16.dist-info/licenses/LICENSE +21 -0
  66. omnipython_applibs-0.1.2.dev16.dist-info/top_level.txt +9 -0
  67. programkit/__init__.py +27 -0
  68. programkit/__init__.pyi +8 -0
  69. programkit/board.py +56 -0
  70. programkit/board.pyi +20 -0
  71. programkit/press.py +63 -0
  72. programkit/press.pyi +17 -0
  73. programkit/py.typed +0 -0
  74. programkit/rows.py +149 -0
  75. programkit/rows.pyi +34 -0
  76. sayso/__init__.py +109 -0
  77. sayso/__init__.pyi +124 -0
  78. sayso/auth.py +811 -0
  79. sayso/auth.pyi +102 -0
  80. sayso/client.py +1286 -0
  81. sayso/client.pyi +138 -0
  82. sayso/keepalive.py +371 -0
  83. sayso/keepalive.pyi +53 -0
  84. sayso/local.py +85 -0
  85. sayso/local.pyi +28 -0
  86. sayso/object_specs.py +706 -0
  87. sayso/object_specs.pyi +8 -0
  88. sayso/objects.py +411 -0
  89. sayso/objects.pyi +854 -0
  90. sayso/py.typed +0 -0
  91. sayso/schema_coverage.py +210 -0
  92. sayso/schema_coverage.pyi +13 -0
  93. sayso/transport.py +426 -0
  94. sayso/transport.pyi +47 -0
  95. songmodel/__init__.py +30 -0
  96. songmodel/__init__.pyi +9 -0
  97. songmodel/link.py +189 -0
  98. songmodel/link.pyi +53 -0
  99. songmodel/model.py +238 -0
  100. songmodel/model.pyi +40 -0
  101. songmodel/page.html +225 -0
  102. songmodel/page_data.py +236 -0
  103. songmodel/page_data.pyi +6 -0
  104. songmodel/py.typed +0 -0
  105. soundmodule/__init__.py +7 -0
  106. soundmodule/__init__.pyi +6 -0
  107. soundmodule/engine.py +1001 -0
  108. soundmodule/engine.pyi +196 -0
  109. soundmodule/names.py +298 -0
  110. soundmodule/names.pyi +30 -0
  111. soundmodule/pipes.py +105 -0
  112. soundmodule/pipes.pyi +31 -0
  113. soundmodule/py.typed +0 -0
  114. soundmodule/run.py +249 -0
  115. soundmodule/run.pyi +49 -0
  116. spectrum/__init__.py +72 -0
  117. spectrum/__init__.pyi +30 -0
  118. spectrum/analyzer.py +231 -0
  119. spectrum/analyzer.pyi +67 -0
  120. spectrum/fake_music.py +201 -0
  121. spectrum/fake_music.pyi +36 -0
  122. spectrum/pump_levels.py +126 -0
  123. spectrum/pump_levels.pyi +46 -0
  124. spectrum/py.typed +0 -0
  125. spectrum/spectrum_view.py +403 -0
  126. spectrum/spectrum_view.pyi +80 -0
  127. touchkit/__init__.py +4 -0
  128. touchkit/__init__.pyi +4 -0
  129. touchkit/cam.py +146 -0
  130. touchkit/cam.pyi +35 -0
  131. touchkit/clock.py +18 -0
  132. touchkit/clock.pyi +6 -0
  133. touchkit/ecp.py +134 -0
  134. touchkit/ecp.pyi +28 -0
  135. touchkit/net.py +347 -0
  136. touchkit/net.pyi +27 -0
  137. touchkit/py.typed +0 -0
  138. touchkit/settings.py +85 -0
  139. touchkit/settings.pyi +17 -0
  140. touchkit/shell.py +268 -0
  141. touchkit/shell.pyi +42 -0
  142. touchkit/ui.py +167 -0
  143. touchkit/ui.pyi +53 -0
songmodel/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The song both of this repo's groovebox applications edit, and what carries it
6
+ to a front panel.
7
+
8
+ - `songmodel.model`: the project, plain JSON data changed only by ops that
9
+ every side applies the same way. Imports on CPython, Pyodide and
10
+ MicroPython.
11
+ - `songmodel.link`: the project as an ``hmilink`` model, so any screen can
12
+ be a front panel (needs ``hmilink``, from omnipython).
13
+ - ``page.html``: the browser front panel a device serves on its hmilink port,
14
+ and ``page_data``, the same page as a module (`page`); tools/songmodel_page.py
15
+ writes the one from the other.
16
+
17
+ Ostinato (``programs/ostinato``) and Vamp (``programs/vamp``) both use it.
18
+ """
19
+
20
+
21
+
22
+ def page():
23
+ """What ``hmilink.tcp.serve(port, page=...)`` takes to answer ``GET /``: the front panel page.
24
+
25
+ It comes from ``page_data``, a module, so a ``mip`` install and a frozen
26
+ build carry it with the Python.
27
+ """
28
+ from songmodel import page_data
29
+
30
+ return lambda: page_data.HTML.encode()
songmodel/__init__.pyi ADDED
@@ -0,0 +1,9 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The song both of this repo's groovebox applications edit, and what carries it to a front panel."""
5
+
6
+ from collections.abc import Callable
7
+
8
+ def page() -> Callable[[], bytes]:
9
+ """The front panel page, as `hmilink.tcp.serve(port, page=...)` takes it."""
songmodel/link.py ADDED
@@ -0,0 +1,189 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Ostinato's song as an hmilink model: any screen as the groovebox's front panel.
6
+
7
+ The project is already plain data changed by ops (`model`), so this is
8
+ a thin coat. The device holds the song; every panel (the desktop UI, the
9
+ browser page the device serves, later the LCD-7) sends JSON Patch ops with
10
+ JSON Pointer paths, and the device numbers them and sends them to every
11
+ panel, so two screens never disagree about the order.
12
+
13
+ import hmilink
14
+ from hmilink import tcp
15
+ from songmodel.link import SongModel
16
+
17
+ song = SongModel(project, forward=engines_apply, host=the_host)
18
+ device = hmilink.Device(song)
19
+ device.add(tcp.serve(9100, page="page.html"))
20
+ while True:
21
+ ... # the sequencer's own loop
22
+ device.poll()
23
+
24
+ Ops a panel sends, as pointers into the project:
25
+
26
+ - ``replace /tempo 120``, ``replace /tracks/0/volume 90``, ``replace /tracks/1/mute true``
27
+ - ``add /tracks/0/patterns/0/notes/- [0, 24, 60, 100]`` adds a note (``-`` appends)
28
+ - ``remove /tracks/0/patterns/0/notes/3``
29
+
30
+ Ostinato's own ops find a track by id (``["track", 7]``), so they survive a
31
+ reorder; a pointer finds it by index. `to_pointer` turns one into the
32
+ other on the panel that sends it, against that panel's copy.
33
+
34
+ Imports on CPython and MicroPython: nothing here touches a file, a thread or
35
+ the audio.
36
+ """
37
+
38
+ import hmilink
39
+
40
+ from songmodel import model as song
41
+
42
+ RANGES = {"tempo": [40, 240], "swing": [0, 100], "volume": [0, 127], "pan": [0, 127]}
43
+
44
+
45
+ def to_pointer(project, op):
46
+ """An Ostinato op as ``(kind, pointer, value)`` for ``Panel.send``.
47
+
48
+ ``set`` is ``replace`` (``add`` when the key is new), ``insert`` is
49
+ ``add`` (index -1 is ``-``), ``remove`` is ``remove``. A ``replace`` of
50
+ the whole project isn't an op on the wire: it's the ``load`` command.
51
+ """
52
+ keys = []
53
+ node = project
54
+ path = op["path"]
55
+ for i, key in enumerate(path):
56
+ if isinstance(key, (list, tuple)) and key[0] == "track":
57
+ tracks = project["tracks"]
58
+ index = tracks.index(song.find_track(project, key[1]))
59
+ keys += ["tracks", index]
60
+ node = tracks[index]
61
+ continue
62
+ last = i == len(path) - 1
63
+ if last and op["op"] == "insert" and key == -1:
64
+ keys.append("-")
65
+ break
66
+ keys.append(key)
67
+ if not last:
68
+ node = node[key]
69
+ pointer = hmilink.join_pointer(keys)
70
+ kind = op["op"]
71
+ if kind == "insert":
72
+ return "add", pointer, op["value"]
73
+ if kind == "remove":
74
+ return "remove", pointer, None
75
+ if kind == "set":
76
+ last = keys[-1]
77
+ exists = isinstance(node, list) or last in node
78
+ return ("replace" if exists else "add"), pointer, op["value"]
79
+ raise ValueError("no pointer form for %r" % kind)
80
+
81
+
82
+ def from_pointer(op):
83
+ """A JSON Patch op as the Ostinato op `model.apply` takes."""
84
+ keys = hmilink.split_pointer(op["path"])
85
+ if not keys:
86
+ raise ValueError("replace the whole song with the load command")
87
+ path = []
88
+ for k in keys:
89
+ if k == "-":
90
+ path.append(-1)
91
+ elif k.isdigit():
92
+ path.append(int(k))
93
+ else:
94
+ path.append(k)
95
+ if op["op"] == "remove":
96
+ return {"op": "remove", "path": path}
97
+ if op["op"] == "add" and isinstance(path[-1], int):
98
+ return {"op": "insert", "path": path, "value": op["value"]}
99
+ return {"op": "set", "path": path, "value": op["value"]}
100
+
101
+
102
+ class SongModel(hmilink.Model):
103
+ """The song a device holds.
104
+
105
+ ``forward(op)`` gets every Ostinato op the song accepts, to apply to the
106
+ sound (the engines). ``host`` answers what the song alone can't:
107
+ ``host.command(name, args)`` for the transport and the engines,
108
+ ``host.telemetry()`` for the playhead and meters.
109
+ """
110
+
111
+ def __init__(self, project=None, forward=None, host=None):
112
+ super().__init__(project if project is not None else song.new_project())
113
+ self.forward = forward
114
+ self.host = host
115
+ #: What the song's SoundFont tracks cost: track id -> what the engine
116
+ #: preloaded, and the totals (see describe).
117
+ self.samples = {}
118
+ #: The panel and number of the load the document came from, so a
119
+ #: panel can tell its own load's echo from someone else's.
120
+ self.loaded = None
121
+
122
+ def describe(self):
123
+ tracks = [{"id": t["id"], "name": t["name"], "kind": t["kind"],
124
+ "instrument": t["instrument"], "patch": t.get("patch", 0)} for t in self.doc["tracks"]]
125
+ return {
126
+ "kind": "ostinato",
127
+ "version": song.VERSION,
128
+ "ppq": song.PPQ,
129
+ "step": song.STEP,
130
+ "bar": song.BAR,
131
+ "tracks": tracks,
132
+ "ranges": RANGES,
133
+ "note": ["start", "length", "pitch", "velocity"],
134
+ "samples": self.sample_cost(),
135
+ "loaded": self.loaded,
136
+ }
137
+
138
+ def sample_cost(self):
139
+ """The preloaded samples, per SoundFont track and in all, against the arena."""
140
+ tracks = {}
141
+ total = 0
142
+ arena = 0
143
+ for tid, s in self.samples.items():
144
+ tracks[str(tid)] = {"samples": s.get("samples", 0), "bytes": s.get("bytes", 0)}
145
+ total += s.get("bytes", 0)
146
+ arena = max(arena, s.get("arena", 0))
147
+ return {"tracks": tracks, "bytes": total, "arena": arena}
148
+
149
+ def apply(self, op):
150
+ ours = from_pointer(op)
151
+ if ours["path"] == ["tempo"]:
152
+ ours["value"] = max(40.0, min(240.0, float(ours["value"])))
153
+ kind = op["op"]
154
+ if ours["op"] == "set":
155
+ # Say what happened, so a panel's own JSON Patch apply agrees:
156
+ # a new key is an add, an existing one a replace.
157
+ node, key = song.resolve(self.doc, ours["path"])
158
+ kind = "replace" if isinstance(node, list) or key in node else "add"
159
+ song.apply(self.doc, ours)
160
+ if self.forward is not None:
161
+ self.forward(ours)
162
+ out = {"op": kind, "path": op["path"]}
163
+ if op["op"] != "remove":
164
+ out["value"] = ours["value"]
165
+ return out
166
+
167
+ def load(self, project, by=None):
168
+ """Replace the whole song (a panel's New or Open) and tell every panel."""
169
+ song.migrate(project)
170
+ song.apply(self.doc, {"op": "replace", "value": project})
171
+ song.migrate(self.doc)
172
+ self.samples = {}
173
+ self.loaded = by
174
+ if self.forward is not None:
175
+ self.forward({"op": "replace", "value": self.doc})
176
+ device = getattr(self, "device", None)
177
+ if device is not None:
178
+ device.reset_doc()
179
+
180
+ def telemetry(self):
181
+ return self.host.telemetry() if self.host is not None else None
182
+
183
+ def command(self, name, args):
184
+ if name == "load":
185
+ self.load(args["project"], args.get("by"))
186
+ return {"name": "loaded", "by": args.get("by")}
187
+ if self.host is not None:
188
+ return self.host.command(name, args)
189
+ raise ValueError("unknown command %r" % name)
songmodel/link.pyi ADDED
@@ -0,0 +1,53 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The song as an hmilink model: any screen as the groovebox's front panel."""
5
+
6
+ from typing import Any, Callable, Protocol
7
+
8
+ from .model import _Op, _Project
9
+
10
+ class Model:
11
+ """The hmilink model base class, as this module uses it."""
12
+
13
+ doc: Any
14
+ def __init__(self, doc: Any = None) -> None: ...
15
+ def describe(self) -> dict[str, Any]: ...
16
+ def apply(self, op: dict[str, Any]) -> dict[str, Any]: ...
17
+ def telemetry(self) -> dict[str, Any] | None: ...
18
+ def command(self, name: str, args: Any) -> dict[str, Any] | None: ...
19
+
20
+ class Host(Protocol):
21
+ """What answers for the transport, the engines, the playhead and meters."""
22
+
23
+ def command(self, name: str, args: Any) -> dict[str, Any] | None: ...
24
+ def telemetry(self) -> dict[str, Any] | None: ...
25
+
26
+ RANGES: dict[str, list[int]]
27
+
28
+ def to_pointer(project: _Project, op: _Op) -> tuple[str, str, Any]:
29
+ """An op as `(kind, pointer, value)` for `Panel.send`."""
30
+ def from_pointer(op: dict[str, Any]) -> _Op:
31
+ """A JSON Patch op as the op `model.apply` takes."""
32
+
33
+ class SongModel(Model):
34
+ """The song a device holds."""
35
+
36
+ forward: Callable[[_Op], Any] | None
37
+ host: Host | None
38
+ samples: dict[int, dict[str, int]]
39
+ loaded: Any
40
+ def __init__(
41
+ self,
42
+ project: _Project | None = None,
43
+ forward: Callable[[_Op], Any] | None = None,
44
+ host: Host | None = None,
45
+ ) -> None: ...
46
+ def describe(self) -> dict[str, Any]: ...
47
+ def sample_cost(self) -> dict[str, Any]:
48
+ """The preloaded samples, per SoundFont track and in all, against the arena."""
49
+ def apply(self, op: dict[str, Any]) -> dict[str, Any]: ...
50
+ def load(self, project: _Project, by: Any = None) -> None:
51
+ """Replace the whole song and tell every panel."""
52
+ def telemetry(self) -> dict[str, Any] | None: ...
53
+ def command(self, name: str, args: Any) -> dict[str, Any] | None: ...
songmodel/model.py ADDED
@@ -0,0 +1,238 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The song: plain data, shared by every panel and the engine that plays it.
6
+
7
+ Ostinato's UI and engines use it, and so does Vamp.
8
+
9
+ A project is dicts, lists, numbers and strings only, so it saves as JSON and
10
+ crosses between workers as a message. Neither side edits it in place behind
11
+ the other's back: every change is an op (`apply`), applied locally and
12
+ sent to the other side, which applies the same op to its copy.
13
+
14
+ Times are in ticks, PPQ to a quarter note. A step on the grid is a
15
+ sixteenth, STEP ticks.
16
+ """
17
+
18
+ VERSION = 1
19
+ PPQ = 96
20
+ STEP = PPQ // 4
21
+ BEATS_PER_BAR = 4
22
+ BAR = PPQ * BEATS_PER_BAR
23
+
24
+ _next_id = [1]
25
+
26
+
27
+ def new_id():
28
+ n = _next_id[0]
29
+ _next_id[0] += 1
30
+ return n
31
+
32
+
33
+ def pattern(bars=1):
34
+ return {"bars": bars, "notes": []} # notes: [start, length, pitch, velocity]
35
+
36
+
37
+ def track(kind, instrument, name=None, patch=0):
38
+ return {
39
+ "id": new_id(),
40
+ "name": name or instrument,
41
+ "kind": kind, # "drums" or "melodic"
42
+ "instrument": instrument,
43
+ "patch": patch,
44
+ "macros": {}, # str(index) -> value, over the patch
45
+ "volume": 100, # MIDI units, 100 = unity-ish
46
+ "pan": 64, # 0 left, 64 centre, 127 right
47
+ "mute": False,
48
+ "solo": False,
49
+ "rack": [], # [{"name": ..., "bypass": False, "macros": {}}]
50
+ "patterns": [pattern()],
51
+ # Which pattern plays in pattern mode: "current", from tick
52
+ # "current_at" (it starts from its beginning there); "next" is a switch
53
+ # waiting for the next bar line, {"pattern": i, "at": tick}, or None.
54
+ "current": 0,
55
+ "current_at": 0,
56
+ "next": None,
57
+ }
58
+
59
+
60
+ def new_project():
61
+ return {
62
+ "version": VERSION,
63
+ "name": "Untitled",
64
+ "tempo": 110.0,
65
+ "swing": 0, # percent, applied to off-beat sixteenths
66
+ "metronome": False,
67
+ "quantise": True, # recorded notes snap to sixteenths
68
+ "overdub": True, # takes add to a pattern; off, a take replaces it
69
+ "loop_pattern": 0, # old projects' one pattern for every track (see migrate)
70
+ "song": [], # [{"patterns": {track_id: index or -1}, "repeat": n}]
71
+ "song_mode": False,
72
+ "loop_scene": None, # a scene index to loop in song mode, or None
73
+ "master": {"volume": 100, "rack": []},
74
+ "tracks": [
75
+ track("drums", "rhythm808", "Drums"),
76
+ track("melodic", "acid303", "Bass"),
77
+ track("melodic", "poly106", "Keys"),
78
+ track("melodic", "mono_synth", "Lead"),
79
+ ],
80
+ "bindings": {}, # "ch:cc" -> target path, from MIDI-learn
81
+ }
82
+
83
+
84
+ def swung(tick, swing):
85
+ """Where a note at ``tick`` plays with ``swing``: sixteenths that fall
86
+ off the beat's eighths are late by ``swing`` percent of a sixteenth."""
87
+ return tick + swing * STEP / 100 if tick % (2 * STEP) == STEP else tick
88
+
89
+
90
+ def migrate(project):
91
+ """Bring an older project up to date in place: each track's own pattern
92
+ (they all played the one "loop_pattern" before) and no pending switch."""
93
+ for t in project.get("tracks", []):
94
+ if "current" not in t:
95
+ t["current"] = min(project.get("loop_pattern", 0), len(t["patterns"]) - 1)
96
+ t.setdefault("current_at", 0)
97
+ t.setdefault("next", None)
98
+ return project
99
+
100
+
101
+ def pattern_at(track, tick):
102
+ """The pattern a track plays at ``tick`` in pattern mode, and the tick its
103
+ start falls on: the pending switch once its bar line has passed."""
104
+ n = track.get("next")
105
+ if n and tick >= n["at"]:
106
+ return n["pattern"], n["at"]
107
+ return track.get("current", 0), track.get("current_at", 0)
108
+
109
+
110
+ def segments(project, t0, t1):
111
+ """What plays between ticks t0 and t1, as (from, to, base, patterns):
112
+ patterns maps track id -> pattern index (or -1 for silence), and a
113
+ pattern's tick 0 falls at ``base``. Pattern mode is one endless segment
114
+ per pending switch: each track plays its own pattern, and a switch splits
115
+ the range at its bar line, its value (pattern, the tick it starts on).
116
+ Song mode walks the scenes, looping the song, or loops the one scene
117
+ ``loop_scene`` names."""
118
+ p = project
119
+ song = p.get("song") or []
120
+ loop = p.get("loop_scene")
121
+ if loop is not None and 0 <= loop < len(song):
122
+ song = [song[loop]]
123
+ if not (p.get("song_mode") and song):
124
+ cuts = sorted({t["next"]["at"] for t in p["tracks"] if t.get("next") and t0 < t["next"]["at"] < t1})
125
+ edges = [t0] + cuts + [t1]
126
+ out = []
127
+ for i in range(len(edges) - 1):
128
+ a = edges[i]
129
+ out.append((a, edges[i + 1], 0, {t["id"]: pattern_at(t, a) for t in p["tracks"]}))
130
+ return out
131
+ lengths = []
132
+ for scene in song:
133
+ bars = 1
134
+ for t in p["tracks"]:
135
+ i = scene["patterns"].get(str(t["id"]), -1)
136
+ if 0 <= i < len(t["patterns"]):
137
+ bars = max(bars, t["patterns"][i]["bars"])
138
+ lengths.append(bars * BAR * max(1, scene.get("repeat", 1)))
139
+ total = sum(lengths)
140
+ out = []
141
+ loop = int(max(t0, 0) // total)
142
+ while True:
143
+ start = loop * total
144
+ for k in range(len(song)):
145
+ scene, length = song[k], lengths[k]
146
+ a, b = start, start + length
147
+ start = b
148
+ if b <= t0:
149
+ continue
150
+ if a >= t1:
151
+ return out
152
+ pats = {t["id"]: scene["patterns"].get(str(t["id"]), -1) for t in p["tracks"]}
153
+ out.append((max(a, t0), min(b, t1), a, pats))
154
+ loop += 1
155
+
156
+
157
+ def shown_pattern(track):
158
+ """The pattern to show and edit for a track: where it's going, if switching."""
159
+ n = track.get("next")
160
+ return n["pattern"] if n else track.get("current", 0)
161
+
162
+
163
+ def find_track(project, track_id):
164
+ for t in project["tracks"]:
165
+ if t["id"] == track_id:
166
+ return t
167
+ return None
168
+
169
+
170
+ def resolve(project, path):
171
+ """The container and key a path ends in. A path step ``("track", id)``
172
+ finds a track by id, so ops survive tracks being reordered."""
173
+ node = project
174
+ for i, key in enumerate(path[:-1]):
175
+ if isinstance(key, list) and key[0] == "track":
176
+ node = find_track(project, key[1])
177
+ else:
178
+ node = node[key]
179
+ if node is None:
180
+ raise KeyError(path)
181
+ last = path[-1]
182
+ if isinstance(last, list) and last[0] == "track":
183
+ tracks = project["tracks"]
184
+ return tracks, tracks.index(find_track(project, last[1]))
185
+ return node, last
186
+
187
+
188
+ def apply(project, op):
189
+ """Apply one op to ``project`` and return it. Ops:
190
+
191
+ ``{"op": "set", "path": [...], "value": v}``
192
+ ``{"op": "insert", "path": [..., index], "value": v}`` (index -1 appends)
193
+ ``{"op": "remove", "path": [..., index]}``
194
+ ``{"op": "replace", "value": project}`` (load a whole project)
195
+ """
196
+ kind = op["op"]
197
+ if kind == "replace":
198
+ value = op["value"]
199
+ if value is project:
200
+ _bump_ids(project)
201
+ return project
202
+ value = _copy(value)
203
+ project.clear()
204
+ project.update(value)
205
+ _bump_ids(project)
206
+ return project
207
+ node, key = resolve(project, op["path"])
208
+ if kind == "set":
209
+ node[key] = op["value"]
210
+ elif kind == "insert":
211
+ if key == -1 or key >= len(node):
212
+ node.append(op["value"])
213
+ else:
214
+ node.insert(key, op["value"])
215
+ elif kind == "remove":
216
+ del node[key]
217
+ else:
218
+ raise ValueError("unknown op %r" % kind)
219
+ return project
220
+
221
+
222
+ def _copy(value):
223
+ """A deep copy of plain data (dicts, lists, scalars)."""
224
+ if isinstance(value, dict):
225
+ return {k: _copy(v) for k, v in value.items()}
226
+ if isinstance(value, list):
227
+ return [_copy(v) for v in value]
228
+ return value
229
+
230
+
231
+ def _bump_ids(project):
232
+ top = max([t["id"] for t in project.get("tracks", [])] + [0])
233
+ if top >= _next_id[0]:
234
+ _next_id[0] = top + 1
235
+
236
+
237
+ def track_path(track_id, *rest):
238
+ return [["track", track_id]] + list(rest)
songmodel/model.pyi ADDED
@@ -0,0 +1,40 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The song: plain data, shared by every panel and the engine that plays it."""
5
+
6
+ from typing import Any
7
+
8
+ _Project = dict[str, Any]
9
+ _Track = dict[str, Any]
10
+ _Pattern = dict[str, Any]
11
+ _Op = dict[str, Any]
12
+
13
+ VERSION: int
14
+ PPQ: int
15
+ STEP: int
16
+ BEATS_PER_BAR: int
17
+ BAR: int
18
+
19
+ def new_id() -> int: ...
20
+ def pattern(bars: int = 1) -> _Pattern: ...
21
+ def track(kind: str, instrument: str, name: str | None = None, patch: int = 0) -> _Track: ...
22
+ def new_project() -> _Project: ...
23
+ def swung(tick: int | float, swing: int | float) -> int | float:
24
+ """Where a note at `tick` plays with `swing` percent applied."""
25
+ def migrate(project: _Project) -> _Project:
26
+ """Bring an older project up to date in place."""
27
+ def pattern_at(track: _Track, tick: int | float) -> tuple[int, int]:
28
+ """The pattern a track plays at `tick` in pattern mode, and the tick its start falls on."""
29
+ def segments(
30
+ project: _Project, t0: int | float, t1: int | float
31
+ ) -> list[tuple[int | float, int | float, int | float, dict[int, Any]]]:
32
+ """What plays between ticks `t0` and `t1`, as (from, to, base, patterns)."""
33
+ def shown_pattern(track: _Track) -> int:
34
+ """The pattern to show and edit for a track."""
35
+ def find_track(project: _Project, track_id: int) -> _Track | None: ...
36
+ def resolve(project: _Project, path: list[Any]) -> tuple[Any, Any]:
37
+ """The container and key a path ends in."""
38
+ def apply(project: _Project, op: _Op) -> _Project:
39
+ """Apply one op to `project` and return it."""
40
+ def track_path(track_id: int, *rest: Any) -> list[Any]: ...