-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmain.py
More file actions
579 lines (466 loc) · 17.2 KB
/
main.py
File metadata and controls
579 lines (466 loc) · 17.2 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
import os
import sys
import time
import gc
import subprocess
import platform
import sentry_sdk
from sentry_sdk.integrations.loguru import LoguruIntegration, LoggingLevels
from posthog import Posthog
from PySide6.QtCore import Qt, QThreadPool, QRunnable, QTimer, qInstallMessageHandler
from PySide6.QtWidgets import QApplication
from loguru import logger
from app.tools.path_utils import get_app_root
from app.tools.config import (
configure_logging,
set_posthog_client,
create_sentry_before_send_filter,
get_geoip_properties_zh_cn,
)
from app.tools.settings_default import manage_settings_file
from app.tools.settings_access import readme_settings_async, get_or_create_user_id
from app.core.usage_counters import (
get_stored_draw_counts,
recompute_and_persist_draw_counts,
)
from app.tools.variable import (
APP_QUIT_ON_LAST_WINDOW_CLOSED,
VERSION,
EXIT_CODE_RESTART,
SENTRY_DSN,
SENTRY_TRACES_SAMPLE_RATE,
DEV_VERSION,
DEV_HINT_DELAY_MS,
UPDATE_CHECK_THREAD_TIMEOUT_MS,
PROCESS_EXIT_WAIT_SECONDS,
POSTHOG_API_KEY,
POSTHOG_HOST,
)
from app.core.single_instance import (
check_single_instance,
setup_local_server,
send_url_to_existing_instance,
)
from app.core.font_manager import (
configure_dpi_scale,
ensure_application_font_point_size,
)
from app.core.window_manager import WindowManager
from app.core.url_handler_setup import create_url_handler
from app.core.cs_ipc_handler_setup import create_cs_ipc_handler
from app.core.app_init import AppInitializer
from app.tools.update_utils import update_check_thread
import app.core.window_manager as wm
# ==================================================
# Sentry 相关函数
# ==================================================
def initialize_sentry():
"""初始化 Sentry 错误监控系统"""
sentry_sdk.init(
dsn=SENTRY_DSN,
integrations=[
LoguruIntegration(
level=LoggingLevels.INFO.value,
event_level=LoggingLevels.ERROR.value,
),
],
before_send=create_sentry_before_send_filter(),
release=VERSION,
send_default_pii=True,
auto_session_tracking=True,
enable_logs=True,
traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
)
user_id = get_or_create_user_id()
sentry_sdk.set_user({"id": user_id, "ip_address": "{{auto}}"})
def initialize_posthog(
total_draw_count: int | None = None,
roll_call_total: int | None = None,
lottery_total: int | None = None,
):
"""初始化 PostHog 产品分析系统"""
posthog = Posthog(
project_api_key=POSTHOG_API_KEY,
host=POSTHOG_HOST,
)
set_posthog_client(posthog)
user_id = get_or_create_user_id()
geoip_properties = get_geoip_properties_zh_cn()
if total_draw_count is None:
stored_counts = get_stored_draw_counts()
if stored_counts is not None:
total_draw_count, roll_call_total, lottery_total = stored_counts
else:
total_draw_count, roll_call_total, lottery_total = (0, 0, 0)
posthog.capture(
distinct_id=user_id,
event="app_started",
properties={
**geoip_properties,
"$set": {
"total_draw_count": total_draw_count,
"roll_call_total_count": roll_call_total,
"lottery_total_count": lottery_total,
},
},
)
def schedule_deferred_startup_tasks(window_manager: WindowManager):
"""在首个窗口可见后执行非关键启动任务。"""
if DEV_VERSION in VERSION:
return
def task():
start = time.perf_counter()
try:
totals = recompute_and_persist_draw_counts()
except Exception as e:
logger.exception(f"补算抽取统计失败,将使用已存储计数发送事件: {e}")
totals = None
try:
if totals is None:
initialize_posthog()
else:
initialize_posthog(*totals)
except Exception as e:
logger.exception(f"初始化 PostHog 失败: {e}")
finally:
elapsed = time.perf_counter() - start
logger.debug(f"启动后分析任务完成,耗时: {elapsed:.3f}s")
window_manager.register_after_first_window_shown(
lambda: QThreadPool.globalInstance().start(QRunnable.create(task))
)
# ==================================================
# 开发提示相关函数
# ==================================================
def add_dev_hint_to_window(window):
"""为窗口添加开发中提示
Args:
window: 要添加提示的窗口对象
"""
from app.view.components.dev_hint_widget import DevHintWidget
if not window.isWindow() or hasattr(window, "_dev_hint_added"):
return
allowed_window_classes = {
"GuideWindow",
"MainWindow",
"SettingsWindow",
"SimpleWindowTemplate",
}
window_class_name = window.__class__.__name__
if window_class_name not in allowed_window_classes:
return
title_bar = getattr(window, "titleBar", None)
if not title_bar:
return
dev_hint = DevHintWidget(title_bar, position_mode="titlebar_center")
dev_hint.show()
window._dev_hint_added = True
original_resize_event = window.resizeEvent
def new_resize_event(event, orig_event=original_resize_event, dh=dev_hint):
if orig_event:
orig_event(event)
dh.update_position()
window.resizeEvent = new_resize_event
dev_hint.update_position()
def add_dev_hints_to_existing_windows():
"""为所有现有窗口添加开发提示"""
for widget in QApplication.topLevelWidgets():
add_dev_hint_to_window(widget)
def setup_dev_hints(app):
"""设置开发提示功能
Args:
app: QApplication 实例
"""
QTimer.singleShot(DEV_HINT_DELAY_MS, add_dev_hints_to_existing_windows)
original_notify = app.notify
def new_notify(receiver, event):
result = original_notify(receiver, event)
if (
hasattr(event, "type")
and event.type() == event.Type.Show
and hasattr(receiver, "isWindow")
and receiver.isWindow()
and not hasattr(receiver, "_dev_hint_added")
):
add_dev_hint_to_window(receiver)
return result
app.notify = new_notify
# ==================================================
# 应用程序初始化相关函数
# ==================================================
def initialize_application():
"""初始化应用程序环境
Returns:
tuple: (program_dir, shared_memory, is_first_instance)
"""
program_dir = str(get_app_root())
if os.getcwd() != program_dir:
os.chdir(program_dir)
logger.debug(f"工作目录已设置为: {program_dir}")
logger.remove()
configure_logging()
if DEV_VERSION not in VERSION:
initialize_sentry()
wm.app_start_time = time.perf_counter()
shared_memory, is_first_instance = check_single_instance()
return program_dir, shared_memory, is_first_instance
def handle_existing_instance(shared_memory):
"""处理已存在的应用程序实例
Args:
shared_memory: 共享内存对象
"""
if len(sys.argv) > 1 and any(arg.startswith("secrandom://") for arg in sys.argv):
for arg in sys.argv[1:]:
if arg.startswith("secrandom://"):
send_url_to_existing_instance(arg)
break
logger.info("程序将退出,已有实例已激活")
shared_memory.detach()
sys.exit(0)
def setup_qt_application():
"""设置 Qt 应用程序
Returns:
tuple: (app, window_manager, url_handler, cs_ipc_handler, local_server)
"""
configure_dpi_scale()
app = QApplication(sys.argv)
handler_holder = {"previous_handler": None}
def qt_message_handler(mode, context, message):
if str(message).startswith("QFont::setPointSize: Point size <= 0"):
return
previous_handler = handler_holder.get("previous_handler")
if previous_handler is not None:
previous_handler(mode, context, message)
else:
sys.__stderr__.write(f"{message}\n")
handler_holder["previous_handler"] = qInstallMessageHandler(qt_message_handler)
ensure_application_font_point_size()
gc.enable()
try:
resident = readme_settings_async("basic_settings", "background_resident")
resident = True if resident is None else resident
app.setQuitOnLastWindowClosed(not resident)
except Exception:
app.setQuitOnLastWindowClosed(APP_QUIT_ON_LAST_WINDOW_CLOSED)
app.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings)
window_manager = WindowManager()
url_handler = create_url_handler()
cs_ipc_handler = create_cs_ipc_handler()
window_manager.set_url_handler(url_handler)
local_server = setup_local_server(
window_manager.get_main_window(), window_manager.get_float_window(), url_handler
)
return app, window_manager, url_handler, cs_ipc_handler, local_server
def initialize_app_components(window_manager):
"""初始化应用程序组件
Args:
window_manager: 窗口管理器实例
"""
app_initializer = AppInitializer(window_manager)
app_initializer.initialize()
# ==================================================
# 应用程序清理相关函数
# ==================================================
def cleanup_resources(
shared_memory, local_server, url_handler, cs_ipc_handler, update_check_thread
):
"""清理应用程序资源
Args:
shared_memory: 共享内存对象
local_server: 本地服务器对象
url_handler: URL 处理器对象
cs_ipc_handler: CS IPC 处理器对象
update_check_thread: 更新检查线程对象
"""
if cs_ipc_handler:
cs_ipc_handler.stop_ipc_client()
if url_handler and hasattr(url_handler, "url_ipc_handler"):
url_handler.url_ipc_handler.stop_ipc_server()
shared_memory.detach()
logger.debug("共享内存已释放")
if local_server:
local_server.close()
logger.debug("本地服务器已关闭")
if update_check_thread and update_check_thread.isRunning():
logger.debug("正在等待更新检查线程完成...")
update_check_thread.wait(UPDATE_CHECK_THREAD_TIMEOUT_MS)
if update_check_thread.isRunning():
logger.warning("更新检查线程超时,强行退出")
else:
logger.debug("更新检查线程已安全完成")
gc.collect()
logger.debug("垃圾回收已完成")
def restart_application(program_dir):
"""重启应用程序
Args:
program_dir: 程序目录路径
"""
logger.info("检测到重启信号,正在重启应用程序...")
filtered_args = [arg for arg in sys.argv if not arg.startswith("--")]
executable = sys.executable
if not os.path.exists(executable):
logger.critical(f"重启失败:无法找到可执行文件: {executable}")
os._exit(1)
try:
os.chdir(program_dir)
# Windows 平台使用 subprocess.Popen 启动新进程
if platform.system() == "Windows":
try:
from app.common.windows.uiaccess import (
ELEVATE_RESTART_ENV,
UIACCESS_RESTART_ENV,
UIACCESS_RESTART_ARG,
start_elevated_process,
start_uiaccess_process,
)
need_uiaccess = bool(os.environ.pop(UIACCESS_RESTART_ENV, "") == "1")
need_elevated = bool(os.environ.pop(ELEVATE_RESTART_ENV, "") == "1")
except Exception:
need_uiaccess = False
need_elevated = False
start_uiaccess_process = None
start_elevated_process = None
UIACCESS_RESTART_ARG = None
if need_elevated and start_elevated_process is not None:
cmd = [executable] + filtered_args
if need_uiaccess and UIACCESS_RESTART_ARG:
cmd.append(str(UIACCESS_RESTART_ARG))
try:
time.sleep(max(0.8, float(PROCESS_EXIT_WAIT_SECONDS or 0)))
except Exception:
time.sleep(0.8)
if bool(start_elevated_process(cmd, cwd=program_dir)):
logger.info("Windows 平台:已请求管理员启动新进程")
os._exit(0)
if need_uiaccess and start_uiaccess_process is not None:
cmd = [executable] + filtered_args
normalized = []
for arg in cmd:
try:
if (
isinstance(arg, str)
and arg
and not os.path.isabs(arg)
and not arg.startswith(("-", "/"))
and os.path.exists(os.path.join(program_dir, arg))
):
normalized.append(os.path.join(program_dir, arg))
else:
normalized.append(arg)
except Exception:
normalized.append(arg)
pid = int(start_uiaccess_process(normalized) or 0)
if pid > 0:
logger.info("Windows 平台:UIAccess 进程已启动")
os._exit(0)
startup_info = subprocess.STARTUPINFO()
startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(
[executable] + filtered_args,
cwd=program_dir,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
| subprocess.DETACHED_PROCESS,
startupinfo=startup_info,
)
logger.info("Windows 平台:新进程已启动")
os._exit(0)
else:
# Linux/Unix/macOS 平台使用 os.execl 替换当前进程
logger.info("Linux/Unix/macOS 平台:使用 execl 重启应用程序")
os.execl(executable, executable, *filtered_args)
except Exception as e:
logger.exception(f"重启应用程序失败: {e}")
os._exit(1)
def handle_exit(
exit_code,
program_dir,
shared_memory,
local_server,
url_handler,
cs_ipc_handler,
update_check_thread,
):
"""处理应用程序退出
Args:
exit_code: 退出代码
program_dir: 程序目录路径
shared_memory: 共享内存对象
local_server: 本地服务器对象
url_handler: URL 处理器对象
cs_ipc_handler: CS IPC 处理器对象
update_check_thread: 更新检查线程对象
"""
logger.debug("Qt 事件循环已结束")
cleanup_resources(
shared_memory, local_server, url_handler, cs_ipc_handler, update_check_thread
)
logger.info("程序退出流程已完成,正在结束进程")
if sys.stdout:
sys.stdout.flush()
if sys.stderr:
sys.stderr.flush()
if exit_code == EXIT_CODE_RESTART:
restart_application(program_dir)
os._exit(0)
# ==================================================
# 主程序入口
# ==================================================
def main():
"""主程序入口"""
try:
if platform.system() == "Windows":
from app.common.windows.uiaccess import (
UIACCESS_RESTART_ARG,
is_uiaccess_process,
)
if UIACCESS_RESTART_ARG in sys.argv:
try:
while UIACCESS_RESTART_ARG in sys.argv:
sys.argv.remove(UIACCESS_RESTART_ARG)
except Exception:
pass
if not bool(is_uiaccess_process()):
try:
wm.pending_uiaccess_restart_after_show = True
except Exception:
pass
except Exception:
pass
program_dir, shared_memory, is_first_instance = initialize_application()
if not is_first_instance:
handle_existing_instance(shared_memory)
manage_settings_file()
app, window_manager, url_handler, cs_ipc_handler, local_server = (
setup_qt_application()
)
if not local_server:
logger.exception("无法启动本地服务器,程序将退出")
shared_memory.detach()
sys.exit(1)
initialize_app_components(window_manager)
schedule_deferred_startup_tasks(window_manager)
if VERSION == DEV_VERSION:
setup_dev_hints(app)
try:
exit_code = app.exec()
handle_exit(
exit_code,
program_dir,
shared_memory,
local_server,
url_handler,
cs_ipc_handler,
update_check_thread,
)
except Exception as e:
logger.exception(f"程序退出过程中发生异常: {e}")
if shared_memory:
shared_memory.detach()
if local_server:
local_server.close()
if sys.stdout:
sys.stdout.flush()
if sys.stderr:
sys.stderr.flush()
os._exit(1)
if __name__ == "__main__":
main()