forked from Class-Widgets/Class-Widgets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu.py
More file actions
6413 lines (5788 loc) · 288 KB
/
menu.py
File metadata and controls
6413 lines (5788 loc) · 288 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 datetime
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import zipfile
from copy import deepcopy
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
from loguru import logger
from packaging.version import Version
from PyQt5 import QtCore, uic
from PyQt5.QtCore import (
QDate,
QLocale,
QObject,
QSize,
Qt,
QThread,
QTime,
QTimer,
QTranslator,
QUrl,
pyqtSignal,
)
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, QPainter
from PyQt5.QtWidgets import (
QApplication,
QFileDialog,
QFrame,
QHBoxLayout,
QHeaderView,
QLabel,
QListWidgetItem,
QScroller,
QSizePolicy,
QSpacerItem,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from qfluentwidgets import (
Action,
BodyLabel,
CalendarPicker,
CaptionLabel,
CardWidget,
ColorDialog,
ComboBox,
Dialog,
DisplayLabel,
DropDownToolButton,
EditableComboBox,
FlowLayout,
FluentTranslator,
FluentWindow,
Flyout,
FlyoutAnimationType,
FlyoutView,
FlyoutViewBase,
HyperlinkLabel,
IconWidget,
ImageLabel,
InfoBar,
InfoBarIcon,
InfoBarPosition,
LineEdit,
ListWidget,
MessageBox,
MessageBoxBase,
NavigationItemPosition,
PlainTextEdit,
PrimaryDropDownPushButton,
PrimaryPushButton,
PushButton,
RadioButton,
RoundMenu,
SearchLineEdit,
Slider,
SmoothScrollArea,
SpinBox,
StrongBodyLabel,
SubtitleLabel,
SwitchButton,
TableWidget,
Theme,
TimeEdit,
ToolButton,
ToolTipFilter,
ToolTipPosition,
TransparentDropDownToolButton,
TransparentToolButton,
isDarkTheme,
setTheme,
)
from qfluentwidgets import FluentIcon as fIcon
from qfluentwidgets.common import themeColor
from qfluentwidgets.components.widgets import ListItemDelegate
import conf
import i18n_manager
import list_
import tip_toast
import utils
import weather as wd
from basic_dirs import CONFIG_HOME, CW_HOME, PLUGIN_HOME, SCHEDULE_DIR, THEME_HOME
from cses_mgr import CSES_Converter
from file import config_center, load_from_json, schedule_center
from generate_speech import (
TTSEngine,
generate_speech_sync,
get_available_engines,
get_supported_languages,
get_tts_service,
get_voice_name_by_id_sync,
)
from network_thread import VersionThread, getCity, scheduleThread
from plugin import p_loader
from plugin_plaza import PluginPlaza
class I18nManager:
"""i18n"""
def __init__(self):
self.translators = []
self.available_languages_view = {}
self.available_languages_widgets = {}
self.current_language_view = 'zh_CN'
self.completed_i18n_config = {}
self.config_file_path = CW_HOME / "data" / "completed_i18n.json"
self.load_completed_i18n_config()
self.scan_available_languages()
def load_completed_i18n_config(self):
"""加载完整翻译配置文件"""
try:
if self.config_file_path.exists():
with open(self.config_file_path, encoding='utf-8') as f:
self.completed_i18n_config = json.load(f)
logger.info(f"已加载翻译完整性配置: {self.config_file_path}")
else:
self.completed_i18n_config = {
"last_updated": "",
"completed_languages": {"main": ["zh_CN"], "themes": {}},
}
logger.warning("翻译完整性配置文件不存在")
except Exception as e:
logger.error(f"加载翻译完整性配置时出错: {e}")
self.completed_i18n_config = {
"last_updated": "",
"completed_languages": {"main": ["zh_CN"], "themes": {}},
}
def scan_available_languages(self):
try:
completed_main_langs = self.completed_i18n_config.get("completed_languages", {}).get(
"main", []
)
for lang_code in completed_main_langs:
if name := self._get_language_display_name(lang_code):
self.available_languages_view[lang_code] = name
else:
logger.warning(f"{lang_code} 未在语言映射中找到显示名称")
completed_themes = self.completed_i18n_config.get("completed_languages", {}).get(
"themes", {}
)
all_theme_langs = set()
for _theme_name, lang_list in completed_themes.items():
all_theme_langs.update(lang_list)
for lang_code in all_theme_langs:
if name := self._get_language_display_name(lang_code):
self.available_languages_widgets[lang_code] = name
if not self.available_languages_view:
self.available_languages_view['zh_CN'] = '简体中文'
if not self.available_languages_widgets:
self.available_languages_widgets['zh_CN'] = '简体中文'
logger.info(f"可用界面语言: {list(self.available_languages_view.keys())}")
logger.info(f"可用组件语言: {list(self.available_languages_widgets.keys())}")
except Exception as e:
logger.error(f"扫描语言包时出错: {e}")
if not self.available_languages_view:
self.available_languages_view['zh_CN'] = '简体中文'
if not self.available_languages_widgets:
self.available_languages_widgets['zh_CN'] = '简体中文'
def _get_language_display_name(self, lang_code):
"""获取语言显示名称"""
language_names = {
'zh_CN': '简体中文',
'zh_HK': '繁體中文(HK)',
'zh_SIMPLIFIED': '梗体中文',
'en_US': 'English',
'ja_JP': '日本語',
'bo': 'བོད་ཡིག', # 藏语
'ug': 'ئۇيغۇرچە', # 维吾尔语
'ko_KR': '한국어',
'fr_FR': 'Français',
'de_DE': 'Deutsch',
'es_ES': 'Español',
'ru_RU': 'Русский',
'pt_BR': 'Português (Brasil)',
'it_IT': 'Italiano',
'ar_SA': 'العربية',
}
return language_names.get(lang_code)
def get_available_languages_QLocale(self, lang_code):
locale_list = {
'zh_CN': QLocale(QLocale.Chinese, QLocale.China),
'zh_HK': QLocale(QLocale.Chinese, QLocale.HongKong),
'en_US': QLocale(QLocale.English, QLocale.UnitedStates),
'ja_JP': QLocale(QLocale.Japanese, QLocale.Japan),
}
return locale_list.get(lang_code, QLocale(QLocale.English, QLocale.UnitedStates))
def get_available_languages_view(self):
"""获取可用界面语言列表"""
keys = set(self.available_languages_view.keys()) & set(
self.available_languages_widgets.keys()
)
return {key: self.available_languages_view[key] for key in keys}
def get_current_language_view_name(self):
"""获取当前界面语言名称"""
return self._get_language_display_name(self.current_language_view)
def get_current_language_widgets_name(self):
"""获取当前组件语言名称"""
return self._get_language_display_name(self.current_language_widgets)
def load_language_view(self, lang_code):
"""加载界面语言文件"""
current_lang = self.current_language_view
try:
app = QApplication.instance()
if not app:
return False
self.clear_translators()
main_translator = self._load_translation_file(CW_HOME / 'i18n' / f'{lang_code}.qm')
if main_translator:
self.translators.append(main_translator)
app.installTranslator(main_translator)
self.current_language_view = lang_code
# config_center.write_conf('General', 'language_view', lang_code)
logger.success(
f"成功加载界面语言: {lang_code} ({self.available_languages_view.get(lang_code, lang_code)})"
)
else:
logger.warning(
f"无法加载界面语言: {lang_code} ({self.available_languages_view.get(lang_code, lang_code)})"
)
self.load_language_view(current_lang)
return False
current_theme = conf.load_theme_config(config_center.read_conf('General', 'theme'))
theme_translator = self._load_translation_file(
Path(current_theme.path / 'i18n' / f'{lang_code}.qm')
)
if theme_translator:
self.translators.append(theme_translator)
app.installTranslator(theme_translator)
self.current_language_widgets = lang_code
logger.success(
f"成功加载组件语言: {lang_code} ({self.available_languages_widgets.get(lang_code, lang_code)})"
)
else:
logger.warning(
f"无法加载组件语言: {lang_code} ({self.available_languages_widgets.get(lang_code, lang_code)})"
)
self.load_language_view(current_lang)
return False
translator_qfw = FluentTranslator(self.get_available_languages_QLocale(lang_code))
if translator_qfw:
self.translators.append(translator_qfw)
app.installTranslator(translator_qfw)
logger.success(f"成功加载 FluentWidgets 语言: {lang_code}")
import importlib
importlib.reload(list_)
if utils.main_mgr is not None:
utils.main_mgr.clear_widgets()
return True
except Exception as e:
logger.error(f"加载界面语言包 {lang_code} 时出错: {e}")
self.load_language_view(current_lang)
return False
def _load_translation_file(self, qm_path):
"""加载翻译"""
try:
if not qm_path.exists():
# 编译,仅开发用(不应该在这编译)
ts_path = qm_path.with_suffix('.ts')
if ts_path.exists():
self._compile_ts_to_qm(ts_path, qm_path)
if qm_path.exists():
translator = QTranslator()
if translator.load(str(qm_path)):
# logger.debug(f"成功加载文件: {qm_path}")
return translator
logger.warning(f"无法加载文件: {qm_path}")
else:
logger.warning(f"文件不存在: {qm_path}")
except Exception as e:
logger.error(f"加载文件 {qm_path} 时出错: {e}")
return None
def _compile_ts_to_qm(self, ts_path, qm_path):
try:
import subprocess
result = subprocess.run(
['lrelease', str(ts_path), '-qm', str(qm_path)],
check=False,
capture_output=True,
text=True,
)
if result.returncode == 0:
logger.info(f"成功编译翻译文件: {ts_path} -> {qm_path}")
return True
logger.warning(f"编译翻译文件失败: {result.stderr}")
except FileNotFoundError:
logger.warning("未找到lrelease工具,无法编译翻译文件")
except Exception as e:
logger.error(f"编译翻译文件时出错: {e}")
return False
def clear_translators(self):
"""清除翻译器"""
app = QApplication.instance()
if app:
for translator in self.translators:
app.removeTranslator(translator)
self.translators.clear()
def init_from_config(self):
"""初始化设置"""
try:
saved_language_view = config_center.read_conf('General', 'language_view', 'system')
if saved_language_view == 'system':
saved_language_view = QLocale.system().name()
if saved_language_view in self.get_available_languages_view():
self.load_language_view(saved_language_view)
else:
logger.warning(f"配置的界面语言 {saved_language_view} 不可用")
self.load_language_view('zh_CN')
except Exception as e:
logger.error(f"从配置初始化语言时出错: {e}")
self.load_language_view('zh_CN')
import builtins
import contextlib
from PyQt5.QtCore import QCoreApplication
global_i18n_manager = None
today = utils.TimeManagerFactory.get_instance().get_today()
plugin_plaza = None
plugin_dict = {} # 插件字典
enabled_plugins = {} # 启用的插件列表
morning_st = 0
afternoon_st = 0
current_week = 0
loaded_data = schedule_center.schedule_data
schedule_dict = {} # 对应时间线的课程表
schedule_even_dict = {} # 对应时间线的课程表(双周)
timeline_dict = {'odd': {}, 'even': {}} # 时间
countdown_dict = {}
def open_plaza():
global plugin_plaza
if plugin_plaza is None or not plugin_plaza.isVisible():
plugin_plaza = PluginPlaza()
plugin_plaza.show()
plugin_plaza.closed.connect(cleanup_plaza)
logger.info('打开“插件广场”')
else:
plugin_plaza.raise_()
plugin_plaza.activateWindow()
def cleanup_plaza():
global plugin_plaza
logger.info('关闭“插件广场”')
def get_timeline() -> Dict[str, Dict[str, List[Tuple[int, str, int, int]]]]:
global loaded_data
loaded_data = schedule_center.schedule_data
return {'odd': loaded_data['timeline'], 'even': loaded_data['timeline_even']}
def open_dir(path: str):
if sys.platform.startswith('win32'):
os.startfile(path)
elif sys.platform.startswith('linux'):
subprocess.run(['xdg-open', path], check=False)
else:
msg_box = Dialog(
QCoreApplication.translate('menu', '无法打开文件夹'),
QCoreApplication.translate(
'menu',
'Class Widgets 在您的系统下不支持自动打开文件夹,请手动打开以下地址:\n{path}',
).format(path=path),
)
msg_box.yesButton.setText(QCoreApplication.translate('menu', '好'))
msg_box.cancelButton.hide()
msg_box.buttonLayout.insertStretch(0, 1)
msg_box.setFixedWidth(550)
msg_box.exec()
def switch_checked(section, key, checked):
if checked:
config_center.write_conf(section, key, '1')
else:
config_center.write_conf(section, key, '0')
if key == 'auto_startup':
if checked:
utils.add_to_startup()
else:
utils.remove_from_startup()
def get_theme_name():
return conf.load_theme_config(config_center.read_conf('General', 'theme')).path.name
def load_schedule_dict(schedule, week_type, part, part_name):
"""
加载课表字典
"""
schedule_dict_ = {}
for week, item in schedule.items():
all_class = []
count = [] # 初始化计数器
for _i in range(len(part)):
count.append(0)
if (
str(week) in loaded_data['timeline_even' if week_type else 'timeline']
and loaded_data['timeline_even' if week_type else 'timeline'][str(week)]
):
timeline = get_timeline()['even' if week_type else 'odd'][str(week)]
else:
timeline = get_timeline()['even' if week_type else 'odd']['default']
for isbreak, item_name, item_index, _item_time in timeline:
if not isbreak:
try:
count_num = 0 if item_name == '0' else sum(count[: int(item_name)])
prefix = item[item_index - 1 + count_num]
period = part_name[str(item_name)]
all_class.append(f'{prefix}-{period}')
except IndexError or ValueError: # 未设置值
prefix = QCoreApplication.translate('menu', '未添加')
period = part_name[str(item_name)]
all_class.append(f'{prefix}-{period}')
count[int(item_name)] += 1
schedule_dict_[week] = all_class
return schedule_dict_
def convert_to_dict(data_dict_):
data_dict = {}
for week, item in data_dict_.items():
cache_list = item
replace_list = []
for activity_num in range(len(cache_list)):
item_info = cache_list[int(activity_num)].split('-')
replace_list.append(item_info[0])
data_dict[str(week)] = replace_list
return data_dict
def se_load_item():
global schedule_dict
global schedule_even_dict
global loaded_data
loaded_data = schedule_center.schedule_data
part_name = loaded_data.get('part_name')
part = loaded_data.get('part')
schedule = loaded_data.get('schedule')
schedule_even = loaded_data.get('schedule_even')
schedule_dict = load_schedule_dict(schedule, 0, part, part_name)
schedule_even_dict = load_schedule_dict(schedule_even, 1, part, part_name)
def cd_load_item():
global countdown_dict
text = config_center.read_conf('Date', 'cd_text_custom').split(',')
date = config_center.read_conf('Date', 'countdown_date').split(',')
if len(text) != len(date):
countdown_dict = {
"Err": f"len(cd_text_custom) (={len(text)}) != len(countdown_date) (={len(date)})"
}
raise Exception(
f"len(cd_text_custom) (={len(text)}) != len(countdown_date) (={len(date)})"
f"len(cd_text_custom) (={len(text)}) != len(countdown_date) (={len(date)}) \n 请检查 config.ini [Date] 项!!"
)
countdown_dict = dict(zip(date, text))
class selectCity(MessageBoxBase): # 选择城市
def __init__(self, parent=None, method='location_key'):
super().__init__(parent)
title_label = SubtitleLabel()
subtitle_label = BodyLabel()
self.method = method
if method == 'location_key':
self.search_edit = SearchLineEdit()
title_label.setText(QCoreApplication.translate('menu', '搜索城市'))
subtitle_label.setText(QCoreApplication.translate('menu', '请输入当地城市名进行搜索'))
self.yesButton.setText(QCoreApplication.translate('menu', '选择此城市'))
self.cancelButton.setText(QCoreApplication.translate('menu', '取消'))
self.search_edit.setPlaceholderText(QCoreApplication.translate('menu', '输入城市名'))
self.search_edit.setClearButtonEnabled(True)
self.search_edit.textChanged.connect(self.search_city)
self.city_list = ListWidget()
self.city_list.addItems(wd.search_by_name(''))
self.get_selected_city()
self.viewLayout.addWidget(title_label)
self.viewLayout.addWidget(subtitle_label)
self.viewLayout.addWidget(self.search_edit)
self.viewLayout.addWidget(self.city_list)
self.widget.setMinimumWidth(500)
self.widget.setMinimumHeight(600)
else:
title_label.setText(QCoreApplication.translate('menu', '手动输入经纬度'))
subtitle_label.setText(QCoreApplication.translate('menu', '请输入当地的经度和纬度'))
self.yesButton.setText(QCoreApplication.translate('menu', '确定'))
self.cancelButton.setText(QCoreApplication.translate('menu', '取消'))
longitude_label = QLabel(QCoreApplication.translate('menu', '经度'))
latitude_label = QLabel(QCoreApplication.translate('menu', '纬度'))
self.longitude_edit = LineEdit()
self.latitude_edit = LineEdit()
self.longitude_edit.setPlaceholderText(
QCoreApplication.translate('menu', '经度,例如 116.40')
)
self.latitude_edit.setPlaceholderText(
QCoreApplication.translate('menu', '纬度,例如 39.90')
)
self._populate_coordinates_from_config()
# 新增按钮
self.btn_internet = PushButton(
QCoreApplication.translate('menu', '通过互联网获取经纬度')
)
self.btn_internet.clicked.connect(self.get_coordinates_from_internet)
# if platform.system() in ['Windows', 'Darwin']:
# btn_sysapi = PushButton(QCoreApplication.translate('menu', '通过系统获取经纬度'))
# btn_sysapi.clicked.connect(self.get_coordinates_from_system)
self.error_text = QLabel()
self.error_text.setStyleSheet("color: red;")
self.error_text.hide()
self.longitude_edit.textChanged.connect(lambda: self._check_coordinates())
self.latitude_edit.textChanged.connect(lambda: self._check_coordinates())
self.viewLayout.addWidget(title_label)
self.viewLayout.addWidget(subtitle_label)
self.viewLayout.addWidget(longitude_label)
self.viewLayout.addWidget(self.longitude_edit)
self.viewLayout.addWidget(latitude_label)
self.viewLayout.addWidget(self.latitude_edit)
self.viewLayout.addWidget(self.btn_internet)
self.viewLayout.addWidget(self.error_text)
# if platform.system() in ['Windows', 'Darwin']:
# self.viewLayout.addWidget(btn_sysapi)
self.widget.setMinimumWidth(400)
self.widget.setMinimumHeight(250)
def search_city(self):
if self.method != 'location_key':
raise ValueError("Method must be 'location_key' for city search.")
self.city_list.clear()
self.city_list.addItems(wd.search_by_name(self.search_edit.text()))
self.city_list.clearSelection() # 清除选中项
def get_selected_city(self):
if self.method != 'location_key':
raise ValueError("Method must be 'location_key' for city search.")
selected_city = self.city_list.findItems(
wd.search_by_num(str(config_center.read_conf('Weather', 'city'))),
QtCore.Qt.MatchFlag.MatchExactly,
)
if selected_city: # 若找到该城市
item = selected_city[0]
# 选中该项
self.city_list.setCurrentItem(item)
# 聚焦该项
self.city_list.scrollToItem(item)
def _lock_input(self):
"""锁定输入框"""
self.longitude_edit.setReadOnly(True)
self.latitude_edit.setReadOnly(True)
self.btn_internet.setEnabled(False)
def _unlock_input(self):
"""解锁输入框"""
self.longitude_edit.setReadOnly(False)
self.latitude_edit.setReadOnly(False)
self.btn_internet.setEnabled(True)
def _catch_error(self, error_message: str):
"""处理错误"""
self._unlock_input()
Flyout.create(
icon=InfoBarIcon.ERROR,
title=self.tr("经纬度获取失败"),
content=f"{error_message}",
target=self.btn_internet,
parent=self,
isClosable=True,
aniType=FlyoutAnimationType.PULL_UP,
)
logger.error(f"获取经纬度失败: {error_message}")
def _check_coordinates(self):
try:
try:
lon, lat = float(self.longitude_edit.text()), float(self.latitude_edit.text())
except ValueError:
raise ValueError(self.tr("经度和纬度必须是数字。"))
if not (-180 <= lon <= 180 and -90 <= lat <= 90):
raise ValueError(
self.tr("经度必须在 -180 到 180 之间,纬度必须在 -90 到 90 之间。")
)
self.yesButton.setEnabled(True)
self.error_text.hide()
except Exception as e:
self.yesButton.setEnabled(False)
self.error_text.setText(f"{e}")
self.error_text.show()
def get_coordinates_from_internet(self):
"""通过网络获取经纬度"""
self._lock_input()
if not hasattr(self, '_coordinates_threads'):
self._coordinates_threads = []
self.coordinates_thread = getCity(mode='coordinates_only')
self.coordinates_thread.coordinates_signal.connect(self.set_coordinates)
self.coordinates_thread.error_signal.connect(self._catch_error)
self.coordinates_thread.finished_signal.connect(
lambda: self._cleanup_coordinates_thread(self.coordinates_thread)
)
self.coordinates_thread.start()
self._coordinates_threads.append(self.coordinates_thread)
def _cleanup_coordinates_thread(self, thread):
"""清理已完成的线程引用"""
if hasattr(self, '_coordinates_threads') and thread in self._coordinates_threads:
self._coordinates_threads.remove(thread)
def set_coordinates(self, latitude, longitude):
"""设置经纬度到输入框"""
self._unlock_input()
self.latitude_edit.setText(str(latitude))
self.longitude_edit.setText(str(longitude))
def _populate_coordinates_from_config(self):
"""从配置文件中读取经纬度信息并填充到输入框"""
try:
city_config = config_center.read_conf('Weather', 'city')
if city_config and ',' in city_config:
coords = city_config.split(',')
if len(coords) == 2:
try:
longitude = float(coords[0].strip())
latitude = float(coords[1].strip())
self.longitude_edit.setText(str(longitude))
self.latitude_edit.setText(str(latitude))
except ValueError:
logger.debug("配置文件中的城市信息不是有效的经纬度格式")
except Exception as e:
logger.error(f"从配置文件读取经纬度信息失败: {e}")
# class getCoordinatesSystem(QThread):
# location_ready = pyqtSignal(float, float)
# def run(self):
# if platform.system() == 'Windows':
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# try:
# result = loop.run_until_complete(self.get_location_windows())
# self.location_ready.emit(*result)
# except Exception as e:
# logger.error(f"获取位置失败: {e}")
# finally:
# loop.close()
# elif platform.system() == 'Darwin':
# self.get_location_macos()
# async def get_location_windows(self):
# if platform.system() != 'Windows':
# raise ValueError("This method is only for Windows.")
# from winrt.windows.devices.geolocation import Geolocator
# geolocator = Geolocator()
# pos = await geolocator.get_geoposition_async()
# coord = pos.coordinate.point.position
# return coord.latitude, coord.longitude
# def get_location_macos(self):
# if platform.system() != 'Darwin':
# raise ValueError("This method is only for macOS.")
# try:
# from Cocoa import NSObject, NSRunLoop, NSDefaultRunLoopMode
# from CoreLocation import CLLocationManager, kCLLocationAccuracyBest
# import time
# class LocationDelegate(NSObject):
# def init(self):
# self = super(LocationDelegate, self).init()
# if self:
# self.location = None
# return self
# def locationManager_didUpdateLocations_(self, manager, locations):
# self.location = locations[-1]
# manager.stopUpdatingLocation()
# delegate = LocationDelegate.alloc().init()
# manager = CLLocationManager.alloc().init()
# manager.setDelegate_(delegate)
# manager.setDesiredAccuracy_(kCLLocationAccuracyBest)
# manager.requestWhenInUseAuthorization()
# manager.startUpdatingLocation()
# timeout = time.time() + 10 # 最多等待10秒
# while not delegate.location and time.time() < timeout:
# NSRunLoop.currentRunLoop().runMode_beforeDate_(
# NSDefaultRunLoopMode, time.time() + 0.1
# )
# if delegate.location:
# coord = delegate.location.coordinate()
# return coord.latitude(), coord.longitude()
# except Exception as e:
# self.location_error.emit(str(e))
# def get_coordinates_from_system(self):
# """通过系统获取经纬度"""
# self.coordinates_thread = self.getCoordinatesSystem()
# self.coordinates_thread.location_ready.connect(self.set_coordinates)
# self.coordinates_thread.start()
class licenseDialog(MessageBoxBase): # 显示软件许可协议
def __init__(self, parent=None):
super().__init__(parent)
title_label = SubtitleLabel()
subtitle_label = BodyLabel()
self.license_text = PlainTextEdit()
title_label.setText(QCoreApplication.translate('menu', '软件许可协议'))
subtitle_label.setText(
QCoreApplication.translate(
'menu', '此项目 (Class Widgets) 基于 GPL-3.0 许可证授权发布,详情请参阅:'
)
)
self.yesButton.setText(QCoreApplication.translate('menu', '好')) # 按钮组件汉化
self.cancelButton.hide()
self.buttonLayout.insertStretch(0, 1)
with open('LICENSE', encoding='utf-8') as f:
self.license_text.setPlainText(f.read())
self.license_text.setReadOnly(True)
# 将组件添加到布局中
self.viewLayout.addWidget(title_label)
self.viewLayout.addWidget(subtitle_label)
self.viewLayout.addWidget(self.license_text)
self.widget.setMinimumWidth(600)
self.widget.setMinimumHeight(500)
class PluginSettingsDialog(MessageBoxBase): # 插件设置对话框
def __init__(self, plugin_dir=None, parent=None):
if plugin_dir not in p_loader.plugins_settings:
return
super().__init__(parent)
self.plugin_widget = None
self.plugin_dir = plugin_dir
self.parent = parent
self.init_ui()
def init_ui(self):
# 加载已定义的UI
self.plugin_widget = p_loader.plugins_settings[self.plugin_dir]
self.viewLayout.addWidget(self.plugin_widget)
self.viewLayout.setContentsMargins(0, 0, 0, 0)
self.cancelButton.hide()
self.buttonLayout.insertStretch(0, 1)
self.widget.setMinimumWidth(875)
self.widget.setMinimumHeight(625)
class PluginCard(CardWidget): # 插件卡片
def __init__(
self,
icon,
title='Unknown',
content='Unknown',
version='1.0.0',
plugin_dir='',
author=None,
parent=None,
enable_settings=None,
url='',
):
super().__init__(parent)
icon_radius = 5
self.plugin_dir = plugin_dir
self.title = title
self.parent = parent
self.url = url
self.enable_settings = enable_settings
self.iconWidget = ImageLabel(icon) # 插件图标
self.titleLabel = StrongBodyLabel(title, self) # 插件名
self.versionLabel = BodyLabel(version, self) # 插件版本
self.authorLabel = BodyLabel(author, self) # 插件作者
self.contentLabel = CaptionLabel(content, self) # 插件描述
self.enableButton = SwitchButton()
self.moreButton = TransparentDropDownToolButton()
self.moreMenu = RoundMenu(parent=self.moreButton)
self.settingsBtn = TransparentToolButton() # 设置按钮
self.settingsBtn.hide()
self.hBoxLayout = QHBoxLayout()
self.hBoxLayout_Title = QHBoxLayout()
self.vBoxLayout = QVBoxLayout()
menu_actions = [
Action(
fIcon.FOLDER,
QCoreApplication.translate('menu', '打开“{title}”插件文件夹').format(title=title),
triggered=lambda: open_dir(str(PLUGIN_HOME / self.plugin_dir)),
)
]
if self.url:
menu_actions.append(
Action(
fIcon.LINK,
QCoreApplication.translate('menu', '访问“{title}”插件页面').format(title=title),
triggered=lambda: QDesktopServices.openUrl(QUrl(self.url)),
)
)
menu_actions.append(
Action(
fIcon.DELETE,
QCoreApplication.translate('menu', '卸载“{title}”插件').format(title=title),
triggered=self.remove_plugin,
)
)
self.moreMenu.addActions(menu_actions)
plugin_config = conf.load_plugin_config()
is_temp_disabled = plugin_dir in plugin_config.get('temp_disabled_plugins', [])
if plugin_dir in enabled_plugins['enabled_plugins']: # 插件是否启用
self.enableButton.setChecked(True)
if enable_settings and plugin_dir in p_loader.plugins_settings:
self.moreMenu.addSeparator()
self.moreMenu.addAction(
Action(fIcon.SETTING, f'"{title}"插件设置', triggered=self.show_settings)
)
self.settingsBtn.show()
if is_temp_disabled:
self.enableButton.setEnabled(False)
self.enableButton.setChecked(False)
self.enableButton.setToolTip(
QCoreApplication.translate('menu', '此插件被临时禁用,重启后将尝试重新加载')
)
self.titleLabel.setText(
QCoreApplication.translate('menu', '{title} (已临时禁用)').format(title=title)
)
self.titleLabel.setStyleSheet('color: #999999;')
self.setFixedHeight(73)
self.iconWidget.setFixedSize(48, 48)
self.moreButton.setFixedSize(34, 34)
self.iconWidget.setBorderRadius(icon_radius, icon_radius, icon_radius, icon_radius) # 圆角
self.contentLabel.setTextColor("#606060", "#d2d2d2")
self.contentLabel.setMaximumWidth(500)
self.contentLabel.setWordWrap(True) # 自动换行
self.versionLabel.setTextColor("#999999", "#999999")
self.authorLabel.setTextColor("#606060", "#d2d2d2")
self.enableButton.checkedChanged.connect(self.set_enable)
self.enableButton.setOffText(QCoreApplication.translate('menu', '禁用'))
self.enableButton.setOnText(QCoreApplication.translate('menu', '启用'))
self.moreButton.setMenu(self.moreMenu)
self.settingsBtn.setIcon(fIcon.SETTING)
self.settingsBtn.clicked.connect(self.show_settings)
self.hBoxLayout.setContentsMargins(20, 11, 11, 11)
self.hBoxLayout.setSpacing(15)
self.hBoxLayout.addWidget(self.iconWidget)
# 内容
self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
self.vBoxLayout.setSpacing(0)
self.vBoxLayout.addLayout(self.hBoxLayout_Title)
self.vBoxLayout.addWidget(self.contentLabel, 0, Qt.AlignmentFlag.AlignVCenter)
self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)
self.hBoxLayout.addLayout(self.vBoxLayout, 1) # !!!
# 标题栏
self.hBoxLayout_Title.setSpacing(12)
self.hBoxLayout_Title.setAlignment(Qt.AlignmentFlag.AlignLeft)
self.hBoxLayout_Title.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignVCenter)
self.hBoxLayout_Title.addWidget(self.authorLabel, 0, Qt.AlignmentFlag.AlignVCenter)
self.hBoxLayout_Title.addWidget(self.versionLabel, 0, Qt.AlignmentFlag.AlignVCenter)
self.hBoxLayout.addStretch(1)
self.hBoxLayout.addWidget(self.settingsBtn, 0, Qt.AlignmentFlag.AlignRight)
self.hBoxLayout.addWidget(self.enableButton, 0, Qt.AlignmentFlag.AlignRight)
self.hBoxLayout.addWidget(self.moreButton, 0, Qt.AlignmentFlag.AlignRight)
self.setLayout(self.hBoxLayout)
def set_enable(self):
global enabled_plugins
if self.enableButton.isChecked():
enabled_plugins['enabled_plugins'].append(self.plugin_dir)
conf.save_plugin_config(enabled_plugins)
else:
enabled_plugins['enabled_plugins'].remove(self.plugin_dir)
conf.save_plugin_config(enabled_plugins)
def show_settings(self):
w = PluginSettingsDialog(self.plugin_dir, self.parent)
if w:
w.exec()
def remove_plugin(self):
alert = MessageBox(
QCoreApplication.translate('menu', "您确定要删除插件“{title}”吗?").format(
title=self.title
),
QCoreApplication.translate('menu', "删除此插件后,将无法恢复。"),
self.parent,
)
alert.yesButton.setText(self.tr('永久删除'))
alert.yesButton.setStyleSheet(
"""
PushButton{
border-radius: 5px;
padding: 5px 12px 6px 12px;
outline: none;
}
PrimaryPushButton{
color: white;
background-color: #FF6167;
border: 1px solid #FF8585;
border-bottom: 1px solid #943333;
}
PrimaryPushButton:hover{
background-color: #FF7E83;
border: 1px solid #FF8084;
border-bottom: 1px solid #B13939;
}
PrimaryPushButton:pressed{