2026-10-12 12:35:55 +09:00
|
|
|
import { app } from "electron"
|
|
|
|
|
import * as fs from "fs"
|
|
|
|
|
import * as path from "path"
|
2025-12-22 09:18:21 +08:00
|
|
|
|
2026-10-12 12:35:55 +09:00
|
|
|
export const USER_LOCALES = ["en", "zh", "ja", "zh-Hant"] as const
|
|
|
|
|
export type UserLocale = (typeof USER_LOCALES)[number]
|
2025-12-22 09:18:21 +08:00
|
|
|
|
2026-10-12 12:35:55 +09:00
|
|
|
// Earlier versions kept their configuration presets in this file too; the
|
|
|
|
|
// name stays so the saved language survives the upgrade
|
|
|
|
|
const CONFIG_FILE = "config-presets.json"
|
2025-12-22 09:18:21 +08:00
|
|
|
|
2026-10-12 12:35:55 +09:00
|
|
|
function getConfigPath(): string {
|
|
|
|
|
return path.join(app.getPath("userData"), CONFIG_FILE)
|
2025-12-22 09:18:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-10-12 12:35:55 +09:00
|
|
|
* Load the config file as an object ({} if it is missing or invalid)
|
2025-12-22 09:18:21 +08:00
|
|
|
*/
|
2026-10-12 12:35:55 +09:00
|
|
|
function loadConfig(): Record<string, unknown> {
|
2025-12-22 09:18:21 +08:00
|
|
|
try {
|
2026-10-12 12:35:55 +09:00
|
|
|
const configPath = getConfigPath()
|
|
|
|
|
if (fs.existsSync(configPath)) {
|
|
|
|
|
const data = JSON.parse(fs.readFileSync(configPath, "utf-8"))
|
|
|
|
|
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
|
|
|
return data
|
2025-12-22 09:18:21 +08:00
|
|
|
}
|
2026-10-12 12:35:55 +09:00
|
|
|
console.error("Ignoring invalid config file:", data)
|
2025-12-22 09:18:21 +08:00
|
|
|
}
|
2026-10-05 22:39:32 +09:00
|
|
|
} catch (error) {
|
2026-10-12 12:35:55 +09:00
|
|
|
console.error("Failed to load config file:", error)
|
2026-10-05 22:39:32 +09:00
|
|
|
}
|
2026-10-12 12:35:55 +09:00
|
|
|
return {}
|
2026-10-05 22:39:32 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-10-12 12:35:55 +09:00
|
|
|
* Get the menu locale the user chose, if any
|
2026-10-05 22:39:32 +09:00
|
|
|
*/
|
2026-10-12 12:35:55 +09:00
|
|
|
export function getUserLocale(): UserLocale | undefined {
|
|
|
|
|
const { userLocale } = loadConfig()
|
|
|
|
|
return (USER_LOCALES as readonly unknown[]).includes(userLocale)
|
|
|
|
|
? (userLocale as UserLocale)
|
|
|
|
|
: undefined
|
2026-10-05 22:39:32 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-10-12 12:35:55 +09:00
|
|
|
* Save the menu locale the user chose
|
2026-10-05 22:39:32 +09:00
|
|
|
*/
|
2026-10-12 12:35:55 +09:00
|
|
|
export function setUserLocale(locale: UserLocale): void {
|
|
|
|
|
const config = { ...loadConfig(), userLocale: locale }
|
|
|
|
|
const configPath = getConfigPath()
|
|
|
|
|
fs.mkdirSync(path.dirname(configPath), { recursive: true })
|
|
|
|
|
// Write a temp file and rename it, so a crash mid-write can't leave
|
|
|
|
|
// a truncated file
|
|
|
|
|
const tempPath = `${configPath}.tmp`
|
|
|
|
|
fs.writeFileSync(tempPath, JSON.stringify(config, null, 2), "utf-8")
|
|
|
|
|
fs.renameSync(tempPath, configPath)
|
2026-01-17 23:10:57 +05:30
|
|
|
}
|