-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQT_ChartAnalyzer.py
More file actions
1868 lines (1535 loc) · 74.4 KB
/
QT_ChartAnalyzer.py
File metadata and controls
1868 lines (1535 loc) · 74.4 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import json
import random
import string
import shutil
import subprocess
import wave
import contextlib
import zipfile
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from qfluentwidgets import *
from PIL import Image, ImageDraw, ImageFont
# 配置文件路径
CONFIG_FILE = "chart_analyzer_config.json"
# 程序文件夹配置
program_folder = ""
# 当前打开的窗口
current_windows = {
'projects': {}, # 工程窗口
'charts': {}, # 谱面搜索窗口
'audio': {} # 音频搜索窗口
}
def load_config():
"""加载配置文件"""
global program_folder
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
if 'program_folder' in config and config['program_folder']:
program_folder = config['program_folder']
return True
except (json.JSONDecodeError, IOError) as e:
print(f"加载配置文件失败: {e}")
return False
def save_config():
"""保存配置文件"""
try:
config = {'program_folder': program_folder}
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=2)
except IOError as e:
print(f"保存配置文件失败: {e}")
def generate_random_path():
"""生成8位随机数字作为Path"""
return ''.join(random.choices(string.digits, k=8))
def create_info_txt(project_folder, project_name):
"""创建info.txt文件"""
path_value = generate_random_path()
info_content = f"""#
Name: {project_name}
Path: {path_value}
Chart: {path_value}.json
Level:
Composer: Phigros
Charter: Phigros
"""
info_path = os.path.join(project_folder, "info.txt")
with open(info_path, 'w', encoding='utf-8') as f:
f.write(info_content)
return path_value
def read_info_txt(project_folder):
"""读取info.txt文件"""
info_path = os.path.join(project_folder, "info.txt")
if not os.path.exists(info_path):
return None
project_info = {}
with open(info_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if ':' in line and not line.startswith('#'):
key, value = line.split(':', 1)
project_info[key.strip()] = value.strip()
return project_info
def update_info_txt(project_folder, project_info):
"""更新info.txt文件"""
info_content = f"""#
Name: {project_info['Name']}
Path: {project_info['Path']}
Chart: {project_info['Chart']}
Level: {project_info['Level']}
Composer: {project_info['Composer']}
Charter: {project_info['Charter']}
"""
info_path = os.path.join(project_folder, "info.txt")
with open(info_path, 'w', encoding='utf-8') as f:
f.write(info_content)
def get_audio_duration(audio_path):
"""获取音频时长(秒)"""
try:
with contextlib.closing(wave.open(audio_path, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return round(duration, 2)
except:
return None
# 移除find_system_font函数,因为我们不再需要系统字体查找功能
def create_chart_art(project_folder, project_name, project_level, path_value, font_path=None):
"""创建曲绘图片"""
try:
# 图片尺寸 (16:9)
width = 1920
height = 1080
# 创建白色背景图片
image = Image.new('RGB', (width, height), 'white')
draw = ImageDraw.Draw(image)
# 初始化字体变量
title_font = None
level_font = None
# 选择字体
if font_path and os.path.exists(font_path):
# 尝试将输入视为字体文件路径
try:
title_font = ImageFont.truetype(font_path, 160)
level_font = ImageFont.truetype(font_path, 80)
except:
# 字体文件加载失败,使用默认字体
title_font = ImageFont.load_default()
level_font = ImageFont.load_default()
else:
# 没有提供字体或字体文件不存在,使用默认字体
title_font = ImageFont.load_default()
level_font = ImageFont.load_default()
# 确保字体有效,如果默认字体不可用则使用基本字体
try:
# 测试字体是否可用
draw.text((0, 0), "Test", font=title_font)
except:
# 如果字体不可用,使用基本的位图字体
title_font = ImageFont.load_default()
level_font = ImageFont.load_default()
# 获取文本尺寸
title_bbox = draw.textbbox((0, 0), project_name, font=title_font)
title_width = title_bbox[2] - title_bbox[0]
title_height = title_bbox[3] - title_bbox[1]
level_bbox = draw.textbbox((0, 0), project_level, font=level_font)
level_width = level_bbox[2] - level_bbox[0]
level_height = level_bbox[3] - level_bbox[1]
# 计算居中位置
title_x = (width - title_width) // 2
title_y = (height - title_height) // 2
# 计算难度位置(右下角偏左上)
level_x = width - level_width - 100 # 距离右边100像素
level_y = height - level_height - 100 # 距离底部100像素
# 绘制文本
draw.text((title_x, title_y), project_name, font=title_font, fill='black')
draw.text((level_x, level_y), project_level, font=level_font, fill='black')
# 保存图片
image_path = os.path.join(project_folder, f"{path_value}.png")
image.save(image_path)
return True
except Exception as e:
print(f"创建曲绘图片失败: {e}")
return False
def scan_projects():
"""扫描程序文件夹中的所有工程"""
projects = []
if not program_folder or not os.path.exists(program_folder):
return projects
for item in os.listdir(program_folder):
item_path = os.path.join(program_folder, item)
if os.path.isdir(item_path):
info_path = os.path.join(item_path, "info.txt")
if os.path.exists(info_path):
project_info = read_info_txt(item_path)
if project_info:
projects.append({
'name': item,
'folder': item_path,
'info': project_info
})
return projects
class Chart:
def __init__(self, file, bpm, aboveNumber, belowNumber, keyMaxTime, eventMaxTime):
# 文件名称
self.file = file
self.fileName = file
# 铺面 bpm
self.bpm = bpm
# 物量
self.aboveNumber = aboveNumber
self.belowNumber = belowNumber
self.objectNumber = aboveNumber + belowNumber
# 最后一个键的时间
self.keyMaxTime = keyMaxTime
self.keyMaxSecond = round(self.keyMaxTime / bpm * 1.875, 2)
# 最后一个事件的事件
self.eventMaxTime = eventMaxTime
self.eventMaxSecond = round(self.eventMaxTime / bpm * 1.875, 2)
# 曲长
self.maxTime = max(eventMaxTime, keyMaxTime)
self.audioLength = round(self.maxTime / bpm * 1.875, 2)
# 排名分数
self.sortingScore = 0
def __str__(self) -> str:
return f"<Chart '{self.fileName}', bpm={self.bpm}, number={self.objectNumber}, maxTime={self.maxTime}, audioLength={self.audioLength}s>"
def __repr__(self) -> str:
return f"<Chart {self.fileName}>"
def analyseJsonChart(chartFile: str):
"""分析铺面文件,生成 Chart 对象"""
try:
with open(chartFile, 'r', encoding="utf-8") as f:
jsonData = json.load(f)
# 铺面 bpm
bpm = jsonData["judgeLineList"][0]["bpm"]
# 物量
aboveNumber = 0
belowNumber = 0
# 最后一个键的时间
keyMaxTime = 0
# 最后一个事件的时间
eventMaxTime = 0
# 统计最后一个判定线动画的时间
for line in jsonData["judgeLineList"]:
aboveNumber += len(line["notesAbove"])
belowNumber += len(line["notesBelow"])
eventList = line["speedEvents"] + line["judgeLineMoveEvents"] + line["judgeLineRotateEvents"] + line["judgeLineDisappearEvents"]
for event in eventList:
eventMaxTime = max(event["startTime"], eventMaxTime)
# 统计最后一个note的时间
for line in jsonData["judgeLineList"]:
for note in line["notesAbove"]:
keyMaxTime = max(note["time"], keyMaxTime)
return Chart(
chartFile,
bpm,
aboveNumber,
belowNumber,
keyMaxTime,
eventMaxTime
)
except Exception as e:
print(f"分析文件 {chartFile} 时出错: {e}")
return None
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.load_config_and_refresh()
def initUI(self):
self.setWindowTitle('PhiChartSearch谱面工程管理器')
self.setGeometry(100, 100, 1000, 700) # 扩大主界面尺寸
# 创建中心部件和主布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
# 标题
title_label = TitleLabel('PhiChartSearch谱面工程管理器')
main_layout.addWidget(title_label)
# 程序文件夹设置
folder_group = CardWidget()
folder_layout = QVBoxLayout(folder_group)
folder_layout.setContentsMargins(20, 20, 20, 20)
folder_label = StrongBodyLabel('程序文件夹(所有工程的总存放路径)')
folder_layout.addWidget(folder_label)
folder_h_layout = QHBoxLayout()
self.folder_line_edit = LineEdit()
self.folder_line_edit.setPlaceholderText('请选择程序文件夹')
folder_h_layout.addWidget(self.folder_line_edit)
self.browse_button = PushButton('浏览')
self.browse_button.clicked.connect(self.select_program_folder)
folder_h_layout.addWidget(self.browse_button)
folder_layout.addLayout(folder_h_layout)
main_layout.addWidget(folder_group)
# 工程列表
project_group = CardWidget()
project_layout = QVBoxLayout(project_group)
project_layout.setContentsMargins(10, 10, 10, 10)
project_label = StrongBodyLabel('工程列表')
project_layout.addWidget(project_label)
# 创建表格
self.project_table = TableWidget()
self.project_table.setBorderRadius(8)
self.project_table.setBorderVisible(True)
self.project_table.setColumnCount(4)
self.project_table.setHorizontalHeaderLabels(['工程名', '谱面名称', '难度', '状态'])
self.project_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
project_layout.addWidget(self.project_table)
main_layout.addWidget(project_group)
# 按钮区域
button_layout = QHBoxLayout()
self.create_button = PrimaryPushButton('创建新工程')
self.create_button.clicked.connect(self.create_project)
button_layout.addWidget(self.create_button)
self.open_button = PushButton('打开工程')
self.open_button.clicked.connect(self.open_project_action)
button_layout.addWidget(self.open_button)
self.delete_button = PushButton('删除工程')
self.delete_button.clicked.connect(self.delete_project_action)
button_layout.addWidget(self.delete_button)
self.refresh_button = PushButton('刷新列表')
self.refresh_button.clicked.connect(self.refresh_project_list)
button_layout.addWidget(self.refresh_button)
# 添加关于按钮
self.about_button = PushButton('关于')
self.about_button.clicked.connect(self.show_about)
button_layout.addWidget(self.about_button)
main_layout.addLayout(button_layout)
# 状态栏
self.status_label = BodyLabel("就绪")
main_layout.addWidget(self.status_label)
def load_config_and_refresh(self):
"""加载配置并刷新工程列表"""
load_config()
if program_folder:
self.folder_line_edit.setText(program_folder)
self.refresh_project_list()
def select_program_folder(self):
"""选择程序文件夹"""
global program_folder
folder_path = QFileDialog.getExistingDirectory(self, "选择程序文件夹(所有工程的总存放路径)")
if folder_path:
program_folder = folder_path
self.folder_line_edit.setText(folder_path)
save_config()
self.refresh_project_list()
def refresh_project_list(self):
"""刷新工程列表"""
# 清空现有列表
self.project_table.setRowCount(0)
# 扫描并显示工程
projects = scan_projects()
for project in projects:
row = self.project_table.rowCount()
self.project_table.insertRow(row)
# 添加项目到表格
self.project_table.setItem(row, 0, QTableWidgetItem(project['name']))
self.project_table.setItem(row, 1, QTableWidgetItem(project['info'].get('Name', '')))
self.project_table.setItem(row, 2, QTableWidgetItem(project['info'].get('Level', '')))
# 检查工程完整性
is_complete = all([
project['info'].get('Chart', ''),
any(f.lower().endswith('.wav') for f in os.listdir(project['folder']) if os.path.isfile(os.path.join(project['folder'], f))),
os.path.exists(os.path.join(project['folder'], f"{project['info'].get('Path', '')}.png")) if project['info'].get('Path') else False
])
status = "完整" if is_complete else "不完整"
self.project_table.setItem(row, 3, QTableWidgetItem(status))
def create_project(self):
"""创建新工程"""
dialog = CreateProjectDialog(self)
if dialog.exec_() == QDialog.Accepted:
# 获取用户输入的数据
project_name = dialog.name_edit.text().strip()
level = dialog.level_edit.text().strip()
composer = dialog.composer_edit.text().strip()
charter = dialog.charter_edit.text().strip()
create_art = dialog.create_art_check.isChecked()
font_path = dialog.font_edit.text().strip()
use_local_art = dialog.use_local_art_check.isChecked()
local_art_path = dialog.local_art_edit.text().strip()
# 验证必填字段
if not project_name:
MessageBox("错误", "请填写工程名称!", self).exec_()
return
if not level:
MessageBox("错误", "请填写难度!", self).exec_()
return
# 检查工程文件夹是否已存在
project_folder = os.path.join(program_folder, project_name)
if os.path.exists(project_folder):
MessageBox("错误", "工程文件夹已存在!", self).exec_()
return
try:
# 创建工程文件夹
os.makedirs(project_folder)
# 创建info.txt
path_value = create_info_txt(project_folder, project_name)
# 更新工程信息
project_info = read_info_txt(project_folder)
project_info['Level'] = level
project_info['Composer'] = composer
project_info['Charter'] = charter
update_info_txt(project_folder, project_info)
# 处理曲绘文件
art_created = False
if use_local_art and local_art_path and os.path.exists(local_art_path):
# 使用本地曲绘文件
try:
target_art_path = os.path.join(project_folder, f"{path_value}.png")
shutil.copy2(local_art_path, target_art_path)
art_created = True
except Exception as e:
MessageBox("警告", f"复制本地曲绘文件失败:{str(e)}", self).exec_()
elif create_art:
# 自动生成曲绘
if not font_path:
MessageBox("警告", "未设置曲绘字体,无法生成曲绘!", self).exec_()
elif create_chart_art(project_folder, project_name, level, path_value, font_path):
art_created = True
else:
MessageBox("警告", "曲绘图片创建失败,但工程已创建。", self).exec_()
if art_created:
MessageBox("成功", "工程创建成功,曲绘已处理!", self).exec_()
else:
MessageBox("成功", "工程创建成功!", self).exec_()
self.refresh_project_list()
# 自动打开新创建的工程
self.open_project(project_name)
except Exception as e:
MessageBox("错误", f"创建工程失败:{str(e)}", self).exec_()
def open_project_action(self):
"""打开选中的工程"""
selected_rows = self.project_table.selectedItems()
if not selected_rows:
MessageBox("警告", "请先选择要打开的工程!", self).exec_()
return
# 获取选中行的工程名
row = selected_rows[0].row()
project_name = self.project_table.item(row, 0).text()
self.open_project(project_name)
def open_project(self, project_name):
"""打开工程管理页面"""
project_folder = os.path.join(program_folder, project_name)
project_info = read_info_txt(project_folder)
if not project_info:
MessageBox("错误", "无法读取工程信息!", self).exec_()
return
# 如果该工程已经打开,则聚焦到该窗口
if project_name in current_windows['projects'] and current_windows['projects'][project_name]:
current_windows['projects'][project_name].raise_()
current_windows['projects'][project_name].activateWindow()
return
# 创建并显示工程管理窗口
project_window = ProjectWindow(project_name, project_folder, project_info, self)
current_windows['projects'][project_name] = project_window
project_window.show()
def delete_project_action(self):
"""删除选中的工程"""
selected_rows = self.project_table.selectedItems()
if not selected_rows:
MessageBox("警告", "请先选择要删除的工程!", self).exec_()
return
# 获取选中行的工程名
row = selected_rows[0].row()
project_name = self.project_table.item(row, 0).text()
# 确认删除
if not MessageBox("确认删除", f"确定要删除工程 '{project_name}' 吗?\n此操作不可恢复!", self).exec_():
return
try:
project_folder = os.path.join(program_folder, project_name)
shutil.rmtree(project_folder)
MessageBox("成功", "工程已删除!", self).exec_()
self.refresh_project_list()
except Exception as e:
MessageBox("错误", f"删除工程失败:{str(e)}", self).exec_()
def show_about(self):
"""显示关于对话框"""
dialog = AboutDialog(self)
dialog.exec_()
class CreateProjectDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("创建新工程")
self.setFixedSize(450, 700)
self.initUI()
def initUI(self):
layout = QVBoxLayout(self)
# 标题
title_label = TitleLabel("创建新的谱面工程")
layout.addWidget(title_label)
# 工程名称
name_label = BodyLabel("工程名称/谱面名称(必填)")
layout.addWidget(name_label)
self.name_edit = LineEdit()
self.name_edit.setPlaceholderText("请输入工程名称")
layout.addWidget(self.name_edit)
# 难度
level_label = BodyLabel("难度(必填)")
layout.addWidget(level_label)
self.level_edit = LineEdit()
self.level_edit.setPlaceholderText("请输入难度")
layout.addWidget(self.level_edit)
# Composer
composer_label = BodyLabel("Composer")
layout.addWidget(composer_label)
self.composer_edit = LineEdit()
self.composer_edit.setText("Phigros")
layout.addWidget(self.composer_edit)
# Charter
charter_label = BodyLabel("Charter")
layout.addWidget(charter_label)
self.charter_edit = LineEdit()
self.charter_edit.setText("Phigros")
layout.addWidget(self.charter_edit)
# 曲绘创建选项
art_card = CardWidget()
art_layout = QVBoxLayout(art_card)
art_layout.setContentsMargins(15, 15, 15, 15)
art_layout.setSpacing(10)
art_title = StrongBodyLabel("曲绘创建选项")
art_layout.addWidget(art_title)
# 是否自创建曲绘
self.create_art_check = CheckBox("自动生成曲绘")
self.create_art_check.stateChanged.connect(self.on_create_art_check_changed)
art_layout.addWidget(self.create_art_check)
# 字体选择
self.font_label = BodyLabel("曲绘字体(可选)")
self.font_label.setEnabled(False)
art_layout.addWidget(self.font_label)
font_layout = QHBoxLayout()
self.font_edit = LineEdit()
self.font_edit.setPlaceholderText("请选择字体文件")
self.font_edit.setEnabled(False)
font_layout.addWidget(self.font_edit)
self.font_button = PushButton("浏览")
self.font_button.clicked.connect(self.browse_font)
self.font_button.setEnabled(False)
font_layout.addWidget(self.font_button)
art_layout.addLayout(font_layout)
# 使用本地曲绘文件
self.use_local_art_check = CheckBox("使用本地曲绘文件")
self.use_local_art_check.stateChanged.connect(self.on_use_local_art_check_changed)
art_layout.addWidget(self.use_local_art_check)
# 本地曲绘文件选择
self.local_art_label = BodyLabel("本地曲绘文件")
self.local_art_label.setEnabled(False)
art_layout.addWidget(self.local_art_label)
local_art_layout = QHBoxLayout()
self.local_art_edit = LineEdit()
self.local_art_edit.setPlaceholderText("请选择本地曲绘文件")
self.local_art_edit.setEnabled(False)
local_art_layout.addWidget(self.local_art_edit)
self.local_art_button = PushButton("浏览")
self.local_art_button.clicked.connect(self.browse_local_art)
self.local_art_button.setEnabled(False)
local_art_layout.addWidget(self.local_art_button)
art_layout.addLayout(local_art_layout)
layout.addWidget(art_card)
# 按钮
button_layout = QHBoxLayout()
button_layout.addStretch()
self.cancel_button = PushButton("取消")
self.cancel_button.clicked.connect(self.reject)
button_layout.addWidget(self.cancel_button)
self.create_button = PrimaryPushButton("创建工程")
self.create_button.clicked.connect(self.accept)
button_layout.addWidget(self.create_button)
layout.addLayout(button_layout)
def on_create_art_check_changed(self, state):
"""处理自动生成曲绘复选框状态变化"""
enabled = state == Qt.Checked
self.font_label.setEnabled(enabled)
self.font_edit.setEnabled(enabled)
self.font_button.setEnabled(enabled)
# 如果启用了自动生成曲绘,则禁用使用本地曲绘文件
if enabled:
self.use_local_art_check.setChecked(False)
def on_use_local_art_check_changed(self, state):
"""处理使用本地曲绘文件复选框状态变化"""
enabled = state == Qt.Checked
self.local_art_label.setEnabled(enabled)
self.local_art_edit.setEnabled(enabled)
self.local_art_button.setEnabled(enabled)
# 如果启用了使用本地曲绘文件,则禁用自动生成曲绘
if enabled:
self.create_art_check.setChecked(False)
def browse_font(self):
"""浏览选择字体文件"""
font_path, _ = QFileDialog.getOpenFileName(
self,
"选择字体文件",
"",
"字体文件 (*.ttf *.otf *.ttc);;所有文件 (*.*)"
)
if font_path:
self.font_edit.setText(font_path)
def browse_local_art(self):
"""浏览选择本地曲绘文件"""
image_path, _ = QFileDialog.getOpenFileName(
self,
"选择曲绘文件",
"",
"图片文件 (*.png *.jpg *.jpeg);;所有文件 (*.*)"
)
if image_path:
self.local_art_edit.setText(image_path)
class ProjectWindow(QMainWindow):
def __init__(self, project_name, project_folder, project_info, parent=None):
super().__init__(parent)
self.project_name = project_name
self.project_folder = project_folder
self.project_info = project_info
self.parent = parent
# 连接窗口关闭事件
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.initUI()
def closeEvent(self, event):
"""窗口关闭事件处理"""
# 从当前窗口字典中移除引用
if self.project_name in current_windows['projects']:
del current_windows['projects'][self.project_name]
event.accept()
def initUI(self):
self.setWindowTitle(f"工程管理 - {self.project_name}")
self.setGeometry(100, 100, 800, 600)
# 创建中心部件和主布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setSpacing(15)
# 标题
title_label = TitleLabel(f"工程管理 - {self.project_name}")
main_layout.addWidget(title_label)
# 文件管理区域
file_group = CardWidget()
file_layout = QVBoxLayout(file_group)
file_layout.setContentsMargins(15, 15, 15, 15)
file_layout.setSpacing(10)
file_title = StrongBodyLabel("文件管理")
file_layout.addWidget(file_title)
# 定义文件类型
file_types = [
("信息", "info.txt", "info"),
("谱面", ".json", "chart"),
("音频", ".wav", "audio"),
("曲绘", ".png", "art")
]
self.file_widgets = {}
for i, (display_name, extension, file_type) in enumerate(file_types):
# 文件类型标签
type_layout = QHBoxLayout()
type_layout.setSpacing(10)
type_label = BodyLabel(display_name)
type_label.setFixedWidth(60) # 设置固定宽度
type_layout.addWidget(type_label)
# 文件名显示
file_name, file_path = self.get_file_info(file_type)
status_label = BodyLabel(file_name)
status_label.setWordWrap(False) # 禁止换行
status_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) # 设置大小策略
type_layout.addWidget(status_label)
# 曲绘预览(仅对曲绘文件类型)
if file_type == "art" and file_path and os.path.exists(file_path):
# 创建预览标签
preview_label = QLabel()
preview_label.setFixedSize(80, 45) # 16:9比例的缩略图
preview_label.setAlignment(Qt.AlignCenter)
preview_label.setStyleSheet("border: 1px solid gray;")
# 加载并缩放图片
try:
pixmap = QPixmap(file_path)
pixmap = pixmap.scaled(80, 45, Qt.KeepAspectRatio, Qt.SmoothTransformation)
preview_label.setPixmap(pixmap)
except Exception as e:
preview_label.setText("预览失败")
type_layout.addWidget(preview_label)
# 按钮框架
button_layout = QHBoxLayout()
button_layout.setSpacing(5)
button_layout.setContentsMargins(0, 0, 0, 0)
modify_button = PushButton("修改")
modify_button.setFixedWidth(60) # 设置固定宽度
modify_button.clicked.connect(lambda _, ft=file_type: self.modify_file(ft))
button_layout.addWidget(modify_button)
delete_button = PushButton("删除")
delete_button.setFixedWidth(60) # 设置固定宽度
delete_button.clicked.connect(lambda _, ft=file_type: self.delete_file(ft))
button_layout.addWidget(delete_button)
type_layout.addLayout(button_layout)
file_layout.addLayout(type_layout)
self.file_widgets[file_type] = {
'status_label': status_label,
'file_path': file_path,
'file_name': file_name
}
main_layout.addWidget(file_group)
# 按钮区域
button_layout = QHBoxLayout()
button_layout.setSpacing(10)
self.open_folder_button = PushButton("打开工程文件夹")
self.open_folder_button.setFixedWidth(120)
self.open_folder_button.clicked.connect(self.open_project_folder)
button_layout.addWidget(self.open_folder_button)
self.pack_button = PrimaryPushButton("一键打包zip")
self.pack_button.setFixedWidth(120)
self.pack_button.clicked.connect(self.pack_project)
button_layout.addWidget(self.pack_button)
# 添加弹性空间
button_layout.addStretch()
main_layout.addLayout(button_layout)
# 设置主布局的边距
main_layout.setContentsMargins(20, 20, 20, 20)
def get_file_info(self, file_type):
"""获取文件信息"""
if file_type == "info":
file_path = os.path.join(self.project_folder, "info.txt")
file_name = "info.txt"
elif file_type == "chart":
chart_file = self.project_info.get("Chart", "")
# 检查文件是否实际存在
if chart_file and os.path.exists(os.path.join(self.project_folder, chart_file)):
file_path = os.path.join(self.project_folder, chart_file)
file_name = chart_file
else:
file_path = ""
file_name = "未设置"
elif file_type == "audio":
# 查找音频文件
audio_file = None
for f in os.listdir(self.project_folder) if os.path.exists(self.project_folder) else []:
if f.lower().endswith('.wav'):
audio_file = f
break
file_path = os.path.join(self.project_folder, audio_file) if audio_file else ""
file_name = audio_file if audio_file else "未设置"
else: # art
art_file = f"{self.project_info.get('Path', '')}.png"
file_path = os.path.join(self.project_folder, art_file) if self.project_info.get('Path') else ""
file_name = art_file if self.project_info.get('Path') and os.path.exists(file_path) else "未设置"
return file_name, file_path
def modify_file(self, file_type):
"""修改文件"""
if file_type == "info":
self.modify_info()
elif file_type == "chart":
self.open_chart_search_window()
elif file_type == "audio":
self.open_audio_search_window()
elif file_type == "art":
self.modify_art()
def modify_info(self):
"""修改信息文件"""
dialog = ModifyInfoDialog(self.project_info, self)
if dialog.exec_() == QDialog.Accepted:
# 更新工程信息
self.project_info['Level'] = dialog.level_edit.text().strip()
self.project_info['Composer'] = dialog.composer_edit.text().strip()
self.project_info['Charter'] = dialog.charter_edit.text().strip()
update_info_txt(self.project_folder, self.project_info)
MessageBox("成功", "工程信息已更新!", self).exec_()
# 刷新窗口
self.close()
self.parent.open_project(self.project_name)
def open_chart_search_window(self):
"""打开谱面搜索窗口"""
dialog = ChartSearchWindow(self.project_folder, self.project_info, self.project_name, self.parent, self)
dialog.exec_()
def open_audio_search_window(self):
"""打开音频搜索窗口"""
dialog = AudioSearchWindow(self.project_folder, self.project_info, self.project_name, self.parent, self)
dialog.exec_()
def modify_art(self):
"""修改曲绘文件"""
dialog = ModifyArtDialog(self.project_folder, self.project_info, self.project_name, self)
if dialog.exec_() == QDialog.Accepted:
# 刷新窗口
self.close()
self.parent.open_project(self.project_name)
def delete_file(self, file_type):
"""删除文件"""
if file_type == "info":
MessageBox("警告", "不能删除信息文件!", self).exec_()
return
if not MessageBox("确认", "确定要删除这个文件吗?", self).exec_():
return
try:
if file_type == "chart":
chart_file = self.project_info.get("Chart", "")
if chart_file:
file_path = os.path.join(self.project_folder, chart_file)
if os.path.exists(file_path):
os.remove(file_path)
self.project_info['Chart'] = ""
update_info_txt(self.project_folder, self.project_info)
elif file_type == "audio":
for f in os.listdir(self.project_folder):
if f.lower().endswith('.wav'):
os.remove(os.path.join(self.project_folder, f))
elif file_type == "art":
art_file = f"{self.project_info.get('Path', '')}.png"
if self.project_info.get('Path'):
file_path = os.path.join(self.project_folder, art_file)
if os.path.exists(file_path):
os.remove(file_path)
MessageBox("成功", "文件已删除!", self).exec_()
# 刷新窗口
self.close()
self.parent.open_project(self.project_name)
except Exception as e:
MessageBox("错误", f"删除文件失败:{str(e)}", self).exec_()
def open_project_folder(self):
"""打开工程文件夹"""
try:
if os.name == 'nt': # Windows
os.startfile(self.project_folder)
elif os.name == 'posix': # macOS and Linux
subprocess.run(['open', self.project_folder])
except Exception as e:
MessageBox("错误", f"无法打开文件夹:{str(e)}", self).exec_()
def pack_project(self):
"""一键打包工程为zip"""
try:
zip_filename = f"{self.project_name}.zip"
zip_path = os.path.join(self.project_folder, zip_filename)
# 定义要打包的核心文件
core_files = []
# info.txt
info_path = os.path.join(self.project_folder, "info.txt")
if os.path.exists(info_path):
core_files.append(("info.txt", info_path))
# 谱面文件
if self.project_info.get("Chart"):
chart_path = os.path.join(self.project_folder, self.project_info["Chart"])
if os.path.exists(chart_path):
core_files.append((self.project_info["Chart"], chart_path))
# 音频文件
for f in os.listdir(self.project_folder):
if f.lower().endswith('.wav'):
audio_path = os.path.join(self.project_folder, f)
core_files.append((f, audio_path))
break
# 曲绘文件
if self.project_info.get("Path"):
art_file = f"{self.project_info['Path']}.png"
art_path = os.path.join(self.project_folder, art_file)
if os.path.exists(art_path):
core_files.append((art_file, art_path))
if not core_files:
MessageBox("警告", "没有找到可打包的文件!", self).exec_()
return
# 创建zip文件
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for filename, file_path in core_files:
zipf.write(file_path, filename)
MessageBox("成功", f"工程已打包为:{zip_filename}", self).exec_()
# 询问是否打开文件夹
if MessageBox("打开文件夹", "是否打开工程文件夹查看打包结果?", self).exec_():
if os.name == 'nt': # Windows
os.startfile(self.project_folder)
elif os.name == 'posix': # macOS and Linux
subprocess.run(['open', self.project_folder])