C++编辑器-6
2026-02-15 14:32:39
发布于:浙江
该代码并不完整,点此进入代码框架页面
class ConfigManager:
"""配置管理器,自动选择保存到注册表或配置文件"""
def __init__(self):
self.config_data = {
'font_family': 'Courier New',
'font_size': 10,
'include_paths': [],
'window_geometry': None,
'window_state': None,
'run_encoding': 'utf-8',
'enable_auto_completion': True, # 新增:是否启用自动补全
}
self.config_file = None
self.use_registry = False
# 确定使用注册表还是配置文件
if sys.platform == 'win32':
# Windows: 尝试使用注册表
try:
self.registry_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Software\CppIdle")
winreg.CloseKey(self.registry_key)
self.use_registry = True
print("使用Windows注册表保存配置")
except:
self.use_registry = False
if not self.use_registry:
# 使用配置文件
if sys.platform == 'win32':
config_dir = os.path.join(os.environ.get('APPDATA', ''), 'CppIdle')
else:
config_dir = os.path.expanduser('~/.config/cppidle')
os.makedirs(config_dir, exist_ok=True)
self.config_file = os.path.join(config_dir, 'config.ini')
print(f"使用配置文件: {self.config_file}")
def save_config(self):
"""保存配置"""
try:
if self.use_registry:
self._save_to_registry()
else:
self._save_to_file()
return True
except Exception as e:
print(f"保存配置失败: {e}")
return False
def load_config(self):
"""加载配置"""
try:
if self.use_registry:
self._load_from_registry()
else:
self._load_from_file()
return True
except Exception as e:
print(f"加载配置失败: {e}")
return False
def _save_to_registry(self):
"""保存到注册表"""
try:
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Software\CppIdle")
# 保存字体设置
winreg.SetValueEx(key, "FontFamily", 0, winreg.REG_SZ, self.config_data['font_family'])
winreg.SetValueEx(key, "FontSize", 0, winreg.REG_DWORD, self.config_data['font_size'])
# 保存include路径
paths_str = json.dumps(self.config_data['include_paths'])
winreg.SetValueEx(key, "IncludePaths", 0, winreg.REG_SZ, paths_str)
# 保存运行编码
winreg.SetValueEx(key, "RunEncoding", 0, winreg.REG_SZ, self.config_data['run_encoding'])
# 保存自动补全设置
winreg.SetValueEx(key, "EnableAutoCompletion", 0, winreg.REG_DWORD, int(self.config_data['enable_auto_completion']))
# 保存窗口状态
if self.config_data['window_geometry']:
winreg.SetValueEx(key, "WindowGeometry", 0, winreg.REG_BINARY, self.config_data['window_geometry'])
if self.config_data['window_state']:
winreg.SetValueEx(key, "WindowState", 0, winreg.REG_BINARY, self.config_data['window_state'])
winreg.CloseKey(key)
except Exception as e:
raise Exception(f"保存到注册表失败: {e}")
def _load_from_registry(self):
"""从注册表加载"""
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\CppIdle", 0, winreg.KEY_READ)
# 加载字体设置
try:
self.config_data['font_family'] = winreg.QueryValueEx(key, "FontFamily")[0]
except:
pass
try:
self.config_data['font_size'] = winreg.QueryValueEx(key, "FontSize")[0]
except:
pass
# 加载include路径
try:
paths_str = winreg.QueryValueEx(key, "IncludePaths")[0]
self.config_data['include_paths'] = json.loads(paths_str)
except:
pass
# 加载运行编码
try:
self.config_data['run_encoding'] = winreg.QueryValueEx(key, "RunEncoding")[0]
except:
pass
# 加载自动补全设置
try:
enable_auto_completion = winreg.QueryValueEx(key, "EnableAutoCompletion")[0]
self.config_data['enable_auto_completion'] = bool(enable_auto_completion)
except:
pass
# 加载窗口状态
try:
self.config_data['window_geometry'] = winreg.QueryValueEx(key, "WindowGeometry")[0]
except:
pass
try:
self.config_data['window_state'] = winreg.QueryValueEx(key, "WindowState")[0]
except:
pass
winreg.CloseKey(key)
except:
# 注册表键不存在,使用默认值
pass
def _save_to_file(self):
"""保存到配置文件"""
if not self.config_file:
return
config = configparser.ConfigParser()
# 字体设置
config['Font'] = {
'family': self.config_data['font_family'],
'size': str(self.config_data['font_size'])
}
# include路径
config['IncludePaths'] = {}
for i, path in enumerate(self.config_data['include_paths']):
config['IncludePaths'][f'path_{i}'] = path
# 运行编码
config['RunEncoding'] = {
'encoding': self.config_data['run_encoding']
}
# 自动补全设置
config['AutoCompletion'] = {
'enabled': str(self.config_data['enable_auto_completion'])
}
# 窗口状态
if self.config_data['window_geometry']:
config['Window'] = {
'geometry': self.config_data['window_geometry'].hex(),
'state': self.config_data['window_state'].hex() if self.config_data['window_state'] else ''
}
with open(self.config_file, 'w', encoding='utf-8') as f:
config.write(f)
def _load_from_file(self):
"""从配置文件加载"""
if not self.config_file or not os.path.exists(self.config_file):
return
config = configparser.ConfigParser()
config.read(self.config_file, encoding='utf-8')
# 字体设置
if 'Font' in config:
if 'family' in config['Font']:
self.config_data['font_family'] = config['Font']['family']
if 'size' in config['Font']:
self.config_data['font_size'] = int(config['Font']['size'])
# include路径
if 'IncludePaths' in config:
self.config_data['include_paths'] = []
for key in config['IncludePaths']:
self.config_data['include_paths'].append(config['IncludePaths'][key])
# 运行编码
if 'RunEncoding' in config:
if 'encoding' in config['RunEncoding']:
self.config_data['run_encoding'] = config['RunEncoding']['encoding']
# 自动补全设置
if 'AutoCompletion' in config:
if 'enabled' in config['AutoCompletion']:
self.config_data['enable_auto_completion'] = config['AutoCompletion']['enabled'].lower() == 'true'
# 窗口状态
if 'Window' in config:
if 'geometry' in config['Window'] and config['Window']['geometry']:
self.config_data['window_geometry'] = bytes.fromhex(config['Window']['geometry'])
if 'state' in config['Window'] and config['Window']['state']:
self.config_data['window_state'] = bytes.fromhex(config['Window']['state'])
def get(self, key, default=None):
"""获取配置值"""
return self.config_data.get(key, default)
def set(self, key, value):
"""设置配置值"""
self.config_data[key] = value
这里空空如也





















有帮助,赞一个