Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1875 lines (1566 loc) · 73.9 KB
/
Copy pathmain.py
File metadata and controls
1875 lines (1566 loc) · 73.9 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 ctypes
import json
import math
import os
import random
import subprocess
import sys
from typing import Any
import requests
from PySide6.QtCore import Qt, QUrl, QThread, QObject, Signal, Slot, QTimer, QSize, QVariantAnimation, QEasingCurve, \
QRect
from PySide6.QtGui import (
QFont, QDesktopServices, QFontDatabase, QIcon, QMovie,
QPainter, QColor, QRadialGradient, QBrush, QPixmap
)
# 添加到现有的 imports 中
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput, QVideoSink
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout,
QLabel, QPushButton, QGridLayout, QHBoxLayout, QMessageBox, QDialog,
QScrollArea, QFrame, QStackedWidget, QLineEdit, QCheckBox
)
from learn_window import LearnWindow
from review_window import ReviewWindow
from setting_window import SettingWindow
from test_window import TestWindow
from user_manager import UserManager
from vocab_model import VocabModel
# 设定当前程序版本号
CURRENT_VERSION = "v2.0.2"
CURRENT_VERSION_DATE = "202602022"
# ★★★ 资源路径获取函数 ★★★
def get_resource_path(relative_path):
if getattr(sys, 'frozen', False):
base_path = getattr(sys, '_MEIPASS', os.path.dirname(sys.executable))
else:
base_path = os.getcwd()
return os.path.join(base_path, relative_path)
# =================================================================
# 账号状态组件 (AccountPanel) - 优化逻辑版
# =================================================================
class AccountPanel(QFrame):
"""
状态区域:
Index 0: 登录入口 (只有一个登录按钮)
Index 1: 登录表单 (输入账号密码)
Index 2: 已登录状态 (头像 + 昵称)
"""
login_success = Signal(str)
def __init__(self, parent=None):
super().__init__(parent)
# 初始化用户管理器
self.user_manager = UserManager()
self.setFixedWidth(260)
self.setObjectName("AccountPanel")
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(15, 25, 15, 25)
self.main_layout.setSpacing(10)
self.stack = QStackedWidget()
# --- 1. 登录入口页 (简洁) ---
self.entry_page = QWidget()
entry_lyt = QVBoxLayout(self.entry_page)
entry_lyt.setAlignment(Qt.AlignmentFlag.AlignCenter)
entry_icon = QLabel("👤")
entry_icon.setStyleSheet("font-size: 48px; color: rgba(255,255,255,0.3); margin-bottom: 10px;")
entry_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.btn_goto_login = QPushButton("登录账户")
self.btn_goto_login.setFixedSize(160, 45)
self.btn_goto_login.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_goto_login.clicked.connect(lambda: self.stack.setCurrentIndex(1))
self.btn_goto_login.setStyleSheet("""
QPushButton {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 12px;
color: white;
font-weight: bold;
font-size: 15px;
}
QPushButton:hover { background: rgba(255, 255, 255, 0.15); border: 1px solid #3b82f6; }
""")
entry_lyt.addStretch()
entry_lyt.addWidget(entry_icon)
entry_lyt.addWidget(self.btn_goto_login)
entry_lyt.addStretch()
# 稍后添加其他页面之后,检查并恢复会话
# --- 2. 登录表单页 ---
self.form_page = QWidget()
form_lyt = QVBoxLayout(self.form_page)
form_lyt.setSpacing(12)
title = QLabel("用户登录")
title.setFont(QFont("MiSans", 15, QFont.Weight.Bold))
title.setStyleSheet("color: white; margin-bottom: 5px;")
self.user_input = QLineEdit()
self.user_input.setPlaceholderText("用户名")
self.pwd_input = QLineEdit()
self.pwd_input.setPlaceholderText("密码")
self.pwd_input.setEchoMode(QLineEdit.EchoMode.Password)
input_style = """
QLineEdit {
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 10px;
color: white;
}
QLineEdit:focus { border: 1px solid #3b82f6; background: rgba(255, 255, 255, 0.12); }
"""
self.user_input.setStyleSheet(input_style)
self.pwd_input.setStyleSheet(input_style)
# ★★★ 新增:记住密码复选框 ★★★
self.remember_pwd_checkbox = QCheckBox("记住密码")
self.remember_pwd_checkbox.setStyleSheet("""
QCheckBox {
color: rgba(255, 255, 255, 0.7);
spacing: 8px;
}
QCheckBox::indicator {
width: 16px;
height: 16px;
border-radius: 3px;
border: 1px solid rgba(255, 255, 255, 0.3);
background: rgba(255, 255, 255, 0.05);
}
QCheckBox::indicator:checked {
background: #3b82f6;
border: 1px solid #3b82f6;
}
""")
# 确认登录按钮
btn_do_login = QPushButton("确认登录")
btn_do_login.setFixedHeight(40)
btn_do_login.setCursor(Qt.CursorShape.PointingHandCursor)
btn_do_login.clicked.connect(self._handle_login)
btn_do_login.setStyleSheet("""
QPushButton { background: #2563eb; color: white; border-radius: 8px; font-weight: bold; }
QPushButton:hover { background: #3b82f6; }
""")
# ★★★ 新增:网页注册按钮 ★★★
self.btn_web_register = QPushButton("还没有账号? 网页注册")
self.btn_web_register.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_web_register.setStyleSheet("""
QPushButton {
color: #3b82f6;
background: transparent;
border: none;
font-size: 12px;
text-decoration: underline;
}
QPushButton:hover { color: #60a5fa; }
""")
# 绑定跳转逻辑(请替换为你的实际部署地址)
reg_url = "https://junpgle.github.io/LearnWord/register.html"
self.btn_web_register.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(reg_url)))
btn_back = QPushButton("返回")
btn_back.clicked.connect(lambda: self.stack.setCurrentIndex(0))
btn_back.setStyleSheet("color: #888; background: transparent; border: none; font-size: 12px;")
btn_back.setCursor(Qt.CursorShape.PointingHandCursor)
form_lyt.addWidget(title)
form_lyt.addWidget(self.user_input)
form_lyt.addWidget(self.pwd_input)
form_lyt.addWidget(self.remember_pwd_checkbox)
form_lyt.addWidget(btn_do_login)
form_lyt.addWidget(self.btn_web_register, 0, Qt.AlignmentFlag.AlignCenter) # 添加注册按钮
form_lyt.addWidget(btn_back)
form_lyt.addStretch()
# --- 3. 个人信息页 (已登录) ---
self.profile_page = QWidget()
profile_lyt = QVBoxLayout(self.profile_page)
profile_lyt.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter)
self.avatar_lbl = QLabel()
self.avatar_lbl.setFixedSize(80, 80)
self.avatar_lbl.setObjectName("UserAvatar")
self.avatar_lbl.setText("🌟")
self.avatar_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.avatar_lbl.setStyleSheet("""
#UserAvatar {
background: qradialgradient(cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(59, 130, 246, 0.4), stop:1 rgba(37, 99, 235, 0.1));
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 40px;
font-size: 40px;
}
""")
self.username_lbl = QLabel("用户名")
self.username_lbl.setFont(QFont("MiSans", 16, QFont.Weight.Bold))
self.username_lbl.setStyleSheet("color: #ffffff; margin-top: 10px;")
self.username_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_tag = QLabel("同步已开启")
self.status_tag.setStyleSheet("""
color: #4ade80; background: rgba(74, 222, 128, 0.1);
padding: 2px 10px; border-radius: 10px; font-size: 11px; margin-top: 5px;
""")
self.status_tag.setAlignment(Qt.AlignmentFlag.AlignCenter)
btn_logout = QPushButton("退出登录")
btn_logout.setFixedWidth(100)
btn_logout.setCursor(Qt.CursorShape.PointingHandCursor)
btn_logout.clicked.connect(self._handle_logout)
btn_logout.setStyleSheet("""
QPushButton { background: transparent; color: #ff4d4f; border: 1px solid rgba(255,77,79,0.3); border-radius: 6px; padding: 4px; font-size: 12px; margin-top: 30px;}
QPushButton:hover { background: rgba(255,77,79,0.1); border: 1px solid #ff4d4f; }
""")
profile_lyt.addSpacing(20)
profile_lyt.addWidget(self.avatar_lbl, 0, Qt.AlignmentFlag.AlignCenter)
profile_lyt.addWidget(self.username_lbl, 0, Qt.AlignmentFlag.AlignCenter)
profile_lyt.addWidget(self.status_tag, 0, Qt.AlignmentFlag.AlignCenter)
profile_lyt.addStretch()
profile_lyt.addWidget(btn_logout, 0, Qt.AlignmentFlag.AlignCenter)
self.stack.addWidget(self.entry_page)
self.stack.addWidget(self.form_page)
self.stack.addWidget(self.profile_page)
self.main_layout.addWidget(self.stack)
self.setStyleSheet("""
#AccountPanel {
background: rgba(20, 25, 40, 0.45);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 24px;
}
""")
# ★★★ 启动时检查并恢复会话 ★★★
self._check_and_restore_session()
def _handle_login(self):
user = self.user_input.text().strip()
pwd = self.pwd_input.text().strip()
if user and pwd:
# 真正调用 UserManager 执行登录
success, msg = self.user_manager.login(user, pwd)
if success:
# ★★★ 新增:如果勾选了"记住密码",保存凭据 ★★★
if self.remember_pwd_checkbox.isChecked():
self.user_manager.save_remember_password(user, pwd)
else:
# 未勾选则清除之前保存的凭据
self.user_manager.clear_remember_password()
self.username_lbl.setText(user)
self.stack.setCurrentIndex(2)
self.login_success.emit(user)
else:
QMessageBox.warning(self, "登录失败", msg)
else:
QMessageBox.warning(self, "提示", "请输入用户名和密码")
def _check_and_restore_session(self):
"""启动时检查并恢复会话"""
# 首先检查是否有有效的会话令牌
if self.user_manager.is_logged_in():
# 有有效的会话,直接显示已登录状态
username = self.user_manager.get_username()
if username:
self.username_lbl.setText(username)
self.stack.setCurrentIndex(2)
self.login_success.emit(username)
return
# 没有会话令牌,尝试使用记住的凭据自动登录
username, password = self.user_manager.get_remember_password()
if username and password:
print(f"[启动恢复] 发现保存的凭据,正在自动登录: {username}")
# 自动填充用户名和密码
self.user_input.setText(username)
self.pwd_input.setText(password)
self.remember_pwd_checkbox.setChecked(True)
# 延迟 500ms 后自动提交登录,确保 UI 已渲染
QTimer.singleShot(500, self._auto_login)
else:
# 无有效会话和记住的凭据,显示登录入口
self.stack.setCurrentIndex(0)
def _auto_login(self):
"""自动登录(从记住的凭据)"""
user = self.user_input.text().strip()
pwd = self.pwd_input.text().strip()
if user and pwd:
success, msg = self.user_manager.login(user, pwd)
if success:
print(f"[启动恢复] ✅ 自动登录成功: {user}")
self.username_lbl.setText(user)
self.stack.setCurrentIndex(2)
self.login_success.emit(user)
else:
print(f"[启动恢复] ❌ 自动登录失败: {msg}")
# 自动登录失败,清除保存的凭据,显示登录表单
self.user_manager.clear_remember_password()
self.user_input.setText("")
self.pwd_input.setText("")
self.remember_pwd_checkbox.setChecked(False)
self.stack.setCurrentIndex(1)
def _handle_logout(self):
"""处理退出登录"""
self.user_manager.logout()
self.user_input.setText("")
self.pwd_input.setText("")
self.stack.setCurrentIndex(0)
# =================================================================
# 梦幻背景组件 (DreamyBackground)
# =================================================================
class DreamyBackground(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.wallpaper_pixmap = None
self.current_video_frame = None # 用于存储当前视频帧
self.wallpaper_opacity = 0.0 # 透明度 (0.0 - 1.0)
self.sentence_text = ""
self.sentence_author = ""
# --- 视频播放组件 ---
self.media_player = QMediaPlayer(self)
self.audio_output = QAudioOutput(self)
self.video_sink = QVideoSink(self)
# 设置静音 & 无限循环
self.audio_output.setVolume(0)
self.audio_output.setMuted(True)
self.media_player.setAudioOutput(self.audio_output)
self.media_player.setVideoSink(self.video_sink)
self.media_player.setLoops(QMediaPlayer.Loops.Infinite)
# 当视频帧更新时,刷新界面
self.video_sink.videoFrameChanged.connect(self._on_video_frame_changed)
# --- 动画相关 ---
self.timer = QTimer(self)
self.timer.timeout.connect(self.update)
self.timer.start(33)
self.time_offset = 0.0
# 渐显动画
self.fade_anim = QVariantAnimation(self)
self.fade_anim.setDuration(1500)
self.fade_anim.setStartValue(0.0)
self.fade_anim.setEndValue(1.0)
self.fade_anim.setEasingCurve(QEasingCurve.Type.InOutQuad)
self.fade_anim.valueChanged.connect(self._update_opacity)
def set_wallpaper(self, pixmap):
"""设置静态图片壁纸"""
self.media_player.stop() # 停止视频
self.current_video_frame = None
if pixmap and not pixmap.isNull():
self.wallpaper_pixmap = pixmap
# 重新播放渐显动画
self.fade_anim.stop()
self.fade_anim.start()
def set_video(self, video_path):
"""设置视频壁纸"""
self.wallpaper_pixmap = None # 清除图片
if os.path.exists(video_path):
self.media_player.setSource(QUrl.fromLocalFile(video_path))
self.media_player.play()
# 视频也播放渐显动画
self.fade_anim.stop()
self.fade_anim.start()
def set_sentence(self, text, author=""):
self.sentence_text = text
self.sentence_author = author
self.update()
@Slot(object)
def _update_opacity(self, value):
self.wallpaper_opacity = float(value)
self.update()
@Slot()
def _on_video_frame_changed(self):
# 获取当前视频帧并转换为 QImage
frame = self.video_sink.videoFrame()
if frame.isValid():
self.current_video_frame = frame.toImage()
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
w = self.width()
h = self.height()
# --- 1. 绘制底层梦幻光晕 ---
painter.fillRect(self.rect(), QColor(10, 12, 18))
self.time_offset += 0.02
def draw_halo(cx, cy, radius, color, alpha_base):
breath = (math.sin(self.time_offset) + 1) / 2
current_alpha = int(alpha_base + 30 * breath)
gradient = QRadialGradient(cx, cy, radius)
c = QColor(color)
c.setAlpha(current_alpha)
gradient.setColorAt(0, c)
c_end = QColor(color)
c_end.setAlpha(0)
gradient.setColorAt(1, c_end)
painter.setBrush(QBrush(gradient))
painter.setPen(Qt.PenStyle.NoPen)
painter.drawRect(self.rect())
x1 = w * 0.2 + math.sin(self.time_offset * 0.5) * 50
y1 = h * 0.3 + math.cos(self.time_offset * 0.3) * 30
draw_halo(x1, y1, w * 0.8, QColor(0, 160, 255), 30)
# --- 2. 绘制壁纸 OR 视频 (带透明度) ---
painter.setOpacity(self.wallpaper_opacity)
target_image = None
# 优先判断视频帧
if self.current_video_frame and not self.current_video_frame.isNull():
target_image = self.current_video_frame
elif self.wallpaper_pixmap and not self.wallpaper_pixmap.isNull():
target_image = self.wallpaper_pixmap
if target_image:
# 无论是 QImage (视频) 还是 QPixmap (图片),绘制逻辑是一样的
# 计算保持比例填满窗口 (Cover模式)
img_w = target_image.width()
img_h = target_image.height()
# 防止除以0
if img_w > 0 and img_h > 0:
scale = max(w / img_w, h / img_h)
new_w = int(img_w * scale)
new_h = int(img_h * scale)
# 居中裁剪绘制
x = (w - new_w) // 2
y = (h - new_h) // 2
# drawImage 支持 QImage, drawPixmap 支持 QPixmap
if isinstance(target_image, QPixmap):
painter.drawPixmap(QRect(x, y, new_w, new_h), target_image)
else:
painter.drawImage(QRect(x, y, new_w, new_h), target_image)
# 绘制黑色遮罩 (让文字更清晰)
painter.fillRect(self.rect(), QColor(0, 0, 0, int(90 * self.wallpaper_opacity)))
painter.setOpacity(1.0)
# --- 3. 绘制底部句子 (保持不变) ---
if self.sentence_text:
font = QFont("MiSans", 12)
font.setItalic(True)
painter.setFont(font)
painter.setPen(QColor(240, 240, 240, 200))
text_str = f"“ {self.sentence_text} ”"
if self.sentence_author:
text_str += f"\n— {self.sentence_author}"
rect = QRect(40, h - 100, w - 80, 80)
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap, text_str)
# =================================================================
# 壁纸加载器 (WallpaperLoader) - 修改版
# =================================================================
class WallpaperLoader(QObject):
finished = Signal(str)
def run_load(self):
appdata = os.getenv('APPDATA')
base_dir = os.path.join(appdata, 'LearnWord')
cache_list_file = os.path.join(base_dir, 'data', 'wallpaper_list_cache.json')
save_dir = os.path.join(base_dir, 'backgrounds')
for d in [os.path.dirname(cache_list_file), save_dir]:
if not os.path.exists(d):
os.makedirs(d, exist_ok=True)
download_url = None
filename = None
# 新增一个标志位:是否强制覆盖本地文件
# 默认不覆盖 (False),只有特定情况(如固定壁纸)才改为 True
should_overwrite = False
# 1. 尝试获取固定壁纸配置 (Manifest)
try:
manifest_url = "https://raw.githubusercontent.com/Junpgle/LearnWord/master/wallpaper_manifest.json"
headers = {"User-Agent": "LearnWord-Client/1.0"}
resp = requests.get(manifest_url, headers=headers, timeout=5)
if resp.status_code == 200:
data = resp.json()
fixed = data.get("fixed_wallpaper", {})
# 如果启用固定壁纸,我们假设这是必须要展示的最新内容
# 所以将 should_overwrite 设为 True
if fixed.get("active") is True:
download_url = fixed.get("url")
filename = fixed.get("name")
should_overwrite = True # <--- 关键修改:标记为强制覆盖
if not filename and download_url:
filename = download_url.split('/')[-1]
# 确保后缀合法
if not filename.lower().endswith(('.jpg', '.jpeg', '.png', '.mp4', '.webm', '.mkv')):
filename = "fixed_wallpaper.jpg"
except Exception:
pass
# 2. 如果没有固定壁纸,则从 GitHub 列表随机获取 (保持原有缓存逻辑)
if not download_url:
try:
# 注意:这里我们不需要 should_overwrite = True,随机图片依然优先用缓存
api_url = "https://api.github.com/repos/Junpgle/LearnWord/contents/background"
headers = {"User-Agent": "LearnWord-Client/1.0", "Accept": "application/vnd.github.v3+json"}
resp = requests.get(api_url, headers=headers, timeout=5)
if resp.status_code == 200:
files = resp.json()
images = [f for f in files if
isinstance(f, dict) and f.get('type') == 'file' and f.get('name', '').lower().endswith(
('.jpg', '.jpeg', '.png', '.mp4', '.webm', '.mkv'))]
if images:
try:
with open(cache_list_file, 'w', encoding='utf-8') as f:
json.dump(images, f, ensure_ascii=False)
except Exception:
pass
target = random.choice(images)
download_url = target.get('download_url')
filename = target.get('name')
except Exception:
pass
# 3. 如果 API 失败,尝试读取本地缓存列表
if not download_url and os.path.exists(cache_list_file):
try:
with open(cache_list_file, 'r', encoding='utf-8') as f:
cached_images = json.load(f)
if cached_images:
target = random.choice(cached_images)
download_url = target.get('download_url')
filename = target.get('name')
except Exception:
pass
# 4. 如果还是没有,使用兜底随机
if not download_url:
idx = random.randint(1, 5)
filename = f"{idx}.jpg"
download_url = f"https://raw.githubusercontent.com/Junpgle/LearnWord/master/background/{filename}"
# 兜底情况通常也建议覆盖一下,防止兜底图片更新了客户端没变
# 但为了保险起见,这里也可以设为 True,或者保持 False
should_overwrite = False
# ★★ 核心下载逻辑修改 ★★★
if download_url and filename:
save_path = os.path.join(save_dir, filename)
try:
# 判断条件修改:
# 如果文件不存在 (not exists) 或者 标记为强制覆盖 (should_overwrite)
# 都要执行下载
if not os.path.exists(save_path) or should_overwrite:
dl_headers = {"User-Agent": "LearnWord-Client/1.0"}
img_resp = requests.get(download_url, headers=dl_headers, timeout=15)
if img_resp.status_code == 200:
with open(save_path, 'wb') as f:
f.write(img_resp.content)
self.finished.emit(save_path)
return
except Exception:
pass
# 如果下载失败(或者不需要下载),但本地文件存在,就用本地的
if os.path.exists(save_path):
self.finished.emit(save_path)
return
self.finished.emit("")
# =================================================================
# 句子加载器 (SentenceLoader)
# =================================================================
class SentenceLoader(QObject):
finished = Signal(str, str)
def run_load(self):
url = "https://raw.githubusercontent.com/Junpgle/LearnWord/master/sentence_manifest.json"
text = "Stay hungry, stay foolish."
author = "Steve Jobs"
try:
headers = {"User-Agent": "LearnWord-Client/1.0"}
resp = requests.get(url, headers=headers, timeout=5)
if resp.status_code == 200:
data = resp.json()
fixed = data.get("fixed_sentence", {})
if fixed.get("active") is True:
text = fixed.get("text", text)
author = fixed.get("author", author)
else:
pool = data.get("pool", [])
if pool:
item = random.choice(pool)
text = item.get("text", text)
author = item.get("author", "")
except Exception:
pass
self.finished.emit(text, author)
# =================================================================
# UpdateChecker 和 AnnouncementLoader
# =================================================================
class UpdateChecker(QObject):
signal_result = Signal(bool, object)
def run_check(self):
manifest_url = "https://raw.githubusercontent.com/Junpgle/LearnWord/refs/heads/master/update_manifest.json"
try:
headers = {"User-Agent": "LearnWord-Client/1.0"}
response = requests.get(manifest_url, headers=headers, timeout=5)
response.raise_for_status()
self.signal_result.emit(True, response.json())
except Exception as e:
self.signal_result.emit(False, str(e))
class AnnouncementLoader(QObject):
signal_result = Signal(bool, object)
def run_load(self):
url = "https://raw.githubusercontent.com/Junpgle/LearnWord/refs/heads/master/announcement.json"
try:
headers = {"User-Agent": "LearnWord-Client/1.0"}
response = requests.get(url, headers=headers, timeout=5)
response.raise_for_status()
self.signal_result.emit(True, response.json())
except Exception as e:
self.signal_result.emit(False, str(e))
# =================================================================
# ★★★ 公共基类: FramelessDialog ★★★
# =================================================================
class FramelessDialog(QDialog):
"""
无边框对话框基类:
1. 自动去除系统边框
2. 提供透明背景支持
3. 封装了拖动逻辑
4. 提供一个内部容器 bg_widget 用于放置内容
"""
def __init__(self, parent=None):
super().__init__(parent)
# 核心修复:必须显式添加 Qt.WindowType.Dialog,否则有父对象时会被视为子控件
self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.drag_pos = None
# 主布局:包含背景容器
self.main_layout = QVBoxLayout(self)
self.main_layout.setContentsMargins(0, 0, 0, 0)
# 背景容器:实际显示圆角和背景色的部分
self.bg_widget = QWidget(self)
self.bg_widget.setObjectName("DialogBg")
self.main_layout.addWidget(self.bg_widget)
# 内容布局:子类将控件添加到这里
self.content_layout = QVBoxLayout(self.bg_widget)
self.content_layout.setContentsMargins(20, 20, 20, 20)
self.content_layout.setSpacing(15)
def setup_title_bar(self, title_text):
"""为对话框添加统一风格的标题栏"""
top_bar = QHBoxLayout()
title_label = QLabel(title_text)
title_label.setFont(QFont("MiSans", 16, QFont.Weight.Bold))
title_label.setStyleSheet("color: #eeeeee; background: transparent;")
close_btn = QPushButton("×")
close_btn.setFixedSize(30, 30)
close_btn.setCursor(Qt.CursorShape.PointingHandCursor)
close_btn.clicked.connect(self.reject)
close_btn.setStyleSheet("""
QPushButton { background: transparent; color: #888; border-radius: 15px; font-size: 20px; font-weight: bold; padding-bottom: 3px;}
QPushButton:hover { background-color: #e81123; color: white; }
""")
top_bar.addWidget(title_label)
top_bar.addStretch()
top_bar.addWidget(close_btn)
# 插入到布局最前面
self.content_layout.insertLayout(0, top_bar)
# --- 拖动逻辑 ---
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.drag_pos = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() & Qt.MouseButton.LeftButton and self.drag_pos:
self.move(event.globalPosition().toPoint() - self.drag_pos)
event.accept()
# --- 修复自动居中逻辑 ---
def showEvent(self, event):
super().showEvent(event)
# 确保使用父窗口的几何信息进行居中
if self.parent() and isinstance(self.parent(), QWidget):
# 获取父窗口(通常是主窗口)的几何形状
parent_geo = self.parent().window().geometry()
self_geo = self.geometry()
# 计算中心点 (屏幕坐标系)
x = parent_geo.x() + (parent_geo.width() - self_geo.width()) // 2
y = parent_geo.y() + (parent_geo.height() - self_geo.height()) // 2
self.move(x, y)
else:
# 如果没有父窗口,则居中于屏幕
screen = QApplication.primaryScreen().availableGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
# --- 统一样式 ---
def set_dark_theme(self):
"""应用通用的深色主题样式"""
self.setStyleSheet("""
#DialogBg {
background-color: #1a1a1a;
border: 1px solid #333333;
border-radius: 12px;
}
QLabel { color: #dddddd; background: transparent; }
QPushButton { font-family: "MiSans"; }
/* 滚动条美化 */
QScrollBar:vertical { background: #222; width: 8px; border-radius: 4px; margin: 0px;}
QScrollBar::handle:vertical { background: #555; border-radius: 4px; min-height: 20px; }
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0px; }
QScrollArea { border: none; background: transparent; }
""")
# =================================================================
# 拟真飘落撒花特效 (ConfettiWidget - Fluttering Style)
# =================================================================
class ConfettiParticle:
"""物理粒子对象"""
def __init__(self, w, h, pixmaps):
# 1. 初始位置:从屏幕上方中心区域喷发,范围稍微宽一点
self.x = random.randint(w // 5, w * 4 // 5)
self.y = random.randint(h // 3, h // 2) # 起始点放低一点,让喷射更明显
# 2. 初始速度:模拟“爆炸式”喷射
# 水平速度:向四周炸开,范围大一点 (-10 到 10)
self.vx = random.uniform(-10, 30)
# 垂直速度:猛烈向上喷射 (-15 到 -25)
self.vy = random.uniform(-25, -10)
# 3. 物理属性:每个粒子的“轻重”不一样
self.gravity = random.uniform(0.15, 0.3) # 重力较小,模拟纸片
self.max_fall_speed = random.uniform(3, 10) # 终端速度:限制最大下落速度,防止像石头一样砸下来
self.sway_speed = random.uniform(0.05, 0.07) # 左右摇摆的频率
self.sway_offset = random.uniform(0, math.pi * 2) # 摇摆相位
# 4. 旋转
self.rotation = random.randint(0, 360)
self.rotation_speed = random.uniform(-3, 3)
# 5. 图片
self.pixmap = random.choice(pixmaps)
# 随机缩放
scale = random.uniform(0.3, 1.5)
if scale != 1.0:
self.pixmap = self.pixmap.scaled(
QSize(int(self.pixmap.width() * scale), int(self.pixmap.height() * scale)),
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation
)
self.half_w = self.pixmap.width() / 2
self.half_h = self.pixmap.height() / 2
# 标记是否已经进入“飘落阶段”
self.is_falling = False
class ConfettiWidget(QWidget):
"""全屏撒花覆盖层 (拟真飘落版)"""
def __init__(self, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
if parent:
self.resize(parent.size())
self.time_step = 0 # 用于计算正弦波
# 预渲染 Emoji
self.cached_pixmaps = self._cache_emojis(['🎉', '🎊', '✨', '🎁', '🎈'], size=48)
# 生成 80 个粒子
self.particles = [ConfettiParticle(self.width(), self.height(), self.cached_pixmaps) for _ in range(20)]
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_physics)
self.timer.start(16)
def _cache_emojis(self, emojis, size):
pixmaps = []
font = QFont("Segoe UI Emoji", size)
if not font.exactMatch():
font = QFont("Apple Color Emoji", size)
font.setBold(True)
for char in emojis:
pix = QPixmap(size * 2, size * 2)
pix.fill(Qt.GlobalColor.transparent)
painter = QPainter(pix)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
painter.setFont(font)
painter.drawText(pix.rect(), Qt.AlignmentFlag.AlignCenter, char)
painter.end()
pixmaps.append(pix)
return pixmaps
def update_physics(self):
active_particles = False
screen_h = self.height()
self.time_step += 1
for p in self.particles:
# --- 阶段1:向上喷射 ---
if p.vy < 0:
# 只有在上升时才受较强的重力减速
p.vy += p.gravity * 2
p.x += p.vx
p.y += p.vy
# 空气阻力:水平速度衰减很快
p.vx *= 0.95
# --- 阶段2:向下飘落 ---
else:
p.is_falling = True
# 垂直方向:加速下落,但不能超过最大飘落速度 (终端速度)
if p.vy < p.max_fall_speed:
p.vy += p.gravity
# 水平方向:加入正弦波摇摆 (Fluttering)
# sway_amount 决定了摇摆的幅度
sway_amount = math.sin(self.time_step * p.sway_speed + p.sway_offset) * 2
p.x += sway_amount
p.y += p.vy
# 旋转永远都在发生
p.rotation += p.rotation_speed
# 边界检查
if p.y < screen_h + 100:
active_particles = True
if not active_particles:
self.timer.stop()
self.deleteLater()
else:
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
screen_h = self.height()
for p in self.particles:
if p.y < -100 or p.y > screen_h + 100: continue
painter.save()
painter.translate(p.x, p.y)
painter.rotate(p.rotation)
painter.drawPixmap(int(-p.half_w), int(-p.half_h), p.pixmap)
painter.restore()
class AnnouncementDialog(FramelessDialog):
def __init__(self, data, current_version, parent=None):
super().__init__(parent)
self.setFixedSize(600, 480)
self.set_dark_theme()
self.all_announcements = data.get("announcements", [])
self.current_ver = current_version
self.current_list = [a for a in self.all_announcements if a.get("version") == self.current_ver]
self.history_list = [a for a in self.all_announcements if a.get("version") != self.current_ver]
self.is_showing_history = False
self.setup_ui()
self.render_content()
# ★★★ 新增:如果是显示最新版本,启动撒花特效 ★★★
# 只有当 current_list 不为空(即有新版本公告)时才撒花
if self.current_list:
self.confetti = ConfettiWidget(self)
self.confetti.show()
self.confetti.raise_() # 确保显示在最上层
def setup_ui(self):
# 1. 标题栏
self.setup_title_bar("系统公告")
# 2. 顶部 Header
top_container = QWidget()
top_layout = QHBoxLayout(top_container)
top_layout.setContentsMargins(30, 5, 30, 5)
top_layout.setSpacing(15)
self.icon_label = QLabel()
self.icon_label.setFixedSize(48, 48)
self.icon_label.setScaledContents(True)
gif_path = get_resource_path(os.path.join("Animation", "Announcement.gif"))
if not os.path.exists(gif_path):
gif_path = os.path.join(os.getcwd(), "Animation", "Announcement.gif")
if os.path.exists(gif_path):
self.movie = QMovie(gif_path)
self.movie.setScaledSize(QSize(48, 48))
self.icon_label.setMovie(self.movie)
self.movie.start()
else:
self.icon_label.setText("📢")
self.icon_label.setStyleSheet("font-size: 36px;")
title_box = QVBoxLayout()
title_box.setSpacing(2)
title_box.setAlignment(Qt.AlignmentFlag.AlignVCenter)
self.lbl_main_title = QLabel("最新动态")
self.lbl_main_title.setFont(QFont("MiSans", 22, QFont.Weight.Bold))
self.lbl_main_title.setStyleSheet("color: white;")
self.lbl_sub_title = QLabel(f"Version {self.current_ver}")
self.lbl_sub_title.setStyleSheet("color: #3b82f6; font-weight: bold; font-size: 15px;")
title_box.addWidget(self.lbl_main_title)
title_box.addWidget(self.lbl_sub_title)
top_layout.addWidget(self.icon_label)
top_layout.addLayout(title_box)
top_layout.addStretch()
self.content_layout.addWidget(top_container)
# 3. 滚动文本区
self.scroll_area = QScrollArea()