omnipython-apps 0.1.4.dev8__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 (218) hide show
  1. apps/__init__.py +5 -0
  2. apps/about/__init__.py +257 -0
  3. apps/about/app.json +1 -0
  4. apps/about/credits.py +12 -0
  5. apps/about/facts.py +398 -0
  6. apps/about/fonts/OFL.txt +93 -0
  7. apps/about/fonts/latin1_14.bin +0 -0
  8. apps/about/fonts/latin1_16.bin +0 -0
  9. apps/about/fonts/latin1_24.bin +0 -0
  10. apps/about/fonts/latin1_32.bin +0 -0
  11. apps/about/fonts/latin1_40.bin +0 -0
  12. apps/backline/__init__.py +58 -0
  13. apps/backline/app.json +1 -0
  14. apps/backline/app.py +475 -0
  15. apps/backline/art.py +717 -0
  16. apps/backline/ask.py +781 -0
  17. apps/backline/box.py +502 -0
  18. apps/backline/cast.py +137 -0
  19. apps/backline/desk/__init__.py +329 -0
  20. apps/backline/desk/editor.py +331 -0
  21. apps/backline/desk/grid.py +154 -0
  22. apps/backline/desk/look.py +169 -0
  23. apps/backline/desk/pedals.py +102 -0
  24. apps/backline/desk/perform.py +157 -0
  25. apps/backline/desk/prompt.py +210 -0
  26. apps/backline/desk/strip.py +159 -0
  27. apps/backline/desk_main.py +226 -0
  28. apps/backline/engine.py +622 -0
  29. apps/backline/floor.py +509 -0
  30. apps/backline/footswitch.py +119 -0
  31. apps/backline/glyphs.py +82 -0
  32. apps/backline/kits.py +428 -0
  33. apps/backline/midipedal.py +362 -0
  34. apps/backline/page_data.py +413 -0
  35. apps/backline/parts.py +145 -0
  36. apps/backline/pedal.py +107 -0
  37. apps/backline/remote.py +134 -0
  38. apps/backline/songs/ballad_68.json +1 -0
  39. apps/backline/songs/bossa.json +1 -0
  40. apps/backline/songs/country_train.json +1 -0
  41. apps/backline/songs/funk.json +1 -0
  42. apps/backline/songs/metal.json +1 -0
  43. apps/backline/songs/pop.json +1 -0
  44. apps/backline/songs/rock.json +1 -0
  45. apps/backline/songs/shuffle.json +1 -0
  46. apps/battery/__init__.py +101 -0
  47. apps/battery/app.json +1 -0
  48. apps/bit_world/act_deck.py +683 -0
  49. apps/bit_world/act_game.py +762 -0
  50. apps/bit_world/act_pet.py +1032 -0
  51. apps/bit_world/app.json +1 -0
  52. apps/bit_world/bit_output.py +45 -0
  53. apps/bit_world/bit_palette.py +503 -0
  54. apps/bit_world/bit_sound.py +431 -0
  55. apps/bit_world/bit_sprites.py +632 -0
  56. apps/bit_world/bit_world.py +534 -0
  57. apps/btreceiver/__init__.py +690 -0
  58. apps/btreceiver/app.json +1 -0
  59. apps/btreceiver/chime.py +155 -0
  60. apps/btreceiver/demo.py +529 -0
  61. apps/btreceiver/screen.py +633 -0
  62. apps/camera/__init__.py +316 -0
  63. apps/camera/app.json +1 -0
  64. apps/card/__init__.py +113 -0
  65. apps/card/app.json +1 -0
  66. apps/cast/__init__.py +631 -0
  67. apps/cast/app.json +1 -0
  68. apps/cast/receivers.py +193 -0
  69. apps/chess/__init__.py +18 -0
  70. apps/chess/app.json +1 -0
  71. apps/chess/app.py +922 -0
  72. apps/chess/art.py +323 -0
  73. apps/chess/ble.py +411 -0
  74. apps/chess/engine.py +925 -0
  75. apps/chess/game.py +327 -0
  76. apps/chess/net.py +261 -0
  77. apps/clock/__init__.py +38 -0
  78. apps/clock/app.json +1 -0
  79. apps/detect/__init__.py +214 -0
  80. apps/detect/app.json +1 -0
  81. apps/fmsynth/__init__.py +41 -0
  82. apps/fmsynth/algorithms.py +61 -0
  83. apps/fmsynth/app.json +1 -0
  84. apps/fmsynth/app.py +355 -0
  85. apps/fmsynth/editor.py +206 -0
  86. apps/fmsynth/engine.py +257 -0
  87. apps/fmsynth/meters.py +262 -0
  88. apps/fmsynth/midi.py +375 -0
  89. apps/fmsynth/panel_view.py +1071 -0
  90. apps/fmsynth/patches/fmsynth-01.syx +0 -0
  91. apps/fmsynth/settings.py +138 -0
  92. apps/fmsynth/voice.py +398 -0
  93. apps/gamepad/__init__.py +685 -0
  94. apps/gamepad/app.json +1 -0
  95. apps/gamepad/pad.py +94 -0
  96. apps/gamepad/watch.py +352 -0
  97. apps/hidden/__init__.py +72 -0
  98. apps/hidden/app.json +1 -0
  99. apps/home/__init__.py +483 -0
  100. apps/home/app.json +1 -0
  101. apps/home/main.py +36 -0
  102. apps/homeassistant/__init__.py +213 -0
  103. apps/homeassistant/api.py +104 -0
  104. apps/homeassistant/app.json +1 -0
  105. apps/huey/__init__.py +287 -0
  106. apps/huey/acting.py +184 -0
  107. apps/huey/actor.py +194 -0
  108. apps/huey/app.json +1 -0
  109. apps/huey/client.py +125 -0
  110. apps/huey/servers.py +121 -0
  111. apps/huey/settings.example.json +8 -0
  112. apps/huey/settings.py +97 -0
  113. apps/huey/turn.py +504 -0
  114. apps/huey/voice.py +217 -0
  115. apps/info/__init__.py +810 -0
  116. apps/info/app.json +1 -0
  117. apps/lora/__init__.py +62 -0
  118. apps/lora/app.json +1 -0
  119. apps/manifest.py +71 -0
  120. apps/medialink_baby_monitor/__init__.py +222 -0
  121. apps/medialink_baby_monitor/app.json +1 -0
  122. apps/medialink_doorbell/__init__.py +251 -0
  123. apps/medialink_doorbell/app.json +1 -0
  124. apps/medialink_hands_free/__init__.py +217 -0
  125. apps/medialink_hands_free/app.json +1 -0
  126. apps/medialink_surveillance_camera/__init__.py +258 -0
  127. apps/medialink_surveillance_camera/app.json +1 -0
  128. apps/medialink_video_doorbell/__init__.py +289 -0
  129. apps/medialink_video_doorbell/app.json +1 -0
  130. apps/medialink_videophone/__init__.py +273 -0
  131. apps/medialink_videophone/app.json +1 -0
  132. apps/medialink_walkie_talkie/__init__.py +228 -0
  133. apps/medialink_walkie_talkie/app.json +1 -0
  134. apps/midicontroller/__init__.py +774 -0
  135. apps/midicontroller/app.json +1 -0
  136. apps/midicontroller/links.py +421 -0
  137. apps/midicontroller/surface.py +343 -0
  138. apps/midiengine/__init__.py +977 -0
  139. apps/midiengine/app.json +1 -0
  140. apps/midiengine/banks.py +85 -0
  141. apps/midiengine/midiin.py +165 -0
  142. apps/midiengine/player.py +392 -0
  143. apps/midiengine/umidiparser.py +1413 -0
  144. apps/mp3/__init__.py +240 -0
  145. apps/mp3/app.json +1 -0
  146. apps/perch/__init__.py +119 -0
  147. apps/perch/app.json +1 -0
  148. apps/perch/huey.py +481 -0
  149. apps/perch/huey_props.py +386 -0
  150. apps/perch/huey_shift.py +42 -0
  151. apps/perch/huey_views.py +296 -0
  152. apps/perch/scene_bench.py +680 -0
  153. apps/perch/scene_coast.py +479 -0
  154. apps/perch/scene_desk.py +492 -0
  155. apps/perch/stage.py +1274 -0
  156. apps/perch/vec.py +366 -0
  157. apps/repl/__init__.py +325 -0
  158. apps/repl/app.json +1 -0
  159. apps/roku/__init__.py +156 -0
  160. apps/roku/app.json +1 -0
  161. apps/rokucam/__init__.py +362 -0
  162. apps/rokucam/app.json +1 -0
  163. apps/security/__init__.py +261 -0
  164. apps/security/app.json +1 -0
  165. apps/settings/__init__.py +221 -0
  166. apps/settings/app.json +1 -0
  167. apps/shell/__init__.py +33 -0
  168. apps/shell/app.json +1 -0
  169. apps/spotify/__init__.py +669 -0
  170. apps/spotify/app.json +1 -0
  171. apps/spotify/screen.py +82 -0
  172. apps/steps/__init__.py +58 -0
  173. apps/steps/app.json +1 -0
  174. apps/stompbox/__init__.py +31 -0
  175. apps/stompbox/app.json +1 -0
  176. apps/stompbox/app.py +668 -0
  177. apps/stompbox/boards.json +20 -0
  178. apps/stompbox/effects.py +241 -0
  179. apps/stompbox/engine.py +340 -0
  180. apps/stompbox/footswitch.py +331 -0
  181. apps/stompbox/inputs.py +449 -0
  182. apps/stompbox/meter.py +72 -0
  183. apps/stompbox/outputs.py +135 -0
  184. apps/stompbox/pedals.txt +45 -0
  185. apps/stompbox/presets.py +106 -0
  186. apps/stompbox/styles.py +135 -0
  187. apps/stompbox/ui.py +817 -0
  188. apps/stompbox/wavfile.py +73 -0
  189. apps/synthstation/__init__.py +20 -0
  190. apps/synthstation/app.json +1 -0
  191. apps/synthstation/audio.py +397 -0
  192. apps/synthstation/catalog.py +50 -0
  193. apps/synthstation/meters.py +136 -0
  194. apps/synthstation/midi.py +380 -0
  195. apps/synthstation/pads.py +177 -0
  196. apps/synthstation/parts.py +128 -0
  197. apps/synthstation/station.py +1069 -0
  198. apps/system/__init__.py +11 -0
  199. apps/system/app.json +1 -0
  200. apps/touchcal/__init__.py +324 -0
  201. apps/touchcal/app.json +1 -0
  202. apps/touchcal/fit.py +262 -0
  203. apps/wake/__init__.py +268 -0
  204. apps/wake/app.json +1 -0
  205. apps/wake/feed.py +155 -0
  206. apps/watch/__init__.py +355 -0
  207. apps/watch/app.json +1 -0
  208. apps/watch/faces.py +35 -0
  209. apps/watch/wheel.py +157 -0
  210. apps/weather/__init__.py +278 -0
  211. apps/weather/app.json +1 -0
  212. apps/weather/icons.py +172 -0
  213. apps/weather/sizing.py +71 -0
  214. apps/weather/zippad.py +172 -0
  215. omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
  216. omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
  217. omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
  218. omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,977 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """midiEngine: a General MIDI sound module in the shape of MIDIPLUS's
5
+ pocket miniEngine. Plug a USB MIDI keyboard into the board's hub, or a
6
+ sequencer into a desktop's MIDI ports, and every one of the 16 channels
7
+ plays (on a desktop, the inputs chosen for ``midi.in`` in the connections
8
+ picker when any are, and it moves to new ones as they're chosen): SoundFont instruments on 1-9 and 11-16, a drum kit on 10. Or play
9
+ a folder of .mid files, and the keyboard on top of them.
10
+
11
+ The panel is the module's face, four cards on one screen. The top one
12
+ is what's playing: the piece's title, its composer, length and place in
13
+ the library, a progress bar, and the transport (previous, play or stop,
14
+ next, loop) with the Library button. Under it the mixer: sixteen strips,
15
+ one per channel, each with its program number and a meter that lights
16
+ with every note and falls away; tap a strip to select its channel. The
17
+ channel card shows the selected channel's number, instrument and program
18
+ (step it with the arrows) and its volume and pan (the faders follow the
19
+ channel, and a CC7 or CC10 arriving on it moves them). The master card
20
+ has the MASTER level (the output's volume, kept as a preference), reverb
21
+ and chorus for the whole module, and PANIC, which stops the player and
22
+ every sound. On a board with Bluetooth LE, BT MIDI under PANIC makes the
23
+ board a Bluetooth MIDI instrument, named midiEngine, that a controller, a
24
+ phone or a computer connects to; it's remembered, and off until turned on.
25
+
26
+ The Library button swaps the lower cards for the browser: the genres
27
+ down the left, the pieces of one (or all of them) on the right, each
28
+ with its title, composer and length; tap a piece to play it. "Genre
29
+ only" keeps next, previous and the end of a piece within the current
30
+ genre; off, they walk the whole library. The library is a folder of
31
+ .mid files, on a desktop ``$MIDI_DIR``, else ``~/midi``
32
+ (``%USERPROFILE%\\midi`` on Windows). On a board it's every ``midi``
33
+ folder: ``/sd/midi`` on the card (mounted read-only while the app is open,
34
+ as the MP3 player does), ``/midi`` on flash and ``/data/midi``
35
+ (`appkit.places`). A ``catalog.json`` at a folder's root names each piece's title, composer, genre
36
+ and length; without one the folder is scanned, subfolders as genres,
37
+ the file's name as its title. With no folder or no files, the face says
38
+ where to put them. ``player.py`` is the player, ``umidiparser.py`` the
39
+ parser it reads files with.
40
+
41
+ The sound is audioinstruments' ``soundfont`` and ``soundfont_drums``,
42
+ reading one .sf2, mixed through audioeffects' Chorus and Reverb and out
43
+ of the 3.5 mm jack. On a computer it's the sound device chosen for
44
+ ``audio.out`` (the connections picker), and choosing another while it plays
45
+ moves the sound there. The bank is ``$SOUNDFONT``, else a .sf2 in
46
+ ``~/soundfonts`` on a desktop, ``/sd/soundfonts``, ``/soundfonts`` or
47
+ ``/data/soundfonts`` on a board; with more than one there, the app opens on a list of them, the
48
+ last one chosen lit, and the sound starts with the one tapped (``banks.py``
49
+ finds them). With none, the face says where to put one. The bank is opened when the sound
50
+ starts; a channel's instrument is made the first time it is played or given a program, and its
51
+ samples are read on its notes, a bounded number of them kept. A tap on a piece only starts the
52
+ player's clock: its first events go on the app's timer.
53
+ The MIDI it answers is the sound module's (the apps repo's ``soundmodule.engine``).
54
+ """
55
+
56
+ import lvgl as lv
57
+ import sys
58
+
59
+ from multimer import ticks_diff, ticks_ms
60
+
61
+ from appkit import connections, places
62
+ from touchkit import ui
63
+
64
+ try:
65
+ from soundmodule import engine as gm # the sound module's engine
66
+ except ImportError as _e:
67
+ gm = None # main() says what's missing, on screen
68
+ _missing = _e
69
+
70
+ from . import midiin
71
+
72
+ from . import banks, player
73
+
74
+ RATE = 48000
75
+ CHANNELS = 2
76
+ CODEC_VOLUME = 85
77
+ MIDI_MS = 4 # how often the file player is serviced, and the port read while no file plays
78
+ DESKTOPS = ("win32", "linux", "darwin") # computers, with MIDI ports of their own
79
+ FILE_MIDI_EVERY = 3 # while a file plays, the port is read every third service (12 ms): a read waits
80
+ # a millisecond or more for the device, time the file's notes need
81
+ UI_MS = 40
82
+ DECAY = 8 # a strip's meter falls this much (of 127) per UI tick: about 0.6 s from full
83
+ SETUP_MS = 500 # how often to look for a keyboard until one is found
84
+ SEP = " \u2022 " # between the facts of a line: a bullet, which every LVGL font has
85
+ MIDI = "midi" # the folder name, on the card, flash and the data root
86
+
87
+ state = None # for the console
88
+
89
+
90
+ def pan_text(v):
91
+ if v == 64:
92
+ return "C"
93
+ return ("L%d" % (64 - v)) if v < 64 else ("R%d" % (v - 64))
94
+
95
+
96
+ def midi_folders(scope):
97
+ """Where the .mid files are: ``$MIDI_DIR`` or ``~/midi`` on a desktop;
98
+ on a board ``/sd/midi`` (the card mounted read-only while the app is
99
+ open), ``/midi`` and ``/data/midi``."""
100
+ if banks.DESKTOP:
101
+ return [banks.getenv("MIDI_DIR") or banks.home() + "/midi"]
102
+ places.hold_card(scope)
103
+ return places.folders(MIDI)
104
+
105
+
106
+ def clock_text(ms):
107
+ """``m:ss``, or ``h:mm:ss`` from an hour (a genre's total)."""
108
+ if ms >= 3600000:
109
+ return "%d:%02d:%02d" % (ms // 3600000, (ms // 60000) % 60, (ms // 1000) % 60)
110
+ return "%d:%02d" % (ms // 60000, (ms // 1000) % 60)
111
+
112
+
113
+ def main(scope):
114
+ global state
115
+ scr = scope.root
116
+ status = ui.status(scope)
117
+ W, H = scope.size
118
+ if gm is None:
119
+ ui.missing(scope, "missing: soundmodule", "midiEngine needs soundmodule, audioinstruments and audiodsp: %s" % (_missing,))
120
+ return
121
+
122
+ st = state = {
123
+ "module": None, "out": None, "port": None, "host": None, "ch": 0, "level": [0] * 16,
124
+ "seen": [0] * 16, "midi": None, "error": None, "short": None, "shown": None, "bank": None, "bank_name": "",
125
+ "merged": False, "midi_told": False, "ticks": 0, "ble": None, "ble_shown": None, "ble_resumed": False,
126
+ "since": ticks_ms(), "player": None, "player_shown": None, "browse": None, "marked": None, "widgets": {},
127
+ "device": None,
128
+ }
129
+ watch = midiin.Watch() # names the hub's MIDI devices for the status line
130
+ prefs = scope.store()
131
+ prefs.setdefault("volume", gm.DEFAULT_MASTER)
132
+ prefs.setdefault("ch", 0)
133
+ prefs.setdefault("loop", False)
134
+ prefs.setdefault("scope", player.ALL)
135
+ st["ch"] = prefs["ch"]
136
+
137
+ # -- the sound ------------------------------------------------------------------
138
+
139
+ def find_banks():
140
+ """The banks to choose from, ``[(path, bytes)]``, or None with the reason in ``st["error"]``."""
141
+ try:
142
+ # Dotted: on MicroPython, audioinstruments' lazy __getattr__ answers a
143
+ # from-import of a submodule not yet loaded with AttributeError.
144
+ import audioinstruments.soundfont # noqa: F401 (the sampler gm.Module plays through)
145
+ except (ImportError, AttributeError) as e:
146
+ st["error"] = "no sampler in this firmware: %s" % (e,)
147
+ return None
148
+ desktop = banks.DESKTOP
149
+ found = banks.candidates(banks.folders(desktop), banks.getenv("SOUNDFONT"))
150
+ if not found:
151
+ st["error"] = ("No SoundFont. Put a .sf2 in ~/soundfonts, or set SOUNDFONT to one." if desktop else
152
+ "No SoundFont, so no sound. Put a .sf2 in %s." % (banks.where_text(),))
153
+ st["short"] = "no SoundFont" # the status line is short; the Channel panel has the sentence
154
+ return None
155
+ return found
156
+
157
+ def start_audio(bank):
158
+ try:
159
+ import board_peripherals as bp
160
+ module = gm.Module(RATE, CHANNELS, bank=bank)
161
+ module.prepare() # the bank's presets read now, not in the first tap on a piece
162
+ power = getattr(bp, "audio_power", None)
163
+ if power is not None:
164
+ power(True, volume=CODEC_VOLUME)
165
+ out = open_out(module)
166
+ except Exception as e:
167
+ st["error"] = "audio: %s" % (e,)
168
+ return
169
+ st["module"], st["out"], st["bank"] = module, out, bank
170
+ st["bank_name"] = banks.name_of(bank)
171
+ resume_ble()
172
+
173
+ def open_out(module):
174
+ """The output *module* plays through, opened and playing."""
175
+ from audiodev import AudioFormat
176
+ import board_peripherals as bp
177
+ # A computer's default output buffers for playback, too long for keys.
178
+ live = {"latency": "low"} if sys.platform in DESKTOPS else {}
179
+ if st["device"] is not None:
180
+ live["device"] = st["device"]
181
+ out = bp.audio_out(AudioFormat(RATE, CHANNELS, 16), **live)
182
+ out.attach(scope) # its service() on the app's timer: pumped here, stops with the app
183
+ module.on_master = out.set_volume
184
+ module.set_master(prefs["volume"])
185
+ out.play(module.output)
186
+ return out
187
+
188
+ def close_out(out):
189
+ try:
190
+ out.stop()
191
+ except Exception:
192
+ pass
193
+ out.detach()
194
+ out.close()
195
+
196
+ def moved(endpoints):
197
+ # Another output was chosen: the module plays on there, its notes,
198
+ # bank and player as they were.
199
+ st["device"] = connections.device(endpoints)
200
+ out, module = st["out"], st["module"]
201
+ if out is None:
202
+ return
203
+ st["out"] = None
204
+ close_out(out)
205
+ try:
206
+ st["out"] = open_out(module)
207
+ except Exception as e:
208
+ st["error"] = "audio: %s" % (e,)
209
+
210
+ st["device"] = connections.device(scope.follow("audio.out", moved))
211
+
212
+ def resume_ble():
213
+ """Turn Bluetooth MIDI back on if it was left on, once: after the
214
+ sound starts, so a board short of internal RAM still plays and says
215
+ why Bluetooth didn't start."""
216
+ if ble_ok and prefs.get("ble") and not st["ble_resumed"]:
217
+ st["ble_resumed"] = True
218
+ ble_btn.add_state(lv.STATE.CHECKED)
219
+ set_ble(True)
220
+
221
+ def stop_audio():
222
+ out, module = st["out"], st["module"]
223
+ st["out"] = st["module"] = None
224
+ if out is not None:
225
+ close_out(out)
226
+ if module is not None:
227
+ module.close() # after the output, so it never pulls a deinitialised node
228
+ try:
229
+ import board_peripherals as bp
230
+ power = getattr(bp, "audio_power", None)
231
+ if power is not None:
232
+ power(False)
233
+ except Exception:
234
+ pass
235
+
236
+ # -- MIDI in --------------------------------------------------------------------
237
+
238
+ def open_midi():
239
+ """Every USB MIDI device in the board's hub at once, merged (ones
240
+ plugged in later are heard too), or all of a desktop's MIDI inputs."""
241
+ # A computer reads its own MIDI ports, even where a usb.core is
242
+ # importable (PyUSB, or a desktop build that carries the package).
243
+ if sys.platform in DESKTOPS + midiin.BROWSERS:
244
+ return open_desktop_midi()
245
+ try:
246
+ import usb.core
247
+ from midiports import usb_host
248
+
249
+ running = usb.core.running # PyUSB on a desktop has no host to start
250
+ except (ImportError, AttributeError):
251
+ return open_desktop_midi()
252
+ # Take the host as it runs: a launcher that started it keeps its
253
+ # speed and its devices. Only a host this app started is its own to stop.
254
+ if st["host"] is None:
255
+ st["host"] = not running()
256
+ st["port"], _out = usb_host.all_ports()
257
+ st["merged"] = True
258
+ return True
259
+
260
+ def open_desktop_midi():
261
+ found = midiin.open_desktop()
262
+ if found is None:
263
+ return False
264
+ st["port"], st["midi"] = found
265
+ return True
266
+
267
+ def midi_moved(endpoints):
268
+ # Other MIDI inputs were chosen for the computer: read those, or
269
+ # every input again when none is.
270
+ port = st["port"]
271
+ if port is None:
272
+ return # not open yet: the setup timer opens what's chosen
273
+ st["port"] = None
274
+ port.close()
275
+ if any(ep.error for ep in endpoints):
276
+ # This app held a port the choice wanted, and a port has one
277
+ # reader at a time: now it's let go, ask for the choice again.
278
+ import endpointkit
279
+
280
+ endpointkit.select("midi.in", endpointkit.chosen("midi.in"))
281
+ if open_desktop_midi():
282
+ status.set_text(st["midi"])
283
+ else:
284
+ st["midi"] = None
285
+ status.set_text("no MIDI in: plug a keyboard in")
286
+
287
+ if sys.platform in DESKTOPS + midiin.BROWSERS:
288
+ scope.follow("midi.in", midi_moved)
289
+
290
+ def midi(t):
291
+ ble = st["ble"]
292
+ if ble is not None:
293
+ try:
294
+ data = ble.read() if ble.any() else None
295
+ except Exception as e: # the link stopped: said, and the key shows it off
296
+ st["ble"] = None
297
+ ble.close()
298
+ ble_btn.clear_state(lv.STATE.CHECKED)
299
+ status.set_text("Bluetooth MIDI stopped: %s" % (e,))
300
+ data = None
301
+ module = st["module"]
302
+ if data and module is not None:
303
+ module.feed(data)
304
+ port = st["port"]
305
+ if port is None:
306
+ return
307
+ try:
308
+ if not port.any():
309
+ return
310
+ data = port.read()
311
+ except Exception as e:
312
+ st["port"] = None
313
+ status.set_text("MIDI: %s" % (e,))
314
+ return
315
+ module = st["module"]
316
+ if data and module is not None:
317
+ module.feed(data)
318
+
319
+ # -- the file player ------------------------------------------------------------
320
+
321
+ def feed(data):
322
+ """The player's sink: the same path as the port's bytes."""
323
+ module = st["module"]
324
+ if module is not None:
325
+ module.feed(data)
326
+
327
+ files = player.Player(midi_folders(scope), feed, loop=bool(prefs["loop"]), scope=prefs["scope"])
328
+ st["player"] = files
329
+
330
+ def guarded(fn):
331
+ """A transport action that reports a file the parser can't read, or
332
+ a part that won't load, on the status line instead of dying in LVGL."""
333
+ def run():
334
+ try:
335
+ fn()
336
+ except Exception as e:
337
+ files.stop()
338
+ status.set_text("MIDI file: %s" % (e,))
339
+ return run
340
+
341
+ serve_player = guarded(files.service)
342
+
343
+ # -- the face -------------------------------------------------------------------
344
+ #
345
+ # Four cards on an 8 px grid: what's playing (with the transport), the
346
+ # mixer (sixteen strips), the selected channel and the master. The
347
+ # LIBRARY button swaps the lower three for the library browser.
348
+
349
+ M, G = 8, 8
350
+ NOW_H, MIX_H = 96, 132
351
+ LOW_Y = M + NOW_H + G + MIX_H + G # the channel and master cards' top
352
+ LOW_H = H - LOW_Y - M
353
+ CW = W - 2 * M # a full-width card
354
+ CHAN_W = 470
355
+ MAST_X = M + CHAN_W + G
356
+ MAST_W = W - MAST_X - M
357
+ PAD = 14 # inside a card
358
+
359
+ def card(x, y, w, h):
360
+ c = ui.box(scr, x, y, w, h, ui.PANEL)
361
+ c.set_style_pad_all(0, 0)
362
+ return c
363
+
364
+ def one_line(lbl, font, w):
365
+ """A label of one line, *w* wide, that ends in dots when the text is longer."""
366
+ lbl.set_size(w, font.get_line_height())
367
+ lbl.set_long_mode(lv.label.LONG_MODE.DOTS)
368
+ return lbl
369
+
370
+ def eyebrow(parent, text, x, y, w=None, right=False):
371
+ lbl = ui.label(parent, text, ui.tiny, ui.MUTED)
372
+ lbl.set_style_text_letter_space(1, 0)
373
+ lbl.set_pos(x, y)
374
+ if w:
375
+ one_line(lbl, ui.tiny, w)
376
+ if right:
377
+ lbl.set_style_text_align(lv.TEXT_ALIGN.RIGHT, 0)
378
+ return lbl
379
+
380
+ def key(parent, text, cb, w, h, font=None, color=None, checkable=False):
381
+ b, lbl = ui.button(parent, text, cb, w=w, h=h, font=font, color=color or ui.KEY)
382
+ b.set_style_radius(10, 0)
383
+ b.set_style_shadow_width(0, 0)
384
+ if checkable:
385
+ b.add_flag(lv.obj.FLAG.CHECKABLE)
386
+ b.set_style_bg_color(ui.ACCENT, lv.STATE.CHECKED) # the one accent, not the theme's second colour
387
+ return b, lbl
388
+
389
+ def fader(parent, x, y, w, text, top, value, changed, accent=False):
390
+ """A labelled horizontal slider: ``(slider, value label)``."""
391
+ cap = eyebrow(parent, text, x, y)
392
+ val = ui.label(parent, "", ui.small, ui.WHITE if accent else ui.MUTED)
393
+ val.set_pos(x, y - 2)
394
+ val.set_width(w)
395
+ val.set_style_text_align(lv.TEXT_ALIGN.RIGHT, 0)
396
+ s = lv.slider(parent)
397
+ s.set_pos(x, y + 24)
398
+ s.set_size(w, 8)
399
+ s.set_range(0, top)
400
+ s.set_value(value, False)
401
+ s.set_style_bg_color(ui.BG, lv.PART.MAIN)
402
+ s.set_style_bg_color(ui.ACCENT, lv.PART.INDICATOR)
403
+ s.set_style_bg_color(ui.ACCENT if accent else ui.WHITE, lv.PART.KNOB)
404
+ s.set_style_pad_all(4, lv.PART.KNOB)
405
+ s.add_event_cb(lambda e: changed(s.get_value()), lv.EVENT.VALUE_CHANGED, None)
406
+ return s, val, cap
407
+
408
+ # -- now playing, with the transport --------------------------------------------
409
+
410
+ now = card(M, M, CW, NOW_H)
411
+ now_eyebrow = eyebrow(now, "", PAD, 10, CW - 2 * PAD - 380)
412
+ TRANSPORT = 3 * 52 + 88 + 92 + 3 * G + 16 # prev, play, next, loop, a breath, library
413
+ TEXT_W = CW - PAD - TRANSPORT - 10 - PAD
414
+ title_lbl = one_line(ui.label(now, "", ui.big, ui.WHITE), ui.big, TEXT_W)
415
+ title_lbl.set_pos(PAD, 28)
416
+ meta_lbl = one_line(ui.label(now, "", ui.small, ui.MUTED), ui.small, TEXT_W)
417
+ meta_lbl.set_pos(PAD, 60)
418
+ progress = lv.bar(now)
419
+ progress.set_pos(PAD, NOW_H - 12)
420
+ progress.set_size(CW - 2 * PAD, 4)
421
+ progress.set_range(0, 1000)
422
+ progress.set_value(0, False)
423
+ progress.set_style_bg_color(ui.BG, lv.PART.MAIN)
424
+ progress.set_style_bg_color(ui.ACCENT, lv.PART.INDICATOR)
425
+
426
+ def set_loop():
427
+ files.loop = bool(loop_btn.has_state(lv.STATE.CHECKED))
428
+ prefs["loop"] = files.loop
429
+
430
+ def set_view():
431
+ show_library(bool(library_btn.has_state(lv.STATE.CHECKED)))
432
+
433
+ BY, BH = 14, 52
434
+ bx = CW - PAD
435
+ bx -= 92
436
+ library_btn, _ = key(now, lv.SYMBOL.LIST + " Library", set_view, 92, BH, checkable=True)
437
+ library_btn.set_pos(bx, BY)
438
+ bx -= 16 + 52
439
+ loop_btn, _ = key(now, lv.SYMBOL.LOOP, set_loop, 52, BH, font=ui.font, checkable=True)
440
+ loop_btn.set_pos(bx, BY)
441
+ bx -= G + 52
442
+ next_btn, _ = key(now, lv.SYMBOL.NEXT, guarded(files.next), 52, BH, font=ui.font)
443
+ next_btn.set_pos(bx, BY)
444
+ bx -= G + 88
445
+ play_btn, play_lbl = key(now, lv.SYMBOL.PLAY, guarded(files.toggle), 88, BH, font=ui.big, color=ui.ACCENT)
446
+ play_btn.set_pos(bx, BY)
447
+ bx -= G + 52
448
+ prev_btn, _ = key(now, lv.SYMBOL.PREV, guarded(files.prev), 52, BH, font=ui.font)
449
+ prev_btn.set_pos(bx, BY)
450
+ if files.loop:
451
+ loop_btn.add_state(lv.STATE.CHECKED)
452
+
453
+ def show_player():
454
+ e = files.entry
455
+ if files.message:
456
+ shown = ("LIBRARY", "No MIDI files", files.message, 0, False)
457
+ else:
458
+ elapsed, length = files.elapsed_ms, files.length_ms
459
+ if files.scope == player.GENRE and e["genre"]:
460
+ siblings = files.indices(e["genre"])
461
+ where = "%d/%d in %s" % (siblings.index(files.index) + 1, len(siblings), e["genre"])
462
+ else:
463
+ where = "%d/%d" % (files.index + 1, len(files.files))
464
+ if e["genre"]:
465
+ where += SEP + e["genre"]
466
+ if files.playing:
467
+ when = "%s / %s" % (clock_text(elapsed), clock_text(length))
468
+ else:
469
+ when = clock_text(e["seconds"] * 1000) if e["seconds"] else ""
470
+ meta = SEP.join(part for part in (e["composer"], when) if part)
471
+ shown = (("NOW PLAYING" if files.playing else "STOPPED") + SEP + where, e["title"], meta,
472
+ (elapsed * 1000 // length) if length else 0, files.playing)
473
+ if shown == st["player_shown"]:
474
+ return
475
+ st["player_shown"] = shown
476
+ now_eyebrow.set_text(shown[0])
477
+ title_lbl.set_text(shown[1])
478
+ meta_lbl.set_text(shown[2])
479
+ if files.message: # the message wraps where the bar would be: nothing to progress
480
+ meta_lbl.set_long_mode(lv.label.LONG_MODE.WRAP)
481
+ meta_lbl.set_height(2 * ui.small.get_line_height())
482
+ progress.add_flag(lv.obj.FLAG.HIDDEN)
483
+ else:
484
+ one_line(meta_lbl, ui.small, TEXT_W)
485
+ progress.remove_flag(lv.obj.FLAG.HIDDEN)
486
+ progress.set_value(shown[3], False)
487
+ play_lbl.set_text(lv.SYMBOL.STOP if shown[4] else lv.SYMBOL.PLAY)
488
+ mark_piece()
489
+
490
+ # -- the mixer: sixteen strips --------------------------------------------------
491
+
492
+ mix = card(M, M + NOW_H + G, CW, MIX_H)
493
+ eyebrow(mix, "MIXER", PAD, 10)
494
+ bank_lbl = eyebrow(mix, "", CW // 3, 10, CW - CW // 3 - PAD, right=True)
495
+ SW, SG, SY, SH = 43, 4, 30, 96
496
+ sx = PAD + (CW - 2 * PAD - 16 * SW - 15 * SG) // 2
497
+ strips = [] # per channel: [strip, program label, meter, number label]
498
+
499
+ def select_channel(ch):
500
+ st["ch"] = ch
501
+ prefs["ch"] = ch
502
+
503
+ for ch in range(16):
504
+ s = ui.box(mix, sx + ch * (SW + SG), SY, SW, SH, ui.BG)
505
+ s.set_style_pad_all(0, 0)
506
+ s.set_style_radius(6, 0)
507
+ s.set_style_border_width(2, 0)
508
+ s.set_style_border_color(ui.BG, 0)
509
+ s.add_flag(lv.obj.FLAG.CLICKABLE)
510
+ s.add_event_cb(lambda e, ch=ch: select_channel(ch), lv.EVENT.CLICKED, None)
511
+ p = ui.label(s, "", ui.tiny, ui.MUTED)
512
+ p.set_width(SW - 4)
513
+ p.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
514
+ p.set_pos(0, 3)
515
+ m = lv.bar(s)
516
+ m.set_size(10, 50)
517
+ m.set_pos((SW - 4 - 10) // 2, 21)
518
+ m.set_range(0, 127)
519
+ m.set_value(0, False)
520
+ m.set_style_bg_color(ui.PANEL, lv.PART.MAIN)
521
+ m.set_style_bg_color(ui.ACCENT, lv.PART.INDICATOR)
522
+ m.set_style_radius(3, lv.PART.MAIN)
523
+ m.set_style_radius(3, lv.PART.INDICATOR)
524
+ m.remove_flag(lv.obj.FLAG.CLICKABLE)
525
+ n = ui.label(s, "%d" % (ch + 1), ui.small, ui.MUTED)
526
+ n.set_width(SW - 4)
527
+ n.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
528
+ n.set_pos(0, SH - 4 - 22)
529
+ strips.append([s, p, m, n])
530
+
531
+ # -- the selected channel -------------------------------------------------------
532
+
533
+ chan = card(M, LOW_Y, CHAN_W, LOW_H)
534
+ eyebrow(chan, "CHANNEL", PAD, 10)
535
+ ch_lbl = ui.label(chan, "", ui.huge, ui.ACCENT)
536
+ ch_lbl.set_pos(PAD, 26)
537
+ NAME_W = CHAN_W - PAD - 66 - 6 - 2 * 48 - 6 - PAD # to the PROG buttons
538
+ name_lbl = one_line(ui.label(chan, "", ui.big, ui.WHITE), ui.big, NAME_W)
539
+ name_lbl.set_pos(PAD + 66, 28)
540
+ part_lbl = one_line(ui.label(chan, "", ui.small, ui.MUTED), ui.small, NAME_W)
541
+ part_lbl.set_pos(PAD + 66, 58)
542
+
543
+ def step_program(d):
544
+ module = st["module"]
545
+ if module is None:
546
+ return
547
+ part = module.parts[st["ch"]]
548
+ if part.drums:
549
+ kits = module.kit_programs()
550
+ i = max(i for i, p in enumerate(kits) if p <= part.program) if kits else 0
551
+ program = kits[(i + d) % len(kits)] if kits else 0
552
+ else:
553
+ program = (part.program + d) % 128
554
+ module.program(part, program)
555
+
556
+ b, _ = key(chan, lv.SYMBOL.LEFT, lambda: step_program(-1), 48, 40, font=ui.font)
557
+ b.set_pos(CHAN_W - PAD - 48 - 6 - 48, 24)
558
+ b, _ = key(chan, lv.SYMBOL.RIGHT, lambda: step_program(1), 48, 40, font=ui.font)
559
+ b.set_pos(CHAN_W - PAD - 48, 24)
560
+
561
+ # The Volume and Pan faders are the selected channel's: the CC7 and
562
+ # CC10 paths on its part. show() moves them when the channel or the
563
+ # part's level changes, so the fader and MIDI take turns; last wins.
564
+ def volume_changed(v):
565
+ module = st["module"]
566
+ if module is not None:
567
+ module.set_volume(module.parts[st["ch"]], v)
568
+
569
+ def pan_changed(v):
570
+ module = st["module"]
571
+ if module is not None:
572
+ module.set_pan(module.parts[st["ch"]], v)
573
+
574
+ def master_changed(v):
575
+ prefs["volume"] = v
576
+ module = st["module"]
577
+ if module is not None:
578
+ module.set_master(v)
579
+ elif st["out"] is not None:
580
+ st["out"].set_volume(v)
581
+
582
+ def reverb_changed(v):
583
+ if st["module"] is not None:
584
+ st["module"].set_reverb(v)
585
+
586
+ def chorus_changed(v):
587
+ if st["module"] is not None:
588
+ st["module"].set_chorus(v)
589
+
590
+ FW = (CHAN_W - 2 * PAD - 24) // 2
591
+ faders = {
592
+ "Volume": fader(chan, PAD, 100, FW, "VOLUME", 127, gm.DEFAULT_VOLUME, volume_changed),
593
+ "Pan": fader(chan, PAD + FW + 24, 100, FW, "PAN", 127, gm.DEFAULT_PAN, pan_changed),
594
+ }
595
+
596
+ # -- the master -----------------------------------------------------------------
597
+
598
+ mast = card(MAST_X, LOW_Y, MAST_W, LOW_H)
599
+ eyebrow(mast, "MASTER", PAD, 10)
600
+ PW = 72
601
+ MW = MAST_W - 2 * PAD - PW - 20
602
+ faders["Master"] = fader(mast, PAD, 28, MW, "LEVEL", 100, prefs["volume"], master_changed, accent=True)
603
+ faders["Reverb"] = fader(mast, PAD, 70, MW, "REVERB", 127, gm.DEFAULT_REVERB, reverb_changed)
604
+ faders["Chorus"] = fader(mast, PAD, 112, MW, "CHORUS", 127, gm.DEFAULT_CHORUS, chorus_changed)
605
+
606
+ def panic():
607
+ """Every sound off: the player too, or its next event is a note."""
608
+ files.stop()
609
+ module = st["module"]
610
+ if module is not None:
611
+ module.panic()
612
+ st["level"] = [0] * 16
613
+
614
+ def set_ble(on):
615
+ """Bluetooth MIDI on or off, remembered. Off lets go of every note
616
+ it left sounding; a failure to start is said on the status line."""
617
+ prefs["ble"] = bool(on)
618
+ port = st["ble"]
619
+ if on and port is None:
620
+ try:
621
+ from midiports import ble
622
+
623
+ st["ble"] = ble.ports("midiEngine")[0]
624
+ except Exception as e:
625
+ prefs["ble"] = False
626
+ ble_btn.clear_state(lv.STATE.CHECKED)
627
+ status.set_text("Bluetooth MIDI didn't start: %s" % (e,))
628
+ return
629
+ elif not on and port is not None:
630
+ st["ble"] = None
631
+ port.close()
632
+ try:
633
+ data = port.read() # the note-offs closing left
634
+ except Exception: # the link had stopped: off either way
635
+ data = None
636
+ if data and st["module"] is not None:
637
+ st["module"].feed(data)
638
+ status.set_text(st["midi"] or "Bluetooth MIDI off")
639
+ st["ble_shown"] = None
640
+
641
+ ble_ok = midiin.ble_available()
642
+ PH = LOW_H - 28 - PAD
643
+ if ble_ok:
644
+ PH = (PH - 8) // 2
645
+ panic_btn, _ = key(mast, "PANIC", panic, PW, PH, font=ui.small, color=ui.BG)
646
+ panic_btn.set_pos(MAST_W - PAD - PW, 28)
647
+ ble_btn = None
648
+ if ble_ok:
649
+ ble_btn, _ = key(mast, "BT MIDI", lambda: set_ble(ble_btn.has_state(lv.STATE.CHECKED)),
650
+ PW, PH, font=ui.small, checkable=True)
651
+ ble_btn.set_pos(MAST_W - PAD - PW, 28 + PH + 8)
652
+ panic_btn.set_style_border_width(2, 0)
653
+ panic_btn.set_style_border_color(ui.BAD, 0)
654
+ panic_btn.set_style_text_color(ui.BAD, 0)
655
+
656
+ # -- the library ----------------------------------------------------------------
657
+
658
+ LIB_Y = M + NOW_H + G
659
+ LIB_H = H - LIB_Y - M
660
+ GENRE_W = 200
661
+ lib = card(M, LIB_Y, CW, LIB_H)
662
+ lib.add_flag(lv.obj.FLAG.HIDDEN)
663
+ eyebrow(lib, "GENRES", PAD, 10)
664
+ genre_lbl = eyebrow(lib, "", GENRE_W + PAD, 10, CW - GENRE_W - 2 * PAD - 180)
665
+ rule = ui.box(lib, GENRE_W, PAD, 1, LIB_H - 2 * PAD, ui.BG)
666
+ rule.set_style_radius(0, 0)
667
+
668
+ def rows(x, y, w, h, parent=None):
669
+ lst = lv.list(parent or lib)
670
+ lst.set_pos(x, y)
671
+ lst.set_size(w, h)
672
+ lst.set_style_bg_opa(lv.OPA.TRANSP, 0)
673
+ lst.set_style_border_width(0, 0)
674
+ lst.set_style_pad_all(0, 0)
675
+ lst.set_style_pad_row(2, 0)
676
+ lst.set_style_radius(0, 0)
677
+ return lst
678
+
679
+ def row(lst, text, cb, detail=None):
680
+ b = lst.add_button(None, text)
681
+ b.set_height(44)
682
+ b.set_style_bg_opa(lv.OPA.TRANSP, 0)
683
+ b.set_style_border_width(0, 0)
684
+ b.set_style_radius(8, 0)
685
+ b.set_style_pad_hor(10, 0)
686
+ b.set_style_text_font(ui.font, 0)
687
+ b.set_style_text_color(ui.WHITE, 0)
688
+ b.set_style_bg_color(ui.KEY, lv.STATE.PRESSED)
689
+ b.set_style_bg_opa(lv.OPA.COVER, lv.STATE.PRESSED)
690
+ b.get_child(0).set_long_mode(lv.label.LONG_MODE.DOTS)
691
+ b.get_child(0).set_height(ui.font.get_line_height())
692
+ if detail:
693
+ ui.label(b, detail, ui.small, ui.MUTED)
694
+ b.add_event_cb(lambda e: cb(), lv.EVENT.CLICKED, None)
695
+ return b
696
+
697
+ def mark(b, on):
698
+ b.set_style_bg_color(ui.ACCENT, 0)
699
+ b.set_style_bg_opa(lv.OPA._30 if on else lv.OPA.TRANSP, 0)
700
+ b.set_style_text_color(ui.ACCENT if on else ui.WHITE, 0)
701
+
702
+ genre_list = rows(PAD, 34, GENRE_W - 2 * PAD, LIB_H - 34 - PAD)
703
+ piece_list = rows(GENRE_W + PAD, 48, CW - GENRE_W - 2 * PAD, LIB_H - 48 - PAD)
704
+ genre_rows = [] # (genre or None, button)
705
+ piece_rows = [] # (index, button)
706
+
707
+ def set_scope():
708
+ files.scope = player.GENRE if scope_btn.has_state(lv.STATE.CHECKED) else player.ALL
709
+ prefs["scope"] = files.scope
710
+ scope_lbl.set_text("Genre only" if files.scope == player.GENRE else "Whole library")
711
+ st["player_shown"] = None
712
+
713
+ scope_btn, scope_lbl = key(lib, "", set_scope, 160, 34, font=ui.small, checkable=True)
714
+ scope_btn.set_pos(CW - PAD - 160, 6)
715
+ if files.scope == player.GENRE:
716
+ scope_btn.add_state(lv.STATE.CHECKED)
717
+ set_scope()
718
+
719
+ def browse(genre):
720
+ """Fill the pieces column with one genre's pieces, or all of them."""
721
+ st["browse"] = genre
722
+ for g, b in genre_rows:
723
+ mark(b, g == genre)
724
+ indices = files.indices(genre)
725
+ seconds = sum(files.entries[i]["seconds"] for i in indices)
726
+ genre_lbl.set_text("%s%s%d piece%s%s" % (
727
+ (genre or "Unsorted") if genre is not None else "ALL", SEP, len(indices), "" if len(indices) == 1 else "s",
728
+ (SEP + clock_text(seconds * 1000)) if seconds else ""))
729
+ piece_list.clean()
730
+ del piece_rows[:]
731
+ st["marked"] = None
732
+ for i in indices:
733
+ e = files.entries[i]
734
+ text = e["title"] + (" - " + e["composer"] if e["composer"] else "")
735
+ b = row(piece_list, text, guarded(lambda i=i: files.play(i)),
736
+ clock_text(e["seconds"] * 1000) if e["seconds"] else None)
737
+ piece_rows.append((i, b))
738
+ mark_piece(scroll=True)
739
+
740
+ def mark_piece(scroll=False):
741
+ """Light the current piece's row and scroll it into view: when asked,
742
+ and whenever the current piece changes (PREV, NEXT, the end of a piece)."""
743
+ current = files.index if files.files else None
744
+ if st["marked"] != current:
745
+ scroll = True
746
+ if scroll:
747
+ st["marked"] = current
748
+ for i, b in piece_rows:
749
+ mark(b, i == current)
750
+ if i == current and scroll:
751
+ b.scroll_to_view(False)
752
+
753
+ def fill_library():
754
+ genre_list.clean()
755
+ del genre_rows[:]
756
+ genre_rows.append((None, row(genre_list, "All", lambda: browse(None), "%d" % len(files.files))))
757
+ for g, count in files.genres():
758
+ genre_rows.append((g, row(genre_list, g or "Unsorted", lambda g=g: browse(g), "%d" % count)))
759
+ browse(files.genre if files.genre in [g for g, _ in genre_rows] else None)
760
+
761
+ def show_library(on):
762
+ if on:
763
+ fill_library()
764
+ for c in (mix, chan, mast):
765
+ if on:
766
+ c.add_flag(lv.obj.FLAG.HIDDEN)
767
+ else:
768
+ c.remove_flag(lv.obj.FLAG.HIDDEN)
769
+ if on:
770
+ lib.remove_flag(lv.obj.FLAG.HIDDEN)
771
+ else:
772
+ lib.add_flag(lv.obj.FLAG.HIDDEN)
773
+
774
+ # -- the SoundFont picker -------------------------------------------------------
775
+ #
776
+ # Over the whole face, once, before the sound starts, when there is more
777
+ # than one bank: one row per bank, its name and size; tap one and the
778
+ # face comes back with the sound on that bank. No switching after.
779
+
780
+ PICK_H = H - 2 * M
781
+ pick = card(M, M, CW, PICK_H)
782
+ pick.add_flag(lv.obj.FLAG.HIDDEN)
783
+ eyebrow(pick, "SOUNDFONT", PAD, 10)
784
+ one_line(ui.label(pick, "Choose a SoundFont", ui.big, ui.WHITE), ui.big, CW - 2 * PAD).set_pos(PAD, 28)
785
+ pick_meta = one_line(ui.label(pick, "", ui.small, ui.MUTED), ui.small, CW - 2 * PAD)
786
+ pick_meta.set_pos(PAD, 60)
787
+ pick_list = rows(PAD, NOW_H, CW - 2 * PAD, PICK_H - NOW_H - PAD, parent=pick)
788
+ pick_rows = [] # (path, button)
789
+ face = (now, mix, chan, mast)
790
+
791
+ def show_picker(found):
792
+ where = []
793
+ for path, _ in found:
794
+ folder = path.rsplit("/", 1)[0]
795
+ if folder not in where:
796
+ where.append(folder)
797
+ pick_meta.set_text("%d banks in %s%stap one to start the sound" % (len(found), " and ".join(where), SEP))
798
+ last = prefs.get("bank")
799
+ for path, size in found:
800
+ detail = banks.mb_text(size)
801
+ if len(where) > 1: # the same name may be on the card and on flash
802
+ detail = path.rsplit("/", 1)[0] + SEP + detail
803
+ b = row(pick_list, banks.name_of(path), lambda path=path: picked(path), detail)
804
+ mark(b, path == last)
805
+ pick_rows.append((path, b))
806
+ for c in face:
807
+ c.add_flag(lv.obj.FLAG.HIDDEN)
808
+ pick.remove_flag(lv.obj.FLAG.HIDDEN)
809
+ for path, b in pick_rows:
810
+ if path == last:
811
+ b.scroll_to_view(False)
812
+
813
+ def picked(path):
814
+ if st["bank"] is not None:
815
+ return # chosen already: one bank per session
816
+ st["bank"] = prefs["bank"] = path
817
+ pick_meta.set_text("Loading %s ..." % banks.name_of(path))
818
+ for p, b in pick_rows:
819
+ mark(b, p == path)
820
+
821
+ def load(t): # after a frame, so the row and the message are drawn before a big bank opens
822
+ start_audio(path)
823
+ pick.add_flag(lv.obj.FLAG.HIDDEN)
824
+ for c in face:
825
+ c.remove_flag(lv.obj.FLAG.HIDDEN)
826
+ st["shown"] = None
827
+
828
+ scope.after(UI_MS * 2, load)
829
+
830
+ st["widgets"] = {"title": title_lbl, "meta": meta_lbl, "progress": progress, "prev": prev_btn, "play": play_btn,
831
+ "play_label": play_lbl, "next": next_btn, "loop": loop_btn, "library": library_btn,
832
+ "scope": scope_btn, "panic": panic_btn, "faders": faders, "strips": strips,
833
+ "genres": genre_rows, "pieces": piece_rows, "now": now, "mix": mix, "chan": chan,
834
+ "mast": mast, "lib": lib, "pick": pick, "pick_rows": pick_rows}
835
+
836
+ def show_fader(name, value, text):
837
+ s, val, _ = faders[name]
838
+ if not s.is_dragged():
839
+ s.set_value(value, False)
840
+ val.set_text(text)
841
+
842
+ def show():
843
+ module = st["module"]
844
+ ch = st["ch"]
845
+ if module is None:
846
+ shown = (ch, st["error"])
847
+ if shown != st["shown"]:
848
+ st["shown"] = shown
849
+ ch_lbl.set_text("%02d" % (ch + 1))
850
+ # The reason on two lines, its first sentence in the name's
851
+ # place, so a folder named in it isn't cut off.
852
+ head, _, rest = (st["error"] or "").partition(". ")
853
+ name_lbl.set_text(head if rest else "---")
854
+ part_lbl.set_height(2 * ui.small.get_line_height())
855
+ part_lbl.set_text(rest if rest else (st["error"] or ""))
856
+ show_fader("Master", prefs["volume"], "%d" % prefs["volume"])
857
+ for c, strip in enumerate(strips):
858
+ strip[0].set_style_border_color(ui.ACCENT if c == ch else ui.BG, 0)
859
+ strip[3].set_style_text_color(ui.WHITE if c == ch else ui.MUTED, 0)
860
+ return
861
+ part = module.parts[ch]
862
+ loaded = sum(1 for p in module.parts if p.inst is not None)
863
+ programs = tuple((p.program, p.inst is not None) for p in module.parts)
864
+ shown = (ch, part.bank_msb, part.bank_lsb, part.volume, part.pan, part.bend, module.reverb_level,
865
+ module.chorus_level, module.master_level, loaded, programs)
866
+ if shown == st["shown"]:
867
+ return
868
+ st["shown"] = shown
869
+ ch_lbl.set_text("%02d" % (ch + 1))
870
+ name_lbl.set_text(module.name(ch))
871
+ part_lbl.set_height(ui.small.get_line_height())
872
+ facts = ["PROG %03d" % (part.program + 1)]
873
+ if part.bank_msb or part.bank_lsb:
874
+ facts.append("bank %d:%d" % (part.bank_msb, part.bank_lsb))
875
+ if part.bend != gm.BEND_CENTER:
876
+ facts.append("bend %+d" % (part.bend - gm.BEND_CENTER))
877
+ if part.inst is None:
878
+ facts.append("not loaded")
879
+ part_lbl.set_text(SEP.join(facts))
880
+ show_fader("Volume", part.volume, "%d" % part.volume)
881
+ show_fader("Pan", part.pan, pan_text(part.pan))
882
+ show_fader("Master", module.master_level, "%d" % module.master_level)
883
+ show_fader("Reverb", module.reverb_level, "%d" % module.reverb_level)
884
+ show_fader("Chorus", module.chorus_level, "%d" % module.chorus_level)
885
+ bank_lbl.set_text("%s%s%d of 16 parts loaded" % (st["bank_name"], SEP, loaded))
886
+ for c, strip in enumerate(strips):
887
+ p = module.parts[c]
888
+ strip[0].set_style_border_color(ui.ACCENT if c == ch else ui.BG, 0)
889
+ strip[1].set_text("KIT" if p.drums else "%03d" % (p.program + 1))
890
+ strip[1].set_style_text_color(ui.WHITE if p.inst is not None else ui.MUTED, 0)
891
+ strip[3].set_style_text_color(ui.WHITE if c == ch else ui.MUTED, 0)
892
+
893
+ def tick(t):
894
+ ble = st["ble"]
895
+ if ble is not None and ble.state != st["ble_shown"]:
896
+ st["ble_shown"] = ble.state
897
+ status.set_text(midiin.ble_text(ble))
898
+ module = st["module"]
899
+ level, seen = st["level"], st["seen"]
900
+ for ch, strip in enumerate(strips):
901
+ if module is not None:
902
+ part = module.parts[ch]
903
+ if part.notes != seen[ch]:
904
+ seen[ch] = part.notes
905
+ level[ch] = max(level[ch], part.last[1] if part.last else 100)
906
+ level[ch] = max(0, level[ch] - DECAY)
907
+ if level[ch] != strip[2].get_value():
908
+ strip[2].set_value(level[ch], False)
909
+ show()
910
+ show_player()
911
+
912
+
913
+ def setup(t):
914
+ if st["port"] is None:
915
+ try:
916
+ open_midi()
917
+ except Exception as e:
918
+ status.set_text("MIDI: %s" % (e,))
919
+ setup_timer.deinit()
920
+ return
921
+ if st["merged"]:
922
+ # The hub's devices come and go: keep the status line current.
923
+ if watch.changed(st["port"]):
924
+ st["midi"] = watch.text
925
+ st["midi_told"] = False
926
+ if watch.text:
927
+ # Without a bank the keys play nothing: say that, not just who is plugged in.
928
+ status.set_text(watch.text if st["module"] is not None or not st["error"] else st["short"] or st["error"])
929
+ elif st["port"] is not None:
930
+ status.set_text(st["midi"])
931
+ setup_timer.deinit()
932
+ return
933
+ if not st["midi"] and not st["midi_told"] and ticks_diff(ticks_ms(), st["since"]) > 8000:
934
+ st["midi_told"] = True
935
+ status.set_text("no MIDI in: plug a keyboard in")
936
+
937
+ def close():
938
+ ble = st["ble"]
939
+ st["ble"] = None
940
+ if ble is not None:
941
+ ble.close()
942
+ port = st["port"]
943
+ st["port"] = None
944
+ files.stop() # its notes off reach the parts before the output goes
945
+ stop_audio()
946
+ if port is not None:
947
+ port.close()
948
+ if st["host"]:
949
+ import usb.core
950
+
951
+ usb.core.stop()
952
+ st["host"] = None
953
+
954
+ scope.on_close(close)
955
+ found = find_banks()
956
+ if found is None and st["error"]:
957
+ status.set_text(st["short"] or st["error"]) # plain on the status line too: keys play nothing without a bank
958
+ if found is not None and len(found) == 1:
959
+ start_audio(found[0][0])
960
+ elif found:
961
+ show_picker(found)
962
+ setup_timer = scope.every(SETUP_MS, setup)
963
+ if not found or st["error"]: # no sound to wait for
964
+ resume_ble()
965
+ def service(t):
966
+ """The port and the player on one timer, the port first: a key
967
+ played never waits behind a file's backlog."""
968
+ st["ticks"] += 1
969
+ with gm.deferred(st["module"]): # what this tick plays leaves together
970
+ if not files.playing or st["ticks"] % FILE_MIDI_EVERY == 0:
971
+ midi(t)
972
+ serve_player()
973
+
974
+ scope.every(MIDI_MS, service)
975
+ scope.every(UI_MS, tick)
976
+ show()
977
+ show_player()