-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
2089 lines (1748 loc) · 72.3 KB
/
main.py
File metadata and controls
2089 lines (1748 loc) · 72.3 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 webview
import webview.http as http
import socket
import platform
import os
import sys
import subprocess
import glob
import urllib.parse
import threading
import json
import random
import re
import time
import queue
import tempfile
from datetime import datetime, timedelta
from PIL import Image, ImageDraw
import pystray
# 根据操作系统设置默认的GUI后端
system = platform.system()
if system == "Linux":
# Linux系统默认使用GTK后端
os.environ["WEBVIEW_GUI"] = "gtk"
# 修改默认端口
http.DEFAULT_HTTP_PORT = 2001
# 日志列表,用于存储所有日志
log_entries = []
# 全局窗口对象
main_window = None
widget_window = None
settings_window = None
widget_process = None
widget_ui_thread = None
widget_command_queue = queue.Queue()
widget_show_request_event = threading.Event()
widget_signal_watcher_started = False
is_main_window_hidden = False
# 调试模式开关
debug_mode = False
# 系统托盘图标对象
tray_icon = None
# 重启标记
should_restart = False
DEFAULT_SETTINGS = {
"theme": "blue",
"fontSize": 14,
"fontFamily": "HarmonyOS Sans SC",
"zoom": 100,
"opacity": 100,
"glassEffect": False,
"showSaying": True,
"showSeconds": True,
"toolbarPosition": "center",
"enableAnimation": True,
"animationSpeed": "normal",
"autoStart": False,
"startMinimized": False,
"enableReminder": True,
"reminderTime": "30分钟",
"autoSaveInterval": "5分钟",
"widgetEngine": "qt",
"debugMode": False,
}
def get_runtime_dir():
"""
获取程序运行目录(强制数据目录基于此路径):
1. 打包运行时使用可执行文件所在目录
2. 脚本运行时使用入口脚本所在目录
"""
if getattr(sys, "frozen", False):
return os.path.dirname(os.path.abspath(sys.executable))
return os.path.dirname(os.path.abspath(sys.argv[0]))
def get_main_script_path():
"""获取主脚本路径"""
if getattr(sys, "frozen", False):
return sys.executable
return sys.argv[0] if sys.argv[0] else __file__
def get_data_dir():
return os.path.join(get_runtime_dir(), "data")
def get_settings_file():
return os.path.join(get_data_dir(), "settings.json")
def get_homework_file():
return os.path.join(get_data_dir(), "homework.json")
def get_homework_template_dir():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "homeworktemple")
def get_pyside_widget_logo():
return os.path.join(get_runtime_dir(), "desktop_widgets", "widgets.png")
def get_widget_signal_file():
return os.path.join(tempfile.gettempdir(), "assignsticker_widget_show.signal")
def get_pyside_widget_script():
return os.path.join(get_runtime_dir(), "desktop_widgets", "pyside_widget.py")
def stop_pyside_widget_process():
global widget_process
# 优先停止 Qt 小组件子进程(稳定)
if widget_process:
try:
if widget_process.poll() is None:
widget_process.terminate()
try:
widget_process.wait(timeout=2)
except Exception:
widget_process.kill()
except Exception as e:
log(f"停止 PySide6 小组件进程失败: {str(e)}", "warning")
finally:
widget_process = None
# 兼容旧逻辑:尝试通知同进程 UI 关闭
try:
widget_command_queue.put_nowait("stop")
except Exception:
pass
def _start_inprocess_pyside_widget():
global widget_ui_thread
if widget_ui_thread and widget_ui_thread.is_alive():
return
def _runner():
try:
from PySide6.QtCore import QPoint, Qt, QTimer
from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QWidget,
)
except Exception as e:
log(f"加载 PySide6 失败: {str(e)}", "error")
return
class DesktopWidget(QWidget):
def __init__(self):
super().__init__()
self._drag_pos = None
self.setWindowTitle("AssignSticker Widget")
self.setFixedSize(80, 80)
self.setWindowFlags(
Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool
)
self.setAttribute(Qt.WA_TranslucentBackground, True)
root = QHBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
card = QFrame()
card.setObjectName("card")
card_layout = QHBoxLayout(card)
card_layout.setContentsMargins(12, 12, 12, 12)
card_layout.setSpacing(0)
logo_label = QLabel()
logo_label.setFixedSize(56, 56)
logo_path = get_pyside_widget_logo()
if os.path.exists(logo_path):
pix = QPixmap(logo_path).scaled(
56, 56, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation
)
logo_label.setPixmap(pix)
logo_label.setCursor(Qt.PointingHandCursor)
logo_label.mousePressEvent = (
lambda e: self._request_show_main()
if e.button() == Qt.LeftButton
else None
)
card_layout.addWidget(logo_label, 0, Qt.AlignCenter)
root.addWidget(card)
self.setStyleSheet("""
#card {
background: rgba(255, 255, 255, 0.96);
border: 1px solid rgba(88, 112, 165, 0.25);
border-radius: 18px;
}
""")
def _request_show_main(self):
widget_show_request_event.set()
self.hide()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self._drag_pos = (
event.globalPosition().toPoint()
- self.frameGeometry().topLeft()
)
event.accept()
def mouseMoveEvent(self, event):
if self._drag_pos and event.buttons() & Qt.LeftButton:
self.move(event.globalPosition().toPoint() - self._drag_pos)
event.accept()
def mouseReleaseEvent(self, event):
self._drag_pos = None
event.accept()
app = QApplication.instance()
owns_app = False
if app is None:
app = QApplication(sys.argv)
owns_app = True
app.setQuitOnLastWindowClosed(False)
widget = DesktopWidget()
screen = app.primaryScreen()
if screen:
geo = screen.availableGeometry()
x = geo.right() - widget.width() - 24
y = geo.bottom() - widget.height() - 80
widget.move(QPoint(x, y))
def _poll_commands():
try:
while True:
cmd = widget_command_queue.get_nowait()
if cmd == "show":
widget.show()
widget.raise_()
widget.activateWindow()
elif cmd == "hide":
widget.hide()
elif cmd == "stop":
widget.hide()
if owns_app:
app.quit()
return
except queue.Empty:
pass
timer = QTimer()
timer.timeout.connect(_poll_commands)
timer.start(80)
if owns_app:
app.exec()
else:
widget.show()
widget_ui_thread = threading.Thread(
target=_runner, daemon=True, name="pyside-widget-ui"
)
widget_ui_thread.start()
def start_widget_signal_watcher(api_instance):
global widget_signal_watcher_started
if widget_signal_watcher_started:
return
def _watch():
signal_file = get_widget_signal_file()
while True:
try:
if os.path.exists(signal_file):
try:
os.remove(signal_file)
except Exception:
pass
api_instance.showMainWindow()
if widget_show_request_event.is_set():
widget_show_request_event.clear()
api_instance.showMainWindow()
time.sleep(0.25)
except Exception:
time.sleep(0.5)
watcher = threading.Thread(target=_watch, daemon=True, name="widget-signal-watcher")
watcher.start()
widget_signal_watcher_started = True
DEFAULT_HOMEWORK_TEMPLATES = [
{
"filename": "workbook.yml",
"name": "练习册",
"body": {"开始页": "spinbox", "结束页": "spinbox", "备注": "rtftextbox"},
},
{"filename": "preview.yml", "name": "预习", "body": {"预习内容": "rtftextbox"}},
{
"filename": "custom.yml",
"name": "自定义作业",
"body": {"作业内容": "rtftextbox"},
},
]
ALLOWED_TEMPLATE_UIS = {"combobox", "textbox", "spinbox", "rtftextbox"}
def parse_template_yaml(content):
"""解析简易模板YML:
name: 模板名
body:
字段名: ui类型
"""
lines = (content or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
name = ""
body = {}
in_body = False
for raw_line in lines:
line = raw_line.rstrip()
if not line.strip() or line.strip().startswith("#"):
continue
stripped = line.lstrip()
indent = len(line) - len(stripped)
if indent == 0 and stripped.startswith("name:"):
name = stripped.split(":", 1)[1].strip().strip('"').strip("'")
in_body = False
continue
if indent == 0 and stripped.startswith("body:"):
in_body = True
continue
if in_body and indent >= 1:
if ":" not in stripped:
continue
key, value = stripped.split(":", 1)
field = key.strip().strip('"').strip("'")
ui = value.strip().strip('"').strip("'").lower()
if field and ui in ALLOWED_TEMPLATE_UIS:
body[field] = ui
if not name:
raise ValueError("模板缺少 name")
if not body:
raise ValueError("模板缺少有效 body 字段")
return {"name": name, "body": body}
def dump_template_yaml(template):
name = str(template.get("name", "")).strip()
body = (
template.get("body", {}) if isinstance(template.get("body", {}), dict) else {}
)
lines = [f"name: {name}", "body:"]
for field, ui in body.items():
field_name = str(field).strip()
ui_name = str(ui).strip().lower()
if not field_name or ui_name not in ALLOWED_TEMPLATE_UIS:
continue
lines.append(f" {field_name}: {ui_name}")
return "\n".join(lines) + "\n"
def _sanitize_template_filename(name):
base = re.sub(
r"[^\w\-\u4e00-\u9fff]+", "_", (name or "").strip(), flags=re.UNICODE
).strip("_")
if not base:
base = f"template_{int(datetime.now().timestamp())}"
return f"{base}.yml"
def load_homework_templates():
# 自定义模板功能已禁用,只返回默认模板
return list(DEFAULT_HOMEWORK_TEMPLATES)
def ensure_default_homework_templates():
template_dir = get_homework_template_dir()
if not os.path.exists(template_dir):
os.makedirs(template_dir)
existing = {
name.lower()
for name in os.listdir(template_dir)
if os.path.isfile(os.path.join(template_dir, name))
}
for tpl in DEFAULT_HOMEWORK_TEMPLATES:
filename = tpl["filename"]
if filename.lower() in existing:
continue
filepath = os.path.join(template_dir, filename)
with open(filepath, "w", encoding="utf-8") as f:
f.write(dump_template_yaml(tpl))
log(f"创建默认模板文件: {filepath}", "info")
def load_settings_data():
settings_file = get_settings_file()
if os.path.exists(settings_file):
try:
with open(settings_file, "r", encoding="utf-8") as f:
loaded = json.load(f)
if isinstance(loaded, dict):
return {**DEFAULT_SETTINGS, **loaded}
except Exception as e:
log(f"读取设置失败,回退默认值: {str(e)}", "warning")
return dict(DEFAULT_SETTINGS)
def save_settings_data(settings):
settings_file = get_settings_file()
with open(settings_file, "w", encoding="utf-8") as f:
json.dump(settings, f, ensure_ascii=False, indent=2)
def save_homework_data(homework_list):
homework_file = get_homework_file()
log(f"保存作业到: {homework_file}", "info")
with open(homework_file, "w", encoding="utf-8") as f:
json.dump(homework_list, f, ensure_ascii=False, indent=2)
log(f"保存成功,作业数量: {len(homework_list)}", "info")
def get_screen_size():
"""获取当前主屏幕分辨率(逻辑像素)"""
try:
import tkinter as tk
root = tk.Tk()
root.withdraw()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.destroy()
return width, height
except Exception as e:
log(f"获取屏幕分辨率失败,使用默认值: {str(e)}", "warning")
return 1920, 1080
def log(message, level="info"):
"""
记录日志
格式: 时间(日期+时间)| 类型(info/error/warning)| 内容
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"{timestamp} | {level} | {message}"
log_entries.append(log_entry)
# 同时输出到控制台
try:
print(log_entry)
except UnicodeEncodeError:
# Windows 控制台编码问题,使用 ASCII 字符
print(
f"{timestamp} | {level} | {message.encode('ascii', 'replace').decode('ascii')}"
)
# 导入通知库
try:
from plyer import notification
HAS_PLYER = True
except ImportError:
HAS_PLYER = False
log("plyer库未安装,通知功能将不可用", "warning")
def save_logs():
"""
保存日志到文件
文件名格式: 时间_次数.log
"""
if not log_entries:
return
# 创建logs目录(在程序运行目录下)
logs_dir = os.path.join(get_runtime_dir(), "logs")
if not os.path.exists(logs_dir):
os.makedirs(logs_dir)
# 获取当前日期
date_str = datetime.now().strftime("%Y%m%d")
# 查找当天的日志文件数量
pattern = os.path.join(logs_dir, f"{date_str}_*.log")
existing_files = glob.glob(pattern)
count = len(existing_files) + 1
# 生成文件名
filename = os.path.join(logs_dir, f"{date_str}_{count}.log")
# 写入日志
with open(filename, "w", encoding="utf-8") as f:
f.write("时间(日期+时间)| 类型(info/error/warning)| 内容\n")
for entry in log_entries:
f.write(entry + "\n")
try:
print(f"日志已保存到: {filename}")
except UnicodeEncodeError:
print(f"Logs saved to: {filename}")
def print_system_info():
"""打印系统信息"""
log("=" * 50, "info")
log("系统信息", "info")
log("=" * 50, "info")
log(f"操作系统: {platform.system()} {platform.release()}", "info")
log(f"处理器架构: {platform.machine()}", "info")
log(f"处理器: {platform.processor()}", "info")
log(f"Python版本: {platform.python_version()}", "info")
log(f"当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", "info")
log("=" * 50, "info")
def check_single_instance():
# 创建一个套接字用于检测程序是否已运行
try:
# 使用一个固定的端口号作为检测标志
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 9999))
return True
except socket.error:
return False
def create_tray_icon():
"""创建托盘图标"""
# 尝试加载 icon.png 文件
icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icon.png")
if os.path.exists(icon_path):
try:
image = Image.open(icon_path)
# 确保图片是RGBA模式
if image.mode != "RGBA":
image = image.convert("RGBA")
return image
except Exception as e:
log(f"加载 icon.png 失败: {str(e)},使用默认图标", "warning")
# 如果加载失败,创建默认图标
width = 64
height = 64
image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
dc = ImageDraw.Draw(image)
# 绘制渐变圆形背景
for i in range(width):
for j in range(height):
# 计算是否在圆内
if (i - width // 2) ** 2 + (j - height // 2) ** 2 <= (width // 2) ** 2:
# 渐变效果
ratio = j / height
r = int(102 + (118 - 102) * ratio)
g = int(126 + (75 - 126) * ratio)
b = int(234 + 162 * ratio)
dc.point((i, j), fill=(r, g, b, 255))
# 绘制字母 "A"
dc.text(
(width // 2 - 12, height // 2 - 18), "A", fill=(255, 255, 255, 255), font=None
)
return image
def show_crash_window(error_msg):
"""显示崩溃窗口"""
try:
encoded_error = urllib.parse.quote(error_msg)
# 创建崩溃窗口
crash_window = webview.create_window(
"AssignSticker - 程序崩溃",
f"htmls/more/crush_screen.html?error={encoded_error}",
width=500,
height=400,
resizable=False,
)
# 定义API函数供JavaScript调用
def restart_app():
"""重启应用程序"""
log("崩溃窗口: 重启程序", "info")
save_logs()
# 关闭崩溃窗口
crash_window.destroy()
# 重新启动主程序(使用--restart参数跳过多开检测)
import sys
import subprocess
subprocess.Popen([sys.executable, get_main_script_path(), "--restart"])
# 退出当前进程
sys.exit(0)
def open_url(url):
"""用默认浏览器打开URL"""
log(f"崩溃窗口: 打开URL {url}", "info")
import subprocess
subprocess.call(["open", url])
def close_window():
"""关闭崩溃窗口并退出程序"""
log("崩溃窗口: 关闭窗口", "info")
save_logs()
crash_window.destroy()
sys.exit(0)
# 暴露API给JavaScript
crash_window.expose(restart_app)
crash_window.expose(open_url)
crash_window.expose(close_window)
webview.start()
except Exception as e:
log(f"显示崩溃窗口失败: {str(e)}", "error")
def setup_tray_icon(window):
"""设置系统托盘图标"""
global tray_icon
def on_show_window(icon, item):
"""显示主窗口"""
log("托盘菜单: 显示主窗口", "info")
if window:
window.show()
window.restore()
def on_toggle_devtools(icon, item):
"""切换开发人员工具"""
log("托盘菜单: 切换开发人员工具", "info")
# 保存日志
save_logs()
# 停止托盘图标
icon.stop()
# 使用子进程重新启动程序,启用调试模式
subprocess.Popen([sys.executable, get_main_script_path(), "--with-devtools"])
# 退出当前程序
if window:
window.destroy()
sys.exit(0)
def on_trigger_crash(icon, item):
"""触发异常(测试崩溃窗口)"""
log("托盘菜单: 触发异常测试", "warning")
# 保存日志
save_logs()
# 停止托盘图标
icon.stop()
# 使用子进程显示崩溃窗口,然后退出主程序
import subprocess
error_msg = "这是从托盘菜单手动触发的测试异常,用于测试崩溃窗口功能"
encoded_error = urllib.parse.quote(error_msg)
subprocess.Popen(
[sys.executable, get_main_script_path(), "--crash-window", encoded_error]
)
# 退出主程序
if window:
window.destroy()
sys.exit(0)
def on_open_logs(icon, item):
"""打开日志文件夹"""
log("托盘菜单: 打开日志文件夹", "info")
import subprocess
logs_path = os.path.join(get_runtime_dir(), "logs")
if os.path.exists(logs_path):
subprocess.call(["open", logs_path])
log("已打开日志文件夹", "info")
else:
log("日志文件夹不存在,正在创建...", "warning")
os.makedirs(logs_path)
subprocess.call(["open", logs_path])
def on_exit(icon, item):
"""退出程序"""
log("托盘菜单: 退出程序", "info")
save_logs()
icon.stop()
if window:
window.destroy()
# 创建托盘菜单
# 检查调试模式设置
try:
settings = load_settings_data()
except:
settings = {}
# 尝试加载 devmode_loader,如果存在则强制写入 .debug_mode 文件
try:
import devmode_loader
devmode_loader.ensure_debug_mode()
except ImportError:
pass
# 检查 .debug_mode 文件,如果存在则强制开启调试模式
data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
debug_file = os.path.join(data_dir, ".debug_mode")
is_debug = settings.get("debugMode", False)
if os.path.isfile(debug_file):
is_debug = True
# 在调试模式开启时显示调试菜单
if is_debug:
menu = pystray.Menu(
pystray.MenuItem("显示主窗口", on_show_window),
pystray.Menu.SEPARATOR,
pystray.MenuItem(
"调试",
pystray.Menu(
pystray.MenuItem("开发人员工具", on_toggle_devtools),
pystray.MenuItem("触发异常(测试)", on_trigger_crash),
),
),
pystray.MenuItem("打开日志文件夹", on_open_logs),
pystray.Menu.SEPARATOR,
pystray.MenuItem("退出", on_exit),
)
else:
menu = pystray.Menu(
pystray.MenuItem("显示主窗口", on_show_window),
pystray.MenuItem("打开日志文件夹", on_open_logs),
pystray.Menu.SEPARATOR,
pystray.MenuItem("退出", on_exit),
)
# 创建托盘图标
icon = pystray.Icon("AssignSticker", create_tray_icon(), "AssignSticker", menu)
tray_icon = icon
# 在macOS上,托盘图标需要在主线程运行
# 使用run_detached方法在后台运行
icon.run_detached()
log("系统托盘图标已启动", "info")
def show_crash_window_standalone(encoded_error):
"""独立显示崩溃窗口(用于子进程模式)"""
try:
crash_window = webview.create_window(
"AssignSticker - 程序崩溃",
f"htmls/more/crush_screen.html?error={encoded_error}",
width=500,
height=400,
resizable=False,
)
def restart_app():
"""重启应用程序"""
crash_window.destroy()
script_path = get_main_script_path()
subprocess.Popen([sys.executable, script_path, "--restart"])
sys.exit(0)
def open_url(url):
"""用默认浏览器打开URL"""
subprocess.call(["open", url])
def close_window():
"""关闭崩溃窗口并退出程序"""
crash_window.destroy()
sys.exit(0)
crash_window.expose(restart_app)
crash_window.expose(open_url)
crash_window.expose(close_window)
webview.start()
except Exception as e:
print(f"显示崩溃窗口失败: {str(e)}")
def ensure_data_directory():
"""确保data目录和homework_save、homework_save_auto目录存在,不存在则创建"""
data_dir = get_data_dir()
if not os.path.exists(data_dir):
os.makedirs(data_dir)
log(f"创建data目录: {data_dir}", "info")
homework_save_dir = os.path.join(data_dir, "homework_save")
if not os.path.exists(homework_save_dir):
os.makedirs(homework_save_dir)
log(f"创建homework_save目录: {homework_save_dir}", "info")
homework_save_auto_dir = os.path.join(data_dir, "homework_save_auto")
if not os.path.exists(homework_save_auto_dir):
os.makedirs(homework_save_auto_dir)
log(f"创建homework_save_auto目录: {homework_save_auto_dir}", "info")
# 确保 settings.json 存在
settings_file = get_settings_file()
if not os.path.exists(settings_file):
with open(settings_file, "w", encoding="utf-8") as f:
json.dump(DEFAULT_SETTINGS, f, ensure_ascii=False, indent=2)
log(f"创建默认设置文件: {settings_file}", "info")
ensure_default_homework_templates()
return data_dir
def get_homework_save_dir():
"""获取作业保存目录路径"""
return os.path.join(get_data_dir(), "homework_save")
def get_homework_save_auto_dir():
"""获取自动保存作业目录路径"""
return os.path.join(get_data_dir(), "homework_save_auto")
class WidgetApi:
"""小组件窗口的API"""
def show_main_window(self):
"""显示主窗口"""
global is_main_window_hidden, widget_window, main_window
log("小组件: 显示主窗口", "info")
is_main_window_hidden = False
if main_window:
main_window.show()
main_window.restore()
# 隐藏小组件
if widget_window:
widget_window.hide()
def move_widget(self, delta_x, delta_y):
"""移动小组件窗口"""
global widget_window
if widget_window:
try:
x, y = widget_window.x, widget_window.y
widget_window.move(x + delta_x, y + delta_y)
except Exception as e:
log(f"移动小组件失败: {str(e)}", "error")
class Api:
"""暴露给前端调用的API"""
def __init__(self):
self.window = None
def _push_settings_to_main_window(self, settings):
"""将设置实时下发到主窗口"""
try:
if self.window:
payload = json.dumps(settings, ensure_ascii=False)
self.window.evaluate_js(
f"window.applySettingsFromBackend && window.applySettingsFromBackend({payload});"
)
except Exception as e:
log(f"下发设置到主窗口失败: {str(e)}", "warning")
def saveHomeworkToFile(self, homework_data):
"""
保存作业数据到JSON文件
homework_data: 作业数据对象或数组
"""
try:
save_dir = get_homework_save_dir()
# 生成文件名:时间戳_随机数.json
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
import random
random_num = random.randint(1000, 9999)
filename = f"homework_{timestamp}_{random_num}.json"
filepath = os.path.join(save_dir, filename)
# 写入JSON文件
with open(filepath, "w", encoding="utf-8") as f:
json.dump(homework_data, f, ensure_ascii=False, indent=2)
# 同步主作业文件,保证导入导出和下次启动可读取
save_homework_data(homework_data)
log(f"作业已保存到: {filepath}", "info")
return {
"success": True,
"message": f"作业已保存到: {filename}",
"filepath": filepath,
}
except Exception as e:
error_msg = str(e)
log(f"保存作业失败: {error_msg}", "error")
return {"success": False, "message": f"保存失败: {error_msg}"}
def getSavedHomeworkFiles(self):
"""获取已保存的作业文件列表"""
try:
save_dir = get_homework_save_dir()
if not os.path.exists(save_dir):
return {"success": True, "files": []}
files = []
for filename in os.listdir(save_dir):
if filename.endswith(".json"):
filepath = os.path.join(save_dir, filename)
stat = os.stat(filepath)
files.append(
{
"filename": filename,
"created": datetime.fromtimestamp(stat.st_ctime).strftime(
"%Y-%m-%d %H:%M:%S"
),
"size": stat.st_size,
}
)
# 按创建时间排序
files.sort(key=lambda x: x["created"], reverse=True)
return {"success": True, "files": files}
except Exception as e:
error_msg = str(e)
log(f"获取作业文件列表失败: {error_msg}", "error")
return {"success": False, "message": f"获取失败: {error_msg}"}
def loadHomeworkFromFile(self, filename):
"""从文件加载作业数据"""
try:
save_dir = get_homework_save_dir()
filepath = os.path.join(save_dir, filename)
# 安全检查:确保文件在保存目录内
if not filepath.startswith(save_dir):
return {"success": False, "message": "非法文件路径"}
if not os.path.exists(filepath):
return {"success": False, "message": "文件不存在"}
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
return {"success": True, "data": data}
except Exception as e:
error_msg = str(e)
log(f"加载作业文件失败: {error_msg}", "error")
return {"success": False, "message": f"加载失败: {error_msg}"}
def autoSaveHomework(self, homework_data):
"""
自动保存作业数据到JSON文件
homework_data: 作业数据对象或数组
"""
try:
save_dir = get_homework_save_auto_dir()
# 生成文件名:auto_时间戳.json
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"auto_{timestamp}.json"
filepath = os.path.join(save_dir, filename)
# 写入JSON文件
with open(filepath, "w", encoding="utf-8") as f:
json.dump(homework_data, f, ensure_ascii=False, indent=2)
# 同步主作业文件
save_homework_data(homework_data)
log(f"作业已自动保存到: {filepath}", "info")
return {
"success": True,