| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- 'use strict';
- const path = require('path');
- const fs = require('fs');
- // 获取当前语言设置
- const getCurrentLanguage = () => {
- try {
- // 1. 优先从用户数据目录的缓存文件读取(由前端设置)
- const userDataPath = getElectronUserDataPath();
- const langCachePath = path.join(userDataPath, 'language.json');
- if (fs.existsSync(langCachePath)) {
- const data = JSON.parse(fs.readFileSync(langCachePath, 'utf-8'));
- if (data.language && ['zh', 'en', 'zh-CN'].includes(data.language)) {
- return data.language;
- }
- }
- // 2. 尝试从配置文件读取
- const configPath = path.join(__dirname, 'config.default.js');
- if (fs.existsSync(configPath)) {
- const config = require(configPath);
- return config.language || 'zh';
- }
- } catch (e) {
- console.log('Failed to read language config:', e.message);
- }
- return 'zh';
- };
- // 获取 Electron 用户数据目录
- const getElectronUserDataPath = () => {
- try {
- const { app } = require('electron');
- return app.getPath('userData');
- } catch (e) {
- // 在非 Electron 环境(如测试)下返回默认路径
- return path.join(__dirname, '..', '..');
- }
- };
- // 加载翻译文件
- const loadTranslations = () => {
- const language = getCurrentLanguage();
- // 标准化语言代码:en -> en, zh-CN/zh -> zh
- let i18nFile = 'en';
- if (language.startsWith('zh')) {
- i18nFile = 'zh';
- }
- const i18nPath = path.join(__dirname, 'i18n', `${i18nFile}.json`);
- try {
- if (fs.existsSync(i18nPath)) {
- return JSON.parse(fs.readFileSync(i18nPath, 'utf-8'));
- }
- } catch (e) {
- console.log('Failed to load i18n file:', e.message);
- }
- // 默认加载中文
- const defaultPath = path.join(__dirname, 'i18n', 'zh.json');
- try {
- return JSON.parse(fs.readFileSync(defaultPath, 'utf-8'));
- } catch (e) {
- console.error('Failed to load default i18n file:', e.message);
- return {};
- }
- };
- // 缓存翻译数据
- let translations = null;
- // 获取翻译
- const t = (key, params = {}) => {
- if (!translations) {
- translations = loadTranslations();
- }
- // 支持嵌套 key 如 "camera.cameraNotConnected"
- const keys = key.split('.');
- let value = translations;
- for (const k of keys) {
- if (value && typeof value === 'object' && k in value) {
- value = value[k];
- } else {
- return key; // 未找到翻译,返回原始 key
- }
- }
- // 如果找到翻译,用参数替换占位符
- if (typeof value === 'string' && Object.keys(params).length > 0) {
- return value.replace(/\{(\w+)\}/g, (match, paramKey) => {
- return params[paramKey] !== undefined ? params[paramKey] : match;
- });
- }
- return value;
- };
- // 重新加载翻译(当语言改变时调用)
- const reloadTranslations = () => {
- translations = loadTranslations();
- console.log('i18n translations reloaded');
- };
- module.exports = {
- t,
- getCurrentLanguage,
- loadTranslations,
- reloadTranslations,
- };
|