-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathstart.py
More file actions
807 lines (724 loc) · 28 KB
/
Copy pathstart.py
File metadata and controls
807 lines (724 loc) · 28 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
import argparse
import os
import re
import requests
import shutil
import signal
import socket
import subprocess
import sys
import time
import webbrowser
from pathlib import Path
PROJECT_ROOT = Path(__file__).parent
BACKEND_HOST = "127.0.0.1"
BACKEND_PORT = 5001
BACKEND_URL = f"http://{BACKEND_HOST}:{BACKEND_PORT}"
HEALTH_ENDPOINT = f"{BACKEND_URL}/api/health"
APP_WM_CLASS = "Fragmenta"
APP_ICON_PATH = PROJECT_ROOT / "app" / "frontend" / "public" / "fragmenta_icon_1024.png"
try:
ABOUT_VERSION = (PROJECT_ROOT / "VERSION").read_text().strip() or "1.0.0"
except Exception:
ABOUT_VERSION = "1.0.0"
ABOUT_COPYRIGHT = "© 2026 Misagh Azimi · www.misaghazimi.com"
ABOUT_CREDITS = (
"Local-first text-to-audio: prepare datasets, train, generate and perform "
"with diffusion models.\n\nMade by the composer and researcher Misagh Azimi."
)
WINDOWS_ICON_PATH = PROJECT_ROOT / "app" / "frontend" / "public" / "fragmenta.ico"
WINDOWS_APP_ID = "Fragmenta.Desktop.1"
WINDOWS_WINDOW_TITLE = "Fragmenta"
CHROMIUM_CANDIDATES = (
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser",
"brave-browser",
)
CHROMIUM_USER_DATA_DIR = Path.home() / ".cache" / "fragmenta-chrome-profile"
CHROMIUM_MIN_SESSION_SECONDS = 15.0
WEBVIEW_STORAGE_DIR = Path.home() / ".cache" / "fragmenta-webview-profile"
DESKTOP_ENTRY_PATH = (
Path.home() / ".local" / "share" / "applications" / "fragmenta.desktop"
)
def _port_available(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
if os.name != "nt":
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind((BACKEND_HOST, port))
return True
except OSError:
return False
def _pick_backend_port(preferred: int = 5001) -> int:
for candidate in (preferred, 0):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
try:
probe.bind((BACKEND_HOST, candidate))
return probe.getsockname()[1]
except OSError:
continue
raise RuntimeError("no free TCP port available for the Fragmenta backend")
def _is_fragmenta_backend(port: int) -> bool:
try:
resp = requests.get(
f"http://{BACKEND_HOST}:{port}/api/health", timeout=1.5
)
return resp.status_code == 200 and "components_ready" in resp.json()
except Exception:
return False
def _install_sigterm_handler() -> None:
def _terminate(_signum, _frame):
raise SystemExit(143)
try:
signal.signal(signal.SIGTERM, _terminate)
except (ValueError, OSError, AttributeError):
pass
def _terminate_backend_on_port(port: int) -> bool:
try:
import psutil
except ImportError:
return False
victim = None
for proc in psutil.process_iter():
try:
for conn in proc.net_connections(kind="tcp"):
if (conn.status == psutil.CONN_LISTEN and conn.laddr
and conn.laddr.port == port):
victim = proc
break
except (psutil.AccessDenied, psutil.NoSuchProcess, psutil.ZombieProcess):
continue
if victim is not None:
break
if victim is None:
return False
try:
victim.terminate()
try:
victim.wait(timeout=10)
except psutil.TimeoutExpired:
victim.kill()
victim.wait(timeout=5)
except psutil.NoSuchProcess:
pass
except Exception:
return False
for _ in range(20):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
if s.connect_ex((BACKEND_HOST, port)) != 0:
return True
time.sleep(0.25)
return False
def _maybe_replace_stale_backend(port: int) -> None:
try:
resp = requests.get(
f"http://{BACKEND_HOST}:{port}/api/health", timeout=1.5
)
running_version = (resp.json() or {}).get("version")
except Exception:
return
if running_version == ABOUT_VERSION:
return
print(
f"The Fragmenta backend already running on port {port} is version "
f"{running_version or 'unknown (older build)'}, but this installation "
f"is {ABOUT_VERSION}. Restarting it so the app matches the installed code."
)
if not _terminate_backend_on_port(port):
print(
"Could not stop the old backend automatically — if the app "
"misbehaves, close the other Fragmenta instance and relaunch."
)
def configure_backend_endpoint() -> None:
global BACKEND_PORT, BACKEND_URL, HEALTH_ENDPOINT
if _port_available(5001):
BACKEND_PORT = 5001
elif _is_fragmenta_backend(5001):
BACKEND_PORT = 5001
_maybe_replace_stale_backend(5001)
else:
BACKEND_PORT = _pick_backend_port()
BACKEND_URL = f"http://{BACKEND_HOST}:{BACKEND_PORT}"
HEALTH_ENDPOINT = f"{BACKEND_URL}/api/health"
if BACKEND_PORT != 5001:
print(
f"Port 5001 is busy with another program; using {BACKEND_URL} "
"instead. Note: presets, MIDI mappings and fragments saved on 5001 "
"won't be visible here (browser storage is per-port)."
)
def announce_ui_ready() -> None:
print("__FRAGMENTA_UI_READY__", flush=True)
if os.environ.get("FRAGMENTA_PACKAGED") == "1":
time.sleep(0.6)
def wait_for_backend(timeout_seconds: int = 60) -> bool:
deadline = time.time() + timeout_seconds
while time.time() < deadline:
if _is_fragmenta_backend(BACKEND_PORT):
return True
time.sleep(0.4)
return False
def backend_process_running() -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(0.5)
return sock.connect_ex((BACKEND_HOST, BACKEND_PORT)) == 0
def start_backend_subprocess() -> subprocess.Popen:
env = os.environ.copy()
env.setdefault("FRAGMENTA_LOG_LEVEL", "INFO")
env["FLASK_HOST"] = BACKEND_HOST
env["FLASK_PORT"] = str(BACKEND_PORT)
return subprocess.Popen(
[sys.executable, "-m", "app.backend.app"],
cwd=str(PROJECT_ROOT),
env=env,
)
def run_browser_mode() -> int:
backend_process = None
try:
if not backend_process_running():
backend_process = start_backend_subprocess()
if not wait_for_backend():
print("Backend failed to start in time.")
return 1
announce_ui_ready()
webbrowser.open(BACKEND_URL)
print(f"Fragmenta is running at {BACKEND_URL}")
print("Press Ctrl+C to stop.")
while True:
time.sleep(1)
if backend_process is not None:
rc = backend_process.poll()
if rc is not None:
print(f"Backend exited (code {rc}); shutting down.")
return 1 if rc else 0
elif not backend_process_running():
print("The reused backend is no longer running; shutting down.")
return 1
except KeyboardInterrupt:
return 0
finally:
if backend_process and backend_process.poll() is None:
backend_process.terminate()
try:
backend_process.wait(timeout=10)
except subprocess.TimeoutExpired:
backend_process.kill()
def _chromium_install_paths() -> list[str]:
if sys.platform == "darwin":
home = Path.home()
return [
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
str(home / "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
]
if sys.platform == "win32":
pf = os.environ.get("PROGRAMFILES", r"C:\Program Files")
pfx86 = os.environ.get("PROGRAMFILES(X86)", r"C:\Program Files (x86)")
local = os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))
return [
rf"{pf}\Google\Chrome\Application\chrome.exe",
rf"{pfx86}\Google\Chrome\Application\chrome.exe",
rf"{local}\Google\Chrome\Application\chrome.exe",
rf"{pf}\Chromium\Application\chrome.exe",
rf"{pf}\Microsoft\Edge\Application\msedge.exe",
rf"{pfx86}\Microsoft\Edge\Application\msedge.exe",
rf"{pf}\BraveSoftware\Brave-Browser\Application\brave.exe",
rf"{pfx86}\BraveSoftware\Brave-Browser\Application\brave.exe",
]
return []
def find_chromium() -> str | None:
for name in CHROMIUM_CANDIDATES:
path = shutil.which(name)
if not path:
continue
resolved = os.path.realpath(path)
if (
path.startswith("/snap/")
or resolved.startswith("/snap/")
or resolved == "/usr/bin/snap"
):
continue
return path
for candidate in _chromium_install_paths():
if candidate and os.path.isfile(candidate):
return candidate
return None
def ensure_desktop_entry() -> None:
if DESKTOP_ENTRY_PATH.exists():
return
DESKTOP_ENTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
contents = (
"[Desktop Entry]\n"
"Type=Application\n"
"Name=Fragmenta\n"
"Comment=Fine-tune and use text-to-audio models\n"
f"Icon={APP_ICON_PATH}\n"
"Categories=AudioVideo;Audio;\n"
f"StartupWMClass={APP_WM_CLASS}\n"
"NoDisplay=true\n"
)
DESKTOP_ENTRY_PATH.write_text(contents)
def run_chromium_app_mode(chromium_path: str) -> int:
backend_process = None
chromium_process = None
try:
if not backend_process_running():
backend_process = start_backend_subprocess()
if not wait_for_backend():
print("Backend failed to start in time.")
return 1
announce_ui_ready()
if sys.platform == "linux":
ensure_desktop_entry()
CHROMIUM_USER_DATA_DIR.mkdir(parents=True, exist_ok=True)
# Sized and scaled from the display, not baked in — this is the
# default launch path on Linux, so a fixed 1400x850 here is what most
# users actually get regardless of their monitor.
screen = detect_screen_size()
scale = ui_scale_for(screen[0]) if screen else 1.0
# --window-size is in device-independent pixels, so the geometry has
# to be worked out in the scaled coordinate space, not raw pixels.
logical = (int(screen[0] / scale), int(screen[1] / scale)) if screen else None
win_w, win_h, _, _ = _window_geometry(logical)
if screen:
print(f"Screen {screen[0]}x{screen[1]} -> scale {scale}, window {win_w}x{win_h} dip")
launch_args_base = [
chromium_path,
f"--app={BACKEND_URL}",
f"--window-size={win_w},{win_h}",
"--no-first-run",
"--no-default-browser-check",
"--log-level=3",
"--disable-logging",
]
# Magnify the whole UI natively. This is what actually fixes a 4K
# panel on an unscaled desktop — it scales layout, type and hit
# targets together, and unlike a CSS zoom in the page it doesn't
# depend on the page being able to measure the display.
if scale != 1.0:
launch_args_base.insert(2, f"--force-device-scale-factor={scale}")
if sys.platform == "linux":
launch_args_base.insert(2, f"--class={APP_WM_CLASS}")
attempts = [
(
"custom profile",
[
*launch_args_base,
f"--user-data-dir={CHROMIUM_USER_DATA_DIR}",
],
),
("default profile", launch_args_base),
]
quiet = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
last_exit_code = 1
for index, (label, args) in enumerate(attempts):
launched_at = time.monotonic()
chromium_process = subprocess.Popen(args, cwd=str(PROJECT_ROOT), **quiet)
chromium_process.wait()
elapsed = time.monotonic() - launched_at
last_exit_code = chromium_process.returncode or 0
if last_exit_code == 0:
return 0
if elapsed >= CHROMIUM_MIN_SESSION_SECONDS:
print(
f"Chromium exited with code {last_exit_code} after "
f"{elapsed:.0f}s — treating it as the end of the session."
)
return 0
if index == 0:
print(
"Chromium app mode failed with "
f"{label} (exit code {last_exit_code}); retrying with default profile."
)
continue
return last_exit_code
except KeyboardInterrupt:
return 0
finally:
if chromium_process and chromium_process.poll() is None:
chromium_process.terminate()
try:
chromium_process.wait(timeout=5)
except subprocess.TimeoutExpired:
chromium_process.kill()
if backend_process and backend_process.poll() is None:
backend_process.terminate()
try:
backend_process.wait(timeout=10)
except subprocess.TimeoutExpired:
backend_process.kill()
def check_linux_webview_deps() -> tuple[bool, str]:
if sys.platform != "linux":
return True, ""
try:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
gi.require_version("WebKit2", "4.1")
from gi.repository import WebKit2
return True, ""
except ImportError as e:
return False, f"Missing GI bindings: {e}"
except ValueError as e:
return False, f"Missing GTK/WebKit: {e}"
def _ensure_windows_icon() -> bool:
if WINDOWS_ICON_PATH.exists():
return True
try:
from PIL import Image
img = Image.open(APP_ICON_PATH)
WINDOWS_ICON_PATH.parent.mkdir(parents=True, exist_ok=True)
img.save(
WINDOWS_ICON_PATH,
format="ICO",
sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
)
return True
except Exception as exc:
print(f"Could not generate Windows icon: {exc}")
return False
def _windows_set_app_id() -> None:
if sys.platform != "win32":
return
try:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(WINDOWS_APP_ID)
except Exception as exc:
print(f"Could not set AppUserModelID: {exc}")
def _macos_set_app_metadata() -> None:
if sys.platform != "darwin":
return
try:
from Foundation import NSBundle, NSProcessInfo
try:
NSProcessInfo.processInfo().setProcessName_("Fragmenta")
except Exception:
pass
bundle = NSBundle.mainBundle()
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
if info is not None:
info["CFBundleName"] = "Fragmenta"
info["CFBundleDisplayName"] = "Fragmenta"
except Exception as exc:
print(f"Could not set macOS app name: {exc}")
def _macos_set_webview_app_name() -> None:
if sys.platform != "darwin":
return
try:
from webview.platforms import cocoa as _cocoa
if getattr(_cocoa, "info", None) is not None:
_cocoa.info["CFBundleName"] = "Fragmenta"
_cocoa.info["CFBundleDisplayName"] = "Fragmenta"
_cocoa.info["CFBundleShortVersionString"] = ABOUT_VERSION
_cocoa.info["NSHumanReadableCopyright"] = ABOUT_COPYRIGHT
try:
from AppKit import NSAttributedString
_cocoa.info["Credits"] = NSAttributedString.alloc().initWithString_(
ABOUT_CREDITS
)
except Exception:
pass
except Exception as exc:
print(f"Could not set webview app name: {exc}")
def _macos_apply_dock_icon() -> None:
if sys.platform != "darwin":
return
try:
from AppKit import NSApplication, NSImage
image = NSImage.alloc().initByReferencingFile_(str(APP_ICON_PATH))
if image is not None:
NSApplication.sharedApplication().setApplicationIconImage_(image)
except Exception as exc:
print(f"Could not set macOS dock icon: {exc}")
def _linux_set_app_metadata() -> None:
if sys.platform != "linux":
return
if not APP_ICON_PATH.exists():
return
try:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk
GLib.set_prgname(APP_WM_CLASS)
GLib.set_application_name("Fragmenta")
try:
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
Gdk.set_program_class(APP_WM_CLASS)
except Exception:
pass
Gtk.Window.set_default_icon_from_file(str(APP_ICON_PATH))
except Exception as exc:
print(f"Could not set Linux app metadata: {exc}")
def _linux_apply_window_icon() -> None:
if sys.platform != "linux":
return
if not APP_ICON_PATH.exists():
return
try:
from webview.platforms.gtk import BrowserView
for inst in BrowserView.instances.values():
gtk_window = getattr(inst, "window", None)
if gtk_window is None:
continue
try:
gtk_window.set_icon_from_file(str(APP_ICON_PATH))
except Exception:
pass
except Exception as exc:
print(f"Could not set Linux window icon: {exc}")
def _windows_apply_window_icon() -> None:
if sys.platform != "win32":
return
if not _ensure_windows_icon():
return
try:
import ctypes
WM_SETICON = 0x0080
ICON_SMALL = 0
ICON_BIG = 1
IMAGE_ICON = 1
LR_LOADFROMFILE = 0x00000010
hwnd = ctypes.windll.user32.FindWindowW(None, WINDOWS_WINDOW_TITLE)
if not hwnd:
return
icon_path = str(WINDOWS_ICON_PATH)
h_small = ctypes.windll.user32.LoadImageW(
None, icon_path, IMAGE_ICON, 16, 16, LR_LOADFROMFILE
)
h_big = ctypes.windll.user32.LoadImageW(
None, icon_path, IMAGE_ICON, 32, 32, LR_LOADFROMFILE
)
if h_small:
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_SMALL, h_small)
if h_big:
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_BIG, h_big)
except Exception as exc:
print(f"Could not set Windows window icon: {exc}")
DEFAULT_WINDOW_SIZE = (1400, 850)
DEFAULT_MIN_SIZE = (1000, 700)
def ui_scale_for(screen_width: int) -> float:
"""How much to magnify the interface on a display this wide.
Deliberately decided here rather than in the web app. The page can't be
trusted to measure its own display: Brave — which is what `find_chromium`
picks up on plenty of Linux boxes — farbles `window.screen` for
fingerprinting resistance and reports a flat 1280x800 no matter what
monitor you're on. The launcher can read the real screen, so it decides.
`screen_width` is physical pixels, so this must only be called with a size
from `detect_screen_size` (which already divides out any desktop scaling).
"""
if screen_width >= 3400:
return 1.5 # 4K and up, unscaled desktop
if screen_width >= 2700:
return 1.3 # 3K / ultrawide
if screen_width >= 2200:
return 1.15 # 1440p
return 1.0 # 1080p and below — already the right size
def detect_screen_size() -> tuple[int, int] | None:
"""Best-effort screen size in logical pixels, or None if it can't be read.
Deliberately avoids importing pywebview: the Chromium launch path is the
default on Linux and shouldn't pay for a GTK initialisation just to ask
how big the display is.
"""
if sys.platform == "win32":
try:
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
width, height = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
if width > 0 and height > 0:
return width, height
except Exception:
pass
if sys.platform == "linux":
# Works under X11 and XWayland. "current WxH" is the composed desktop
# size across all outputs, so it also covers multi-monitor setups.
try:
out = subprocess.run(
["xrandr", "--current"], capture_output=True, text=True, timeout=3,
).stdout
match = re.search(r"current\s+(\d+)\s*x\s*(\d+)", out)
if match:
width, height = int(match.group(1)), int(match.group(2))
# xrandr reports physical pixels; if the desktop is running
# scaled, the toolkit's logical space is smaller by that factor.
try:
gdk_scale = int(os.environ.get("GDK_SCALE", "1"))
except ValueError:
gdk_scale = 1
if gdk_scale > 1:
width, height = width // gdk_scale, height // gdk_scale
if width > 0 and height > 0:
return width, height
except Exception:
pass
if sys.platform == "darwin":
try:
out = subprocess.run(
["system_profiler", "SPDisplaysDataType"],
capture_output=True, text=True, timeout=6,
).stdout
match = re.search(r"Resolution:\s+(\d+)\s*x\s*(\d+)", out)
if match:
return int(match.group(1)), int(match.group(2))
except Exception:
pass
# Portable last resort. Tk isn't always installed, hence the guard.
try:
import tkinter
root = tkinter.Tk()
root.withdraw()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.destroy()
if width > 0 and height > 0:
return width, height
except Exception:
pass
return None
def _window_geometry(screen: tuple[int, int] | None) -> tuple[int, int, int, int]:
"""Size the window from the display instead of a baked-in 1400x850.
A fixed size that looks generous on a 1080p laptop covers about a third
of a 4K panel. Open at a share of the screen instead, clamped so it stays
sane on both very small and very large displays.
Returns (width, height, min_width, min_height), falling back to the old
fixed size when the screen can't be read.
"""
default_w, default_h = DEFAULT_WINDOW_SIZE
min_w, min_h = DEFAULT_MIN_SIZE
if not screen:
return default_w, default_h, min_w, min_h
sw, sh = int(screen[0]), int(screen[1])
if sw <= 0 or sh <= 0:
return default_w, default_h, min_w, min_h
# 70% of the screen. Capped because past ~2000px the layout just grows
# margins rather than showing more.
width = min(int(sw * 0.70), 2000)
height = min(int(sh * 0.70), 1300)
# Don't shrink below the size we've always shipped — but never grow past
# the screen doing it, or a small laptop gets a window it can't display.
width = max(width, min(default_w, sw - 40))
height = max(height, min(default_h, sh - 60))
# Never demand a minimum the screen can't satisfy, or the window manager
# gets a window that won't fit on the display.
min_w = min(min_w, max(640, sw - 80))
min_h = min(min_h, max(480, sh - 80))
# And never open smaller than the minimum.
width, height = max(width, min_w), max(height, min_h)
print(f"Screen {sw}x{sh} -> window {width}x{height}")
return width, height, min_w, min_h
def run_pywebview_mode() -> int:
_macos_set_app_metadata()
try:
import webview
except ImportError:
print("pywebview is unavailable; falling back to browser mode.")
return run_browser_mode()
_macos_set_webview_app_name()
_windows_set_app_id()
_linux_set_app_metadata()
if sys.platform == "linux":
deps_ok, deps_error = check_linux_webview_deps()
if not deps_ok:
print("=" * 60)
print("DESKTOP MODE UNAVAILABLE")
print("=" * 60)
print(f"Reason: {deps_error}")
print()
print("To use the desktop window, install system dependencies:")
print()
print(" Ubuntu/Debian:")
print(" sudo apt install python3-gi python3-gi-cairo gir1.2-webkit2-4.1")
print()
print(" Fedora:")
print(" sudo dnf install python3-gobject webkit2gtk4.1")
print()
print(" Arch:")
print(" sudo pacman -S python-gobject webkit2gtk")
print()
print("Falling back to browser mode...")
print("=" * 60)
return run_browser_mode()
backend_process = None
try:
if not backend_process_running():
backend_process = start_backend_subprocess()
if not wait_for_backend():
print("Backend failed to start in time.")
return 1
announce_ui_ready()
try:
win_w, win_h, min_w, min_h = _window_geometry(detect_screen_size())
window = webview.create_window(
title=WINDOWS_WINDOW_TITLE,
url=BACKEND_URL,
width=win_w,
height=win_h,
min_size=(min_w, min_h),
background_color="#0D1117",
)
if sys.platform == "win32":
window.events.shown += _windows_apply_window_icon
elif sys.platform == "linux":
window.events.shown += _linux_apply_window_icon
elif sys.platform == "darwin":
window.events.shown += _macos_apply_dock_icon
WEBVIEW_STORAGE_DIR.mkdir(parents=True, exist_ok=True)
webview.start(private_mode=False, storage_path=str(WEBVIEW_STORAGE_DIR))
return 0 if window else 1
except Exception as exc:
print(
"pywebview initialization failed "
f"({exc}); falling back to browser mode."
)
print(
"Tip: ensure required GTK/WebKit system packages are installed."
)
return run_browser_mode()
finally:
if backend_process and backend_process.poll() is None:
backend_process.terminate()
try:
backend_process.wait(timeout=10)
except subprocess.TimeoutExpired:
backend_process.kill()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Launch Fragmenta desktop app")
parser.add_argument(
"--browser",
action="store_true",
help="Use the system browser instead of the pywebview window",
)
parser.add_argument(
"--chromium",
action="store_true",
help=(
"Launch in a real Chromium browser (--app mode) instead of the "
"native window. Only needed for cue output-device routing "
"(AudioContext.setSinkId), which the OS WebViews lack on mac/linux."
),
)
return parser.parse_args()
def main() -> int:
args = parse_args()
_install_sigterm_handler()
configure_backend_endpoint()
if args.browser:
return run_browser_mode()
prefer_chromium = args.chromium or sys.platform == "linux"
if prefer_chromium:
chromium_path = find_chromium()
if chromium_path:
chromium_exit_code = run_chromium_app_mode(chromium_path)
if chromium_exit_code == 0:
return 0
print(
"Chromium app mode failed "
f"(exit code {chromium_exit_code}); falling back to pywebview."
)
return run_pywebview_mode()
if __name__ == "__main__":
raise SystemExit(main())