-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1208 lines (1041 loc) · 50.2 KB
/
main.py
File metadata and controls
1208 lines (1041 loc) · 50.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
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
# -*- coding: utf-8 -*-
import sys
import random
import os
import ctypes
import msvcrt
import traceback
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QCursor, QFontMetrics, QKeySequence, QFontDatabase, QFont
from PyQt5.QtCore import Qt, QTimer, QCoreApplication, QFile, QThreadPool, pyqtSignal, QRunnable, QObject, QCoreApplication
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QScroller, QShortcut, QSizePolicy
from Ui import *
from modules import *
from window import *
from window.Setting import SettingsWindow
# import debugpy
# debugpy.listen(("0.0.0.0", 5678))
# debugpy.wait_for_client() # 等待调试器连接
# 初始化全局应用状态
state = app_state
# 初始化 AppData 路径
state.appdata_path = os.path.join(os.getenv('APPDATA'), 'CMXZ', 'CRP')
os.makedirs(state.appdata_path, exist_ok=True)
os.makedirs(os.path.join(state.appdata_path, 'history'), exist_ok=True)
os.makedirs(os.path.join(state.appdata_path, 'name'), exist_ok=True)
os.makedirs(os.path.join(state.appdata_path, 'dmmusic'), exist_ok=True)
# 初始化日志
init_log(os.path.join(state.appdata_path, 'log.txt'))
# init i18n with config language if present
try:
config_path = os.path.join(state.appdata_path, 'config.ini')
_config_boot = read_config_file(config_path)
state.language_value = _config_boot.get('language', 'zh_CN')
init_gettext(state.language_value)
except Exception as e:
try:
init_gettext('zh_CN')
except Exception as e2:
user32 = ctypes.windll.user32
user32.MessageBoxW(None, f"程序启动时遇到严重错误:{e2}", "Warning!", 0x30)
# 设置默认名单(需要翻译)
state.default_name_list = _("默认名单")
class MainWindow(QtWidgets.QMainWindow, Ui_CRPmain):
def __init__(self):
super().__init__()
self.setupUi(self) # 初始化UI
# 设置窗口标志
self.setWindowFlag(Qt.FramelessWindowHint)
# 设置半透明背景
self.setAttribute(Qt.WA_TranslucentBackground)
# 鼠标拖动标志
self.m_flag = False
self.resize_flag = False
self.font_m = None
self.setMinimumSize(QtCore.QSize(780, 445))
self.spinBox.setValue(1)
self.label_7.setText("")
self.progressBar.hide()
self.commandLinkButton.hide()
# 加载翻译
self.apply_translations()
# 添加横线遮罩的 FrameWithLines
self.linemask = FrameWithLines(self)
self.linemask.setObjectName("linemask")
self.gridLayout.addWidget(self.linemask, 0, 0, 1, 1)
self.linemask.lower()
self.linemask.setSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.setCentralWidget(self.frame)
# 定义空格快捷键
self.shortcut = QShortcut(QKeySequence(Qt.Key_Space), self)
# 连接按钮
self.pushButton_2.clicked.connect(self.start)
self.pushButton_4.clicked.connect(self.run_settings)
self.pushButton_5.clicked.connect(self.small_mode)
self.pushButton.clicked.connect(lambda: self.mini(1))
self.commandLinkButton.clicked.connect(
lambda: self.restoresize("init"))
# 启用触摸手势滚动
for lw in (self.listWidget, self.listWidget_2):
scroller = QScroller.scroller(lw)
scroller.grabGesture(
lw.viewport(), QScroller.LeftMouseButtonGesture)
# 启动时执行的函数
self.read_config()
self.read_name_list(2)
self.set_bgimg()
self.check_new_version()
self.change_space(1)
self.init_font()
self.restoresize()
self.small_Window = smallWindow(self)
if state.need_move_config == 1:
self.if_need_move_config()
self.timer = None
if state.first_use == 0:
self.first_use_introduce()
def init_font(self):
font_path = ":/fonts/font.ttf"
# 读取字体文件
font_file = QFile(font_path)
if not font_file.open(QFile.ReadOnly):
log_print("字体文件打开失败")
return
data = font_file.readAll()
font_file.close()
# 直接从内存加载字体,无需写入临时文件
font_id = QFontDatabase.addApplicationFontFromData(data)
if font_id != -1: # 确保字体加载成功
state.cust_font = QFontDatabase.applicationFontFamilies(font_id)[0]
self.font_m = QFont(state.cust_font, 52)
self.label_3.setFont(self.font_m)
self.pushButton_2.setFont(self.font_m)
self.pushButton_5.setFont(self.font_m)
else:
log_print("字体加载失败")
self.label_3.setText(state.title_text)
def apply_translations(self):
"""Update runtime UI texts to the current language."""
try:
self.setWindowTitle(QCoreApplication.translate(
"MainWindow", _("沉梦课堂点名器 %s") % state.dmversion))
self.pushButton_2.setText(_(" 开始"))
self.pushButton_5.setText(_(" 小窗模式"))
self.label_5.setText(_("当前名单:"))
self.label_4.setText(_("抽取人数:"))
self.tabWidget.setTabText(
self.tabWidget.indexOf(self.tab), _("历史记录"))
self.tabWidget.setTabText(
self.tabWidget.indexOf(self.tab_2), _("名单列表"))
# Update background label if needed
if state.bgimg == 2:
self.label_6.setText(_("自定义背景"))
# Update title text from config
if state.title_text:
self.label_3.setText(state.title_text)
except Exception as e:
log_print(f"apply_translations error: {e}")
def mouseMoveEvent(self, event):
# 获取鼠标相对于窗口的坐标
pos = event.pos()
rect = self.rect() # 窗口的区域
# 判断是否在右下角区域
if (rect.width() - pos.x() <= 35 and
rect.height() - pos.y() <= 35):
self.setCursor(QCursor(Qt.SizeFDiagCursor)) # 设置调整大小的鼠标指针
else:
self.setCursor(QCursor(Qt.ArrowCursor)) # 恢复默认光标
if self.resize_flag:
# 调整窗口大小
diff = event.globalPos() - self.m_Position
new_width = self.width() + diff.x()
new_height = self.height() + diff.y()
self.resize(
max(new_width, self.minimumWidth()),
max(new_height, self.minimumHeight())
)
self.m_Position = event.globalPos()
elif self.m_flag:
# 拖动窗口
self.move(event.globalPos() - self.m_Position)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
if (self.width() - event.pos().x() <= 35 and
self.height() - event.pos().y() <= 35):
self.resize_flag = True
self.m_Position = event.globalPos()
elif event.pos().y() <= self.height() // 2:
self.m_flag = True
self.m_Position = event.globalPos() - self.pos()
def mouseReleaseEvent(self, event):
self.m_flag = False
self.resize_flag = False
self.setCursor(QCursor(Qt.ArrowCursor)) # 恢复光标
def resizeEvent(self, event):
super().resizeEvent(event)
screen_geometry = QApplication.primaryScreen().availableGeometry()
# 检查窗口尺寸
if self.width() > screen_geometry.width() * 0.9 or self.height() > screen_geometry.height() * 0.9:
self.commandLinkButton.show() # 显示按钮
if self.width() > screen_geometry.width() or self.height() > screen_geometry.height():
self.resize(screen_geometry.width(), screen_geometry.height())
else:
self.commandLinkButton.hide() # 隐藏按钮
if self.width() > 905 or self.height() > 495:
state.windows_move_flag = True
else:
state.windows_move_flag = False
# 保存窗口尺寸
state.saved_size = f"{self.width()},{self.height()}"
self.update_config("saved_size", state.saved_size, "w")
def set_bgimg(self):
self.label_6.setText("")
if state.bgimg == 2: # 自定义背景
folder_path = os.path.join(state.appdata_path, 'images')
os.makedirs(folder_path, exist_ok=True)
file_list = os.listdir(folder_path)
if not file_list: # 文件夹为空, 就约战壁纸
log_print("要使用自定义背景功能,请在 %s 中放入图片文件" % folder_path)
self.frame.setStyleSheet("#frame {\n"
"border-image: url(:/images/(1070).webp);"
"border-radius: 28px;"
"}")
return
self.label_6.setText(_("自定义背景"))
if state.bind_picture != "None" and ":" in state.bind_picture and state.selected_file:
# 构建绑定字典
items = [i for i in state.bind_picture.replace(
"None", "").split(",") if ":" in i]
state.bind_picture_dict = dict(
item.split(":", 1) for item in items)
pic_name = state.bind_picture_dict.get(
state.selected_file, None)
if pic_name is not None:
bind_path = os.path.join(folder_path, pic_name)
bind_path = bind_path.replace("\\", "/")
if os.path.exists(bind_path):
self.label_6.setText(_("自定义绑定背景"))
self.frame.setStyleSheet("#frame {\n"
f"border-image: url('{bind_path}');"
"border-radius: 28px;"
"}")
return
random_file = random.choice(file_list)
log_print(random_file)
file_path = os.path.join(folder_path, random_file)
file_path = file_path.replace("\\", "/") # 替换反斜杠为正斜杠
self.frame.setStyleSheet("#frame {\n"
f"border-image: url('{file_path}');"
"border-radius: 28px;"
"}")
elif state.bgimg == 1 or state.bgimg == 0: # eva背景
self.frame.setStyleSheet("#frame {\n"
"border-image: url(:/images/eva.webp);"
"border-radius: 28px;"
"}")
elif state.bgimg == 3: # 纯色背景
self.frame.setStyleSheet("#frame {\n"
"background-color: rgba(42, 45, 47, 0.92);\n"
"border-radius: 28px;"
"}")
def small_mode(self):
# 保留对子窗口实例的引用
if state.small_window_flag is None:
self.showMinimized()
state.small_window_flag = self.small_Window.run_small_window()
def run_settings(self, target_tab=None):
if state.settings_flag is None:
self.settings_window = SettingsWindow(
self, target_tab, self.small_Window)
state.settings_flag = self.settings_window.run_settings_window()
else:
if hasattr(self, "settings_window"):
self.settings_window.activateWindow()
def closeEvent(self, event):
# 关闭其他窗口的代码
try:
for widget in QApplication.topLevelWidgets():
if isinstance(widget, QWidget) and widget != self:
widget.close()
except:
pass
event.accept()
def mini(self, mode):
if mode == 1:
self.showMinimized()
elif mode == 2:
self.showNormal()
# 功能实现代码
def restoresize(self, mode=None):
x, y = state.saved_size.split(",") if state.saved_size else (905, 495)
if mode == "init":
x, y = 905, 495
self.resize(int(x), int(y))
screen_geometry = QApplication.primaryScreen().availableGeometry()
x = (screen_geometry.width() - self.width()) // 2
y = (screen_geometry.height() - self.height()) // 2
self.move(x, y)
def make_name_list(self):
for i in range(1, 21):
yield str(i).rjust(2, "0")
def init_name(self, name_list):
state.name_path = os.path.join(
state.appdata_path, "name", f"{state.default_name_list}.txt") # 打开文件并写入内容
with open(state.name_path, "w", encoding="utf8") as f:
for i in name_list:
f.write(i)
f.write("\n")
f.write("\n")
def read_name_list(self, mode=None):
folder_name = os.path.join(state.appdata_path, "name")
if not os.path.exists(folder_name) or not os.listdir(folder_name):
self.init_name(self.make_name_list())
log_print("first_run")
txt_name = [filename for filename in os.listdir(
folder_name) if filename.endswith(".txt")]
# 获取所有txt文件
mdnum = len(txt_name)
if mdnum == 0:
self.show_message(_("名单文件不存在,且默认名单无法生成,请反馈给我们!"), _("名单生成异常!"))
sys.exit()
log_print("共读取到 %d 个名单" % mdnum)
txt_files_name = [os.path.splitext(
filename)[0] for filename in txt_name]
# 去除扩展名
if mode == 1: # 设置调用,仅返回名单列表
return txt_files_name
else: # 初始化或设置关闭后重新读取名单
self.comboBox.disconnect()
self.comboBox.clear()
self.comboBox.addItems(txt_files_name) # 添加文件名到下拉框
try:
self.comboBox.setCurrentText(state.last_name_list)
except:
pass
self.comboBox.currentIndexChanged.connect(
lambda: self.get_selected_file(0))
if mode == 2:
self.get_selected_file(1)
else:
pass
def get_selected_file(self, first=None):
# 先检查有无切换前的文件(保存不重复名单列表)
if state.selected_file is not None and state.non_repetitive == 1 and first != 2:
self.get_saved_non_repetitive_list(
state.selected_file, mode="save")
# 获取当前选中的文件名
state.selected_file = self.comboBox.currentText()
self.update_config("last_name_list", state.selected_file)
state.file_path = os.path.join(
state.appdata_path, "name", state.selected_file+".txt")
state.history_file = os.path.join(
state.appdata_path, "history", "%s中奖记录.txt" % state.selected_file)
if not os.path.exists(state.file_path):
self.show_message(_("所选名单文件已被移动或删除!"), _("找不到文件!"))
try:
self.comboBox.setCurrentIndex(0)
except:
log_print("first_run")
else:
log_print(f"所选文件的路径为: {state.file_path}\n")
self.process_name_file(state.file_path)
if state.non_repetitive == 1:
state.non_repetitive_list = self.get_saved_non_repetitive_list(
state.selected_file, "read")
# first: 1 首次加载,0 切换
if first == 1:
info = _("\'%s\',共 %s 人") % (state.selected_file, state.namelen)
else:
text = _("剩余 %s 人") % len(state.non_repetitive_list) if state.non_repetitive == 1 else _(
"共 %s 人") % state.namelen
info = _("切换至>\'%s\' %s") % (state.selected_file, text)
if state.non_repetitive == 1:
info += _("(不放回)")
self.listWidget.addItem(info)
# 切换时自动选中最后一行
if first == 0:
self.listWidget.setCurrentRow(self.listWidget.count() - 1)
self.update_name_listwidget()
self.set_bgimg()
def update_name_listwidget(self):
"""更新名单列表 Widget_2"""
if not hasattr(self, "listWidget_2"):
return
self.listWidget_2.clear()
if state.non_repetitive == 1:
list_to_show = state.non_repetitive_list or state.name_list
if state.non_repetitive_list:
remaining = len(state.non_repetitive_list)
self.listWidget_2.addItem(_("剩余:%s 人") % remaining)
else:
self.listWidget_2.addItem(_("此名单已完成抽取!"))
self.listWidget_2.addItems(list_to_show)
else:
self.listWidget_2.addItems(state.name_list)
def get_saved_non_repetitive_list(self, selected_file, mode=None):
"""切换名单时保存或读取不重复名单列表"""
if state.non_repetitive_dict is None:
state.non_repetitive_dict = {}
if mode == "read":
# 如果没有记录,就初始化为当前 name_list 的副本
state.non_repetitive_dict.setdefault(
selected_file, state.name_list.copy())
# 如果对应名单是空的,也填入 name_list 的副本
if not state.non_repetitive_dict[selected_file]:
state.non_repetitive_dict[selected_file] = state.name_list.copy(
)
return state.non_repetitive_dict[selected_file]
elif mode == "save": # 保存
state.non_repetitive_dict[selected_file] = state.non_repetitive_list.copy(
)
log_print(f"不重复名单列表已保存 {state.non_repetitive_list}")
def read_config(self):
config_path = os.path.join(state.appdata_path, 'config.ini')
# 配置文件不存在,创建空文件
if not os.path.exists(config_path):
open(config_path, 'w', encoding='utf-8').close()
config = read_config_file(config_path)
# 配置项表:key → (state属性名, 默认值, 是否需要 int)
config_map = {
'language': ('language_value', 'zh_CN', False),
'allownametts': ('allownametts', 1, True),
'checkupdate': ('checkupdate', 2, True),
'bgimg': ('bgimg', 1, True),
'last_name_list': ('last_name_list', "None", False),
'latest_version': ('latest_version', 0, False),
'non_repetitive': ('non_repetitive', 1, True),
'bgmusic': ('bgmusic', 0, True),
'first_use': ('first_use', 0, True),
'inertia_roll': ('inertia_roll', 1, True),
'roll_speed': ('roll_speed', 80, True),
'title_text': ('title_text', _("幸运儿是:"), False),
'need_move_config': ('need_move_config', 1, True),
'small_window_transparent': ('small_window_transparent', 80, True),
'saved_size': ('saved_size', "905,495", False),
'bind_picture': ('bind_picture', "None", False),
}
try:
for key, (state_attr, default, need_int) in config_map.items():
val = config.get(key)
if val is None:
# 写入默认值
self.update_config(key, default, mode="w!")
setattr(state, state_attr, default)
else:
setattr(state, state_attr, int(val) if need_int else val)
except Exception as e:
log_print(f"配置文件错误,重置为默认:{e}")
self.show_message(_("配置文件读取失败,已重置为默认值!\n%s") % e, _("读取配置文件失败!"))
os.remove(config_path)
return self.read_config()
return config
def update_config(self, variable, new_value, mode=None):
# delegate to config manager
config_path = os.path.join(state.appdata_path, 'config.ini')
update_entry(variable, str(new_value)
if new_value is not None else None, config_path)
log_print(f"更新配置文件:[{variable}]={new_value}\n")
if mode == "w!":
pass
else:
self.read_config()
if variable == 'bgimg':
self.set_bgimg()
elif variable == 'title_text':
self.label_3.setText(new_value)
elif variable == 'roll_speed':
try:
self.dynamic_speed_preview(state.roll_speed)
except:
pass
def process_name_file(self, file_path):
try:
with open(file_path, encoding='utf8') as f:
# 读取每一行,去除行尾换行符,过滤掉空行和仅包含空格的行
state.name_list = [line.strip()
for line in f.readlines() if line.strip()]
except:
log_print("utf8解码失败,尝试gbk")
try:
with open(file_path, encoding='gbk') as f:
state.name_list = [line.strip()
for line in f.readlines() if line.strip()]
except:
self.show_message(
_("Error: 名单文件%s编码错误,请检查文件编码是否为utf8或gbk") % file_path, _("错误"))
self.label_3.setText(_("名单文件无效!"))
log_print("\n", state.name_list)
state.namelen = len(state.name_list)
self.spinBox.setMaximum(state.namelen)
log_print("读取到的有效名单长度:", state.namelen)
# if state.non_repetitive == 1:
# state.non_repetitive_list = state.name_list.copy()
def ttsinitialize(self):
"""语音初始化"""
if state.allownametts == 2:
log_print("语音播报(正常模式)")
elif state.allownametts == 3:
log_print("语音播报(听写模式)")
elif state.allownametts == 1 or state.allownametts == 0:
log_print("语音播报已禁用")
def opentext(self, path):
if sys.platform == "win32":
os.system("start %s" % path)
else:
os.system("vim %s" % path)
def save_history(self, mode=None, name_set=None):
state.history_file = os.path.join(
state.appdata_path, "history", "%s中奖记录.txt" % state.selected_file)
if mode == 1:
write_name = name_set
else:
write_name = state.name
if write_name != '' or name_set != None:
with open(state.history_file, "a", encoding="utf-8") as file:
if mode == 1:
content = "%s 沉梦课堂点名器%s 幸运儿是:%s\n" % (
state.today, state.dmversion, name_set)
else:
content = "%s 沉梦课堂点名器%s 幸运儿是:%s\n" % (
state.today, state.dmversion, write_name)
file.write(content)
log_print(state.today, "幸运儿是: %s " % write_name)
else:
pass
def change_space(self, value: int):
try:
self.shortcut.activated.disconnect()
except:
pass
if value == 1:
self.shortcut.activated.connect(self.pushButton_2.click)
elif value == 0:
self.shortcut.activated.connect(self.pushButton_5.click)
def start(self):
num = self.spinBox.value()
if num > 1:
self.start_mulit()
else:
self.thread = StartRollThread()
self.thread.signals.show_progress.connect(self.update_progress_bar)
self.thread.signals.update_pushbotton.connect(
self.update_pushbotton)
self.thread.signals.update_list.connect(self.update_list)
self.thread.signals.enable_button.connect(self.enable_button)
self.thread.signals.qtimer.connect(self.qtimer)
self.thread.signals.save_history.connect(self.save_history)
self.thread.signals.key_space.connect(self.change_space)
self.thread.signals.change_speed.connect(
self.dynamic_speed_preview)
self.thread.signals.finished.connect(
lambda: log_print("结束点名") or self.ttsinitialize() or self.update_name_listwidget() or self.del_temp_list())
state.threadpool.start(self.thread)
def check_new_version(self):
self.update_thread = UpdateThread()
state.threadpool.start(self.update_thread)
self.update_thread.signals.find_new_version.connect(
self.update_message)
self.update_thread.signals.update_list.connect(
self.update_list)
self.update_thread.signals.finished.connect(
lambda: log_print("检查更新线程结束"))
def update_message(self, message, title): # 更新弹窗
msgBox = QMessageBox()
msgBox.setWindowTitle(title)
msgBox.setText(message)
msgBox.setWindowIcon(QtGui.QIcon(':/icons/picker.ico'))
okButton = msgBox.addButton("立刻前往", QMessageBox.AcceptRole)
noButton = msgBox.addButton("下次一定", QMessageBox.RejectRole)
# ignoreButton = msgBox.addButton("忽略本次更新", QMessageBox.RejectRole)
msgBox.exec_()
clickedButton = msgBox.clickedButton()
if clickedButton == okButton:
os.system("start https://cmxz.top/ktdmq")
self.update_list(1, title)
# elif clickedButton == ignoreButton:
# self.update_list(1, title)
# self.update_config("latest_version", state.newversion)
else:
self.update_list(1, title)
def start_mulit(self):
num = self.spinBox.value()
if state.non_repetitive == 1:
namelist = state.non_repetitive_list
else:
namelist = state.name_list
if num > len(namelist):
if num < len(state.name_list) and state.non_repetitive == 1:
state.non_repetitive_list = state.name_list.copy()
self.update_list(1, _("大于名单人数,不放回名单已重置"))
namelist = state.non_repetitive_list
else:
self.show_message(_("Error: 连抽人数大于名单人数!"), _("错误"))
self.spinBox.setValue(len(namelist))
return
if state.mrunning == False:
self.ptimer = QTimer(self)
self.progressBar.setMaximum(100)
self.progressBar.show()
self.ptimer.timeout.connect(self.update_progress_bar_mulit)
self.value = 0
self.ptimer.start(5)
log_print("连抽:%d 人" % num)
name_set = random.sample(namelist, num)
try:
self.save_history(1, name_set)
except:
log_print("无法写入历史记录")
self.listWidget.addItem("----------------------------")
leave_name_num = _(",剩余:%s") % (len(
state.non_repetitive_list) - len(name_set)) if state.non_repetitive == 1 else ""
self.listWidget.addItem(_("连抽:%d 人%s") % (num, leave_name_num))
for state.name in name_set:
self.listWidget.addItem(state.name)
if state.non_repetitive == 1:
try:
state.non_repetitive_list.remove(state.name)
except ValueError:
log_print(f"无法从不重复列表中移除 {state.name},可能已不存在于列表中。")
self.listWidget.addItem("----------------------------")
target_line = num - 2 if num > 2 else num - 1
self.listWidget.setCurrentRow(
self.listWidget.count() - target_line)
self.label_3.setText(state.title_text)
self.update_name_listwidget()
else:
log_print("连抽中...")
def reset_repetive_list(self):
self.process_name_file(state.file_path)
log_print("已重置不重复列表")
self.update_list(1, _("已重置单抽列表(%s人)") % state.namelen)
state.non_repetitive_list = state.name_list.copy()
self.update_name_listwidget()
def update_progress_bar_mulit(self):
state.mrunning = True
self.update_progress_bar("", "", "", "mulit") # 金色传说
if self.progressBar.value() < 100:
self.value += 1
self.progressBar.setValue(self.value)
else:
state.mrunning = False
self.value = 0
self.progressBar.setValue(self.value)
self.update_progress_bar(0, "", "", "default") # 隐藏并恢复默认进度条样式
self.ptimer.stop() # 停止定时器
def update_progress_bar(self, mode, value, value2, style=None):
if value == "" and value2 == "":
pass
else:
self.progressBar.setValue(value)
self.progressBar.setMaximum(value2)
if mode == 1:
self.progressBar.show()
elif mode == 0:
self.progressBar.hide()
if style == "default":
self.progressBar.setStyleSheet("""
QProgressBar {
border: 2px solid rgba(88, 88, 88, 0.81);
border-radius: 2px;
background-color: rgba(0, 0, 0, 0);
}
QProgressBar::chunk {
background-color: QLinearGradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 #00BCD4, stop: 1 #8BC34A
);
border-radius: 8px;
}
""")
elif style == "mulit" or style == "mulit_radius":
radius_style = f" border-radius: 8px;\n" if style == "mulit_radius" else ""
self.progressBar.setStyleSheet(f"""
QProgressBar {{
border: 2px solid rgba(88, 88, 88, 0.81);
border-radius: 2px;
background-color: rgba(0, 0, 0, 0);
}}
QProgressBar::chunk {{
background-color: QLinearGradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 #ffda95, stop: 1 #FF9800
);
{radius_style}
}}
""")
def update_pushbotton(self, text, mode=None):
if mode == 1:
self.pushButton_2.setText(text)
else:
self.pushButton_5.setText(text)
def enable_button(self, value):
if value == 1: # 初始状态
self.pushButton_5.setEnabled(True)
self.pushButton_2.setEnabled(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/swindow.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_5.setIcon(icon)
self.pushButton_2.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(118, 218, 96, 1);border-radius:5px;}QPushButton:hover{background:rgba(80, 182, 84, 1);}")
self.pushButton_5.clicked.disconnect()
self.pushButton_5.clicked.connect(self.small_mode)
self.pushButton_5.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(237, 237, 237, 1);border-radius:5px;}QPushButton:hover{background:rgba(210, 210, 210, 0.6);}")
self.pushButton_2.clicked.disconnect()
self.pushButton_2.clicked.connect(self.start)
elif value == 2: # 开始单抽
self.pushButton_2.setEnabled(False)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/stop.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_5.setIcon(icon)
self.pushButton_5.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(249, 117, 83, 1);border-radius:5px;}QPushButton:hover{background:rgba(226, 82, 44, 1);}")
self.pushButton_2.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(237, 237, 237, 1);border-radius:5px;}QPushButton:hover{background:rgba(80, 182, 84, 1);}")
self.pushButton_5.clicked.disconnect()
self.pushButton_5.clicked.connect(self.start)
elif value == 3: # 禁用开始键
self.pushButton_5.setEnabled(False)
elif value == 4: # 启用开始键
self.pushButton_5.setEnabled(True)
elif value == 5: # 不重复单抽开始
self.pushButton_2.setEnabled(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/stop.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_5.setIcon(icon)
self.pushButton_5.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(249, 117, 83, 1);border-radius:5px;}QPushButton:hover{background:rgba(226, 82, 44, 1);}")
self.pushButton_2.setStyleSheet("QPushButton {\n"
" font-size: 20px;\n"
" color: rgb(58, 58, 58);\n"
"}\n"
"QPushButton{background:rgba(112, 198, 232, 1);border-radius:5px;}QPushButton:hover{background:rgba(93, 167, 196, 1);}")
self.pushButton_5.clicked.disconnect()
self.pushButton_5.clicked.connect(self.start)
self.pushButton_2.clicked.disconnect()
self.pushButton_2.clicked.connect(self.reset_repetive_list)
elif value == 6:
self.spinBox.setEnabled(False) # 开始单抽后不允许选择人数
elif value == 7:
self.spinBox.setEnabled(True)
def update_list(self, mode, value):
if mode == 2:
mode = 1
value = f" {state.origin_name_list}" if state.origin_name_list else ""
if state.non_repetitive == 1:
value += _(" (还剩%s人)") % (len(state.non_repetitive_list)
) if state.origin_name_list else ""
if mode == 1:
if value == "":
pass
else:
self.listWidget.addItem(value)
self.listWidget.setCurrentRow(self.listWidget.count() - 1)
elif mode == 0:
self.font_m.setPointSize(54)
self.label_3.setFont(self.font_m)
self.label_3.setText(value)
elif mode == 7:
self.label_7.setText(value)
def qtimer(self, start):
if start == 1:
if len(state.name_list) == 0:
self.show_message(
_("Error: 名单文件为空,请输入名字(一行一个)后再重新点名!"), _("错误"))
self.qtimer(2)
self.pushButton_5.setEnabled(True)
self.pushButton_5.click() # 名单没有人就自动按结束按钮
state.origin_name_list = None
self.font_m.setPointSize(45)
self.label_3.setText(_(" 名单为空!"))
state.name = ""
try:
self.run_settings(f"1&{state.file_path}")
except Exception as e:
self.show_message(_("选择的名单文件%s不存在!") %
state.file_path, "\n%s" % e)
else:
self.timer = QTimer(self)
log_print(f"滚动速度:{state.roll_speed}")
self.timer.start(state.roll_speed)
self.timer.timeout.connect(self.setname)
elif start == 2:
try:
if self.timer:
self.timer.stop()
except Exception as e:
log_print(f"停止计时器失败:{e}")
elif start == 0:
try:
if self.timer:
self.timer.stop()
# log_print("Debug:",state.name)
if state.allownametts != 1:
self.tts_read(state.origin_name_list)
except Exception as e:
log_print(f"计时器启动语音播报线程失败:{e}")
def setname(self):
max_width = self.label_3.width()
max_height = self.label_3.height()
if state.windows_move_flag:
self.font_m.setPointSize(150) # 字体大小
self.label_3.setSizePolicy(
QSizePolicy.Expanding, QSizePolicy.Expanding) # 允许 QLabel 扩展
self.label_3.setMaximumSize(16777215, 16777215)
else:
self.font_m.setPointSize(90)
self.label_3.setMaximumSize(max_width, max_height)
self.label_3.setFont(self.font_m)
if state.non_repetitive == 1:
if len(state.non_repetitive_list) == 0:
self.process_name_file(state.file_path)
state.non_repetitive_list = state.name_list.copy()
if state.namelen == 0:
self.show_message(_("Error: 名单文件为空,请输入名字(一行一个)后再重新点名!"), _("错误"))
state.name = ""
try:
self.run_settings(f"1&{state.file_path}")
except Exception as e:
log_print(f"文件不存在:{e}")
self.show_message(_("选择的名单文件%s不存在!") %
state.file_path, "\n%s" % e)
finally:
self.font_m.setPointSize(54)
self.label_3.setFont(self.font_m)
self.label_3.setText(_(" 名单为空!"))
self.pushButton_5.setEnabled(True)
self.pushButton_5.click() # 名单没有人就自动按结束按钮(中途切换名单)
state.origin_name_list = None
self.qtimer(2)
return
try:
if state.non_repetitive == 1:
state.name = random.choice(state.non_repetitive_list)
else:
state.name = random.choice(state.name_list)
except:
pass
font_size = self.font_m.pointSize()
metrics = QFontMetrics(self.font_m)
# 估算一行字符数
a = max(1, round(metrics.horizontalAdvance(
state.name) / max_width, 1)) # 估计行数
b = metrics.height() # 字体高度
d = 1.2 if font_size < 80 and len(state.name) < 6 else 2.2
c = a * (b * d) # b*2考虑到字符行间隔
# 如果文本换行后的高度超出了标签高度,逐步减小字体
while c > max_height and font_size > 0:
font_size -= 3
self.font_m.setPointSize(font_size)
self.label_3.setFont(self.font_m)
metrics = QFontMetrics(self.font_m)
b = metrics.height()
d = 1.2 if font_size < 80 and len(state.name) < 6 else 2.2
# 再次计算换行后估算行数
a = max(1, round(metrics.horizontalAdvance(state.name) / max_width, 1))
c = a * (b * d)
state.origin_name_list = state.name
self.label_3.setText(state.origin_name_list)
# log_print(font_size,d)
def show_message(self, message, title, first=None):
msgBox = QMessageBox()