-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
4273 lines (3783 loc) · 131 KB
/
Copy pathmain.py
File metadata and controls
4273 lines (3783 loc) · 131 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
import shutil
import sys
import os
import ctypes
from pathlib import Path
def register_url_protocol():
if sys.platform != "win32":
return
try:
import winreg
key_path = r"Software\Classes\luminalium"
# 构建命令行
if getattr(sys, "frozen", False):
exe_path = os.path.abspath(sys.executable)
new_cmd = f'"{exe_path}" "%1"'
icon_path = f'"{exe_path}",0'
else:
main_py = os.path.abspath(__file__)
python_exe = os.path.abspath(sys.executable)
# 用 pythonw.exe 启动以避免弹出 CMD 窗口
pythonw_exe = python_exe.replace("python.exe", "pythonw.exe")
if not os.path.exists(pythonw_exe):
pythonw_exe = python_exe
new_cmd = f'"{pythonw_exe}" "{main_py}" "%1"'
icon_path = f'"{pythonw_exe}",0'
# 检查现有命令是否最新,过旧或不存在则重新注册
try:
cmd_key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
key_path + r"\shell\open\command",
0,
winreg.KEY_READ,
)
old_cmd = winreg.QueryValue(cmd_key, "")
winreg.CloseKey(cmd_key)
if old_cmd == new_cmd:
return # 已是最新
except FileNotFoundError:
pass
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path)
winreg.SetValue(key, "", winreg.REG_SZ, "URL:Luminalium Protocol")
winreg.SetValueEx(key, "URL Protocol", 0, winreg.REG_SZ, "")
icon_key = winreg.CreateKey(key, "DefaultIcon")
winreg.SetValue(icon_key, "", winreg.REG_SZ, icon_path)
winreg.CloseKey(icon_key)
cmd_key = winreg.CreateKey(key, r"shell\open\command")
winreg.SetValue(cmd_key, "", winreg.REG_SZ, new_cmd)
winreg.CloseKey(cmd_key)
winreg.CloseKey(key)
except Exception as e:
print(f"Failed to register URL protocol: {e}")
def unregister_url_protocol():
if sys.platform != "win32":
return
try:
import winreg
key_path = r"Software\Classes\luminalium"
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path + r"\shell\open\command")
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path + r"\shell\open")
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path + r"\shell")
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path + r"\DefaultIcon")
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path)
print("[Protocol] URL protocol unregistered successfully")
except FileNotFoundError:
pass
except Exception as e:
print(f"Failed to unregister URL protocol: {e}")
def parse_luminalium_url(url: str) -> dict | None:
if not url or not url.startswith("luminalium://"):
return None
try:
from urllib.parse import parse_qs, urlparse
parsed = urlparse(url)
path = parsed.path.strip("/")
parts = [p for p in path.split("/") if p]
query = parse_qs(parsed.query or "")
host = parsed.hostname or ""
if host == "app" and len(parts) >= 1:
if parts[0] == "settings":
page = parts[1] if len(parts) >= 2 else "main"
return {"action": "settings", "page": page}
elif host == "intergrate" and len(parts) >= 1:
target = parts[0]
if target in ("timer", "board"):
route = {"action": target}
for key, values in query.items():
if values:
route[key] = values[-1]
return route
except Exception:
pass
return None
# Nuitka standalone detection and compatibility
if hasattr(sys, "nuitka_binary"):
sys.frozen = True
import traceback
import tempfile
import subprocess
import json
import importlib
import importlib.util
import faulthandler
from typing import Optional
import time
import warnings
if sys.platform == "linux":
_HAS_X11_DISPLAY = bool(os.environ.get("DISPLAY"))
_HAS_WAYLAND_DISPLAY = bool(os.environ.get("WAYLAND_DISPLAY"))
_HAS_DISPLAY = _HAS_X11_DISPLAY or _HAS_WAYLAND_DISPLAY
_LINUX_QPA_OVERRIDE = str(os.environ.get("LUMINALIUM_QPA_PLATFORM", "")).strip()
_FORCE_X11 = str(os.environ.get("LUMINALIUM_FORCE_X11", "")).strip().lower() in (
"1",
"true",
"yes",
)
if "QT_QPA_PLATFORM" not in os.environ:
if _LINUX_QPA_OVERRIDE:
os.environ["QT_QPA_PLATFORM"] = _LINUX_QPA_OVERRIDE
elif _HAS_X11_DISPLAY:
os.environ["QT_QPA_PLATFORM"] = "xcb"
if _FORCE_X11:
print(
"[Main] LUMINALIUM_FORCE_X11 is set, using X11/XWayland for WPS RPC compatibility"
)
elif _HAS_WAYLAND_DISPLAY:
os.environ["QT_QPA_PLATFORM"] = "wayland"
else:
os.environ["QT_QPA_PLATFORM"] = "offscreen"
_SELECTED_QPA_PLATFORM = str(os.environ.get("QT_QPA_PLATFORM", "")).strip().lower()
if _SELECTED_QPA_PLATFORM.startswith("xcb") and _HAS_X11_DISPLAY:
if _HAS_WAYLAND_DISPLAY:
os.environ["LUMINALIUM_XWAYLAND_SESSION"] = "1"
original_wayland_display = os.environ.get("WAYLAND_DISPLAY")
if original_wayland_display:
os.environ["LUMINALIUM_ORIGINAL_WAYLAND_DISPLAY"] = (
original_wayland_display
)
os.environ.pop("WAYLAND_DISPLAY", None)
if "LUMINALIUM_ORIGINAL_XDG_SESSION_TYPE" not in os.environ:
current_session_type = os.environ.get("XDG_SESSION_TYPE")
os.environ["LUMINALIUM_ORIGINAL_XDG_SESSION_TYPE"] = (
current_session_type if current_session_type is not None else ""
)
os.environ["XDG_SESSION_TYPE"] = "x11"
print(
"[Main] Normalized Linux environment for QtWebEngine:"
" xcb session will hide WAYLAND_DISPLAY and force XDG_SESSION_TYPE=x11",
flush=True,
)
else:
os.environ.pop("LUMINALIUM_XWAYLAND_SESSION", None)
print(
"[Main] Linux display detection:"
f" wayland={_HAS_WAYLAND_DISPLAY}"
f" x11={_HAS_X11_DISPLAY}"
f" qpa={os.environ.get('QT_QPA_PLATFORM', '')}"
f" force_x11={_FORCE_X11}"
)
# Add --no-sandbox to avoid zygote crash on some Linux environments
# This must be done BEFORE any Qt import or QApp creation
if "--no-sandbox" not in sys.argv:
sys.argv.append("--no-sandbox")
# Delay heavy imports or move them inside if __name__ == "__main__" logic
# to allow --webview-runner to start fast and clean.
if __name__ == "__main__":
if "--webview-runner" in sys.argv:
idx = sys.argv.index("--webview-runner")
import plugins.webview_runner as _wv
sys.argv = ["webview_runner.py"] + sys.argv[idx + 1 :]
_wv.main()
sys.exit(0)
if "--dialog" in sys.argv or "--crash-file" in sys.argv:
import plugins.webview_runner as _wv
_wv.main()
sys.exit(0)
if "--memory-cleaner" in sys.argv:
from ppt_assistant.core.memory_cleaner import run_memory_cleaner
parent_pid = int(os.environ.get("LUMINALIUM_PARENT_PID", "0"))
interval = int(os.environ.get("LUMINALIUM_MEMCLEAN_INTERVAL", "30"))
if parent_pid:
run_memory_cleaner(parent_pid, interval)
sys.exit(0)
from PySide6.QtWidgets import (
QApplication,
QWidget,
QLabel,
QFrame,
QProgressBar,
)
from PySide6.QtCore import Qt, QTimer, Slot, QPoint, QCoreApplication, QEvent, QObject, QPropertyAnimation, QEasingCurve, QParallelAnimationGroup, QRect, QRectF, QEventLoop
from PySide6.QtGui import (
QFontDatabase,
QFont,
QColor,
QIcon,
QPainter,
QPainterPath,
QPen,
QBrush,
QFontMetrics,
QRegion,
)
from ppt_assistant.core.ppt_monitor import PPTMonitor
from ppt_assistant.ui.overlay import create_overlay_window
from ppt_assistant.ui.tray import SystemTray, is_system_tray_supported
from ppt_assistant.core.config import (
cfg,
SETTINGS_PATH as _SETTINGS_PATH_ORIG,
PLUGINS_DIR,
reload_cfg,
_apply_theme_and_color,
Theme,
FIRST_RUN,
ROOT_DIR,
)
from ppt_assistant.core.system_theme_watcher import SystemThemeWatcherManager
from ppt_assistant.core.config_base import setThemeColor
def _apply_resolved_theme_color(theme_value):
"""Apply resolved theme to qfluentwidgets engine and accent color.
Used by SystemThemeWatcher when AUTO mode resolves to actual system theme.
Does NOT write cfg.themeMode (stays as AUTO)."""
from qfluentwidgets import qconfig
qconfig.theme = theme_value
if theme_value == Theme.DARK:
setThemeColor("#E1EBFF")
else:
setThemeColor("#3275F5")
def _get_active_settings_path():
settings_dir = os.path.dirname(_SETTINGS_PATH_ORIG)
active_marker = os.path.join(settings_dir, "_active")
if os.path.exists(active_marker):
try:
with open(active_marker, "r", encoding="utf-8") as f:
name = f.read().strip()
if name and name != "default":
profile_path = os.path.join(settings_dir, name + ".json")
if os.path.exists(profile_path):
return profile_path
except Exception:
pass
return _SETTINGS_PATH_ORIG
SETTINGS_PATH = _get_active_settings_path()
from ppt_assistant.core.timer_manager import TimerManager
from ppt_assistant.core.i18n import t
from ppt_assistant.core.app_icon import load_app_icon
from ppt_assistant.core.linux_focus_watcher import LinuxFocusWatcher
from ppt_assistant.core.win_focus_watcher import WindowsFocusWatcher
from ppt_assistant.core.resource_monitor import SystemResourceMonitor
from ppt_assistant.core.classisland_monitor import ClassIslandMonitor
from ppt_assistant.core.platform_integration import open_path
from ppt_assistant.core.windows_notifications import (
configure_current_process_for_notifications,
send_windows_notification,
)
from utils.env_utils import get_device_uuid
class WindowIconEventFilter(QObject):
def __init__(self, icon: QIcon):
super().__init__()
self._icon = icon
def eventFilter(self, obj, event):
# Early-return on event type before touching `obj`. PySide must wrap
# `obj` into a Python object (`getWrapperForQObject`) before invoking
# this Python eventFilter; on Linux/xcb that wrapping has crashed for
# short-lived QQuickItem objects in the QML hover delivery path. Even
# though the application-level filter has been replaced with per-window
# installs, this early-return is kept as a defensive backstop.
et = event.type()
if et != QEvent.Show and et != QEvent.Polish:
return False
if self._icon.isNull():
return False
try:
if (
isinstance(obj, QWidget)
and obj.isWindow()
and obj.windowIcon().isNull()
):
obj.setWindowIcon(self._icon)
except Exception:
return False
return False
def _try_install_window_icon_filter(widget):
"""Helper to install the icon filter on a widget from its constructor.
This is called before QApplication.exec() starts, so we retrieve the
installer function from `QApplication.instance()._install_window_icon_filter_on`
which is set up in the main entry point.
"""
try:
app = QApplication.instance()
if app is not None and hasattr(app, "_install_window_icon_filter_on"):
app._install_window_icon_filter_on(widget)
except Exception:
pass
SPLASH_I18N = {
"zh-CN": {
"initializing": "正在启动",
"loading_config": "加载配置",
"loading_fonts": "加载字体",
"init_monitor": "启动监视器",
"prepare_ui_env": "准备界面环境",
"init_ui": "创建界面",
"loading_plugins": "加载插件",
"loading_settings": "加载设置",
"loading_timer": "加载计时器",
"init_tray": "创建托盘图标",
"finalizing": "正在完成启动后操作",
"watermark.1": "开发中版本",
"watermark.2": "技术预览版",
"watermark.3": "Release Preview",
"watermark.4": "重新评估版本",
"dev_watermark": "{type}\n不保证最终品质 ({version}/{codename}/{uuid})",
},
"zh-TW": {
"initializing": "正在初始化",
"loading_config": "載入設定",
"loading_fonts": "載入字型",
"init_monitor": "啟動監視器",
"prepare_ui_env": "準備介面環境",
"init_ui": "建立介面",
"loading_plugins": "載入插件",
"loading_settings": "載入設定",
"loading_timer": "載入計時器",
"init_tray": "建立系統匣圖示",
"finalizing": "正在完成啓動後操作",
"watermark.1": "開發中版本",
"watermark.2": "技術預覽版",
"watermark.3": "Release Preview",
"watermark.4": "重新評估版本",
"dev_watermark": "{type}\n不保證最終品質 ({version}/{codename}/{uuid})",
},
"yue-HK": {
"initializing": "開工中",
"loading_config": "撈緊設定",
"loading_fonts": "撈緊字型",
"init_monitor": "啟動監視器",
"prepare_ui_env": "準備介面環境",
"init_ui": "砌緊介面",
"loading_plugins": "載入插件",
"loading_settings": "載入設定",
"loading_timer": "載入計時器",
"init_tray": "整緊托盤圖示",
"finalizing": "正喺完成啟動後操作",
"watermark.1": "開發中版本",
"watermark.2": "技術預覽版",
"watermark.3": "Release Preview",
"watermark.4": "重新評估版本",
"dev_watermark": "{type}\n品質唔包({version}/{codename}/{uuid})",
},
"ja-JP": {
"initializing": "初期化中",
"loading_config": "設定を読み込み中",
"loading_fonts": "フォントを読み込み中",
"init_monitor": "モニターを起動中",
"prepare_ui_env": "UI環境を準備中",
"init_ui": "UIを作成中",
"loading_plugins": "プラグインを読み込み中",
"loading_settings": "設定を読み込み中",
"loading_timer": "タイマーを読み込み中",
"init_tray": "トレイアイコンを作成中",
"finalizing": "起動後の操作を実行中",
"watermark.1": "開発中バージョン",
"watermark.2": "テクニカルプレビュー",
"watermark.3": "Release Preview",
"watermark.4": "再評価バージョン",
"dev_watermark": "{type}\n品質は保証されません ({version}/{codename}/{uuid})",
},
"en-US": {
"initializing": "Initializing",
"loading_config": "Loading config",
"loading_fonts": "Loading fonts",
"init_monitor": "Starting monitor",
"prepare_ui_env": "Preparing UI environment",
"init_ui": "Creating UI",
"loading_plugins": "Loading plugins",
"loading_settings": "Loading settings",
"loading_timer": "Loading timer",
"init_tray": "Creating system tray",
"finalizing": "Completing post-startup operations",
"watermark.1": "In-Development",
"watermark.2": "Technical Preview",
"watermark.3": "Release Preview",
"watermark.4": "Re-evaluated Version",
"dev_watermark": "{type}\nFinal quality not guaranteed ({version}/{codename}/{uuid})",
},
}
def _is_windows7():
try:
v = sys.getwindowsversion()
return v.major == 6 and v.minor == 1
except Exception:
return False
def _get_screen_refresh_rate() -> int:
try:
user32 = ctypes.windll.user32
hdc = user32.GetDC(0)
rate = ctypes.windll.gdi32.GetDeviceCaps(hdc, 116) # VREFRESH
user32.ReleaseDC(0, hdc)
return rate if rate > 1 else 60
except Exception:
return 60
def _env_flag_enabled(name: str, default: bool = False) -> bool:
raw = os.environ.get(name)
if raw is None:
return default
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
def _is_compatibility_mode_enabled() -> bool:
try:
data = _load_settings_json()
general = data.get("General", {}) if isinstance(data, dict) else {}
return (
bool(general.get("CompatibilityMode", False))
if isinstance(general, dict)
else False
)
except Exception:
return False
_VIRTUAL_GPU = None
def _is_virtual_gpu() -> bool:
global _VIRTUAL_GPU
if _VIRTUAL_GPU is not None:
return _VIRTUAL_GPU
names = []
try:
from ctypes import wintypes
class DISPLAY_DEVICEW(ctypes.Structure):
_fields_ = [
("cb", wintypes.DWORD),
("DeviceName", wintypes.WCHAR * 32),
("DeviceString", wintypes.WCHAR * 128),
("StateFlags", wintypes.DWORD),
("DeviceID", wintypes.WCHAR * 128),
("DeviceKey", wintypes.WCHAR * 128),
]
user32 = ctypes.windll.user32
i = 0
while True:
dd = DISPLAY_DEVICEW()
dd.cb = ctypes.sizeof(DISPLAY_DEVICEW)
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dd), 0):
break
for field in (dd.DeviceString, dd.DeviceID, dd.DeviceName):
try:
if field:
names.append(str(field).lower())
except Exception:
continue
i += 1
except Exception:
_VIRTUAL_GPU = False
return _VIRTUAL_GPU
hay = " ".join(names)
keywords = [
"vmware",
"virtualbox",
"vbox",
"svga",
"qxl",
"virtio",
"parallels",
"hyper-v",
"microsoft basic display",
"basic display adapter",
"remote display",
"citrix",
"xen",
"bochs",
"rdpdd",
"rdp chain",
"idriver",
"vnc",
"microsoft remote display",
]
_VIRTUAL_GPU = any(k in hay for k in keywords)
if _VIRTUAL_GPU:
print(f"[Main] Virtual GPU or headless environment detected: {hay[:200]}", flush=True)
return _VIRTUAL_GPU
def _force_directwrite_font_engine():
if sys.platform != "win32":
return
qpa = os.environ.get("QT_QPA_PLATFORM", "windows")
if ":fontengine=" not in qpa:
os.environ["QT_QPA_PLATFORM"] = qpa + ":fontengine=directwrite"
print("[Main] DirectWrite font engine forced.", flush=True)
def _apply_graphics_settings():
if sys.platform == "linux":
os.environ["QTWEBENGINE_DISABLE_SANDBOX"] = "1"
# Disable a11y to avoid QAccessibleCache crash with Qt WebEngine on
# KDE/AT-SPI. See `D:\sectl\PID7233.txt` for the SIGSEGV stack going
# through `QAccessibleCache::deleteInterface` -> QDebug stream of a
# destroyed `QAccessibleInterface*`.
os.environ.setdefault("NO_AT_BRIDGE", "1")
os.environ.setdefault("QT_ACCESSIBILITY", "0")
extra_chrome_flags = "--disable-renderer-accessibility"
cur = os.environ.get("QTWEBENGINE_CHROMIUM_FLAGS", "")
if extra_chrome_flags not in cur:
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = (
cur + " " + extra_chrome_flags
).strip()
return
if sys.platform == "win32":
_force_directwrite_font_engine()
use_software_webengine = (
_is_compatibility_mode_enabled()
or _env_flag_enabled("LUMINALIUM_WEBENGINE_SOFTWARE", False)
or _is_virtual_gpu()
)
if use_software_webengine:
os.environ["QSG_RHI_BACKEND"] = "software"
os.environ["QT_QUICK_BACKEND"] = "software"
os.environ["QT_OPENGL"] = "software"
os.environ["QTWEBENGINE_DISABLE_GPU"] = "1"
flags = [
"--disable-gpu",
"--disable-gpu-compositing",
"--disable-gpu-rasterization",
"--no-sandbox",
]
else:
# Base flags tuned for smoother rendering and lower memory usage
flags = [
"--enable-gpu-rasterization",
"--enable-zero-copy",
"--enable-features=VaapiVideoDecoder,VaapiVideoEncoder",
"--ignore-gpu-blocklist",
"--enable-hardware-overlays",
# Memory and performance optimizations
"--js-flags=--max-old-space-size=64",
"--disable-site-isolation-trials",
"--renderer-process-limit=1",
"--disable-features=Translate",
"--disable-logging",
"--enable-low-res-tiling",
"--max-decoded-image-size-bytes=10485760",
"--disk-cache-size=10485760",
"--aggressive-cache-discard",
]
# Get refresh rate for target FPS
rate = _get_screen_refresh_rate()
target_fps = rate * 3
os.environ["LUMINALIUM_TARGET_FPS"] = str(target_fps)
if sys.platform == "win32":
flags.append("--gpu-memory-buffer-budget=67108864")
# Windows 7 Fallback
if _is_windows7():
candidates = [
r"C:\Program Files\VxKex\Kex64",
r"C:\Program Files\VxKex\Kex86",
r"C:\Program Files (x86)\VxKex\Kex64",
r"C:\Program Files (x86)\VxKex\Kex86",
]
existing = os.environ.get("PATH", "")
for path in candidates:
dll_path = os.path.join(path, "KxNt.dll")
if os.path.exists(dll_path):
if path not in existing.split(os.pathsep):
os.environ["PATH"] = path + os.pathsep + existing
break
def _should_enable_system_tray() -> bool:
value = str(os.environ.get("LUMINALIUM_ENABLE_TRAY", "")).strip().lower()
if value in ("0", "false", "no", "off"):
return False
if value in ("1", "true", "yes", "on"):
return True
return is_system_tray_supported()
_SETTINGS_CACHED_MTIME = 0
_SETTINGS_CACHED_DATA = {}
def _load_settings_json(force_reload=False):
global _SETTINGS_CACHED_MTIME, _SETTINGS_CACHED_DATA
if not os.path.exists(SETTINGS_PATH):
_SETTINGS_CACHED_DATA = {}
_SETTINGS_CACHED_MTIME = 1
return {}
try:
current_mtime = os.path.getmtime(SETTINGS_PATH)
if not force_reload and _SETTINGS_CACHED_MTIME > 0 and current_mtime <= _SETTINGS_CACHED_MTIME:
return _SETTINGS_CACHED_DATA
except Exception:
pass
try:
with open(SETTINGS_PATH, "rb") as f:
raw = f.read()
except Exception:
return {}
for enc in ("utf-8", "utf-8-sig", "gbk"):
try:
text = raw.decode(enc)
except UnicodeDecodeError:
continue
try:
data = json.loads(text)
except Exception:
continue
if isinstance(data, dict):
_SETTINGS_CACHED_DATA = data
try:
_SETTINGS_CACHED_MTIME = os.path.getmtime(SETTINGS_PATH)
except Exception:
_SETTINGS_CACHED_MTIME = 1
return data
_SETTINGS_CACHED_DATA = {}
_SETTINGS_CACHED_MTIME = 1
return {}
def _create_focus_watcher(parent):
if sys.platform == "linux":
return LinuxFocusWatcher(parent)
return WindowsFocusWatcher(parent)
def _get_settings_reset_marker_path():
return os.path.join(os.path.dirname(SETTINGS_PATH), "settings.reset")
def _get_restart_marker_path():
return os.path.join(os.path.dirname(SETTINGS_PATH), "restart.marker")
def _write_restart_marker():
try:
path = _get_restart_marker_path()
data = {"pid": os.getpid(), "ts": time.time()}
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
except Exception:
pass
def _consume_restart_marker(max_age_seconds: float = 5.0) -> bool:
path = _get_restart_marker_path()
if not os.path.exists(path):
return False
data = {}
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {}
finally:
try:
os.remove(path)
except Exception:
pass
try:
ts = float(data.get("ts", 0))
except Exception:
ts = 0.0
if ts <= 0:
return False
return (time.time() - ts) <= max_age_seconds
def _get_current_language():
data = _load_settings_json()
return data.get("General", {}).get("Language", "zh-CN")
def _normalize_font_weight_value(value):
if isinstance(value, bool):
return None
if isinstance(value, QFont.Weight):
return value
if isinstance(value, float):
if not value.is_integer():
return None
value = int(value)
if isinstance(value, int):
num = value
elif isinstance(value, str):
text = value.strip()
if not text.isdigit():
return None
num = int(text)
else:
return None
if num < 100 or num > 1000 or num % 100 != 0:
return None
try:
return QFont.Weight(num)
except ValueError:
return None
def _get_font_weight_from_settings(
data, lang: str, scene: str, fallback_scene: str = ""
):
fonts = data.get("Fonts", {}) or {}
weights = fonts.get("Weights", {}) or {}
lang_weights = weights.get(lang, {}) or {}
value = _normalize_font_weight_value(lang_weights.get(scene))
if value is not None:
return value
if fallback_scene:
return _normalize_font_weight_value(lang_weights.get(fallback_scene))
return None
_BUNDLED_FONT_FILES = {
"google_sans_flex": "Google Sans Flex.ttf",
"misans_vf": "MiSansVF.ttf",
"misans_japanese_vf": "MiSansJapaneseVF.ttf",
"misans_tc_vf": "MiSansTCVF.ttf",
}
_BUNDLED_FONT_CACHE = None
def _dedupe_font_families(families):
seen = set()
ordered = []
for family in families or []:
if not isinstance(family, str):
continue
name = family.strip()
if not name or name in seen:
continue
seen.add(name)
ordered.append(name)
return ordered
def _load_bundled_font_families(root_dir: str):
global _BUNDLED_FONT_CACHE
if _BUNDLED_FONT_CACHE is not None:
return _BUNDLED_FONT_CACHE
families = {}
fonts_dir = os.path.join(root_dir, "fonts")
for key, file_name in _BUNDLED_FONT_FILES.items():
font_path = os.path.join(fonts_dir, file_name)
if not os.path.exists(font_path):
continue
try:
font_id = QFontDatabase.addApplicationFont(font_path)
if font_id == -1:
continue
loaded = QFontDatabase.applicationFontFamilies(font_id)
if loaded:
families[key] = loaded[0]
except Exception:
continue
_BUNDLED_FONT_CACHE = families
return families
def _get_default_font_family_stack(lang: str, bundled_families=None):
if bundled_families is None:
bundled_families = {}
google = bundled_families.get("google_sans_flex", "Google Sans Flex")
misans = bundled_families.get("misans_vf", "MiSans VF")
misans_jp = bundled_families.get("misans_japanese_vf", "MiSans Japanese VF")
misans_tc = bundled_families.get("misans_tc_vf", "MiSans TC VF")
if lang in ("zh-TW", "ja-JP"):
return _dedupe_font_families([google, misans_jp, misans_tc, "Segoe UI"])
if lang == "ug-CN":
return _dedupe_font_families([google, "Segoe UI", misans])
return _dedupe_font_families([google, misans, "Segoe UI"])
def _build_css_font_family_value(families):
parts = []
for family in _dedupe_font_families(families):
safe = family.replace("\\", "\\\\").replace("'", "\\'")
parts.append(f"'{safe}'")
if not parts:
parts.append("sans-serif")
else:
parts.append("sans-serif")
return ", ".join(parts)
def _apply_global_font(app: QApplication):
root_dir = os.path.dirname(os.path.abspath(__file__))
selected_family = ""
data = _load_settings_json()
lang = data.get("General", {}).get("Language", "zh-CN")
profiles = (data.get("Fonts", {}) or {}).get("Profiles", {}) or {}
v = (profiles.get(lang, {}) or {}).get("qt", "")
if isinstance(v, str) and v.strip():
selected_family = v.strip()
bundled_families = _load_bundled_font_families(root_dir)
default_families = _get_default_font_family_stack(lang, bundled_families)
if selected_family:
font = QFont(selected_family)
font.setFamilies([selected_family] + default_families)
else:
if not default_families:
return
font = QFont()
font.setStyleHint(QFont.SansSerif)
if default_families:
font.setFamily(default_families[0])
font.setFamilies(default_families)
weight = _get_font_weight_from_settings(data, lang, "qt")
if weight is not None:
font.setWeight(weight)
app.setFont(font)
def _apply_font_to_widget(widget):
try:
widget.setFont(font)
for child in widget.findChildren(QWidget):
_apply_font_to_widget(child)
except Exception:
pass
for window in app.topLevelWidgets():
if window.__class__.__name__ == "StartupSplash":
continue
_apply_font_to_widget(window)
try:
from PySide6.QtWebEngineCore import QWebEngineProfile, QWebEngineSettings
for profile in [QWebEngineProfile.defaultProfile()]:
if profile is not None:
settings = profile.settings()
if settings is not None:
family = font.family()
settings.setFontFamily(QWebEngineSettings.FontFamily.StandardFont, family)
settings.setFontFamily(QWebEngineSettings.FontFamily.SansSerifFont, family)
settings.setFontFamily(QWebEngineSettings.FontFamily.SerifFont, family)
settings.setFontFamily(QWebEngineSettings.FontFamily.FixedFont, family)
except Exception:
pass
def _load_version_info():
root_dir = os.path.dirname(os.path.abspath(__file__))
version_path = os.path.join(root_dir, "version.json")
version = ""
code_name = ""
code_name_cn = ""
if os.path.exists(version_path):
try:
with open(version_path, "r", encoding="utf-8") as f:
data = json.load(f)
version = data.get("version", "")
raw_code_name = data.get("code_name", "")
code_name_cn = data.get("code_name_CN", "")
mapping = {
"MomokaKawaragi": "Momoka Kawaragi",
"NinaIseri": "Nina Iseri",
"SubaruAwa": "Subaru Awa",
"TomoEbizuka": "Tomo Ebizuka",
}
code_name = mapping.get(raw_code_name, raw_code_name)
except Exception:
pass
return version, code_name, code_name_cn
def _format_version_display(version: str) -> str:
if not version:
return ""
parts = str(version).strip().split(".")
if len(parts) < 2:
return str(version).strip()
suffix = parts[-1]
if suffix in ["5", "6", "7"]:
patch_num = int(suffix) - 4
base = ".".join(parts[:-1])
return f"{base} Patch {patch_num}"
return str(version).strip()
def _is_dev_preview_version(version: str) -> bool:
if not version:
return False
parts = str(version).strip().split(".")
if len(parts) < 2:
return False
# 除了 .0 是正式版,其他后缀 (.1, .2, .3, .4) 都带水印
suffix = parts[-1]
return suffix in ["1", "2", "3", "4"]
def _get_user_root_dir() -> str:
return ROOT_DIR
def _ensure_user_dirs():
"""Ensure user directories exist for themes and splash screens."""
try:
root_dir = _get_user_root_dir()
# Prefer "user" but check for "users"
user_dir = os.path.join(root_dir, "user")
if not os.path.exists(user_dir) and os.path.exists(
os.path.join(root_dir, "users")
):
user_dir = os.path.join(root_dir, "users")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
for sub in ["themes", "splash"]:
path = os.path.join(user_dir, sub)
if not os.path.exists(path):
os.makedirs(path)
except Exception as e:
print(f"Error ensuring user directories: {e}")
def _resolve_user_splash_dir(splash_style: str) -> Optional[str]:
if not splash_style:
return None
root_dir = _get_user_root_dir()
# Support both "user" and "users" folder names
splash_dir = os.path.join(root_dir, "user", "splash", splash_style)
if not os.path.exists(splash_dir):
splash_dir = os.path.join(root_dir, "users", "splash", splash_style)
if os.path.exists(splash_dir):
return splash_dir
return None
def _is_valid_splash_package(splash_dir: str, splash_style: str) -> bool:
if not splash_dir or not os.path.isdir(splash_dir):
return False
manifest_path = os.path.join(splash_dir, "manifest.json")
preview_png = os.path.join(splash_dir, "preview.png")
preview_jpg = os.path.join(splash_dir, "preview.jpg")
splash_path = os.path.join(splash_dir, "splash.py")
if not os.path.exists(splash_path):
return False
if not os.path.exists(manifest_path):
return False
if not (os.path.exists(preview_png) or os.path.exists(preview_jpg)):
return False
try: