diff --git a/desktop/package.json b/desktop/package.json new file mode 100644 index 0000000..e6aaf89 --- /dev/null +++ b/desktop/package.json @@ -0,0 +1,16 @@ +{ + "name": "scanner-record-desktop", + "version": "1.0.0", + "private": true, + "main": "dist/main.js", + "scripts": { + "dev": "tsc && electron dist/main.js", + "build": "tsc", + "start": "electron dist/main.js" + }, + "devDependencies": { + "electron": "^34.0.0", + "tsx": "^4.19.0", + "typescript": "^5.7.0" + } +} diff --git a/desktop/src/main.ts b/desktop/src/main.ts new file mode 100644 index 0000000..ff7054f --- /dev/null +++ b/desktop/src/main.ts @@ -0,0 +1,217 @@ +import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain, Notification } from 'electron' +import { spawn, ChildProcess } from 'child_process' +import fs from 'fs' +import path from 'path' + +/* ===== Paths ===== */ +const PROJECT_DIR = path.resolve(__dirname, '../../project') +const LOG_DIR = path.resolve(PROJECT_DIR, 'logs') +const isDev = !app.isPackaged + +/* ===== Tray icon ===== */ +const ICON_B64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII=' + +function createIcon(): Electron.NativeImage { + return nativeImage.createFromBuffer(Buffer.from(ICON_B64, 'base64')) +} + +/* ===== Backend process ===== */ +let backend: ChildProcess | null = null +let backendExited = false + +function startBackend(): void { + const cmd = isDev ? 'npx' : 'node' + const args = isDev ? ['tsx', 'src/index.ts'] : ['dist/index.js'] + + const env: NodeJS.ProcessEnv = { + ...process.env, + SKIP_PLC: '1', + PORT: '3000', + } + + backend = spawn(cmd, args, { + cwd: PROJECT_DIR, + stdio: ['ignore', 'pipe', 'pipe'], + env, + windowsHide: true, // No console window on Windows + }) + + backend.stdout?.on('data', (d: Buffer) => { + const lines = d.toString().split('\n').filter(Boolean) + for (const line of lines) { + broadcastLog(line) + } + }) + + backend.stderr?.on('data', (d: Buffer) => { + const lines = d.toString().split('\n').filter(Boolean) + for (const line of lines) { + broadcastLog(`[E] ${line}`) + } + }) + + backend.on('exit', (code) => { + backendExited = true + broadcastLog(`[后端] 进程退出 (code=${code})`) + if (!app.isQuitting) { + setTimeout(startBackend, 3000) // auto-restart + } + }) +} + +function stopBackend(): void { + if (backend && !backendExited) { + backend.kill('SIGTERM') + } +} + +/* ===== Log window ===== */ +let logWindow: BrowserWindow | null = null +let logBuffer: string[] = [] +let logWatcher: fs.FSWatcher | null = null + +function broadcastLog(line: string): void { + logBuffer.push(line) + if (logBuffer.length > 1000) logBuffer.shift() + logWindow?.webContents.send('log', line) +} + +function getTodayLogPath(): string { + const d = new Date() + const y = d.getFullYear() + const m = String(d.getMonth() + 1).padStart(2, '0') + const dd = String(d.getDate()).padStart(2, '0') + return path.join(LOG_DIR, `${y}-${m}-${dd}.log`) +} + +function watchLogFile(): void { + const logPath = getTodayLogPath() + if (!fs.existsSync(logPath)) return + + let fileSize = fs.statSync(logPath).size + + logWatcher = fs.watch(logPath, () => { + try { + const stats = fs.statSync(logPath) + if (stats.size > fileSize) { + const fd = fs.openSync(logPath, 'r') + const buf = Buffer.alloc(stats.size - fileSize) + fs.readSync(fd, buf, 0, buf.length, fileSize) + fs.closeSync(fd) + fileSize = stats.size + const lines = buf.toString().split('\n').filter(Boolean) + for (const line of lines) { + broadcastLog(line) + } + } + } catch { /* ignore */ } + }) +} + +function createLogWindow(): void { + logWindow = new BrowserWindow({ + width: 850, + height: 500, + show: false, + resizable: true, + frame: true, + title: '质量追溯系统 - 日志', + icon: createIcon(), + webPreferences: { + preload: path.join(__dirname, 'preload.js'), + contextIsolation: true, + nodeIntegration: false, + }, + }) + + logWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(LOG_HTML)}`) + + logWindow.on('close', (e) => { + if (!app.isQuitting) { + e.preventDefault() + logWindow?.hide() + } + }) +} + +/* ===== Log window HTML ===== */ +const LOG_HTML = ` + +
+ + + + + + +` + +/* ===== Tray ===== */ +let tray: Tray | null = null + +function createTray(): void { + tray = new Tray(createIcon()) + tray.setToolTip('质量追溯系统') + + const ctx = Menu.buildFromTemplate([ + { + label: '显示/隐藏 日志', + click: () => { logWindow?.isVisible() ? logWindow?.hide() : logWindow?.show() }, + }, + { type: 'separator' }, + { + label: '重启后端', + click: () => { stopBackend(); setTimeout(startBackend, 1000) }, + }, + { type: 'separator' }, + { + label: '退出', + click: () => { app.isQuitting = true; stopBackend(); app.quit() }, + }, + ]) + + tray.setContextMenu(ctx) + tray.on('double-click', () => { + logWindow?.isVisible() ? logWindow?.hide() : logWindow?.show() + }) +} + +/* ===== App lifecycle ===== */ +app.whenReady().then(() => { + createTray() + createLogWindow() + startBackend() + watchLogFile() + + // Show log window on first launch + setTimeout(() => logWindow?.show(), 1500) +}) + +app.on('window-all-closed', () => { + // Don't quit - keep running in tray +}) + +app.on('before-quit', () => { + app.isQuitting = true + stopBackend() + if (logWatcher) logWatcher.close() +}) + +ipcMain.handle('get-log-buffer', () => logBuffer) diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts new file mode 100644 index 0000000..32f1c87 --- /dev/null +++ b/desktop/src/preload.ts @@ -0,0 +1,8 @@ +import { contextBridge, ipcRenderer } from 'electron' + +contextBridge.exposeInMainWorld('electronAPI', { + onLog: (callback: (line: string) => void) => { + ipcRenderer.on('log', (_event, line: string) => callback(line)) + }, + getLogBuffer: () => ipcRenderer.invoke('get-log-buffer'), +}) diff --git a/desktop/tsconfig.json b/desktop/tsconfig.json new file mode 100644 index 0000000..f3a3438 --- /dev/null +++ b/desktop/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "sourceMap": true + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +}