streonor-mcp 0.8.2__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.
@@ -0,0 +1 @@
1
+ """STREONOR MCP."""
streonor_mcp/app.py ADDED
@@ -0,0 +1,76 @@
1
+ """Opt-in Windows app lifecycle around guarded profile edits."""
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import time
6
+ import sys
7
+ import logging
8
+ from . import profiles
9
+
10
+
11
+ def _request_relaunch(exe):
12
+ # Launch through the desktop shell so the app outlives the MCP process.
13
+ launch = subprocess.Popen(
14
+ ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command',
15
+ "$ErrorActionPreference = 'Stop'; "
16
+ "$shell = New-Object -ComObject Shell.Application; $handle = 0; "
17
+ "$desktop = $shell.Windows().FindWindowSW(0, 0, 8, [ref]$handle, 1); "
18
+ "if ($null -eq $desktop) { throw 'Missing desktop shell' }; "
19
+ "$exe = $env:STREONOR_RELAUNCH_EXE; "
20
+ "$desktop.Document.Application.ShellExecute($exe, '', (Split-Path -LiteralPath $exe), 'open', 1); "
21
+ "for ($i = 0; $i -lt 30; $i++) { "
22
+ "if (Get-Process Streonor -ErrorAction SilentlyContinue) { exit 0 }; "
23
+ "Start-Sleep -Milliseconds 100 }; throw 'STREONOR did not start'"],
24
+ env={**os.environ, 'STREONOR_RELAUNCH_EXE': str(exe)},
25
+ stdout=subprocess.DEVNULL,
26
+ stderr=subprocess.DEVNULL,
27
+ )
28
+ if launch.wait(timeout=5) != 0:
29
+ raise OSError('Windows could not start STREONOR')
30
+
31
+
32
+ def edit_with_restart(edit, manage_app=False, force_close=False):
33
+ if force_close and not manage_app:
34
+ raise ValueError('force_close requires manage_app=True')
35
+ if manage_app and sys.platform != 'win32':
36
+ raise RuntimeError('Automatic app restart is only verified on Windows; close the vendor app manually and use manage_app=False')
37
+ if not manage_app or not profiles.vendor_running():
38
+ return edit()
39
+ exe = Path(os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')) / 'Streonor' / 'Streonor.exe'
40
+ if not exe.is_file():
41
+ raise RuntimeError('Cannot find STREONOR executable to reopen; no edit attempted')
42
+ result = None
43
+ failure = None
44
+ try:
45
+ # Fast restart is opt-in because it can discard changes held only in memory.
46
+ command = ['taskkill', '/IM', 'Streonor.exe']
47
+ if force_close or os.environ.get('STREONOR_FAST_RESTART') == '1':
48
+ command.append('/F')
49
+ subprocess.run(command, capture_output=True, timeout=10,
50
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0), check=True)
51
+ for _ in range(20):
52
+ if not profiles.vendor_running():
53
+ break
54
+ time.sleep(0.25)
55
+ else:
56
+ raise RuntimeError('STREONOR did not exit; no edit attempted')
57
+ # The existing hash check catches changes saved by the app during exit.
58
+ result = edit()
59
+ return result
60
+ except Exception as error:
61
+ failure = error
62
+ raise
63
+ finally:
64
+ try:
65
+ if not profiles.vendor_running():
66
+ _request_relaunch(exe)
67
+ if result is not None:
68
+ result['app_relaunch_requested'] = True
69
+ except (OSError, subprocess.SubprocessError) as error:
70
+ logging.getLogger(__name__).error('Could not relaunch STREONOR: %s', error)
71
+ if result is not None:
72
+ result['app_relaunch_requested'] = False
73
+ result['relaunch_error'] = str(error)
74
+ elif failure is not None:
75
+ failure.add_note(f'Could not relaunch STREONOR: {error}')
76
+
@@ -0,0 +1,67 @@
1
+ """Construct native action slots from installed Toolbox metadata, without user templates."""
2
+ import copy
3
+ import json
4
+ import uuid
5
+
6
+
7
+ def build_action(name, settings=None, controller='Keypad', in_flow=False, hotkey=''):
8
+ from .profiles import list_installed_actions
9
+ if not isinstance(name, str) or not name.strip():
10
+ raise ValueError('Provide an installed action name or UUID')
11
+ query = name.strip().casefold()
12
+ installed = list_installed_actions()
13
+ if query in ('hotkeyswitch', 'com.hotspot.streamdock.system.hotkeyswitch') and not any(
14
+ action['uuid'] == 'com.hotspot.streamdock.system.hotkeySwitch' for action in installed
15
+ ):
16
+ installed.append({'uuid': 'com.hotspot.streamdock.system.hotkeySwitch', 'name': 'HotkeySwitch',
17
+ 'plugin': 'System', 'controllers': ['Keypad'],
18
+ 'states': [{'Image': 'Images/btn_custom_trigger_hotkeySwitch1'},
19
+ {'Image': 'Images/btn_custom_trigger_hotkeySwitch2'}]})
20
+ matches = [a for a in installed if query == a['uuid'].casefold()]
21
+ if not matches:
22
+ matches = [a for a in installed if query in ((a['name'] or '').casefold(), ((a['plugin'] or '') + '/' + (a['name'] or '')).casefold())]
23
+ if len(matches) != 1:
24
+ raise ValueError('Action not found or ambiguous. Use an exact UUID or plugin/name from list_available_actions')
25
+ metadata = matches[0]
26
+ if metadata['uuid'] == 'com.hotspot.streamdock.profile.openchild':
27
+ raise ValueError('Use the STREONOR app to create folders and their linked pages')
28
+ if metadata.get('only_in_flows') and not in_flow:
29
+ raise ValueError('This Toolbox item can only be added inside a flow')
30
+ if in_flow and metadata.get('supported_in_flows') is False:
31
+ raise ValueError('This Toolbox item declares that it does not support flows')
32
+ if controller not in ('Keypad', 'Knob', 'SecondaryScreen', 'Information'):
33
+ raise ValueError('Controller must be Keypad, Knob, SecondaryScreen or Information')
34
+ if metadata.get('controllers') and controller not in metadata['controllers']:
35
+ raise ValueError('Action does not declare support for this controller')
36
+ defaults = copy.deepcopy(metadata.get('default_settings') or {})
37
+ if metadata['uuid'] == 'com.hotspot.streamdock.system.website':
38
+ defaults = {'browser': '', 'openInBrowser': True, 'path': ''}
39
+ elif metadata['uuid'] in ('com.hotspot.streamdock.system.hotkey', 'com.hotspot.streamdock.system.hotkeySwitch'):
40
+ key = {'KeyCmd': False, 'KeyCtrl': False, 'KeyModifiers': 65536, 'KeyOption': False, 'KeyShift': False, 'NativeCode': -1, 'QTKeyCode': -1, 'RKeyCmd': False, 'RKeyCtrl': False, 'RKeyOption': False, 'RKeyShift': False, 'VKeyCode': -1}
41
+ defaults = {'Coalesce': True, 'Hotkeys': [copy.deepcopy(key) for _ in range(3)]}
42
+ if metadata['uuid'].endswith('hotkeySwitch'):
43
+ defaults['Index'] = 0
44
+ if settings is not None:
45
+ if not isinstance(settings, dict):
46
+ raise ValueError('Action settings must be an object')
47
+ for key, value in settings.items():
48
+ if key in defaults and type(defaults[key]) is not type(value):
49
+ raise ValueError('Settings must match declared default JSON types')
50
+ defaults[key] = value
51
+ if hotkey:
52
+ if metadata['uuid'] not in ('com.hotspot.streamdock.system.hotkey', 'com.hotspot.streamdock.system.hotkeySwitch') or controller != 'Keypad':
53
+ raise ValueError('A direct hotkey requires a native Hotkey keypad action')
54
+ if settings is not None and 'Hotkeys' in settings:
55
+ raise ValueError('Supply a hotkey chord or native Hotkeys settings, not both')
56
+ from .hotkeys import settings_for_chord
57
+ defaults = settings_for_chord(defaults, hotkey)
58
+ if metadata['uuid'].endswith('hotkeySwitch'):
59
+ defaults['Hotkeys'][1] = copy.deepcopy(defaults['Hotkeys'][0])
60
+ json.dumps(defaults, allow_nan=False)
61
+ states = copy.deepcopy(metadata.get('states') or [{'Image': ''}])
62
+ return {'ActionID': str(uuid.uuid4()), 'Controller': '' if in_flow else controller,
63
+ 'Name': metadata['name'], 'Settings': defaults, 'State': 0,
64
+ 'States': states, 'UUID': metadata['uuid']}, {
65
+ 'uuid': metadata['uuid'], 'name': metadata['name'],
66
+ 'execution_verified': False,
67
+ 'configuration_note': 'Created from installed metadata. Required plugin-specific settings and runtime connections must be verified in the native app.'}
@@ -0,0 +1,40 @@
1
+ """One registry for community device specs; generic profile tooling lives elsewhere."""
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class DeviceSpec:
7
+ id: str
8
+ name: str
9
+ software_ids: tuple[str, ...]
10
+ key_count: int | None = None
11
+ dial_count: int | None = None
12
+ boot_logo_size: tuple[int, int] | None = None
13
+ boot_logo_format: str | None = None
14
+ boot_logo_upload: str | None = None
15
+ supported: bool = False
16
+
17
+
18
+ # Add new hardware here. Leave unknown values as None/'unknown'; never infer a write protocol.
19
+ DEVICES = (
20
+ DeviceSpec('streonor-s6-mini', 'STREONOR S6 Mini', ('StreonorS6',), 6, 3, (320, 240), 'unknown', None, True),
21
+ DeviceSpec('streonor-s10-pro', 'STREONOR S10 Pro', ('StreonorS10',), supported=False),
22
+ DeviceSpec('streonor-s15-standard', 'STREONOR S15 Standard', ('StreonorS15',), supported=False),
23
+ DeviceSpec('streonor-s32-max', 'STREONOR S32 Max', ('StreonorS32',), supported=False),
24
+ )
25
+
26
+
27
+ def get_device(device_id):
28
+ for spec in DEVICES:
29
+ if device_id == spec.id or device_id in spec.software_ids:
30
+ return spec
31
+ raise ValueError(f'Unsupported device: {device_id}')
32
+
33
+
34
+ def describe(device_id):
35
+ spec = get_device(device_id)
36
+ return {'id': spec.id, 'name': spec.name, 'software_ids': list(spec.software_ids),
37
+ 'keys': spec.key_count, 'dials': spec.dial_count,
38
+ 'boot_logo_size': list(spec.boot_logo_size) if spec.boot_logo_size else None,
39
+ 'boot_logo_format': spec.boot_logo_format, 'boot_logo_upload': spec.boot_logo_upload,
40
+ 'supported': spec.supported}
streonor_mcp/flows.py ADDED
@@ -0,0 +1,56 @@
1
+ """Native sequential Multi Actions, based on observed vendor profile structure."""
2
+ import copy
3
+ import json
4
+ import uuid
5
+
6
+
7
+ def build_flow(actions, coordinate, steps, title):
8
+ if not isinstance(steps, list) or not 1 <= len(steps) <= 32:
9
+ raise ValueError('Provide 1 to 32 flow steps')
10
+ if not isinstance(title, str) or not title.strip() or len(title) > 80:
11
+ raise ValueError('Provide a flow title of 1 to 80 characters')
12
+ children = []
13
+ for step in steps:
14
+ if not isinstance(step, dict) or set(step) - {'source_coordinate', 'action_name', 'settings', 'delay_ms', 'hotkey'}:
15
+ raise ValueError('Steps accept source_coordinate or action_name, settings, delay_ms and hotkey')
16
+ if bool(step.get('source_coordinate')) == bool(step.get('action_name')):
17
+ raise ValueError('Choose exactly one source_coordinate or action_name for each step')
18
+ if step.get('action_name'):
19
+ from .catalog import build_action
20
+ source, _ = build_action(step['action_name'], step.get('settings'), in_flow=True)
21
+ else:
22
+ source = actions.get(step.get('source_coordinate'))
23
+ if not isinstance(source, dict) or 'Actions' in source or not isinstance(source.get('Settings'), dict) or not isinstance(source.get('States'), list):
24
+ raise ValueError('Each source must be an existing single action on this page')
25
+ overrides = step.get('settings', {})
26
+ delay = step.get('delay_ms', 0)
27
+ if not isinstance(overrides, dict) or type(delay) is not int or not 0 <= delay <= 60000:
28
+ raise ValueError('Settings must be an object; delay_ms must be 0 to 60000')
29
+ action = copy.deepcopy(source)
30
+ for key, value in ({} if step.get('action_name') else overrides).items():
31
+ if key not in action['Settings'] or type(value) is not type(action['Settings'][key]):
32
+ raise ValueError('Flow setting overrides must match existing setting names and JSON types')
33
+ json.dumps(value, allow_nan=False)
34
+ action['Settings'][key] = value
35
+ if 'hotkey' in step:
36
+ if action.get('UUID') != 'com.hotspot.streamdock.system.hotkey' or 'Hotkeys' in overrides:
37
+ raise ValueError('A hotkey step requires a native Hotkey source and no Hotkeys override')
38
+ from .hotkeys import settings_for_chord
39
+ action['Settings'] = settings_for_chord(action['Settings'], step['hotkey'])
40
+ if action.get('UUID') == 'com.hotspot.streamdock.system.openApps':
41
+ selected = action['Settings'].get('appId')
42
+ apps = action['Settings'].get('applications', [])
43
+ if type(selected) is not int or not 0 <= selected < len(apps):
44
+ raise ValueError('Selected application is outside the source action application list')
45
+ action['ActionID'] = str(uuid.uuid4())
46
+ action['Controller'] = ''
47
+ action['Settings']['delay'] = delay
48
+ children.append(action)
49
+ states = copy.deepcopy(actions.get(coordinate, {}).get('States', [{'Image': ''}]))
50
+ if not states or not isinstance(states[0], dict):
51
+ states = [{'Image': ''}]
52
+ states[0]['Title'] = title
53
+ return {'ActionID': str(uuid.uuid4()), 'Actions': children,
54
+ 'Controller': actions.get(coordinate, {}).get('Controller', 'Keypad'),
55
+ 'Name': 'Multi Action', 'Settings': {'cycleDelay': 100, 'cycleMode': 0, 'cycleNumber': 1, 'enablingCycle': 0},
56
+ 'State': 0, 'States': states, 'UUID': 'com.hotspot.streamdock.multiactions.routine'}
@@ -0,0 +1,53 @@
1
+ """Keypad chords using the observed native STREONOR Hotkeys record format."""
2
+ import copy
3
+ import re
4
+
5
+
6
+ def settings_for_chord(template, chord):
7
+ if not isinstance(chord, str) or len(chord) > 80:
8
+ raise ValueError('Provide one key combination such as Ctrl+Shift+P')
9
+ parts = [p.strip().casefold() for p in chord.split('+')]
10
+ if not parts or any(not p for p in parts):
11
+ raise ValueError('Invalid hotkey combination')
12
+ aliases = {'control': 'ctrl', 'option': 'alt', 'cmd': 'win', 'super': 'win'}
13
+ parts = [aliases.get(p, p) for p in parts]
14
+ modifiers = set(parts[:-1])
15
+ if len(modifiers) != len(parts)-1 or modifiers - {'ctrl', 'alt', 'shift', 'win'}:
16
+ raise ValueError('Use modifiers followed by exactly one key')
17
+ key = parts[-1]
18
+ named = {'enter': 13, 'tab': 9, 'escape': 27, 'esc': 27, 'space': 32, 'backspace': 8, 'delete': 46, 'insert': 45, 'home': 36, 'end': 35, 'pageup': 33, 'pagedown': 34, 'left': 37, 'up': 38, 'right': 39, 'down': 40}
19
+ if len(key) == 1 and key.isascii() and key.isalnum():
20
+ code = ord(key.upper())
21
+ elif re.fullmatch(r'f(?:[1-9]|1[0-9]|2[0-4])', key):
22
+ code = 111 + int(key[1:])
23
+ elif key in named:
24
+ code = named[key]
25
+ else:
26
+ raise ValueError('Unsupported hotkey. Use a letter, digit, F1-F24 or a named navigation key')
27
+ entries = template.get('Hotkeys')
28
+ if not isinstance(entries, list) or not entries or not isinstance(entries[0], dict):
29
+ raise ValueError('Hotkey source has no native Hotkeys template')
30
+ result = copy.deepcopy(template)
31
+ first = copy.deepcopy(entries[0])
32
+ required = {'KeyCtrl', 'KeyOption', 'KeyShift', 'KeyCmd', 'VKeyCode'}
33
+ if not required.issubset(first):
34
+ raise ValueError('Unrecognized native hotkey template')
35
+ for field, modifier in [('KeyCtrl', 'ctrl'), ('KeyOption', 'alt'), ('KeyShift', 'shift'), ('KeyCmd', 'win')]:
36
+ first[field] = modifier in modifiers
37
+ first['VKeyCode'] = code
38
+ for field in ('RKeyCtrl', 'RKeyOption', 'RKeyShift', 'RKeyCmd'):
39
+ if field in first:
40
+ first[field] = False
41
+ for field in ('NativeCode', 'QTKeyCode'):
42
+ if field in first:
43
+ first[field] = -1
44
+ result['Hotkeys'] = [first]
45
+ # Native files retain unused slots. Clear them instead of copying dial bindings.
46
+ for entry in entries[1:]:
47
+ unused = copy.deepcopy(first)
48
+ unused['VKeyCode'] = -1
49
+ for field in required - {'VKeyCode'}:
50
+ unused[field] = False
51
+ result['Hotkeys'].append(unused)
52
+ result['Coalesce'] = True
53
+ return result
streonor_mcp/icons.py ADDED
@@ -0,0 +1,87 @@
1
+ """Local icon matching and a deterministic fallback with no network requests."""
2
+ import io
3
+ from pathlib import Path
4
+ import re
5
+ from urllib.parse import urlsplit
6
+ from PIL import Image, ImageDraw, ImageFont
7
+
8
+
9
+ def label_for_action(action):
10
+ settings = action.get('Settings', {})
11
+ if action.get('Name') == 'Multi Action':
12
+ return action.get('States', [{}])[0].get('Title') or 'Flow'
13
+ apps = settings.get('applications', [])
14
+ index = settings.get('appId')
15
+ if type(index) is int and 0 <= index < len(apps):
16
+ return apps[index].get('name') or action.get('Name', 'Key')
17
+ value = settings.get('path', '')
18
+ if isinstance(value, str) and value:
19
+ host = urlsplit(value).hostname
20
+ if host:
21
+ return host.removeprefix('www.').split('.')[0]
22
+ return Path(value).stem or 'Key'
23
+ return action.get('States', [{}])[0].get('Title') or action.get('Name', 'Key')
24
+
25
+
26
+ def resolve(query, preferred_path=''):
27
+ from . import profiles
28
+ if not isinstance(query, str) or not query.strip() or len(query) > 100:
29
+ raise ValueError('Icon query must be 1 to 100 characters')
30
+ key = re.sub(r'[^a-z0-9]', '', query.casefold())
31
+ if not key and not any(c.isalnum() for c in query):
32
+ raise ValueError('Icon query must include letters or numbers')
33
+ aliases = {'visualstudiocode': 'visualstudiocode', 'vscode': 'visualstudiocode', 'windows terminal': 'windowsterminal'}
34
+ key = aliases.get(query.casefold(), key) or 'key'
35
+ matches = profiles.find_icons(key, 100)
36
+ matches.sort(key=lambda x: (re.sub(r'[^a-z0-9]', '', x['name'].casefold()) != key, str(x['path']).casefold()))
37
+ candidates = ([{'path': preferred_path, 'name': query}] if preferred_path else []) + [m for m in matches if re.sub(r'[^a-z0-9]', '', m['name'].casefold()) == key]
38
+ for match in candidates:
39
+ try:
40
+ data = profiles.normalize_icon(profiles.read_icon(match['path']), '#000000')
41
+ # Dark monochrome SVG marks need contrast on a black key background.
42
+ if Path(match['path']).suffix.lower() == '.svg':
43
+ with Image.open(io.BytesIO(data)) as image:
44
+ rgb = image.convert('RGB')
45
+ if max(rgb.getextrema()[i][1] for i in range(3)) < 96:
46
+ source = profiles.read_icon(match['path'])
47
+ with Image.open(io.BytesIO(source)) as transparent:
48
+ mark = Image.new('RGBA', transparent.size, 'white')
49
+ mark.putalpha(transparent.convert('RGBA').getchannel('A'))
50
+ buffer = io.BytesIO()
51
+ mark.save(buffer, format='PNG')
52
+ data = profiles.normalize_icon(buffer.getvalue(), '#000000')
53
+ return data, {'origin': 'installed', 'query': query, 'source_path': match['path'], 'sha256': profiles.fingerprint(data)}
54
+ except (OSError, ValueError, Image.DecompressionBombError):
55
+ if preferred_path and match['path'] == preferred_path:
56
+ raise
57
+ words = re.findall(r'[A-Za-z0-9]+', query) or ['Key']
58
+ text = (''.join(w[0] for w in words[:3]) if len(words) > 1 else words[0][:3]).upper()
59
+ image = Image.new('RGBA', (1254, 1254), '#000000')
60
+ draw = ImageDraw.Draw(image)
61
+ font = ImageFont.load_default(size=360)
62
+ box = draw.textbbox((0, 0), text, font=font)
63
+ draw.text(((1254-box[2]+box[0])//2, (1254-box[3]+box[1])//2-box[1]), text, font=font, fill='white')
64
+ buffer = io.BytesIO()
65
+ image.save(buffer, format='PNG')
66
+ data = buffer.getvalue()
67
+ return data, {'origin': 'generated_label', 'query': query, 'sha256': profiles.fingerprint(data)}
68
+
69
+
70
+ def for_action(action, folder, query='', image_path=''):
71
+ if image_path:
72
+ data, info = resolve(query or label_for_action(action), image_path)
73
+ info['origin'] = 'provided'
74
+ return data, info
75
+ states = action.get('States') or [{}]
76
+ current = states[0].get('Image', '')
77
+ if not query and current and not current.startswith('Images/btn_'):
78
+ return None, {'origin': 'preserved', 'image': current}
79
+ settings = action.get('Settings', {})
80
+ apps = settings.get('applications', [])
81
+ index = settings.get('appId')
82
+ preferred = ''
83
+ if type(index) is int and 0 <= index < len(apps):
84
+ candidate = apps[index].get('image', '')
85
+ if candidate and Path(candidate).is_file():
86
+ preferred = candidate
87
+ return resolve(query or label_for_action(action), preferred)
streonor_mcp/layout.py ADDED
@@ -0,0 +1,136 @@
1
+ """Plan several page changes together before asking STREONOR to import them."""
2
+ import json
3
+ import re
4
+ import uuid
5
+
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+ from . import live, profiles, scenes
9
+ from .catalog import build_action
10
+ from .flows import build_flow
11
+ from .icons import for_action
12
+
13
+
14
+ class ControlEdit(BaseModel):
15
+ model_config = ConfigDict(extra='forbid')
16
+
17
+ action_name: str = ''
18
+ settings: dict | None = None
19
+ controller: str = ''
20
+ hotkey: str = ''
21
+ flow_steps: list[dict] | None = None
22
+ flow_title: str = ''
23
+ state_index: int = 0
24
+ image_path: str = ''
25
+ icon_query: str = ''
26
+ auto_icon: bool | None = None
27
+
28
+
29
+ class PageEdit(BaseModel):
30
+ model_config = ConfigDict(extra='forbid')
31
+
32
+ page: str = ''
33
+ replace: bool = False
34
+ controls: dict[str, ControlEdit | None]
35
+
36
+
37
+ def _preview_action(action):
38
+ result = {key: value for key, value in action.items() if key != 'ActionID'}
39
+ if 'Actions' in result:
40
+ result['Actions'] = [_preview_action(child) for child in result['Actions']]
41
+ return result
42
+
43
+
44
+ def plan(profile, name, pages, root):
45
+ if not 1 <= len(pages) <= 16 or sum(len(p.controls) for p in pages) > 128:
46
+ raise ValueError('Provide 1 to 16 pages and at most 128 control edits')
47
+ root_doc, root_hash, order = live.scene_pages(profile, root)
48
+ name = scenes.validate_new_name(name, root)
49
+ edits, images, details = {}, {}, {}
50
+ image_bytes = 0
51
+ source_hashes = {profile: root_hash}
52
+ for update in pages:
53
+ page = update.page or profile
54
+ if page not in order or page in edits:
55
+ raise ValueError('Each page must be registered to the scene and appear once')
56
+ if not update.controls and not update.replace:
57
+ raise ValueError('Provide controls to edit or explicitly replace the page')
58
+ member = live.page_member(profile, page)
59
+ path = profiles.profile_path(profile, page, root)
60
+ if path != root.resolve() / profile / member:
61
+ raise ValueError('Live imports require a page stored directly in its scene')
62
+ doc, digest = (root_doc, root_hash) if page == profile else profiles.read_manifest(profile, page, root)
63
+ source_hashes[page] = digest
64
+ before = doc['Actions']
65
+ actions = {} if update.replace else dict(before)
66
+ changes = {}
67
+ for coordinate, control in update.controls.items():
68
+ if not re.fullmatch(r'(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2})', coordinate):
69
+ raise ValueError(f'Invalid coordinate: {coordinate}')
70
+ old = actions.get(coordinate)
71
+ if control is None:
72
+ if old is None:
73
+ raise ValueError(f'No control to remove at {coordinate}')
74
+ del actions[coordinate]
75
+ changes[coordinate] = {'operation': 'remove'}
76
+ continue
77
+ if control.flow_title and control.flow_steps is None:
78
+ raise ValueError(f'Provide flow_steps with flow_title at {coordinate}')
79
+ if control.flow_steps is not None:
80
+ if control.action_name or control.settings is not None or control.controller or control.hotkey:
81
+ raise ValueError(f'Use flow_steps and flow_title to define the flow at {coordinate}')
82
+ action = build_flow(before, coordinate, control.flow_steps, control.flow_title)
83
+ operation = 'replace' if coordinate in before else 'create'
84
+ elif control.action_name:
85
+ controller = control.controller or (old or {}).get('Controller') or 'Keypad'
86
+ action, _ = build_action(control.action_name, control.settings, controller, hotkey=control.hotkey)
87
+ operation = 'replace' if coordinate in before else 'create'
88
+ else:
89
+ if old is None or control.controller or control.hotkey:
90
+ raise ValueError(f'Choose an installed action to create or replace {coordinate}')
91
+ if control.settings is None and not (control.image_path or control.icon_query or control.auto_icon):
92
+ raise ValueError(f'Provide settings or an icon for {coordinate}')
93
+ action = dict(old)
94
+ settings = dict(old.get('Settings') or {})
95
+ for key, value in (control.settings or {}).items():
96
+ if key in settings and type(settings[key]) is not type(value):
97
+ raise ValueError(f'New value for {coordinate} {key} must match its existing JSON type')
98
+ settings[key] = value
99
+ if control.settings is not None:
100
+ action['Settings'] = settings
101
+ operation = 'edit'
102
+ change = {'operation': operation, 'action': (
103
+ dict(action) if operation == 'edit' else _preview_action(action)
104
+ )}
105
+ destination_changed = (operation == 'edit'
106
+ and any(key in (control.settings or {})
107
+ and old.get('Settings', {}).get(key) != control.settings[key]
108
+ for key in ('path', 'appId')))
109
+ if (control.image_path or control.icon_query or control.auto_icon is True
110
+ or control.auto_icon is not False and (operation != 'edit' or destination_changed)):
111
+ states = list(action.get('States') or [{}])
112
+ index = control.state_index
113
+ if not 0 <= index < len(states) or not isinstance(states[index], dict):
114
+ raise ValueError(f'No editable icon at state {index} on {coordinate}')
115
+ data, icon = for_action({**action, 'States': [states[index]]},
116
+ path.parent, control.icon_query, control.image_path)
117
+ change['icon'] = {**icon, 'state_index': index}
118
+ if data is not None:
119
+ image_bytes += len(data)
120
+ if image_bytes > live.MAX_ARCHIVE_BYTES:
121
+ raise ValueError('New icons exceed the live import size limit')
122
+ filename = uuid.uuid4().hex.upper() + '.png'
123
+ states[index] = {**states[index], 'Image': filename}
124
+ action['States'] = states
125
+ images[member.parent / 'Images' / filename] = data
126
+ elif control.state_index:
127
+ raise ValueError(f'Choose an icon when specifying a state at {coordinate}')
128
+ actions[coordinate] = action
129
+ changes[coordinate] = change
130
+ edits[page] = {**doc, 'Actions': actions}
131
+ details[page] = {'replace': update.replace, 'changes': changes,
132
+ 'cleared': sorted(before.keys() - actions.keys())}
133
+ preview = {'source_profile': profile, 'name': name, 'source_hashes': source_hashes,
134
+ 'pages': details}
135
+ digest = profiles.fingerprint(json.dumps(preview, sort_keys=True, allow_nan=False).encode())
136
+ return {**preview, 'layout_sha256': digest}, edits, images