-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_loader.py
More file actions
438 lines (358 loc) · 19.7 KB
/
config_loader.py
File metadata and controls
438 lines (358 loc) · 19.7 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
"""配置加载模块。
该模块负责从配置文件中加载和解析应用程序的配置信息。
包括按键绑定、鼠标移动设置、滚动设置等。
"""
import configparser
import os
import sys
import logging
import logging.handlers
from typing import List, Set, Dict, Tuple, Optional, Any
from utool import KEY_TO_VK, NAME_TO_PYNPUT_KEY
def get_base_path() -> str:
"""
获取应用程序的根目录。
这是在任何环境(源代码、打包后)下都绝对可靠的终极方法。
"""
if getattr(sys, 'frozen', False):
# 如果是打包状态 (frozen), 根目录就是可执行文件所在的目录
return os.path.dirname(sys.executable)
else:
# 如果是源代码状态, 根目录就是主脚本 (__file__) 所在的目录
return os.path.dirname(os.path.abspath(__file__))
# 定义配置文件路径常量
MAPPINGS_PATH = os.path.join(get_base_path(), 'key_mappings.json')
DEFAULTS_PATH = os.path.join(get_base_path(), 'defaults.json')
class AppConfig:
"""应用程序配置类。
负责加载和存储所有应用程序配置,包括按键绑定、鼠标设置等。
属性:
config_path: 配置文件的完整路径
MOVE_*_VK: 移动相关的虚拟按键码
SCROLL_*_VK: 滚动相关的虚拟按键码
*_CLICK_VK: 点击相关的虚拟按键码
MOUSE_CONTROL_VKS: 所有鼠标控制相关的虚拟按键码集合
其他各种配置属性
"""
def __init__(self, config_file: str = 'config.ini') -> None:
"""初始化配置对象。
Args:
config_file: 配置文件名,默认为'config.ini'
Raises:
FileNotFoundError: 配置文件不存在时抛出
KeyError: 必需的配置键缺失时抛出
ValueError: 区域选择布局配置无效时抛出
"""
base_path = get_base_path()
self.config_path = os.path.join(base_path, config_file)
self.config_parser = configparser.ConfigParser(interpolation=None)
if not os.path.exists(self.config_path):
raise FileNotFoundError(f"配置文件 '{config_file}' 在路径 '{self.config_path}' 未找到!")
self.config_parser.read(self.config_path, encoding='utf-8')
# 为了兼容性,创建一个局部变量 config
config = self.config_parser
# [GUI Integration] Add key_mapping_config_path
self.key_mapping_config_path = os.path.join(base_path, config.get('Settings', 'key_mapping_config_file', fallback='key_mappings.json'))
def get_key(section: configparser.SectionProxy, option: str) -> str:
"""获取配置项的值,如果不存在则抛出异常。"""
value = section.get(option)
if value is None:
raise KeyError(f"在配置文件的 [{section.name}] 节中,未找到必需的键 '{option}'!")
return value
# 配置版本
self._config_version = 0
# 加载按键绑定配置 (静态配置 - 不可热加载)
keybindings = config['Keybindings']
self._load_movement_keys(keybindings, get_key)
self._load_mouse_action_keys(keybindings, get_key)
self._load_scroll_keys(keybindings, get_key)
self._load_hotkey_settings(keybindings, get_key)
self._load_character_mappings(keybindings, get_key)
# 加载通用设置 (部分可热加载)
self._load_general_settings(config['Settings'])
# 加载平滑滚动设置 (可热加载)
self._load_smooth_scrolling_settings(config['SmoothScrolling'])
# 加载日志配置
self._load_logging_settings(config['Logging'] if 'Logging' in config else {})
# 加载区域选择布局 (静态配置 - 不可热加载)
self.REGION_SELECT_LAYOUT = self._load_region_select_layout(config)
self.COMMAND_MODE_TOGGLE_VK = KEY_TO_VK[get_key(keybindings, 'command_mode_toggle')]
# 加载命令模式宏 (静态配置 - 不可热加载)
self.command_macros = self._load_command_macros(config)
def reload(self) -> bool:
"""
重新加载配置文件。
Returns:
bool: 重载是否成功
"""
try:
config = configparser.ConfigParser(interpolation=None)
config.read(self.config_path, encoding='utf-8')
# 重新加载配置项
if 'Settings' in config:
self._load_general_settings(config['Settings'])
if 'SmoothScrolling' in config:
self._load_smooth_scrolling_settings(config['SmoothScrolling'])
if 'Logging' in config:
self._load_logging_settings(config['Logging'])
# 更新日志配置
self._update_logging_config()
print("Configuration reloaded successfully.")
return True
except Exception as e:
print(f"Configuration reload failed: {e}")
return False
def _load_logging_settings(self, logging_settings) -> None:
"""加载日志设置。
Args:
logging_settings: 日志配置节或字典
"""
self._log_config = {}
if hasattr(logging_settings, 'items'):
for key, value in logging_settings.items():
self._log_config[key] = value
elif isinstance(logging_settings, dict):
self._log_config = logging_settings.copy()
def _update_logging_config(self) -> None:
"""更新日志配置。"""
if 'log_level' in self._log_config:
level_str = self._log_config['log_level'].upper()
level_map = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
}
level = level_map.get(level_str, logging.INFO)
logging.getLogger().setLevel(level)
print(f"Log level updated to: {level_str}")
def _load_movement_keys(self, keybindings: configparser.SectionProxy, get_key: callable) -> None:
"""加载移动相关的按键设置。"""
self.MOVE_UP_VK = KEY_TO_VK[get_key(keybindings, 'move_up')]
self.MOVE_DOWN_VK = KEY_TO_VK[get_key(keybindings, 'move_down')]
self.MOVE_LEFT_VK = KEY_TO_VK[get_key(keybindings, 'move_left')]
self.MOVE_RIGHT_VK = KEY_TO_VK[get_key(keybindings, 'move_right')]
def _load_mouse_action_keys(self, keybindings: configparser.SectionProxy, get_key: callable) -> None:
"""加载鼠标动作相关的按键设置。"""
self.LEFT_CLICK_VK = KEY_TO_VK[get_key(keybindings, 'left_click')]
self.RIGHT_CLICK_VK = KEY_TO_VK[get_key(keybindings, 'right_click')]
self.MIDDLE_CLICK_VK = KEY_TO_VK[get_key(keybindings, 'middle_click')]
self.STICKY_LEFT_CLICK_VK = KEY_TO_VK[get_key(keybindings, 'sticky_left_click')]
self.TOGGLE_MODE_INTERNAL_VK = KEY_TO_VK[get_key(keybindings, 'toggle_mode_internal')]
self.ENTER_REGION_SELECT_VK = KEY_TO_VK[get_key(keybindings, 'enter_region_select_mode')]
def _load_scroll_keys(self, keybindings: configparser.SectionProxy, get_key: callable) -> None:
"""加载滚动相关的按键设置。"""
self.SCROLL_UP_VK = KEY_TO_VK[get_key(keybindings, 'scroll_up')]
self.SCROLL_DOWN_VK = KEY_TO_VK[get_key(keybindings, 'scroll_down')]
def _load_hotkey_settings(self, keybindings: configparser.SectionProxy, get_key: callable) -> None:
"""加载热键设置。"""
# 从配置文件中获取热键组合字符串,格式如 "<alt>+a"
hotkey_str = get_key(keybindings, 'toggle_mode_hotkey')
# 解析热键组合字符串:
# 1. 移除 < 和 > 符号
# 2. 转换为小写
# 3. 用 + 分割成修饰键和触发键
parts = hotkey_str.replace('<', '').replace('>', '').lower().split('+')
# 第一部分是修饰键(如 ctrl, alt, shift)
self.HOTKEY_MODIFIER = parts[0]
# 第二部分是触发键(如 h, j, k)
self.HOTKEY_TRIGGER_KEY = parts[1]
# 将触发键转换为对应的虚拟键码
self.HOTKEY_TRIGGER_VK = KEY_TO_VK[self.HOTKEY_TRIGGER_KEY]
def _load_character_mappings(self, keybindings:
configparser.SectionProxy, get_key: callable) -> None:
"""加载字符映射设置。"""
# 存储原始按键字符,用于后续的按键检测
# 例如: 如果配置文件中move_up='k',这里就存储'k'字符本身
self.MOVE_UP_CHAR = get_key(keybindings, 'move_up')
self.MOVE_DOWN_CHAR = get_key(keybindings, 'move_down')
self.MOVE_LEFT_CHAR = get_key(keybindings, 'move_left')
self.MOVE_RIGHT_CHAR = get_key(keybindings, 'move_right')
self.SCROLL_UP_CHAR = get_key(keybindings, 'scroll_up')
self.SCROLL_DOWN_CHAR = get_key(keybindings, 'scroll_down')
self.LEFT_CLICK_CHAR = get_key(keybindings, 'left_click')
self.RIGHT_CLICK_CHAR = get_key(keybindings, 'right_click')
self.MIDDLE_CLICK_CHAR = get_key(keybindings, 'middle_click')
self.STICKY_LEFT_CLICK_CHAR = get_key(keybindings,'sticky_left_click')
self.ENTER_REGION_SELECT_CHAR = get_key(keybindings,'enter_region_select_mode')
# 加载退出程序的按键,并转换为pynput库可识别的格式
exit_key_name = get_key(keybindings, 'exit_program')
self.EXIT_PROGRAM_PYNPUT = NAME_TO_PYNPUT_KEY[exit_key_name]
self.EXIT_PROGRAM_VK = KEY_TO_VK[exit_key_name]
# 重新初始化所有鼠标控制相关的虚拟按键码集合
self.MOUSE_CONTROL_VKS: Set[int] = {
self.MOVE_UP_VK, self.MOVE_DOWN_VK, self.MOVE_LEFT_VK, self.MOVE_RIGHT_VK,
self.SCROLL_UP_VK, self.SCROLL_DOWN_VK, self.LEFT_CLICK_VK,
self.RIGHT_CLICK_VK, self.MIDDLE_CLICK_VK, self.TOGGLE_MODE_INTERNAL_VK,
self.STICKY_LEFT_CLICK_VK, self.EXIT_PROGRAM_VK
}
def _load_general_settings(self, settings: configparser.SectionProxy) -> None:
"""加载通用设置。"""
# 直接从配置中读取值
self.MOUSE_MOVE_SPEED = settings.getint('mouse_move_speed')
self.MOUSE_SPEED_SHIFT = settings.getfloat('mouse_speed_shift_multiplier')
self.MOUSE_SPEED_CAPLOCK = settings.getfloat('mouse_speed_capslock_multiplier')
self.DELAY_PER_STEP = settings.getfloat('delay_per_step')
# 运行时设置(需要重启才能更改)
self.RUN_AS_ADMIN = settings.getboolean('run_as_admin', False)
self.TEMP_DATA_DIR_NAME = settings.get('temp_data_dir', fallback='temp_data')
self.TEMP_DATA_PATH = os.path.join(get_base_path(), self.TEMP_DATA_DIR_NAME)
def _load_smooth_scrolling_settings(self, scrolling_settings: configparser.SectionProxy) -> None:
"""加载平滑滚动设置。"""
# 直接从配置中读取值
self.SCROLL_INITIAL_VELOCITY = scrolling_settings.getfloat('initial_velocity')
self.SCROLL_MAX_VELOCITY = scrolling_settings.getfloat('max_velocity')
self.SCROLL_ACCELERATION = scrolling_settings.getfloat('acceleration')
def _load_region_select_layout(self, config: configparser.ConfigParser) -> List[List[str]]:
"""加载区域选择布局配置。
Args:
config: 配置解析器对象
Returns:
包含区域选择布局的二维列表
Raises:
ValueError: 布局配置无效时抛出
"""
if 'RegionSelectLayout' not in config:
return [['1','2','3','4','5'],['q','w','e','r','t'],['a','s','d','f','g'],['z','x','c','v','b']]
layout = []
for i in range(1, 10):
key = f'row{i}'
if config.has_option('RegionSelectLayout', key):
layout.append(config.get('RegionSelectLayout', key).split())
else:
break
if not layout:
raise ValueError("配置文件 [RegionSelectLayout] 区域为空!")
first_row_len = len(layout[0])
if not all(len(row) == first_row_len for row in layout):
raise ValueError("配置文件 [RegionSelectLayout] 中所有行的键位数必须相同!")
return layout
def _load_command_macros(self, config: configparser.ConfigParser) -> Dict[str, Tuple[str, str]]:
"""加载命令模式宏配置。"""
macros = {}
if 'CommandModeMacros' in config:
for key, value in config['CommandModeMacros'].items():
try:
action_type, action_value = value.split(':', 1)
macros[key] = (action_type.strip(), action_value.strip())
except ValueError:
# 记录一个警告,而不是将其视为不同的类型
print(f"警告: 在 [CommandModeMacros] 中发现无效的宏格式: '{key}={value}',已忽略。")
return macros
# ======================================================================
# 动态配置访问属性和方法 - Story 1.1 实现
# ======================================================================
# 配置属性
# 这些属性在 _load_general_settings 和 _load_smooth_scrolling_settings 方法中初始化
def save_config(self) -> bool:
"""
保存配置到文件
Returns:
bool: 保存是否成功
"""
try:
# 使用已导入的configparser模块
config = configparser.ConfigParser(interpolation=None)
# 添加Keybindings节
config['Keybindings'] = {}
# 创建反向映射从虚拟键码到按键名称
VK_TO_KEY = {vk: key for key, vk in KEY_TO_VK.items()}
# 移动键
config['Keybindings']['move_up'] = VK_TO_KEY.get(self.MOVE_UP_VK, 'i')
config['Keybindings']['move_down'] = VK_TO_KEY.get(self.MOVE_DOWN_VK, 'k')
config['Keybindings']['move_left'] = VK_TO_KEY.get(self.MOVE_LEFT_VK, 'j')
config['Keybindings']['move_right'] = VK_TO_KEY.get(self.MOVE_RIGHT_VK, 'l')
# 滚动键
config['Keybindings']['scroll_up'] = VK_TO_KEY.get(self.SCROLL_UP_VK, 'comma')
config['Keybindings']['scroll_down'] = VK_TO_KEY.get(self.SCROLL_DOWN_VK, 'm')
# 鼠标动作键
config['Keybindings']['left_click'] = VK_TO_KEY.get(self.LEFT_CLICK_VK, 'semicolon')
config['Keybindings']['right_click'] = VK_TO_KEY.get(self.RIGHT_CLICK_VK, 'apostrophe')
config['Keybindings']['middle_click'] = VK_TO_KEY.get(self.MIDDLE_CLICK_VK, 'rshift')
config['Keybindings']['sticky_left_click'] = VK_TO_KEY.get(self.STICKY_LEFT_CLICK_VK, 'n')
config['Keybindings']['toggle_mode_internal'] = VK_TO_KEY.get(self.TOGGLE_MODE_INTERNAL_VK, 'q')
config['Keybindings']['enter_region_select_mode'] = VK_TO_KEY.get(self.ENTER_REGION_SELECT_VK, 'f')
# 热键设置
hotkey_str = f"<{self.HOTKEY_MODIFIER}>+{self.HOTKEY_TRIGGER_KEY}"
config['Keybindings']['toggle_mode_hotkey'] = hotkey_str
config['Keybindings']['exit_program'] = VK_TO_KEY.get(self.EXIT_PROGRAM_VK, 'esc')
config['Keybindings']['command_mode_toggle'] = VK_TO_KEY.get(self.COMMAND_MODE_TOGGLE_VK, 'h')
# 添加Settings节 - 简化版本,添加调试
config['Settings'] = {}
try:
config['Settings']['mouse_move_speed'] = str(self.MOUSE_MOVE_SPEED)
logging.debug(f"mouse_move_speed: {self.MOUSE_MOVE_SPEED} -> {config['Settings']['mouse_move_speed']}")
except Exception as e:
logging.error(f"设置 mouse_move_speed 失败: {e}")
try:
config['Settings']['mouse_speed_shift_multiplier'] = str(self.MOUSE_SPEED_SHIFT)
logging.debug(f"mouse_speed_shift_multiplier: {self.MOUSE_SPEED_SHIFT} -> {config['Settings']['mouse_speed_shift_multiplier']}")
except Exception as e:
logging.error(f"设置 mouse_speed_shift_multiplier 失败: {e}")
try:
config['Settings']['mouse_speed_capslock_multiplier'] = str(self.MOUSE_SPEED_CAPLOCK)
logging.debug(f"mouse_speed_capslock_multiplier: {self.MOUSE_SPEED_CAPLOCK} -> {config['Settings']['mouse_speed_capslock_multiplier']}")
except Exception as e:
logging.error(f"设置 mouse_speed_capslock_multiplier 失败: {e}")
try:
config['Settings']['delay_per_step'] = str(self.DELAY_PER_STEP)
logging.debug(f"delay_per_step: {self.DELAY_PER_STEP} -> {config['Settings']['delay_per_step']}")
except Exception as e:
logging.error(f"设置 delay_per_step 失败: {e}")
try:
config['Settings']['run_as_admin'] = str(self.RUN_AS_ADMIN).lower()
logging.debug(f"run_as_admin: {self.RUN_AS_ADMIN} -> {config['Settings']['run_as_admin']}")
except Exception as e:
logging.error(f"设置 run_as_admin 失败: {e}")
try:
config['Settings']['temp_data_dir'] = str(self.TEMP_DATA_DIR_NAME)
logging.debug(f"temp_data_dir: {self.TEMP_DATA_DIR_NAME} -> {config['Settings']['temp_data_dir']}")
except Exception as e:
logging.error(f"设置 temp_data_dir 失败: {e}")
# 添加SmoothScrolling节 - 简化版本
config['SmoothScrolling'] = {}
config['SmoothScrolling']['initial_velocity'] = str(self.SCROLL_INITIAL_VELOCITY)
config['SmoothScrolling']['max_velocity'] = str(self.SCROLL_MAX_VELOCITY)
config['SmoothScrolling']['acceleration'] = str(self.SCROLL_ACCELERATION)
# 添加Logging节 - 使用默认格式避免插值问题
config['Logging'] = {}
config['Logging']['log_level'] = 'INFO'
config['Logging']['log_format'] = '%(asctime)s - [%(levelname)s] - %(message)s'
config['Logging']['log_file_path'] = 'logs/main.log'
config['Logging']['log_max_size'] = '10485760'
config['Logging']['log_backup_count'] = '5'
config['Logging']['error_log_file'] = 'logs/error.log'
# 添加RegionSelectLayout节 - 简化版本
config['RegionSelectLayout'] = {}
for i, row_values in enumerate(self.REGION_SELECT_LAYOUT, 1):
row_key = f'row{i}'
config['RegionSelectLayout'][row_key] = ' '.join(row_values)
# 添加CommandModeMacros节
config['CommandModeMacros'] = {}
for macro_key, macro_value in self.command_macros.items():
config['CommandModeMacros'][macro_key] = f"{macro_value[0]}:{macro_value[1]}"
# 添加CommandModeMacrosNotes节 - 使用默认备注
config['CommandModeMacrosNotes'] = {}
notes = {
'c': '复制 (Ctrl+C)',
'v': '粘贴 (Ctrl+V)',
'x': '剪切 (Ctrl+X)',
's': '保存 (Ctrl+S)',
'a': '全选 (Ctrl+A)',
'z': '撤销 (Ctrl+Z)',
't': '切换全屏',
'w': '关闭窗口 (Alt+F4)'
}
for macro_key, macro_note in notes.items():
if macro_key in self.command_macros:
config['CommandModeMacrosNotes'][macro_key] = macro_note
# 写入配置文件
with open(self.config_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
logging.info(f"配置已保存到: {self.config_path}")
logging.debug("配置保存调试信息完成")
return True
except Exception as e:
logging.error(f"保存配置失败: {e}")
return False