This repository was archived by the owner on Apr 18, 2026. It is now read-only.
forked from verygoodplugins/streamdeck-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile_manager.py
More file actions
1438 lines (1238 loc) · 54.7 KB
/
profile_manager.py
File metadata and controls
1438 lines (1238 loc) · 54.7 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
"""
Helpers for reading and writing Elgato Stream Deck profile manifests.
The Elgato desktop app stores device profiles in ProfilesV3 on newer installs
and ProfilesV2 on older installs. V3 uses page UUIDs as directory names; V2
uses opaque directory identifiers, so V2 page updates work best when callers
target pages by directory ID or page index.
"""
from __future__ import annotations
import copy
import json
import os
import re
import secrets
import shlex
import shutil
import string
import subprocess
import sys
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any
try:
from PIL import Image, ImageDraw, ImageFont
HAS_PILLOW = True
except ImportError:
HAS_PILLOW = False
DEFAULT_BG_COLOR = "#000000"
DEFAULT_TEXT_COLOR = "#FFFFFF"
DEFAULT_FONT_SIZE = 12
DEFAULT_TITLE_ALIGNMENT = "bottom"
DEFAULT_ICON_SIZE = (72, 72)
TOUCHSTRIP_ICON_SIZE = (200, 100)
ICON_SHAPES = {"button": DEFAULT_ICON_SIZE, "touchstrip": TOUCHSTRIP_ICON_SIZE}
KEYPAD = "Keypad"
ENCODER = "Encoder"
CONTROLLER_ALIASES: dict[str, str] = {
"keypad": KEYPAD,
"key": KEYPAD,
"button": KEYPAD,
"encoder": ENCODER,
"dial": ENCODER,
}
DEFAULT_PAGE_MANIFEST = {
"Controllers": [
{
"Actions": None,
"Type": KEYPAD,
}
],
"Icon": "",
"Name": "",
}
MODEL_LAYOUTS: dict[str, dict[str, tuple[int, int]]] = {
# Stream Deck Original (15 keys)
"20GBA9901": {KEYPAD: (5, 3)},
# Stream Deck MK.2 (15 keys)
"20GAA9901": {KEYPAD: (5, 3)},
# Stream Deck XL (32 keys)
"20GAT9902": {KEYPAD: (8, 4)},
# Stream Deck XL rev2 (32 keys)
"20GBA9902": {KEYPAD: (8, 4)},
# Stream Deck + XL (36 keys, 6 dials with 1200x100 touchstrip)
"20GBX9901": {KEYPAD: (9, 4), ENCODER: (6, 1)},
# Stream Deck Mini (6 keys)
"20GAI9501": {KEYPAD: (3, 2)},
# Stream Deck Neo (8 keys + touchscreen)
"20GBD9901": {KEYPAD: (4, 2)},
# Emulator used by the Elgato desktop app
"UI Stream Deck": {KEYPAD: (4, 2)},
}
# The Elgato Stream Deck desktop app caches every profile in memory and rewrites the
# on-disk manifests when it quits, so any edit made while it is running gets clobbered
# the next time the user closes or restarts the app.
STREAM_DECK_APP_PROCESS_NAMES = ("Stream Deck", "Elgato Stream Deck")
DEFAULT_STREAM_DECK_APP_PATH = Path("/Applications/Elgato Stream Deck.app")
STREAM_DECK_APP_PATH_ENV = "STREAMDECK_APP_PATH"
HEX_COLOR_PATTERN = re.compile(r"^#[0-9a-fA-F]{6}$")
POSITION_PATTERN = re.compile(r"^\d+,\d+$")
UUID_PATTERN = re.compile(
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
)
SLUG_PATTERN = re.compile(r"[^a-z0-9]+")
FONT_PATHS = [
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/SFNSText.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
"C:/Windows/Fonts/arial.ttf",
]
class ProfileManagerError(Exception):
"""Base exception for profile manager operations."""
class ProfileNotFoundError(ProfileManagerError):
"""Raised when a requested profile cannot be found."""
class PageNotFoundError(ProfileManagerError):
"""Raised when a requested profile page cannot be found."""
class ProfileValidationError(ProfileManagerError):
"""Raised when inputs for profile operations are invalid."""
class StreamDeckAppRunningError(ProfileManagerError):
"""Raised when a write is attempted while the Elgato desktop app is running.
The app rewrites every profile manifest from its in-memory snapshot on quit, so
writes made while it is running are silently discarded. Callers must quit the
app first (pass `auto_quit_app=True` to `write_page`) and then call
`restart_app` once their edits are complete to see the changes.
"""
@dataclass
class PageRef:
"""Resolved page directory metadata."""
page_index: int
directory_id: str
page_uuid: str | None
manifest_path: Path
version: str
mapping: str
is_default: bool
is_current: bool
name: str
button_count: int
icon_count: int
@property
def directory_path(self) -> Path:
return self.manifest_path.parent
def to_dict(self) -> dict[str, Any]:
return {
"page_index": self.page_index,
"directory_id": self.directory_id,
"page_uuid": self.page_uuid,
"version": self.version,
"mapping": self.mapping,
"is_default": self.is_default,
"is_current": self.is_current,
"name": self.name,
"button_count": self.button_count,
"icon_count": self.icon_count,
"manifest_path": str(self.manifest_path),
}
def _normalize_uuid(value: str) -> str:
return value.strip().lower()
def _looks_like_uuid(value: str) -> bool:
return bool(UUID_PATTERN.match(value))
def _load_json(path: Path) -> dict[str, Any]:
try:
return json.loads(path.read_text())
except FileNotFoundError as exc:
raise ProfileManagerError(f"Missing file: {path}") from exc
except json.JSONDecodeError as exc:
raise ProfileManagerError(f"Invalid JSON in {path}: {exc}") from exc
def _write_json_atomic(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix(f"{path.suffix}.tmp")
temp_path.write_text(json.dumps(data, indent=2, sort_keys=True))
temp_path.replace(path)
def _candidate_profiles_dirs() -> list[Path]:
home = Path.home()
if sys.platform == "darwin":
base = home / "Library/Application Support/com.elgato.StreamDeck"
elif sys.platform == "win32":
appdata = os.environ.get("APPDATA")
if not appdata:
raise ProfileManagerError("APPDATA is not set; cannot locate Stream Deck profiles.")
base = Path(appdata) / "Elgato/StreamDeck"
else:
base = home / ".local/share/Elgato/StreamDeck"
return [base / "ProfilesV3", base / "ProfilesV2"]
def get_profiles_dir(version: str = "auto") -> Path:
"""Resolve the active Stream Deck profiles directory."""
candidates = _candidate_profiles_dirs()
if version == "auto":
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0]
normalized = version.lower().removeprefix("profiles")
if normalized in {"3", "v3"}:
return candidates[0]
if normalized in {"2", "v2"}:
return candidates[1]
raise ProfileValidationError(
f"Unsupported profiles version '{version}'. Use 'auto', '2', or '3'."
)
def _find_controller(page_manifest: dict[str, Any], controller_type: str) -> dict[str, Any] | None:
for controller in page_manifest.get("Controllers") or []:
if controller.get("Type") == controller_type:
return controller
return None
def _ensure_controller(page_manifest: dict[str, Any], controller_type: str) -> dict[str, Any]:
controllers = page_manifest.setdefault("Controllers", [])
for controller in controllers:
if controller.get("Type") == controller_type:
return controller
new_controller: dict[str, Any] = {"Type": controller_type, "Actions": None}
controllers.append(new_controller)
return new_controller
def _controller_actions(
page_manifest: dict[str, Any], controller_type: str = KEYPAD
) -> dict[str, Any]:
controller = _find_controller(page_manifest, controller_type)
if not controller:
return {}
return controller.get("Actions") or {}
def _normalize_controller(value: str | None) -> str:
if not value:
return KEYPAD
canonical = CONTROLLER_ALIASES.get(value.lower())
if canonical is None:
raise ProfileValidationError(
f"Unknown controller '{value}'. Use one of: {sorted(set(CONTROLLER_ALIASES))}"
)
return canonical
def _total_action_count(page_manifest: dict[str, Any]) -> int:
return sum(
len(controller.get("Actions") or {})
for controller in page_manifest.get("Controllers") or []
)
def _slugify(value: str) -> str:
slug = SLUG_PATTERN.sub("-", value.strip().lower()).strip("-")
return slug or "streamdeck-action"
def _quote_open_path(path: Path) -> str:
escaped = str(path).replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def _ensure_hex_color(value: str, *, field_name: str) -> str:
normalized = value.strip()
if not HEX_COLOR_PATTERN.match(normalized):
raise ProfileValidationError(
f"{field_name} must be a hex color like '#112233', got '{value}'."
)
return normalized.lower()
def _resolve_font(size: int) -> Any:
for font_path in FONT_PATHS:
try:
return ImageFont.truetype(font_path, size)
except OSError:
continue
return ImageFont.load_default()
def _count_icons(page_dir: Path) -> int:
images_dir = page_dir / "Images"
if not images_dir.exists():
return 0
return len([path for path in images_dir.iterdir() if path.is_file()])
def _resolve_app_path() -> Path:
override = os.environ.get(STREAM_DECK_APP_PATH_ENV)
if override:
return Path(override).expanduser()
return DEFAULT_STREAM_DECK_APP_PATH
def get_plugins_dir() -> Path:
"""Return the Elgato Stream Deck plugins directory for the current OS."""
home = Path.home()
if sys.platform == "darwin":
return home / "Library/Application Support/com.elgato.StreamDeck/Plugins"
if sys.platform == "win32":
appdata = os.environ.get("APPDATA")
if not appdata:
raise ProfileManagerError("APPDATA is not set; cannot locate Stream Deck plugins.")
return Path(appdata) / "Elgato/StreamDeck/Plugins"
return home / ".local/share/Elgato/StreamDeck/Plugins"
def ensure_mcp_plugin_installed(*, force: bool = False) -> dict[str, Any]:
"""Install the bundled streamdeck-mcp plugin into the Elgato Plugins directory.
The plugin declares an encoder-capable action so that the Stream Deck app
accepts per-instance ``Encoder.Icon`` and ``Encoder.background`` writes made
by the profile writer. Without it, those fields are stripped on quit for any
action whose plugin does not declare encoder support.
Idempotent: returns ``installed=False`` when the plugin directory already
exists at the current bundled version, unless ``force=True`` is passed.
Automatically upgrades when the installed manifest version is older than the
bundled version so that new action UUIDs (e.g. layout variants) are available.
"""
from importlib.resources import as_file, files
from streamdeck_plugin import PLUGIN_DIR_NAME, PLUGIN_VERSION
plugins_dir = get_plugins_dir()
dst = plugins_dir / PLUGIN_DIR_NAME
if dst.exists() and not force:
installed_version: str | None = None
try:
installed_manifest = dst / "manifest.json"
installed_version = json.loads(installed_manifest.read_text(encoding="utf-8")).get(
"Version"
)
except Exception:
pass
if installed_version == PLUGIN_VERSION:
return {"installed": False, "reason": "already installed", "path": str(dst)}
# Installed version is missing or outdated — fall through to reinstall.
plugins_dir.mkdir(parents=True, exist_ok=True)
if dst.exists():
if dst.is_symlink() or dst.is_file():
dst.unlink()
else:
shutil.rmtree(dst)
src_resource = files("streamdeck_plugin").joinpath(PLUGIN_DIR_NAME)
with as_file(src_resource) as src_path:
shutil.copytree(src_path, dst)
return {"installed": True, "path": str(dst)}
def is_stream_deck_app_running() -> bool:
"""Return True if the Elgato Stream Deck desktop app is currently running."""
if sys.platform != "darwin":
return False
for name in STREAM_DECK_APP_PROCESS_NAMES:
result = subprocess.run(
["pgrep", "-x", name],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0 and result.stdout.strip():
return True
return False
def stop_stream_deck_app(*, graceful_timeout: float = 3.0) -> dict[str, Any]:
"""Quit the Elgato Stream Deck desktop app.
Tries an AppleScript quit first so the app can persist any unrelated state, then
falls back to `killall` if it does not exit in time. Returns a small report about
which path was taken.
"""
if sys.platform != "darwin":
return {"stopped": False, "graceful": [], "forced": [], "reason": "non-darwin platform"}
if not is_stream_deck_app_running():
return {"stopped": False, "graceful": [], "forced": [], "reason": "not running"}
graceful: list[str] = []
for name in STREAM_DECK_APP_PROCESS_NAMES:
result = subprocess.run(
["osascript", "-e", f'tell application "{name}" to quit'],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
graceful.append(name)
deadline = time.monotonic() + graceful_timeout
while time.monotonic() < deadline and is_stream_deck_app_running():
time.sleep(0.2)
forced: list[str] = []
if is_stream_deck_app_running():
for name in STREAM_DECK_APP_PROCESS_NAMES:
result = subprocess.run(
["killall", name],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
forced.append(name)
return {
"stopped": not is_stream_deck_app_running(),
"graceful": graceful,
"forced": forced,
}
class ProfileManager:
"""Read and write Elgato Stream Deck profiles."""
def __init__(
self,
profiles_dir: Path | None = None,
*,
profiles_version: str = "auto",
scripts_dir: Path | None = None,
generated_icons_dir: Path | None = None,
) -> None:
self.profiles_dir = (
Path(profiles_dir) if profiles_dir else get_profiles_dir(profiles_version)
)
self.scripts_dir = (
Path(scripts_dir).expanduser() if scripts_dir else (Path.home() / "StreamDeckScripts")
)
self.generated_icons_dir = (
Path(generated_icons_dir).expanduser()
if generated_icons_dir
else (Path.home() / ".streamdeck-mcp" / "generated-icons")
)
def list_profiles(self) -> list[dict[str, Any]]:
"""List profiles in the selected Elgato profiles directory."""
if not self.profiles_dir.exists():
return []
profiles: list[dict[str, Any]] = []
for profile_dir in sorted(self.profiles_dir.glob("*.sdProfile")):
manifest = _load_json(profile_dir / "manifest.json")
page_refs = self._page_refs(profile_dir, manifest)
profiles.append(
{
"profile_id": profile_dir.stem,
"name": manifest.get("Name", profile_dir.stem),
"version": manifest.get("Version", "unknown"),
"profiles_dir": str(self.profiles_dir),
"profiles_root": self.profiles_dir.name,
"profile_path": str(profile_dir),
"device": manifest.get("Device", {}),
"current_page_uuid": manifest.get("Pages", {}).get("Current"),
"default_page_uuid": manifest.get("Pages", {}).get("Default"),
"page_count": len(page_refs),
"pages": [page_ref.to_dict() for page_ref in page_refs],
}
)
return profiles
def read_page(
self,
*,
profile_name: str | None = None,
profile_id: str | None = None,
page_index: int | None = None,
directory_id: str | None = None,
) -> dict[str, Any]:
"""Read a specific page manifest and return a simplified view."""
profile_dir, profile_manifest = self._resolve_profile(
profile_name=profile_name, profile_id=profile_id
)
page_ref = self._resolve_page_ref(
profile_dir,
profile_manifest,
page_index=page_index,
directory_id=directory_id,
)
page_manifest = _load_json(page_ref.manifest_path)
keypad_cols, keypad_rows = self._resolve_layout(profile_manifest, page_manifest, KEYPAD)
buttons: list[dict[str, Any]] = []
layouts: dict[str, dict[str, int]] = {}
for controller in page_manifest.get("Controllers") or []:
controller_type = controller.get("Type", KEYPAD)
cols, rows = self._resolve_layout(profile_manifest, page_manifest, controller_type)
layouts[controller_type.lower()] = {"columns": cols, "rows": rows}
actions = controller.get("Actions") or {}
for position, action in sorted(
actions.items(),
key=lambda item: self._position_sort_key(item[0]),
):
col, row = [int(part) for part in position.split(",")]
key = (row * cols + col) if cols else col
states = action.get("States") or [{}]
state_index = min(max(int(action.get("State", 0)), 0), max(len(states) - 1, 0))
active_state = states[state_index] if states else {}
buttons.append(
{
"controller": controller_type.lower(),
"key": key,
"position": position,
"action_id": action.get("ActionID"),
"action_uuid": action.get("UUID"),
"plugin_uuid": action.get("Plugin", {}).get("UUID"),
"plugin_name": action.get("Plugin", {}).get("Name"),
"name": action.get("Name"),
"state": action.get("State", 0),
"title": active_state.get("Title"),
"image": active_state.get("Image"),
"settings": action.get("Settings", {}),
"show_title": active_state.get("ShowTitle"),
"raw": action,
}
)
return {
"profiles_root": self.profiles_dir.name,
"profile": {
"profile_id": profile_dir.stem,
"name": profile_manifest.get("Name", profile_dir.stem),
"version": profile_manifest.get("Version", "unknown"),
"device": profile_manifest.get("Device", {}),
"current_page_uuid": profile_manifest.get("Pages", {}).get("Current"),
"default_page_uuid": profile_manifest.get("Pages", {}).get("Default"),
},
"page": page_ref.to_dict(),
"layout": {"columns": keypad_cols, "rows": keypad_rows},
"layouts": layouts,
"buttons": buttons,
"raw_manifest": page_manifest,
}
def write_page(
self,
*,
profile_name: str | None = None,
profile_id: str | None = None,
page_index: int | None = None,
directory_id: str | None = None,
page_name: str | None = None,
buttons: list[dict[str, Any]] | None = None,
clear_existing: bool = True,
create_new: bool = False,
make_current: bool = False,
auto_quit_app: bool = False,
) -> dict[str, Any]:
"""Create a page or rewrite an existing page manifest."""
app_stop_report: dict[str, Any] | None = None
if is_stream_deck_app_running():
if not auto_quit_app:
raise StreamDeckAppRunningError(
"The Elgato Stream Deck app is running and will overwrite this "
"edit on quit. Retry with auto_quit_app=True to quit it first, "
"then call streamdeck_restart_app once your edits are complete "
"to apply the changes."
)
app_stop_report = stop_stream_deck_app()
stop_failed = not app_stop_report.get("stopped", False)
still_running = is_stream_deck_app_running()
if stop_failed or still_running:
reason = app_stop_report.get("reason", "")
detail = f" Reason: {reason}." if reason else ""
raise StreamDeckAppRunningError(
f"The Elgato Stream Deck app could not be stopped.{detail} Aborting "
"page write because the running app may overwrite these edits on quit."
)
profile_dir, profile_manifest = self._resolve_profile(
profile_name=profile_name, profile_id=profile_id
)
buttons = buttons or []
version = str(profile_manifest.get("Version", "2.0"))
page_uuid: str | None
if create_new:
page_uuid = str(uuid.uuid4())
directory_name = (
page_uuid.upper() if version.startswith("3") else self._generate_directory_id()
)
page_dir = profile_dir / "Profiles" / directory_name
page_dir.mkdir(parents=True, exist_ok=False)
(page_dir / "Images").mkdir(exist_ok=True)
page_manifest = copy.deepcopy(DEFAULT_PAGE_MANIFEST)
else:
page_ref = self._resolve_page_ref(
profile_dir,
profile_manifest,
page_index=page_index,
directory_id=directory_id,
)
page_uuid = page_ref.page_uuid
page_dir = page_ref.directory_path
page_manifest = _load_json(page_ref.manifest_path)
if page_name is not None:
page_manifest["Name"] = page_name
# Group incoming buttons by the controller they target so a single write can
# update the Keypad and Encoder controllers together without touching the other.
buttons_by_controller: dict[str, list[dict[str, Any]]] = {}
for button in buttons:
controller_type = _normalize_controller(button.get("controller"))
buttons_by_controller.setdefault(controller_type, []).append(button)
# When clear_existing is requested but no buttons were supplied, default to
# targeting the Keypad controller so that the caller can still clear a page
# by writing an empty button list (restores pre-multi-controller behaviour).
if clear_existing and not buttons_by_controller:
buttons_by_controller[KEYPAD] = []
layouts_out: dict[str, dict[str, int]] = {}
# If any encoder button will land on the bundled streamdeck-mcp dial plugin,
# make sure the plugin bundle is actually installed in the Elgato Plugins dir.
# The app just quit (or was already stopped) so now is the right window for
# a filesystem install that the app will pick up on relaunch.
plugin_install_report: dict[str, Any] | None = None
if self._any_button_needs_mcp_plugin(buttons_by_controller):
plugin_install_report = ensure_mcp_plugin_installed()
for controller_type, ctl_buttons in buttons_by_controller.items():
cols, rows = self._resolve_layout(profile_manifest, page_manifest, controller_type)
if cols <= 0 or rows <= 0:
raise ProfileValidationError(
f"Device model does not expose a '{controller_type}' controller."
)
controller = _ensure_controller(page_manifest, controller_type)
existing = {} if clear_existing else copy.deepcopy(controller.get("Actions") or {})
for button in ctl_buttons:
position = self._resolve_button_position(button, columns=cols, rows=rows)
existing[position] = self._materialize_action(
button, page_dir, controller_type=controller_type
)
controller["Actions"] = existing or None
layouts_out[controller_type.lower()] = {"columns": cols, "rows": rows}
# New pages always carry a Keypad controller slot so the Elgato app can render them.
if create_new:
_ensure_controller(page_manifest, KEYPAD)
primary_cols, primary_rows = self._resolve_layout(profile_manifest, page_manifest, KEYPAD)
total_button_count = _total_action_count(page_manifest)
if create_new:
pages_section = profile_manifest.setdefault("Pages", {})
pages_section.setdefault("Pages", [])
pages_section["Pages"].append(page_uuid)
pages_section["Current"] = (
page_uuid
if make_current or not pages_section.get("Current")
else pages_section["Current"]
)
if not pages_section.get("Default"):
pages_section["Default"] = page_uuid
elif make_current:
if not page_uuid:
raise ProfileValidationError(
"Cannot mark an existing ProfilesV2 page current without a stable page UUID."
)
profile_manifest.setdefault("Pages", {})["Current"] = page_uuid
_write_json_atomic(page_dir / "manifest.json", page_manifest)
if create_new or make_current:
_write_json_atomic(profile_dir / "manifest.json", profile_manifest)
return {
"created": create_new,
"profiles_root": self.profiles_dir.name,
"profile_id": profile_dir.stem,
"page_index": None if create_new else page_index,
"directory_id": page_dir.name,
"page_uuid": page_uuid,
"layout": {"columns": primary_cols, "rows": primary_rows},
"layouts": layouts_out,
"button_count": total_button_count,
"page_name": page_manifest.get("Name", ""),
"manifest_path": str(page_dir / "manifest.json"),
"app_quit": app_stop_report,
"mcp_plugin_install": plugin_install_report,
}
def create_icon(
self,
*,
text: str | None = None,
icon: str | None = None,
icon_color: str | None = None,
icon_scale: float = 1.0,
bg_color: str = DEFAULT_BG_COLOR,
text_color: str = DEFAULT_TEXT_COLOR,
font_size: int = 18,
filename: str | None = None,
shape: str = "button",
transparent_bg: bool = False,
) -> dict[str, Any]:
"""Generate a PNG icon.
``shape`` controls the output canvas:
- ``"button"`` (default): 72x72 — keypad keys and encoder dial faces.
- ``"touchstrip"``: 200x100 — the per-segment strip background above a
Stream Deck + / + XL dial, set via ``strip_background_path`` on
``streamdeck_write_page``.
``transparent_bg=True`` produces an RGBA PNG with a transparent canvas
(``bg_color`` is ignored). Use this for dial Icons that overlay a
touchstrip background so the glyph composes cleanly like Elgato's own
transparent icons. Keypad faces and touchstrip backgrounds usually want
the solid-background default.
Provide exactly one of:
- ``icon``: a Material Design Icons name (e.g. ``mdi:cpu-64-bit``) rendered in
``icon_color`` over ``bg_color``. Labels should be set via the button's
``title`` field on ``streamdeck_write_page`` — Elgato renders titles over the
image, so baking text into the PNG would produce double text.
- ``text``: centered text rendered in ``text_color`` over ``bg_color``.
Icon names accept ``mdi:cpu``, ``mdi-cpu``, or bare ``cpu``; aliases are
honored. On an unknown name the error message lists close-match suggestions.
"""
if not HAS_PILLOW:
raise ProfileManagerError("Pillow is required for icon generation.")
if not text and not icon:
raise ProfileValidationError("create_icon requires 'text' or 'icon'.")
if text and icon:
raise ProfileValidationError(
"create_icon accepts either 'text' or 'icon', not both. "
"Use the button's 'title' field on streamdeck_write_page for labels."
)
if not 0.1 <= icon_scale <= 1.0:
raise ProfileValidationError("icon_scale must be between 0.1 and 1.0.")
if shape not in ICON_SHAPES:
raise ProfileValidationError(
f"shape must be one of {sorted(ICON_SHAPES)}, got '{shape}'."
)
canvas_size = ICON_SHAPES[shape]
if not transparent_bg:
bg_color = _ensure_hex_color(bg_color, field_name="bg_color")
text_color = _ensure_hex_color(text_color, field_name="text_color")
resolved_icon_color = _ensure_hex_color(
icon_color or text_color, field_name="icon_color"
)
self.generated_icons_dir.mkdir(parents=True, exist_ok=True)
canonical_icon_name: str | None = None
glyph: str | None = None
if icon:
from mdi_icons import font_path as _mdi_font_path
from mdi_icons import resolve as _resolve_mdi
canonical_icon_name, glyph = _resolve_mdi(icon)
stem_source = filename or canonical_icon_name or text or "streamdeck-icon"
stem = _slugify(stem_source)
if shape != "button" and filename is None:
stem = f"{stem}-{shape}"
icon_path = self.generated_icons_dir / f"{stem}.png"
if transparent_bg:
image = Image.new("RGBA", canvas_size, (0, 0, 0, 0))
else:
image = Image.new("RGB", canvas_size, bg_color)
draw = ImageDraw.Draw(image)
if glyph is not None:
short_side = min(canvas_size)
target_glyph_px = max(8, int(short_side * icon_scale))
from importlib.resources import as_file as _as_file
try:
with _as_file(_mdi_font_path()) as font_file:
# MDI glyphs have built-in em-square padding, so a font set to N
# px renders a visual glyph noticeably smaller than N. Measure the
# actual bbox at a reference size, then pick the real font size
# that makes the bbox fill `icon_scale * short_side` pixels.
ref_size = 200
ref_font = ImageFont.truetype(str(font_file), ref_size)
ref_bbox = draw.textbbox((0, 0), glyph, font=ref_font)
ref_w = max(1, ref_bbox[2] - ref_bbox[0])
ref_h = max(1, ref_bbox[3] - ref_bbox[1])
scale = target_glyph_px / max(ref_w, ref_h)
glyph_font_size = max(8, int(round(ref_size * scale)))
glyph_font = ImageFont.truetype(str(font_file), glyph_font_size)
except OSError as exc:
raise ProfileManagerError(
f"Could not load bundled MDI font: {exc}"
) from exc
bbox = draw.textbbox((0, 0), glyph, font=glyph_font)
gw = bbox[2] - bbox[0]
gh = bbox[3] - bbox[1]
gx = (canvas_size[0] - gw) / 2 - bbox[0]
gy = (canvas_size[1] - gh) / 2 - bbox[1]
draw.text((gx, gy), glyph, font=glyph_font, fill=resolved_icon_color)
else:
label_font = _resolve_font(font_size)
bbox = draw.multiline_textbbox((0, 0), text or "", font=label_font, align="center")
tw = bbox[2] - bbox[0]
th = bbox[3] - bbox[1]
tx = (canvas_size[0] - tw) / 2
ty = (canvas_size[1] - th) / 2
draw.multiline_text(
(tx, ty), text or "", font=label_font, fill=text_color, align="center"
)
image.save(icon_path, format="PNG")
result: dict[str, Any] = {
"path": str(icon_path),
"size": {"width": canvas_size[0], "height": canvas_size[1]},
"shape": shape,
"transparent_bg": transparent_bg,
}
if canonical_icon_name:
result["icon"] = f"mdi:{canonical_icon_name}"
return result
def create_action(
self,
*,
name: str,
command: str,
working_directory: str | None = None,
filename: str | None = None,
) -> dict[str, Any]:
"""Create a shell script and return an Open action block for it."""
if not command.strip():
raise ProfileValidationError("command cannot be empty.")
if sys.platform == "win32":
raise ProfileValidationError(
"streamdeck_create_action is currently only supported on POSIX systems."
)
self.scripts_dir.mkdir(parents=True, exist_ok=True)
stem = _slugify(filename or name)
script_path = self.scripts_dir / f"{stem}.sh"
lines = ["#!/bin/bash", "set -e"]
if working_directory:
lines.append(f"cd {shlex.quote(working_directory)}")
lines.append(command)
script_path.write_text("\n".join(lines) + "\n")
script_path.chmod(0o755)
action = self._build_open_action(path=script_path, title=name)
return {
"script_path": str(script_path),
"action": action,
}
def restart_app(self) -> dict[str, Any]:
"""Restart the Stream Deck desktop app on macOS."""
if sys.platform != "darwin":
raise ProfileManagerError(
"streamdeck_restart_app is currently only supported on macOS."
)
app_path = _resolve_app_path()
if not app_path.exists():
raise ProfileManagerError(
f"Stream Deck app not found at {app_path}. "
f"Set {STREAM_DECK_APP_PATH_ENV} to override the default install path."
)
stop_report = stop_stream_deck_app()
# `open -a <name>` relies on LaunchServices name lookup, which returns error
# -600 on some systems even when the bundle is present. Launching by explicit
# path bypasses that lookup.
result = subprocess.run(
["open", str(app_path)],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
message = result.stderr.strip() or result.stdout.strip()
raise ProfileManagerError(
f"Failed to relaunch Stream Deck ({app_path}): {message or 'unknown error'}"
)
return {
"restarted": True,
"app_path": str(app_path),
"stop": stop_report,
}
def _resolve_profile(
self,
*,
profile_name: str | None,
profile_id: str | None,
) -> tuple[Path, dict[str, Any]]:
if not self.profiles_dir.exists():
raise ProfileNotFoundError(f"Profiles directory does not exist: {self.profiles_dir}")
matches: list[tuple[Path, dict[str, Any]]] = []
for profile_dir in sorted(self.profiles_dir.glob("*.sdProfile")):
manifest = _load_json(profile_dir / "manifest.json")
if profile_id and profile_dir.stem.lower() == profile_id.lower():
return profile_dir, manifest
if profile_name and str(manifest.get("Name", "")).lower() == profile_name.lower():
matches.append((profile_dir, manifest))
if len(matches) == 1:
return matches[0]
if len(matches) > 1:
raise ProfileValidationError(
f"Multiple profiles match '{profile_name}'. Use profile_id instead."
)
requested = profile_id or profile_name or "<unspecified>"
raise ProfileNotFoundError(f"Profile not found: {requested}")
def _page_refs(self, profile_dir: Path, profile_manifest: dict[str, Any]) -> list[PageRef]:
profiles_path = profile_dir / "Profiles"
if not profiles_path.exists():
return []
version = str(profile_manifest.get("Version", "2.0"))
if version.startswith("3"):
return self._page_refs_v3(profiles_path, profile_manifest)
return self._page_refs_v2(profiles_path, profile_manifest)
def _page_refs_v3(self, profiles_path: Path, profile_manifest: dict[str, Any]) -> list[PageRef]:
page_refs: list[PageRef] = []
ordered_page_ids: list[tuple[str, bool]] = []
pages = profile_manifest.get("Pages", {})
default_uuid = pages.get("Default")
if default_uuid:
ordered_page_ids.append((default_uuid, True))
for page_uuid in pages.get("Pages", []):
ordered_page_ids.append((page_uuid, False))
used: set[str] = set()
for page_index, (page_uuid, is_default) in enumerate(ordered_page_ids):
directory_id = str(page_uuid).upper()
manifest_path = profiles_path / directory_id / "manifest.json"
if not manifest_path.exists():
continue
used.add(directory_id)
page_refs.append(
self._build_page_ref(
page_index=page_index,
directory_id=directory_id,
page_uuid=str(page_uuid).lower(),
manifest_path=manifest_path,
version=str(profile_manifest.get("Version", "unknown")),
mapping="page-uuid",
is_default=is_default,
is_current=_normalize_uuid(str(page_uuid))
== _normalize_uuid(str(pages.get("Current", ""))),
)
)
for manifest_path in sorted(profiles_path.glob("*/manifest.json")):