-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3487 lines (2900 loc) · 152 KB
/
main.py
File metadata and controls
3487 lines (2900 loc) · 152 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
# ### 1.4.4
# - **新增**:`Alt+B` 立即备份(顶部显示提示,2秒后消失,颜色可自定义)
# - **新增**:内置配置模板与自动补全(旧版 config.txt 直接放入即自动添加新配置项,保留你的所有修改)
__author__ = "蜜柑魚"
# 在頂部導入
import os
import sys
import re
import time
import logging
import shutil
import threading
import queue
from datetime import datetime, timedelta
from pathlib import Path
from collections import deque
# tkinter 相關
import tkinter as tk
import tkinter.font as tkfont
# Windows API
import ctypes
# 鍵盤全局快捷鍵
try:
import keyboard
KEYBOARD_AVAILABLE = True
KEYBOARD_MODULE = keyboard # 新增:保存模組引用
except ImportError:
KEYBOARD_AVAILABLE = False
KEYBOARD_MODULE = None # 新增:設置為 None
logging.warning("keyboard 庫未安裝,全局快捷鍵不可用")
# 創建虛擬的 KeyboardEvent 類以避免 NameError
class KeyboardEvent:
pass
def get_base_path():
"""获取程序运行的基础路径"""
try:
if getattr(sys, 'frozen', False):
base_path = os.path.dirname(sys.executable)
else:
base_path = os.path.dirname(os.path.abspath(__file__))
# 确保路径存在
if not os.path.exists(base_path):
os.makedirs(base_path, exist_ok=True)
return base_path
except Exception as e:
logging.error(f"获取基础路径失败: {str(e)}")
return os.getcwd() # 回退到当前工作目录
# 配置日志系统 - 只保留控制台输出
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[logging.StreamHandler()]
)
class ConfigLoader:
# 內嵌完整設定檔模板(基於用戶提供的 config.txt,log_path 保持註解狀態)
DEFAULT_CONFIG_TEMPLATE = '''# BetterGI日志悬浮窗配置文件
# =============================================
# 基本设置段 - 程序运行必需的核心参数
# =============================================
# 日志文件目录路径(必须设置)
# 请修改为您的BetterGI日志实际目录路径
# 示例:log_path=C:\\Program Files\\BetterGI\\log
# log_path=D:\\BetterGI\\BetterGI_060\\log
# 日志文件名前缀(通常不需要修改)
log_filename_prefix=better-genshin-impact
# 窗口预设位置X坐标
initial_x=0
# 窗口预设位置Y坐标
initial_y=0
# 是否跳过调试日志 (true-跳过, false-显示)
skip_debug_log=false
# 自适应高度
dynamic_height=true
# 备份配置
# -----------------
# 备份目录路径(留空则不备份,设置路径会自动启用备份功能)
# backup_path=X:\\我的雲端硬碟\\BGI_log
# backup_path=
# 备份间隔(分钟),默认30
backup_interval=30
# 保留最近多少天的备份文件,默认7
backup_keep_days=6
# 调试开关:启动时立即备份一次
backup_debug=false
# 是否启用准点备份(true-按整点分钟对齐,false-相对时间模式)
backup_align_to_clock=true
# =============================================
# 主样式段 - 用户自定义设置
# =============================================
# 窗口透明度 (0.1-1.0,1.0为完全不透明)
window_alpha=0.7
# 窗口背景颜色(十六进制颜色代码)
bg_color=#000000
# 正常状态文字颜色
normal_color=#00FF00
# 超时警告文字颜色(60秒无更新时显示)
stale_color=#FF0000
# 高频切换警告文字颜色
high_freq_color=#FFA500
# 备份临时消息文字颜色
backup_msg_color=#FFD700
# DBG级别日志文字颜色
debug_color=#808080
# ERR级别日志文字颜色
error_color=#FF6B6B
# WRN级别日志文字颜色
warning_color=#FFD700
# 状态行标题颜色(配置组行)
status_header_color=#87CEFA
# 任务行标题颜色
task_header_color=#87CEFA
# 字体名称(请确保系统中已安装该字体)
font_name=Consolas
# 字体大小
font_size=12
# 字体粗细 (normal-正常, bold-粗体)
font_weight=bold
# 窗口最大宽度(像素)
max_width=768
# 窗口最大高度(像素)
max_height=288
# 日志记录显示行数
display_lines=13
# 窗口刷新间隔(毫秒)
refresh_interval=1000
# 是否啟用自動換行
auto_wrap=true
# =============================================
# 第二样式配置段 - 使用Alt+K切换到此样式
# =============================================
# 第二样式窗口透明度
style2_window_alpha=0.7
# 第二样式窗口背景颜色
style2_bg_color=#000000
# 第二样式正常状态文字颜色
style2_normal_color=#FFFFFF
# 第二样式超时警告文字颜色
style2_stale_color=#FFFFFF
# 第二样式高频警告文字颜色
style2_high_freq_color=#FFFFFF
# 备份临时消息文字颜色(第二样式)
style2_backup_msg_color=#FFD700
# 第二样式DBG级别日志文字颜色
style2_debug_color=#808080
# 第二样式ERR级别日志文字颜色
style2_error_color=#FF6B6B
# 第二样式WRN级别日志文字颜色
style2_warning_color=#FFD700
# 第二样式状态行标题颜色
style2_status_header_color=#00FF00
# 第二样式任务行标题颜色
style2_task_header_color=#00FFFF
# 第二样式字体名称
style2_font_name=Consolas
# 第二样式字体大小
style2_font_size=9
# 第二样式字体粗细
style2_font_weight=bold
# 第二样式窗口最大宽度
style2_max_width=460
# 第二样式窗口最大高度
style2_max_height=220
# 第二样式日志记录显示行数
style2_display_lines=12
# 第二样式窗口刷新间隔
style2_refresh_interval=500
# 第二样式是否啟用自動換行
style2_auto_wrap=true
# =============================================
[程序自动管理配置段]
# 注意:以下配置由程序自动管理,请勿手动修改
# =============================================
# 透明背景模式状态 (true-开启, false-关闭)
# 程序根据Alt+I快捷键自动更新
transparent_mode=false
# 不可选中模式状态 (true-开启, false-关闭)
# 程序根据Alt+N快捷键自动更新
click_through=false
# 第二样式启用状态 (true-开启, false-关闭)
# 程序根据Alt+K快捷键自动更新
author_style2=false
# 窗口记忆位置X坐标
# 程序自动保存窗口关闭时的位置
window_x=
# 窗口记忆位置Y坐标
# 程序自动保存窗口关闭时的位置
window_y=
'''
def __init__(self, config_file="config.txt"):
"""配置文件加载器 - 从config.txt读取用户设置"""
script_dir = get_base_path()
self.config_file = Path(script_dir) / config_file
# 默认配置值
self.default_config = {
"log_path": "", # 原神日志文件目录路径
"log_filename_prefix": "better-genshin-impact", # 日志文件名前缀
"skip_debug_log": False, # 是否跳过调试日志
"backup_path": "", # 备份目录路径,为空则不备份
"backup_interval": 60, # 备份间隔(分钟)
"backup_debug": False, # 调试开关:初始备份一次
"backup_align_to_clock": False, # 是否启用准点备份
"backup_enabled": False, # 备份功能总开关(根据backup_path是否为空自动设置)
"backup_keep_days": 10, # 保留最近多少天的备份文件
"window_alpha": 0.7, # 窗口透明度
"bg_color": "#000000", # 背景颜色
"normal_color": "#00FF00",# 正常状态文字颜色
"stale_color": "#FF0000", # 超时警告颜色
"high_freq_color": "#FFA500", # 高频切换警告颜色
"debug_color": "#808080", # DBG级别日志颜色(灰色)
"error_color": "#FF6B6B", # ERR级别日志颜色(浅红色)
"warning_color": "#FFD700", # WRN级别日志颜色(浅黄色)
"status_header_color": "#87CEFA", # 状态行标题颜色(配置组行)
"task_header_color": "#87CEFA", # 任务行标题颜色
"backup_msg_color": "#FFD700", # 备份临时消息颜色(黄色)
"font_name": "Consolas", # 字体名称
"font_size": 11, # 字体大小
"font_weight": "bold", # 字体粗细
"max_height": 220, # 窗口最大高度
"max_width": 460, # 窗口最大宽度
"initial_x": 0, # 窗口预设位置X坐标
"initial_y": 0, # 窗口预设位置Y坐标
"display_lines": 11, # 显示行数
"refresh_interval": 1000, # 刷新间隔(毫秒)
"auto_wrap": False, # 是否启用自动换行 - 主样式默认
"transparent_mode": False, # 透明背景模式默认状态
"click_through": False, # 不可选中模式默认状态
"author_style2": False, # 仿BGI日志窗口样式默认状态
"window_x": None, # 窗口X坐标
"window_y": None, # 窗口Y坐标
"dynamic_height": False # 动态调整窗口高度
}
# 第二样式配置
self.second_style_config = {
"window_alpha": 0.7,
"bg_color": "#000000",
"normal_color": "#FFFFFF",
"stale_color": "#FFFFFF",
"high_freq_color": "#FFFFFF",
"debug_color": "#808080", # DBG级别日志颜色(灰色)
"error_color": "#FF6B6B", # ERR级别日志颜色(浅红色)
"warning_color": "#FFD700", # WRN级别日志颜色(浅黄色)
"status_header_color": "#00FF00", # 第二样式的状态行颜色
"task_header_color": "#00FFFF", # 第二样式的任务行颜色
"backup_msg_color": "#FFD700", # 第二样式备份消息颜色
"font_name": "Consolas",
"font_size": 9,
"font_weight": "bold",
"max_width": 460,
"max_height": 220,
"display_lines": 12,
"refresh_interval": 500,
"auto_wrap": True # 第二样式默认启用换行
}
self.config = self.default_config.copy()
self.user_config = self.default_config.copy() # 保存用户自定义配置
self.log_path_configured = False # 标记log_path是否已正确配置
# 保存初始的日志路径配置(只在程序开始时加载一次)
self.initial_log_path = ""
self.initial_log_filename_prefix = "better-genshin-impact"
self.initial_log_path_configured = False
# 確保設定檔完整(自動補全缺失項目)
self._ensure_config_complete()
# 加载所有配置
self.load_all_settings()
# 保存初始的日志路径配置
self.initial_log_path = self.config.get("log_path", "")
self.initial_log_filename_prefix = self.config.get("log_filename_prefix", "better-genshin-impact")
self.initial_log_path_configured = self.log_path_configured
# 如果配置中启用了第二样式,则应用
if self.config.get("author_style2", False):
self.apply_second_style()
def _ensure_config_complete(self):
"""確保 config.txt 完整:若不存在則寫入模板,若存在則補全缺失的配置項(排除 log_path 和 backup_enabled)"""
if not self.config_file.exists():
# 檔案不存在,直接寫入完整模板
try:
with open(self.config_file, 'w', encoding='utf-8') as f:
f.write(self.DEFAULT_CONFIG_TEMPLATE)
logging.info(f"已建立完整設定檔: {self.config_file}")
except Exception as e:
logging.error(f"建立設定檔失敗: {str(e)}")
return
# 檔案存在,需要補全缺失的項目
# 步驟1:讀取現有檔案中所有有效的 key=value(跳過註解行、空行)
existing_keys = set()
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
key = line.split('=', 1)[0].strip()
existing_keys.add(key)
except Exception as e:
logging.error(f"讀取設定檔失敗: {str(e)}")
return
# 步驟2:定義所有應該存在的配置項(排除 log_path 和 backup_enabled)
all_expected_keys = set()
# 加入主樣式 default_config 中的所有 key(排除 log_path 和 backup_enabled)
for key in self.default_config:
if key not in ("log_path", "backup_enabled"):
all_expected_keys.add(key)
# 加入第二樣式中的所有 key(因為它們在模板中是以 style2_ 前綴存在)
for key in self.second_style_config:
all_expected_keys.add(f"style2_{key}")
# 確保 backup_msg_color 和 style2_backup_msg_color 存在(已包含在上面的邏輯中)
# 額外確保 window_x, window_y 等程式自動管理的項目也納入補全(它們在 default_config 中)
# 但注意:backup_enabled 已經被排除
# 找出缺失的 keys
missing_keys = all_expected_keys - existing_keys
if not missing_keys:
logging.debug("設定檔完整,無需補全")
return
logging.info(f"發現缺失的配置項: {missing_keys},將自動補全")
# 步驟3:備份原檔案
backup_file = self.config_file.with_suffix('.txt.bak')
try:
shutil.copy2(self.config_file, backup_file)
logging.info(f"已備份原設定檔至: {backup_file}")
except Exception as e:
logging.warning(f"備份設定檔失敗: {str(e)}")
# 步驟4:將缺失的項目追加到檔案末尾
try:
with open(self.config_file, 'a', encoding='utf-8') as f:
f.write("\n\n# ===== 以下為程式自動補全的配置項 =====\n")
for key in sorted(missing_keys):
# 取得預設值
if key.startswith("style2_"):
# 第二樣式 key,去掉前綴後從 second_style_config 取值
inner_key = key[7:] # 移除 "style2_"
default_value = self.second_style_config.get(inner_key, "")
else:
# 主樣式 key
default_value = self.default_config.get(key, "")
# 寫入 key=預設值
f.write(f"{key}={default_value}\n")
logging.info(f"已自動補全 {len(missing_keys)} 個配置項")
except Exception as e:
logging.error(f"補全設定檔失敗: {str(e)}")
def load_all_settings(self):
"""加载所有配置 - 直接根据配置项名称读取,不依赖段落标记"""
if not self.config_file.exists():
logging.warning(f"配置文件 {self.config_file} 不存在,使用默认配置")
return
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
# 跳过注释行和空行
if not line or line.startswith('#'):
continue
# 解析配置行
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# 处理第二样式配置(以style2_开头的配置项)
if key.startswith('style2_'):
self._process_second_style_config(key, value, line_num)
else:
# 处理普通配置
self._process_config_value(key, value, line_num)
logging.info("所有配置加载成功")
except Exception as e:
logging.error(f"配置文件读取失败: {str(e)}")
def _process_second_style_config(self, key, value, line_num):
"""处理第二样式配置"""
# 移除style2_前缀
clean_key = key[7:] # 移除"style2_"前缀
# 只处理第二样式配置中存在的键
if clean_key in self.second_style_config:
try:
# 根据数据类型转换
if clean_key in ["window_alpha"]:
self.second_style_config[clean_key] = float(value)
elif clean_key in ["font_size", "max_width", "max_height",
"display_lines", "refresh_interval"]:
self.second_style_config[clean_key] = int(value)
elif clean_key in ["auto_wrap"]:
self.second_style_config[clean_key] = value.lower() in ('true', '1', 'yes', 'on')
else:
self.second_style_config[clean_key] = value
except (ValueError, TypeError) as e:
logging.warning(f"第二样式配置第{line_num}行: {clean_key} 配置值无效: {value} - {str(e)}")
def _process_config_value(self, key, value, line_num):
"""处理配置值转换"""
try:
# 特殊处理log_path
if key == "log_path":
self._handle_log_path_config(value)
return
if key in ["window_x", "window_y"]:
try:
if value and value.strip():
self.config[key] = int(value)
self.user_config[key] = int(value)
else:
self.config[key] = None
self.user_config[key] = None
except (ValueError, TypeError):
self.config[key] = None
self.user_config[key] = None
logging.warning(f"第{line_num}行: {key} 轉換為整數失敗,設為 None")
elif key == "window_alpha":
self.config[key] = float(value)
self.user_config[key] = float(value)
elif key in ["font_size", "max_width", "max_height",
"initial_x", "initial_y", "display_lines", "refresh_interval"]:
self.config[key] = int(value)
self.user_config[key] = int(value)
elif key in ["transparent_mode", "click_through", "author_style2", "skip_debug_log", "dynamic_height", "auto_wrap"]:
self.config[key] = value.lower() in ('true', '1', 'yes', 'on')
self.user_config[key] = value.lower() in ('true', '1', 'yes', 'on')
elif key in ["backup_interval", "backup_keep_days", "backup_align_to_clock"]:
if key == "backup_align_to_clock":
self.config[key] = value.lower() in ('true', '1', 'yes', 'on')
self.user_config[key] = self.config[key]
else:
self.config[key] = int(value)
self.user_config[key] = int(value)
elif key in ["backup_debug", "backup_enabled"]:
self.config[key] = value.lower() in ('true', '1', 'yes', 'on')
self.user_config[key] = value.lower() in ('true', '1', 'yes', 'on')
elif key == "backup_path":
# 處理備份路徑
value_stripped = value.strip() if value else ""
self.config[key] = value_stripped
self.user_config[key] = value_stripped
# 如果備份路徑不為空,則自動啟用備份功能
if value_stripped:
self.config["backup_enabled"] = True
self.user_config["backup_enabled"] = True
else:
self.config["backup_enabled"] = False
self.user_config["backup_enabled"] = False
elif key == "backup_msg_color":
self.config[key] = value
self.user_config[key] = value
else:
self.config[key] = value
self.user_config[key] = value
except (ValueError, TypeError) as e:
logging.warning(f"第{line_num}行: {key} 配置值无效: {value} - {str(e)}")
# 使用默认值
if key in self.default_config:
self.config[key] = self.default_config[key]
self.user_config[key] = self.default_config[key]
def _handle_log_path_config(self, value):
"""处理log_path配置"""
if value: # 只有非空值才视为有效配置
self.log_path_configured = True
self.config["log_path"] = value
self.user_config["log_path"] = value
logging.info(f"找到log_path配置: {value}")
else:
self.log_path_configured = False
logging.warning("log_path配置为空")
def apply_second_style(self):
"""应用第二样式"""
# 保存当前的log_filename_prefix、窗口位置和skip_debug_log
current_log_prefix = self.config.get("log_filename_prefix", "better-genshin-impact")
current_window_x = self.config.get("window_x", 0)
current_window_y = self.config.get("window_y", 0)
current_skip_debug_log = self.config.get("skip_debug_log", False)
# 应用第二样式配置
self.config.update(self.second_style_config)
# 恢复log_filename_prefix、窗口位置和skip_debug_log
self.config["log_filename_prefix"] = current_log_prefix
self.config["window_x"] = current_window_x
self.config["window_y"] = current_window_y
self.config["log_path"] = self.user_config["log_path"]
self.config["skip_debug_log"] = current_skip_debug_log
# 设置第二样式状态
self.config["author_style2"] = True
logging.info("应用第二样式")
def restore_user_style(self):
"""恢复用户自定义样式"""
# 保存当前的窗口位置、功能状态和skip_debug_log
current_window_x = self.config.get("window_x", 0)
current_window_y = self.config.get("window_y", 0)
current_transparent_mode = self.config.get("transparent_mode", False)
current_click_through = self.config.get("click_through", False)
current_skip_debug_log = self.config.get("skip_debug_log", False)
# 使用 update 方法更新配置,而不是完全替换对象
self.config.update(self.user_config)
# 恢复窗口位置和功能状态(这些应该在切换样式时保持不变)
self.config["window_x"] = current_window_x
self.config["window_y"] = current_window_y
self.config["transparent_mode"] = current_transparent_mode
self.config["click_through"] = current_click_through
self.config["skip_debug_log"] = current_skip_debug_log
self.config["author_style2"] = False # 明确设置为False
# 同时更新user_config中的这些项,确保一致性
self.user_config["window_x"] = current_window_x
self.user_config["window_y"] = current_window_y
self.user_config["transparent_mode"] = current_transparent_mode
self.user_config["click_through"] = current_click_through
self.user_config["skip_debug_log"] = current_skip_debug_log
self.user_config["author_style2"] = False
logging.info("恢复用户自定义样式 - 已应用用户config.txt配置")
def save_window_state(self, x, y, transparent_mode=False, click_through=False, author_style2=False):
"""保存窗口位置和状态到config.txt"""
try:
# 读取现有配置文件内容
config_lines = []
if self.config_file.exists():
with open(self.config_file, 'r', encoding='utf-8') as f:
config_lines = f.readlines()
# 要更新的配置项
updates = {
"window_x": str(x),
"window_y": str(y),
"transparent_mode": str(transparent_mode).lower(),
"click_through": str(click_through).lower(),
"author_style2": str(author_style2).lower()
}
# 构建新的配置内容
new_lines = []
found_keys = set()
for line in config_lines:
stripped_line = line.strip()
# 处理注释行和空行
if not stripped_line or stripped_line.startswith('#'):
new_lines.append(line)
continue
# 解析配置行
if '=' in stripped_line:
key, original_value = stripped_line.split('=', 1)
key = key.strip()
if key in updates:
# 找到原始行中的注释部分
line_without_newline = line.rstrip('\n')
if '#' in line_without_newline:
# 找到注释开始位置(在等号之后)
hash_index = line_without_newline.find('#', equal_index)
equal_index = line_without_newline.find('=')
if hash_index > equal_index:
# 注释在等号后面,保留注释
new_line = line_without_newline[:equal_index+1] + updates[key] + line_without_newline[hash_index:] + '\n'
else:
# 注释在等号前面,不应该发生
new_line = line_without_newline[:equal_index+1] + updates[key] + '\n'
else:
# 没有注释
equal_index = line_without_newline.find('=')
new_line = line_without_newline[:equal_index+1] + updates[key] + '\n'
new_lines.append(new_line)
found_keys.add(key)
else:
# 保留其他配置项
new_lines.append(line)
else:
# 保留无法解析的行
new_lines.append(line)
# 添加未找到的配置项(放在文件末尾)
for key, value in updates.items():
if key not in found_keys:
new_lines.append(f"{key}={value}\n")
# 写回配置文件
with open(self.config_file, 'w', encoding='utf-8') as f:
f.writelines(new_lines)
# 更新内存中的配置
self.config["window_x"] = x
self.config["window_y"] = y
self.config["transparent_mode"] = transparent_mode
self.config["click_through"] = click_through
self.config["author_style2"] = author_style2
logging.info(f"保存窗口位置到config.txt: ({x}, {y}), 透明模式: {transparent_mode}, 不可选中模式: {click_through}, 仿BGI日志窗口样式: {author_style2}")
except Exception as e:
logging.error(f"保存窗口位置到config.txt失败: {str(e)}")
def get(self, key, default=None):
"""获取配置值"""
return self.config.get(key, default)
def is_log_path_configured(self):
"""检查log_path是否已正确配置"""
return self.log_path_configured
def get_initial_log_config(self):
"""获取初始的日志配置(只在程序开始时加载一次)"""
return {
"log_path": self.initial_log_path,
"log_filename_prefix": self.initial_log_filename_prefix,
"log_path_configured": self.initial_log_path_configured
}
class GlobalShortcutManager:
"""全局快捷键管理器"""
def __init__(self, root_window):
self.root = root_window
self.event_queue = queue.Queue()
self.listening = False
self.thread = None
self.hotkeys_registered = False
self.last_health_check = time.time()
self.health_check_interval = 30 # 每30秒检查一次健康状态
self._lock = threading.Lock() # 新增
# 使用全局的 keyboard 模組
self.keyboard_module = KEYBOARD_MODULE
def start_listening(self):
"""启动全局快捷键监听"""
with self._lock:
if self.listening: # 防止重複啟動
return
if not KEYBOARD_AVAILABLE:
logging.warning("keyboard 库不可用,跳过全局快捷键初始化")
return
try:
# 确保先清理可能的热键
self._safe_unhook_all()
self.listening = True
self.thread = threading.Thread(target=self._listen_loop, daemon=True)
self.thread.start()
# 在主线程中处理事件
self.root.after(100, self._process_events)
# 新增健康检查定时器
self.root.after(30000, self._health_check) # 30秒后开始健康检查
logging.info("全局快捷键监听已启动")
except Exception as e:
logging.error(f"启动全局快捷键监听失败: {str(e)}")
def _health_check(self):
"""健康检查 - 定期检查快捷键是否正常工作"""
if not self.listening:
return
try:
current_time = time.time()
# 每30秒检查一次
if current_time - self.last_health_check >= self.health_check_interval:
if not self.hotkeys_registered:
logging.warning("健康检查: 热键未注册,尝试重新注册")
self._safe_register_hotkeys()
else:
logging.debug("健康检查: 快捷键状态正常")
self.last_health_check = current_time
# 继续健康检查
if self.listening:
self.root.after(30000, self._health_check)
except Exception as e:
logging.error(f"健康检查失败: {str(e)}")
if self.listening:
self.root.after(30000, self._health_check)
def _safe_unhook_all(self):
"""安全地清理所有热键"""
if not KEYBOARD_AVAILABLE or self.keyboard_module is None:
return
try:
self.keyboard_module.unhook_all()
self.hotkeys_registered = False
time.sleep(0.1) # 短暂延迟确保清理完成
except Exception as e:
logging.warning(f"清理热键时出现警告: {str(e)}")
def _safe_register_hotkeys(self):
"""安全注册热键 - 增强错误处理"""
if not KEYBOARD_AVAILABLE:
return False
try:
# 先清理可能冲突的热键
self._safe_unhook_all()
# 短暂延迟确保系统稳定
time.sleep(0.2)
# 尝试注册全局快捷键
try:
keyboard.add_hotkey('alt+p', self._create_event_callback('close'), suppress=True)
keyboard.add_hotkey('alt+u', self._create_event_callback('reset_position'), suppress=True)
keyboard.add_hotkey('alt+i', self._create_event_callback('toggle_transparent'), suppress=True)
keyboard.add_hotkey('alt+n', self._create_event_callback('toggle_click_through'), suppress=True)
keyboard.add_hotkey('alt+k', self._create_event_callback('toggle_second_style'), suppress=True)
keyboard.add_hotkey('alt+b', self._create_event_callback('backup'), suppress=True) # 新增 Alt+B 立即备份
self.hotkeys_registered = True
logging.info("全局快捷键注册完成: Alt+P(关闭), Alt+U(重置位置), Alt+I(透明模式), Alt+N(不可选中), Alt+K(第二样式), Alt+B(立即备份), P(隐藏/显示)")
return True
except Exception as register_error:
logging.warning(f"全局快捷键注册失败(可能是安全软件阻止),回退到窗口内快捷键: {str(register_error)}")
# 回退到窗口内快捷键
self._fallback_to_window_hotkeys()
return False
except Exception as e:
logging.error(f"注册全局快捷键失败: {str(e)}")
self.hotkeys_registered = False
# 即使失败也尝试回退
self._fallback_to_window_hotkeys()
return False
def _fallback_to_window_hotkeys(self):
"""回退到窗口内快捷键"""
logging.info("使用窗口内快捷键替代全局快捷键")
# 这里实际上不需要做太多,因为FloatingLogViewer会自己设置窗口内快捷键
# 主要是在状态日志中表明正在使用备用方案
self.hotkeys_registered = False # 标记为未注册成功
def _create_event_callback(self, event_type):
"""创建事件回调函数 - 避免lambda函数的内存问题"""
def callback():
self._queue_event(event_type)
return callback
def _listen_loop(self):
"""后台监听循环 - 增强稳定性"""
retry_count = 0
max_retries = 5 # 增加最大重试次数
base_retry_delay = 2
last_success_time = time.time()
while self.listening and retry_count < max_retries:
try:
# 注册热键
success = self._safe_register_hotkeys()
if not success:
logging.error(f"无法注册热键,重试 {retry_count + 1}/{max_retries}")
retry_count += 1
# 指数退避策略
delay = base_retry_delay * (2 ** (retry_count - 1))
time.sleep(min(delay, 30)) # 最大延迟30秒
continue
# 重置重试计数和计时
retry_count = 0
last_success_time = time.time()
# 保持线程运行,定期检查状态
while self.listening:
# 检查热键是否仍然有效
if not self.hotkeys_registered:
logging.warning("热键可能已失效,尝试重新注册")
break
# 检查是否长时间没有成功事件(可能表示热键失效)
if time.time() - last_success_time > 120: # 2分钟没有成功事件
logging.warning("长时间没有检测到快捷键事件,可能已失效")
break
time.sleep(1) # 减少CPU使用
except Exception as e:
logging.error(f"全局快捷键监听循环异常: {str(e)}")
retry_count += 1
delay = base_retry_delay * (2 ** (retry_count - 1))
time.sleep(min(delay, 30))
if retry_count >= max_retries:
logging.error("全局快捷键监听达到最大重试次数,已停止")
# 尝试最后一次恢复
self._attempt_recovery()
else:
logging.info("全局快捷键监听正常退出")
def _attempt_recovery(self):
"""尝试恢复快捷键功能"""
logging.info("尝试恢复快捷键功能...")
try:
self._safe_unhook_all()
time.sleep(1)
success = self._safe_register_hotkeys()
if success:
logging.info("快捷键功能恢复成功")
# 重置重试计数
self.listening = True
# 重新启动监听线程
self.thread = threading.Thread(target=self._listen_loop, daemon=True)
self.thread.start()
else:
logging.error("快捷键功能恢复失败")
except Exception as e:
logging.error(f"恢复快捷键功能时发生错误: {str(e)}")
def _queue_event(self, event_type):
"""将事件放入队列 - 增强版本"""
try:
current_time = time.time()
# 限制事件频率 - 防止过快连续触发
if hasattr(self, '_last_event_time'):
time_since_last = current_time - self._last_event_time
if time_since_last < 0.1: # 最少100毫秒间隔
return
self._last_event_time = current_time
if self.event_queue.qsize() < 20: # 增加队列容量
self.event_queue.put(event_type)
logging.debug(f"事件已加入队列: {event_type}")
else:
logging.warning("事件队列已满,丢弃事件")
except Exception as e:
logging.error(f"事件队列操作失败: {str(e)}")
def _process_events(self):
"""在主线程中处理快捷键事件 - 增强错误处理"""
try:
processed_count = 0
max_events_per_cycle = 10 # 增加每次处理的事件数量
while processed_count < max_events_per_cycle:
try:
event = self.event_queue.get_nowait()
self._handle_event(event)
processed_count += 1
except queue.Empty:
break
except Exception as e:
logging.error(f"处理事件队列时发生错误: {str(e)}")
# 不退出,继续处理
# 继续检查事件
if self.listening:
self.root.after(50, self._process_events)
def _handle_event(self, event):
"""处理具体的事件 - 增强错误处理"""
try:
logging.info(f"处理快捷键事件: {event}")
# 检查主窗口是否仍然有效
if not self.root or not hasattr(self.root, 'winfo_exists') or not self.root.winfo_exists():
logging.warning("主窗口已销毁,停止处理事件")
self.stop_listening()
return
if event == 'close':
self.root._on_close_shortcut()
elif event == 'reset_position':
self.root._on_reset_position_shortcut()
elif event == 'toggle_transparent':
self.root._on_transparent_toggle_shortcut()
elif event == 'toggle_click_through':
self.root._on_click_through_toggle_shortcut()
elif event == 'toggle_second_style':
self.root._on_second_style_toggle_shortcut()
elif event == 'toggle_visibility': # 新增:处理隐藏/显示事件
self.root._on_toggle_visibility_shortcut()
elif event == 'backup': # 新增:处理立即备份事件
self.root._on_backup_shortcut()
except Exception as e:
logging.error(f"处理快捷键事件失败: {str(e)}")
# 不重新抛出异常,防止事件处理循环中断
def stop_listening(self):
"""停止监听 - 增强版本"""
with self._lock:
if not self.listening:
return
self.listening = False
self._safe_unhook_all()
logging.info("全局快捷键监听已停止")
class SmartLogReader:
def __init__(self, log_dir, log_filename_prefix, log_path_configured, display_lines=11,
skip_debug_log=False, dynamic_height=False, auto_wrap=False,
max_width=460, font_config=None, backup_path="", backup_interval=60,
backup_debug=False, backup_enabled=False, backup_keep_days=10,
backup_align_to_clock=False):
"""智能日志读取器 - 负责读取和解析原神日志文件"""
# 在初始化时验证log_dir的有效性
if not log_path_configured:
self.log_dir = None