-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch_browser_ui.py
More file actions
executable file
·2058 lines (1735 loc) · 86.8 KB
/
Copy pathpatch_browser_ui.py
File metadata and controls
executable file
·2058 lines (1735 loc) · 86.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pi-Surge-MPE Patch Browser UI
Single-encoder patch browser with 1.3" OLED display for browsing and loading
Surge XT patches in headless/CLI mode.
Features:
- 128x64 OLED display (I2C) showing category and patch names
- Single rotary encoder with click button
- Click to toggle between category/patch scroll modes
- Auto-loads selected patch immediately (low CPU overhead)
- Scans all Surge factory and 3rd-party patches
"""
import time
import signal
import sys
import os
import threading
from pathlib import Path
from dataclasses import dataclass, field
from gpiozero import RotaryEncoder, Button
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from PIL import ImageFont
import subprocess
# Kernel-level encoder support (optional, falls back to gpiozero)
try:
import evdev
from evdev import InputDevice, ecodes
EVDEV_AVAILABLE = True
except ImportError:
EVDEV_AVAILABLE = False
# Try to detect display type automatically, fallback to SH1106
try:
from luma.oled.device import sh1106 as display_device
DISPLAY_TYPE = "SH1106"
except ImportError:
from luma.oled.device import ssd1306 as display_device
DISPLAY_TYPE = "SSD1306"
# ============================================================================
# CONFIGURATION
# ============================================================================
@dataclass
class Config:
"""Centralized configuration for patch browser"""
# GPIO Pins
encoder_clk: int = 17 # GPIO 17 (Pin 11)
encoder_dt: int = 27 # GPIO 27 (Pin 13)
encoder_sw: int = 22 # GPIO 22 (Pin 15)
# I2C Configuration
i2c_port: int = 1
i2c_address: int = 0x3C
# Timing Constants
debounce_time: float = 0.005 # Encoder debounce (5ms)
button_debounce: float = 0.01 # Button debounce (10ms)
scroll_processing_interval: float = 0.001 # Scroll event processing (1ms)
load_debounce_time: float = 1.25 # Wait before loading patch (1.25s)
button_encoder_isolation: float = 0.05 # Isolation window (50ms)
encoder_post_button_cooldown: float = 0.05 # Cooldown after button (50ms)
# Press Duration Thresholds
bold_press_min: float = 0.5 # Mode toggle (500ms+, up to power menu at 8s)
poweroff_press_min: float = 8.0 # Power menu (8s)
# Scroll Modes
scroll_mode_category: int = 0
scroll_mode_patch: int = 1
# User quick-access folder (on-disk name under ~/Documents/Surge XT/Patches/)
# Override via MPE_FAVORITES_NAME in /etc/mpe/mpe.env — see docs/PATCH_BROWSER_UI.md
favorites_name: str = field(
default_factory=lambda: os.environ.get("MPE_FAVORITES_NAME", "!Quick Access")
)
# Global config instance
CONFIG = Config()
# Alias used throughout scanner/UI (set MPE_FAVORITES_NAME before patch-browser starts)
FAVORITES_NAME = CONFIG.favorites_name
def favorites_display_name(name=None):
"""Browser category label — leading ! sorts first. Idempotent if name already has !."""
n = name if name is not None else FAVORITES_NAME
return n if n.startswith("!") else f"!{n}"
def favorites_folder_matches(name):
"""True if on-disk folder/category name matches MPE_FAVORITES_NAME (with or without !)."""
return name.lstrip("!").lower() == FAVORITES_NAME.lstrip("!").lower()
# Backwards compatibility - keep old constant names pointing to config
ENCODER_CLK = CONFIG.encoder_clk
ENCODER_DT = CONFIG.encoder_dt
ENCODER_SW = CONFIG.encoder_sw
I2C_PORT = CONFIG.i2c_port
I2C_ADDRESS = CONFIG.i2c_address
DEBOUNCE_TIME = CONFIG.debounce_time
BUTTON_DEBOUNCE = CONFIG.button_debounce
SCROLL_PROCESSING_INTERVAL = CONFIG.scroll_processing_interval
LOAD_DEBOUNCE_TIME = CONFIG.load_debounce_time
BUTTON_ENCODER_ISOLATION = CONFIG.button_encoder_isolation
ENCODER_POST_BUTTON_COOLDOWN = CONFIG.encoder_post_button_cooldown
BOLD_PRESS_MIN = CONFIG.bold_press_min
POWEROFF_PRESS_MIN = CONFIG.poweroff_press_min
SCROLL_MODE_CATEGORY = CONFIG.scroll_mode_category
SCROLL_MODE_PATCH = CONFIG.scroll_mode_patch
# Surge Patch Directories
SURGE_PATCH_DIRS = [
Path.home() / "surge" / "resources" / "data" / "patches_factory",
Path.home() / "surge" / "resources" / "data" / "patches_3rdparty",
Path.home() / "Documents" / "Surge XT" / "Patches", # User patches (includes favorites category)
]
# State persistence files
LAST_PATCH_FILE = Path.home() / ".patch_browser_last_patch.json"
# ============================================================================
# PATCH SCANNER
# ============================================================================
class PatchScanner:
"""Scans and organizes Surge patches by category"""
def __init__(self, patch_dirs, last_patch_file=LAST_PATCH_FILE):
self.patch_dirs = patch_dirs
self.last_patch_file = last_patch_file
self.patches = {} # {category: [patch_paths]}
# Threading support for background scanning
self.scan_complete = threading.Event()
self.scan_lock = threading.Lock()
self.scan_thread = None
# Do NOT call scan_patches() here anymore - will be called explicitly
def scan_patches(self):
"""Scan all patch directories and organize by category"""
print("Scanning Surge patches...")
total_patches = 0
# Clear patches dict for full scan (removes any quick-scan temporary data)
with self.scan_lock:
self.patches = {}
for patch_dir in self.patch_dirs:
if not patch_dir.exists():
print(f"Warning: Patch directory not found: {patch_dir}")
continue
# Walk through directory structure
for root, dirs, files in os.walk(patch_dir):
# Category is the immediate subdirectory name
rel_path = Path(root).relative_to(patch_dir)
category = str(rel_path.parts[0]) if rel_path.parts else "Uncategorized"
# Force the favorites category to the top by prepending "!"
if favorites_folder_matches(category):
category = favorites_display_name(category)
# Find all .fxp files
fxp_files = [f for f in files if f.lower().endswith('.fxp')]
if fxp_files:
if category not in self.patches:
self.patches[category] = []
for fxp_file in fxp_files:
patch_path = Path(root) / fxp_file
patch_name = fxp_file.replace('.fxp', '').replace('.FXP', '')
# Check for duplicates by name (prevent same patch appearing twice in same category)
# This handles cases where a patch exists in both original location and the favorites folder
existing_patch = next((p for p in self.patches[category] if p['name'] == patch_name), None)
if existing_patch:
# Patch with same name already exists - prefer the one in the favorites folder
if category == favorites_display_name() and favorites_folder_matches(str(patch_path)):
# Replace with the one from the favorites folder
existing_patch['path'] = str(patch_path)
# Otherwise keep the existing one (skip duplicate)
continue
self.patches[category].append({
'name': patch_name,
'path': str(patch_path),
'category': category
})
total_patches += 1
# Sort categories and patches alphabetically, but put favorites first
def sort_key(item):
category_name = item[0]
if category_name == favorites_display_name():
return ('', category_name) # Empty string sorts before all letters
return (category_name, category_name)
# Update patches dict atomically to prevent race conditions with UI thread
with self.scan_lock:
self.patches = {k: sorted(v, key=lambda x: x['name'])
for k, v in sorted(self.patches.items(), key=sort_key)}
print(f"Found {total_patches} patches in {len(self.patches)} categories")
# Debug: Show first 3 categories
cat_names = list(self.patches.keys())
print(f"First 3 categories: {cat_names[:3]}")
return self.patches
def scan_patches_background(self):
"""
Start background thread to scan patches.
Returns immediately, sets scan_complete event when done.
"""
def _scan_worker():
try:
self.scan_patches()
self.scan_complete.set()
print("Background patch scan complete")
except Exception as e:
print(f"Error during background scan: {e}")
# Still signal completion and add error category
with self.scan_lock:
if not self.patches:
self.patches = {"Error": [{"name": "Scan failed", "path": "", "category": "Error"}]}
self.scan_complete.set()
self.scan_thread = threading.Thread(target=_scan_worker, daemon=True, name="PatchScanner")
self.scan_thread.start()
print("Started background patch scanning...")
def wait_for_scan(self, timeout=None):
"""Wait for background scan to complete"""
return self.scan_complete.wait(timeout=timeout)
def quick_scan_category(self, category_path):
"""
Quickly scan a single category directory without full scan.
Used to load last patch immediately before full background scan.
Args:
category_path: Path object pointing to category directory
Returns:
List of patch dicts in the category
"""
patches = []
if not category_path.exists():
return patches
for fxp_file in category_path.glob("*.fxp"):
patch_name = fxp_file.stem
category_name = category_path.name
# Force the favorites category to the top
if favorites_folder_matches(category_name):
category_name = favorites_display_name(category_name)
patches.append({
'name': patch_name,
'path': str(fxp_file),
'category': category_name
})
return sorted(patches, key=lambda x: x['name'])
def save_last_patch(self, category, patch_path):
"""Save the last loaded patch for restoration on reconnect"""
import json
try:
state = {
'category': category,
'patch_path': str(patch_path)
}
with open(self.last_patch_file, 'w') as f:
json.dump(state, f, indent=2)
except Exception as e:
print(f"Warning: Could not save last patch state: {e}")
def load_last_patch(self):
"""Load the last patch state (returns dict with category and patch_path, or None)"""
import json
if self.last_patch_file.exists():
try:
with open(self.last_patch_file, 'r') as f:
state = json.load(f)
# Validate the patch still exists
patch_path = Path(state['patch_path'])
if patch_path.exists():
return state
else:
print(f"Last patch no longer exists: {patch_path}")
except Exception as e:
print(f"Warning: Could not load last patch state: {e}")
return None
def get_categories(self):
"""Get sorted list of category names (favorites will be first due to ! prefix)"""
with self.scan_lock:
return list(self.patches.keys())
def get_patches_in_category(self, category):
"""Get all patches in a specific category"""
with self.scan_lock:
return self.patches.get(category, [])
def is_in_favorites_folder(self, patch_path):
"""Check if a patch is already in the favorites folder"""
patch_path_obj = Path(patch_path)
for patch_dir in self.patch_dirs:
favorites_folder = patch_dir / FAVORITES_NAME
if favorites_folder.exists() and patch_path_obj.is_relative_to(favorites_folder):
return True
return False
def get_favorites_folder_path(self):
"""Get the path to the favorites folder (creates if needed)"""
# Use the user patches directory for the favorites folder
user_patches_dir = Path.home() / "Documents" / "Surge XT" / "Patches"
favorites_folder = user_patches_dir / FAVORITES_NAME
favorites_folder.mkdir(parents=True, exist_ok=True)
return favorites_folder
def copy_patch_to_favorites(self, patch_path):
"""Copy a patch file to the favorites folder"""
try:
source_path = Path(patch_path)
if not source_path.exists():
print(f"Error: Source patch not found: {patch_path}")
return False
favorites_folder = self.get_favorites_folder_path()
dest_path = favorites_folder / source_path.name
# Check if file already exists in the favorites folder
if dest_path.exists():
print(f"Patch already exists in favorites folder: {source_path.name}")
return False # Don't create duplicate
# Copy the file
import shutil
shutil.copy2(source_path, dest_path)
print(f"Copied patch to favorites folder: {source_path.name}")
# Rescan to pick up the new patch
self.scan_patches()
return True
except Exception as e:
print(f"Error copying patch to favorites folder: {e}")
return False
# ============================================================================
# OLED DISPLAY MANAGER
# ============================================================================
class PatchDisplay:
"""Manages the 128x64 OLED display for patch browsing"""
def __init__(self, i2c_port=I2C_PORT, i2c_address=I2C_ADDRESS):
print(f"Initializing {DISPLAY_TYPE} display on I2C port {i2c_port}, address 0x{i2c_address:02X}")
# Initialize I2C interface
serial = i2c(port=i2c_port, address=i2c_address)
# Initialize display device with 180 degree rotation (inverted vertically)
self.device = display_device(serial, rotate=2) # rotate=2 = 180 degrees
# Load default font (built-in, always available)
self.font_small = ImageFont.load_default()
# Try to load a larger font if available
try:
# Try to use a TrueType font for better readability
self.font_large = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 12)
except:
self.font_large = self.font_small
print(f"Display initialized: {self.device.width}x{self.device.height}")
self.show_splash()
def show_splash(self):
"""Show startup splash screen"""
with canvas(self.device) as draw:
draw.text((0, 10), "Pi-Surge-MPE", fill="white", font=self.font_large)
draw.text((0, 25), "Patch Browser", fill="white", font=self.font_small)
draw.text((0, 40), "Initializing...", fill="white", font=self.font_small)
time.sleep(0.2) # Reduced from 1s for faster boot
def show_patch(self, category, patch_name, loaded_category, category_idx, category_total,
patch_idx, patch_total, scroll_mode, patches_list=None, categories_list=None, loading=False, scanner=None, loaded_patch_name=None):
"""
Display current patch selection with optimized layout
PATCH MODE Layout:
┌─────────────────────┐
│ Category [12/51] │ Header with count
│ ─────────────── │ Separator
│ > Current Patch · │ Selected (with >) + loading dot
│ Next Patch │ Preview
│ Next Patch 2 │ Preview
└─────────────────────┘
CATEGORY MODE Layout:
┌─────────────────────┐
│ [12/51] │ Just count
│ ─────────────── │ Separator
│ > Current Category │ Selected (with >)
│ Next Category │ Preview
│ Next Category 2 │ Preview
└─────────────────────┘
"""
with canvas(self.device) as draw:
if scroll_mode == SCROLL_MODE_PATCH:
# PATCH MODE: Show category name + patch count
category_display = category[:14] if len(category) > 14 else category
count_text = f"[{patch_idx+1}/{patch_total}]"
draw.text((0, 0), category_display, fill="white", font=self.font_small)
# Right-align the count
count_width = len(count_text) * 6 # Approximate width
draw.text((128 - count_width, 0), count_text, fill="white", font=self.font_small)
else:
# CATEGORY MODE: Show "LoadedCategory/LoadedPatch" on left, count on right
# Display format: "Category/Patch" (showing what's actually playing, not what's being browsed)
if loaded_category:
# Show the actually loaded patch info
path_display = f"{loaded_category}/{patch_name[:8]}" if patch_name != "(No patches)" else loaded_category
else:
# Fallback if nothing loaded yet
path_display = f"{category}/{patch_name[:8]}" if patch_name != "(No patches)" else category
# Truncate to fit with count
path_display = path_display[:14] if len(path_display) > 14 else path_display
draw.text((0, 0), path_display, fill="white", font=self.font_small)
# Category count (right-aligned)
count_text = f"[{category_idx+1}/{category_total}]"
count_width = len(count_text) * 6
draw.text((128 - count_width, 0), count_text, fill="white", font=self.font_small)
# Separator line
draw.line((0, 10, 127, 10), fill="white")
# Current item (larger, with indicator)
if scroll_mode == SCROLL_MODE_PATCH:
current_display = patch_name[:17] if len(patch_name) > 17 else patch_name
else:
current_display = category[:19] if len(category) > 19 else category
draw.text((0, 14), f">{current_display}", fill="white", font=self.font_large)
# Show indicators for current patch (right-aligned)
if scroll_mode == SCROLL_MODE_PATCH and scanner and patches_list and patch_idx < len(patches_list):
current_patch = patches_list[patch_idx]
# Show loaded indicator (filled circle) if this is the currently loaded patch
if loaded_patch_name and loaded_category == category and loaded_patch_name == patch_name:
draw.ellipse((108, 16, 112, 20), fill="white", outline="white")
# Show loading indicator (small dot at end of current line, left of heart)
# Only show if we're actively loading AND it's not the currently loaded patch
if loading and scroll_mode == SCROLL_MODE_PATCH:
draw.ellipse((114, 16, 118, 20), fill="white", outline="white")
# Preview next items (smaller font)
y_offset = 28
if scroll_mode == SCROLL_MODE_PATCH and patches_list:
# Show next 2-3 patches with favorite hearts
for i in range(1, min(4, len(patches_list))):
next_idx = (patch_idx + i) % len(patches_list)
next_patch_obj = patches_list[next_idx]
next_patch = next_patch_obj['name']
next_display = next_patch[:20] if len(next_patch) > 20 else next_patch
draw.text((2, y_offset), next_display, fill="white", font=self.font_small)
y_offset += 12
elif scroll_mode == SCROLL_MODE_CATEGORY and categories_list:
# Show next 2-3 categories
for i in range(1, min(4, len(categories_list))):
next_idx = (category_idx + i) % len(categories_list)
next_cat = categories_list[next_idx]
next_display = next_cat[:20] if len(next_cat) > 20 else next_cat
draw.text((2, y_offset), next_display, fill="white", font=self.font_small)
y_offset += 12
def show_loading(self, patch_name):
"""Show loading screen when applying patch"""
with canvas(self.device) as draw:
draw.text((0, 20), "Loading...", fill="white", font=self.font_large)
patch_display = patch_name[:18] if len(patch_name) > 18 else patch_name
draw.text((0, 35), patch_display, fill="white", font=self.font_small)
def show_error(self, message, timeout=7):
"""
Show error message with optional timeout
Args:
message: Error text to display
timeout: Seconds to show error (0 = indefinite)
"""
with canvas(self.device) as draw:
draw.text((0, 10), "ERROR:", fill="white", font=self.font_large)
# Word wrap for long messages
words = message.split()
line = ""
y = 25
for word in words:
test_line = f"{line} {word}".strip()
if len(test_line) > 20:
draw.text((0, y), line, fill="white", font=self.font_small)
line = word
y += 12
else:
line = test_line
if line:
draw.text((0, y), line, fill="white", font=self.font_small)
if timeout > 0:
time.sleep(timeout)
self.device.clear()
def show_error_and_continue(self, message, timeout=7):
"""
Show error message, wait, then clear display and continue.
Helper for error recovery pattern.
"""
print(f"ERROR: {message}")
self.show_error(message, timeout=timeout)
# Display is already cleared by show_error
def show_dialog(self, dialog_type, selection, patch=None, power_action=None):
"""Show confirmation dialog"""
with canvas(self.device) as draw:
if dialog_type == "copy_to_favorites":
# Show copy to favorites confirmation
patch_name = patch['name'][:18] if patch and len(patch['name']) > 18 else (patch['name'] if patch else "")
draw.text((0, 0), f"Copy to {favorites_display_name()}?"[:20], fill="white", font=self.font_small)
draw.text((0, 12), patch_name, fill="white", font=self.font_small)
draw.text((0, 30), "> No" if selection == 0 else " No", fill="white", font=self.font_small)
draw.text((0, 42), " Yes" if selection == 0 else "> Yes", fill="white", font=self.font_small)
elif dialog_type == "power_menu":
# Show power menu with shutdown/restart/cancel
draw.text((0, 0), "Power Menu", fill="white", font=self.font_small)
draw.text((0, 20), "> Shutdown" if selection == 0 else " Shutdown", fill="white", font=self.font_small)
draw.text((0, 32), " Restart" if selection != 1 else "> Restart", fill="white", font=self.font_small)
draw.text((0, 44), " Cancel" if selection != 2 else "> Cancel", fill="white", font=self.font_small)
elif dialog_type == "power_confirm":
# Show power confirmation
action_text = "Shutdown?" if power_action == "shutdown" else "Restart?"
draw.text((0, 0), action_text, fill="white", font=self.font_small)
draw.text((0, 20), "Are you sure?", fill="white", font=self.font_small)
draw.text((0, 36), "> No" if selection == 0 else " No", fill="white", font=self.font_small)
draw.text((0, 48), " Yes" if selection == 0 else "> Yes", fill="white", font=self.font_small)
elif dialog_type == "surge_error":
# Show Surge error/restart screen
status = patch.get('status', 'ERROR') if patch else 'ERROR'
details = patch.get('details', 'Unknown error') if patch else 'Unknown error'
can_restart = patch.get('can_restart', False) if patch else False
draw.text((0, 0), "SURGE XT CLI", fill="white", font=self.font_small)
draw.text((0, 12), f"Status: {status}", fill="white", font=self.font_small)
# Show error details (word wrapped)
words = details.split()
line = ""
y = 26
for word in words:
test_line = f"{line} {word}".strip()
if len(test_line) > 20:
draw.text((0, y), line, fill="white", font=self.font_small)
line = word
y += 11
if y > 48: # Stop if too many lines
break
else:
line = test_line
if line and y <= 48:
draw.text((0, y), line, fill="white", font=self.font_small)
# Show restart option if applicable
if can_restart:
draw.text((0, 54), "> Restart Back" if selection == 0 else " Restart > Back",
fill="white", font=self.font_small)
else:
draw.text((0, 54), "Press to continue", fill="white", font=self.font_small)
# ============================================================================
# PATCH LOADER
# ============================================================================
class PatchLoader:
"""Loads patches into Surge XT CLI via OSC"""
def __init__(self, osc_host='127.0.0.1', osc_port=53280):
"""
Initialize OSC client for Surge XT
Args:
osc_host: IP address of Surge (default: localhost)
osc_port: OSC port (default: 53280)
"""
try:
from pythonosc import udp_client
self.osc_client = udp_client.SimpleUDPClient(osc_host, osc_port)
self.osc_enabled = True
print(f"OSC client initialized: {osc_host}:{osc_port}")
except ImportError:
print("Warning: python-osc not installed, patch loading disabled")
self.osc_enabled = False
except Exception as e:
print(f"Warning: OSC client failed to initialize: {e}")
self.osc_enabled = False
def set_volume(self, volume=1.5):
"""
Set Surge XT master volume via OSC
Args:
volume: Volume level (1.0 = default, 1.5 = 150%, etc.)
Returns:
True if command sent successfully, False otherwise
"""
if not self.osc_enabled:
return False
try:
# Set volume for both scenes
self.osc_client.send_message('/param/a/amp/volume', volume)
self.osc_client.send_message('/param/b/amp/volume', volume)
return True
except Exception as e:
print(f"Error setting volume via OSC: {e}")
return False
def load_patch(self, patch_path):
"""
Load a patch into Surge XT via OSC
Surge OSC command: /patch/load <path_without_fxp_extension>
Surge automatically appends .fxp to the path
Args:
patch_path: Full path to .fxp file
Returns:
True if command sent successfully, False otherwise
"""
if not self.osc_enabled:
print(f"OSC disabled, cannot load: {patch_path}")
return False
try:
# Remove .fxp extension (Surge adds it automatically)
path_no_ext = str(patch_path)
if path_no_ext.endswith('.fxp') or path_no_ext.endswith('.FXP'):
path_no_ext = path_no_ext[:-4]
# Send OSC message: /patch/load <path>
self.osc_client.send_message('/patch/load', [path_no_ext])
print(f"Loaded patch: {Path(patch_path).name}")
# Volume is at default (100%) - no adjustment needed
return True
except Exception as e:
print(f"Error loading patch via OSC: {e}")
return False
# ============================================================================
# SURGE XT CLI HEALTH MONITOR
# ============================================================================
class SurgeMonitor:
"""Monitors Surge XT CLI process health and provides restart capability"""
def __init__(self, log_file=None):
if log_file is None:
log_file = os.environ.get('MPE_SURGE_LOG', os.path.expanduser('~/surge-cli.log'))
"""
Initialize Surge health monitor
Args:
log_file: Path to Surge CLI log file for error checking
"""
self.log_file = Path(log_file)
self.surge_pid = None
self.last_check_time = 0
self.check_interval = 2.0 # Check every 2 seconds
self.is_healthy = False
self.last_error = None
self.startup_time = time.time()
# Try to find existing Surge process
self._find_surge_process()
def _find_surge_process(self):
"""Find running Surge XT CLI process"""
try:
result = subprocess.run(
['pgrep', '-f', 'surge-xt-cli'],
capture_output=True,
text=True,
timeout=1
)
if result.returncode == 0 and result.stdout.strip():
self.surge_pid = int(result.stdout.strip().split()[0])
self.is_healthy = True
print(f"Found existing Surge process: PID {self.surge_pid}")
else:
self.is_healthy = False
self.last_error = "Surge not running"
except Exception as e:
print(f"Error finding Surge process: {e}")
self.is_healthy = False
self.last_error = str(e)
def check_health(self):
"""
Check if Surge is running and healthy
Returns:
tuple: (is_healthy: bool, error_message: str or None)
"""
current_time = time.time()
# Rate limit checks
if current_time - self.last_check_time < self.check_interval:
return self.is_healthy, self.last_error
self.last_check_time = current_time
# Skip checks during initial startup (give Surge time to start)
if current_time - self.startup_time < 5.0:
return True, None
# Check if process is still running
if self.surge_pid is not None:
try:
# Send signal 0 to check if process exists
os.kill(self.surge_pid, 0)
self.is_healthy = True
self.last_error = None
return True, None
except OSError:
# Process doesn't exist
self.is_healthy = False
self.last_error = "Surge crashed or exited"
# Try to get error from log
error_detail = self._get_last_error_from_log()
if error_detail:
self.last_error = error_detail
return False, self.last_error
else:
# No PID tracked, try to find process
self._find_surge_process()
return self.is_healthy, self.last_error
def _get_last_error_from_log(self):
"""Extract last error message from Surge log file"""
try:
if not self.log_file.exists():
return None
# Read last 50 lines of log
result = subprocess.run(
['tail', '-50', str(self.log_file)],
capture_output=True,
text=True,
timeout=1
)
if result.returncode != 0:
return None
lines = result.stdout.strip().split('\n')
# Look for error indicators
for line in reversed(lines):
line_lower = line.lower()
if any(keyword in line_lower for keyword in ['error', 'fatal', 'crash', 'failed', 'unable']):
# Extract meaningful part
if 'error' in line_lower:
parts = line.split('Error:', 1)
if len(parts) > 1:
return parts[1].strip()[:50] # Limit to 50 chars
return line.strip()[:50]
return None
except Exception as e:
print(f"Error reading Surge log: {e}")
return None
def restart_surge(self):
"""
Restart Surge XT CLI service
Returns:
tuple: (success: bool, message: str)
"""
try:
print("Attempting to restart Surge XT CLI...")
result = subprocess.run(
['sudo', 'systemctl', 'restart', 'surge-xt-cli.service'],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
# Wait for process to start
time.sleep(3)
self._find_surge_process()
if self.is_healthy:
return True, "Surge restarted"
else:
return False, "Restart failed - check logs"
else:
return False, f"systemctl error: {result.stderr[:30]}"
except subprocess.TimeoutExpired:
return False, "Restart timeout"
except Exception as e:
return False, f"Error: {str(e)[:30]}"
def get_status_summary(self):
"""
Get human-readable status summary
Returns:
dict: {'status': str, 'details': str, 'can_restart': bool}
"""
is_healthy, error = self.check_health()
if is_healthy:
return {
'status': 'Running',
'details': f'PID {self.surge_pid}',
'can_restart': False
}
else:
return {
'status': 'Not Running',
'details': error or 'Unknown error',
'can_restart': True
}
# ============================================================================
# ENCODER EVENT HANDLER (KERNEL-LEVEL)
# ============================================================================
class EncoderEventHandler:
"""Reads rotary encoder events from Linux kernel via evdev
This class interfaces with the kernel's rotary-encoder driver to get
hardware-timed, debounced encoder events. Much more reliable than
software polling with gpiozero.
"""
def __init__(self, scroll_callback):
"""Initialize encoder event handler
Args:
scroll_callback: Function to call with encoder value (+1 CW, -1 CCW)
"""
self.device = self._find_encoder_device()
self.scroll_callback = scroll_callback
self.running = True
self.thread = None
self.last_event_time = 0
self.last_direction = 0
self.event_counter = 0
self.direction_change_delay_ms = 2 # Minimal delay (2ms) - hardware capacitors handle noise
def _find_encoder_device(self):
"""Find rotary encoder device by capabilities"""
if not EVDEV_AVAILABLE:
raise ImportError("python-evdev not installed")
# Try by-path first (most stable across reboots)
paths = [
'/dev/input/by-path/platform-rotary@11-event',
'/dev/input/by-path/platform-rotary@17-event',
]
for path in paths:
if Path(path).exists():
return InputDevice(str(path))
# Fallback: scan all devices by capabilities
for path in evdev.list_devices():
device = InputDevice(path)
caps = device.capabilities()
# Look for device with REL_DIAL capability (rotary encoder)
if ecodes.EV_REL in caps:
if ecodes.REL_DIAL in caps[ecodes.EV_REL]:
print(f"Found rotary encoder: {device.name} at {path}")
return device
raise FileNotFoundError("Rotary encoder device not found. Is the device tree overlay configured?")
def _event_loop(self):
"""Blocking event loop (runs in separate thread)"""
try:
for event in self.device.read_loop():
if not self.running:
break
# Process encoder rotation events
if event.type == ecodes.EV_REL:
# Check for both REL_X and REL_DIAL (depends on overlay config)
if event.code in (ecodes.REL_X, ecodes.REL_DIAL):
current_time = time.time() * 1000 # Convert to ms
direction = event.value # +1 (CW) or -1 (CCW)
# Direction change detection with time-based filter
if direction != self.last_direction:
# Direction changed - only accept if enough time passed since last event
time_since_last = current_time - self.last_event_time
if time_since_last < self.direction_change_delay_ms:
# Too soon for direction change - likely noise, ignore
continue
# Accept direction change
self.last_direction = direction
self.event_counter = 1
self.last_event_time = current_time
else:
# Same direction - increment counter
self.event_counter += 1
# Process after seeing 1 event (hardware capacitors handle noise)
# KY-040 generates 2 events per detent, but with hardware debouncing we can process immediately
if self.event_counter >= 1:
self.scroll_callback(direction)
self.event_counter = 0 # Reset for next detent
self.last_event_time = current_time
except OSError:
pass # Device closed during shutdown
def start(self):
"""Start event handler thread"""
self.thread = threading.Thread(target=self._event_loop, daemon=True, name="EncoderThread")
self.thread.start()
def stop(self):
"""Stop event handler and close device"""
self.running = False
if self.device:
self.device.close()
# ============================================================================
# MAIN BROWSER APPLICATION
# ============================================================================
class PatchBrowser:
"""Main application coordinating encoder, display, and patch loading"""
def _wait_for_surge_ready(self, timeout=30):
"""Wait for Surge XT CLI to be ready before proceeding
Checks:
1. Surge service is active
2. OSC port is listening
3. Surge process is running
Returns when ready, or after timeout
"""
import subprocess
import socket
print("Waiting for Surge XT CLI to be ready...")
start_time = time.time()
while (time.time() - start_time) < timeout:
# Check 1: Is Surge service active?
try:
result = subprocess.run(
['systemctl', 'is-active', 'surge-xt-cli.service'],
capture_output=True,
text=True,
timeout=1
)
if result.returncode != 0 or result.stdout.strip() != 'active':
time.sleep(0.5)
continue
except Exception:
time.sleep(0.5)
continue
# Check 2: Is OSC port listening?