"""DSP Control desktop app: the web server runs inside the app and the UI opens in its own window. The window logs in with a one-time token (no PIN). Other devices only get access when "Fernzugriff" is switched on in the settings - and then they need the PIN. Runs on Windows and macOS. Build: python packaging/build.py """ import asyncio import base64 import ctypes import json import logging import os import secrets import subprocess import sys import threading from pathlib import Path import webview import server APP_NAME = "DSP Control" def data_dir() -> Path: if sys.platform == "darwin": d = Path.home() / "Library" / "Application Support" / APP_NAME else: d = Path(os.environ.get("APPDATA") or Path.home()) / APP_NAME d.mkdir(parents=True, exist_ok=True) return d # texts of this file and pywebview's own (menus, file dialogs); the page itself is translated in static/i18n.js TEXTS = { "en": {"running": "DSP Control is already running.", "failed": "DSP Control could not start:\n{error}", "timeout": "timeout"}, "de": {"running": "DSP Control läuft bereits.", "failed": "DSP Control konnte nicht starten:\n{error}", "timeout": "Zeitüberschreitung"}, } WEBVIEW_DE = { "global.quitConfirmation": "Wirklich beenden?", "global.ok": "OK", "global.quit": "Beenden", "global.cancel": "Abbrechen", "global.saveFile": "Datei speichern", "cocoa.menu.about": "Über", "cocoa.menu.services": "Dienste", "cocoa.menu.view": "Darstellung", "cocoa.menu.edit": "Bearbeiten", "cocoa.menu.hide": "Ausblenden", "cocoa.menu.hideOthers": "Andere ausblenden", "cocoa.menu.showAll": "Alle einblenden", "cocoa.menu.quit": "Beenden", "cocoa.menu.fullscreen": "Vollbild", "cocoa.menu.cut": "Ausschneiden", "cocoa.menu.copy": "Kopieren", "cocoa.menu.paste": "Einsetzen", "cocoa.menu.selectAll": "Alles auswählen", "windows.fileFilter.allFiles": "Alle Dateien", "windows.fileFilter.otherFiles": "Andere Dateitypen", } def ui_lang() -> str: """Language chosen in the app (kept in config.json by the server), English by default.""" try: lang = json.loads((data_dir() / "config.json").read_text(encoding="utf-8")).get("lang") except (OSError, ValueError, AttributeError): lang = None return lang if lang in TEXTS else "en" def text(key: str, **kw) -> str: return TEXTS[ui_lang()][key].format(**kw) _lock = None def single_instance() -> bool: """False if the app is already running (Windows named mutex, elsewhere a locked file).""" global _lock if sys.platform == "win32": ctypes.windll.kernel32.CreateMutexW(None, False, "Local\\DSPControlDesktop") return ctypes.windll.kernel32.GetLastError() != 183 # ERROR_ALREADY_EXISTS import fcntl _lock = open(data_dir() / ".lock", "w") # held until the process ends try: fcntl.flock(_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return False return True def message(text: str): if sys.platform == "win32": ctypes.windll.user32.MessageBoxW(None, text, APP_NAME, 0x40) elif sys.platform == "darwin": subprocess.run(["osascript", "-e", "on run argv", "-e", f'display dialog (item 1 of argv) with title "{APP_NAME}" buttons {{"OK"}} default button 1', "-e", "end run", text], check=False) else: print(text) class Api: """Called from the page (window.pywebview.api): native save/open dialogs for backups and presets.""" def __init__(self): self._window = None # underscore: not exposed to JavaScript def save_file(self, name: str, text: str) -> bool: res = self._window.create_file_dialog(webview.FileDialog.SAVE, save_filename=name) path = res[0] if isinstance(res, (list, tuple)) else res if not path: return False Path(path).write_text(text, encoding="utf-8") return True def open_file(self) -> dict | None: res = self._window.create_file_dialog(webview.FileDialog.OPEN) if not res: return None path = Path(res[0] if isinstance(res, (list, tuple)) else res) if path.stat().st_size > 5_000_000: raise ValueError("File is too large") return {"name": path.name, "data": base64.b64encode(path.read_bytes()).decode()} def main(): if not single_instance(): message(text("running")) return d = data_dir() logging.basicConfig(filename=d / "dsp-control.log", level=logging.INFO, encoding="utf-8", format="%(asctime)s %(name)s %(levelname)s %(message)s") app = server.App(d / "config.json") app.app_token = secrets.token_urlsafe(24) loop = asyncio.new_event_loop() started = threading.Event() state: dict = {} async def start(): app.load() srv = await asyncio.start_server(app.handle, "127.0.0.1", 0) state["port"] = srv.sockets[0].getsockname()[1] await app.start_remote() def run(): asyncio.set_event_loop(loop) try: loop.run_until_complete(start()) except Exception as e: # noqa: BLE001 - shown to the user below logging.exception("start failed") state["error"] = e started.set() loop.run_forever() threading.Thread(target=run, daemon=True, name="server").start() started.wait(20) if "port" not in state: message(text("failed", error=state.get("error", text("timeout")))) return api = Api() api._window = webview.create_window(APP_NAME, f"http://127.0.0.1:{state['port']}/app-login?t={app.app_token}", width=1280, height=840, min_size=(380, 560), background_color="#0b0c0f", js_api=api) webview.start(private_mode=False, storage_path=str(d / "webview"), localization=WEBVIEW_DE if ui_lang() == "de" else {}) # window closed: disconnect the DSPs cleanly so the next connection is accepted right away try: asyncio.run_coroutine_threadsafe(app.shutdown(), loop).result(5) except Exception: # noqa: BLE001 logging.exception("shutdown") if __name__ == "__main__": main()