// electron/utils/readConfig.js const fs = require('fs'); const path = require('path'); const { app } = require('electron'); const defaultConfig = require('./config.default'); const configPath = path.join(app.getPath("userData"),'config.default.json'); // Smart Shooter 5 的历史默认安装目录。用户目录里的旧配置会盖掉代码默认值, // 只有仍停在这套出厂值时才自动切到 6;手动选过别的目录则保持不动。 const LEGACY_SMARTSHOOTER5 = { controlType: "SmartShooter", controlPath: "C:\\Program Files\\Smart Shooter 5", } function migrateLegacySmartShooter(config) { if (!config || config.smartShooter6Migrated) return { config, changed: false } const stillFactoryDefault = config.controlType === LEGACY_SMARTSHOOTER5.controlType && config.controlPath === LEGACY_SMARTSHOOTER5.controlPath config.smartShooter6Migrated = true if (!stillFactoryDefault) return { config, changed: true } config.controlType = defaultConfig.controlType config.controlPath = defaultConfig.controlPath config.SmartShooterPath = config.SmartShooterPath || LEGACY_SMARTSHOOTER5.controlPath config.SmartShooter6Path = defaultConfig.SmartShooter6Path return { config, changed: true } } /** * 读取配置文件 */ function readConfigFile() { try { if (fs.existsSync(configPath)) { const data = fs.readFileSync(configPath, 'utf8'); const parsed = JSON.parse(data); const { config: merged, changed } = migrateLegacySmartShooter({ ...defaultConfig, ...parsed, }); if (changed) { fs.writeFileSync(configPath, JSON.stringify(merged, null, 2), 'utf8'); } return merged; } else { console.log('配置文件不存在'); // 创建空白JSON文件 fs.writeFileSync(configPath, '{}', 'utf8'); return { ...defaultConfig, }; } } catch (error) { console.error('读取配置文件出错:', error); return null; } } /** * 写入配置文件 * @param {string} key - 要写入的配置项键名 * @param {*} value - 要写入的配置项值 */ function writeConfigFile(key, value) { try { let config = {}; // 如果配置文件存在,则读取现有内容 if (fs.existsSync(configPath)) { const data = fs.readFileSync(configPath, 'utf8'); config = { ...defaultConfig, ...JSON.parse(data), }; }else { console.log('配置文件不存在'); // 创建空白JSON文件 fs.writeFileSync(configPath, '{}', 'utf8'); config = { ...defaultConfig, } } // 更新配置项 config[key] = value; // 将更新后的配置写回文件 fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(`成功写入配置项: ${key}`); } catch (error) { console.error('写入配置文件出错:', error); } } module.exports = { readConfigFile, writeConfigFile };