Files
SoonMachine/app/src/main/services/native-path.ts
T
2026-05-22 19:56:22 +08:00

89 lines
2.5 KiB
TypeScript

import { app } from 'electron'
import path from 'path'
import fs from 'fs'
import log from 'electron-log'
const RUNTIME_CONFIG_FILES = ['CapSettings.json'] as const
const DEFAULT_PRINT_TASKS = path.join('C:', 'PrintTasks')
const DEFAULT_CAP_SETTINGS = `{
"printerList": [],
"Img": [],
"Text": []
}
`
export function getNativeDir(): string {
if (app.isPackaged) {
return path.join(process.resourcesPath, 'native')
}
return path.join(app.getAppPath(), 'resources', 'native')
}
export function getProcessExecDir(): string {
return path.dirname(process.execPath)
}
function ensureBundledConfig(nativeDir: string): void {
fs.mkdirSync(nativeDir, { recursive: true })
for (const name of RUNTIME_CONFIG_FILES) {
const filePath = path.join(nativeDir, name)
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, DEFAULT_CAP_SETTINGS, 'utf8')
log.info(`Created default native config: ${filePath}`)
}
}
}
function deployConfigFile(src: string, destDir: string): void {
const dest = path.join(destDir, path.basename(src))
try {
fs.mkdirSync(destDir, { recursive: true })
if (!fs.existsSync(dest)) {
fs.copyFileSync(src, dest)
log.debug(`Deployed ${path.basename(src)} -> ${dest}`)
return
}
const srcStat = fs.statSync(src)
const destStat = fs.statSync(dest)
if (srcStat.mtimeMs > destStat.mtimeMs) {
fs.copyFileSync(src, dest)
log.debug(`Updated ${path.basename(src)} -> ${dest}`)
}
} catch (e) {
log.warn(`Deploy ${path.basename(src)} to ${destDir} failed`, e)
}
}
function deployRuntimeConfigs(nativeDir: string): void {
const deployDirs = new Set<string>([
nativeDir,
getProcessExecDir(),
DEFAULT_PRINT_TASKS,
path.join(app.getPath('userData'), 'Cardsoon', 'runtime')
])
for (const name of RUNTIME_CONFIG_FILES) {
const src = path.join(nativeDir, name)
if (!fs.existsSync(src)) continue
deployDirs.forEach((dir) => deployConfigFile(src, dir))
}
try {
fs.mkdirSync(DEFAULT_PRINT_TASKS, { recursive: true })
} catch (e) {
log.warn(`Cannot create ${DEFAULT_PRINT_TASKS}`, e)
}
}
export function setupNativeWorkingDir(): void {
const nativeDir = getNativeDir()
if (!fs.existsSync(path.join(nativeDir, 'workDll.dll'))) {
throw new Error(`Native DLL directory not found or incomplete: ${nativeDir}`)
}
ensureBundledConfig(nativeDir)
deployRuntimeConfigs(nativeDir)
process.chdir(nativeDir)
log.debug(`Native working directory: ${nativeDir}`)
}