145 lines
4.7 KiB
TypeScript
145 lines
4.7 KiB
TypeScript
import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain } from 'electron'
|
||
import { spawn, ChildProcess } from 'child_process'
|
||
import fs from 'fs'
|
||
import path from 'path'
|
||
|
||
/* ===== Paths ===== */
|
||
const IS_PACKAGED = app.isPackaged
|
||
const ROOT = IS_PACKAGED
|
||
? path.dirname(process.execPath)
|
||
: path.resolve(__dirname, '../..')
|
||
|
||
const PROJECT_DIR = path.join(ROOT, 'project')
|
||
const LOG_DIR = path.join(PROJECT_DIR, 'logs')
|
||
let isQuitting = false
|
||
|
||
/* ===== Icon ===== */
|
||
const ICON_B64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII='
|
||
function createIcon(size = 32): Electron.NativeImage {
|
||
return nativeImage.createFromBuffer(Buffer.from(ICON_B64, 'base64')).resize({ width: size, height: size })
|
||
}
|
||
|
||
/* ===== Backend process ===== */
|
||
let backend: ChildProcess | null = null
|
||
|
||
function startBackend(): void {
|
||
const tsx = path.join(PROJECT_DIR, 'node_modules', 'tsx', 'dist', 'cli.mjs')
|
||
const node = process.execPath // Use Electron's bundled Node.js
|
||
|
||
backend = spawn(node, [tsx, 'src/index.ts'], {
|
||
cwd: PROJECT_DIR,
|
||
stdio: ['ignore', 'pipe', 'pipe'],
|
||
env: {
|
||
...process.env,
|
||
PORT: '3000',
|
||
SKIP_PLC: '1',
|
||
},
|
||
windowsHide: true,
|
||
})
|
||
|
||
backend.stdout?.on('data', (d: Buffer) => {
|
||
for (const line of d.toString().split('\n').filter(Boolean)) broadcastLog(line)
|
||
})
|
||
backend.stderr?.on('data', (d: Buffer) => {
|
||
for (const line of d.toString().split('\n').filter(Boolean)) broadcastLog(`[E] ${line}`)
|
||
})
|
||
backend.on('exit', (code) => {
|
||
broadcastLog(`[后端] 进程退出 (code=${code}),3s 后重启`)
|
||
setTimeout(startBackend, 3000)
|
||
})
|
||
}
|
||
|
||
function stopBackend(): void {
|
||
if (backend) { backend.kill('SIGTERM'); backend = null }
|
||
}
|
||
|
||
/* ===== Log window ===== */
|
||
let logWindow: BrowserWindow | null = null
|
||
let logBuffer: string[] = []
|
||
const MAX_LOG = 2000
|
||
|
||
function broadcastLog(line: string): void {
|
||
logBuffer.push(line)
|
||
if (logBuffer.length > MAX_LOG) logBuffer.shift()
|
||
logWindow?.webContents.send('log', line)
|
||
}
|
||
|
||
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 (!isQuitting) { e.preventDefault(); logWindow?.hide() }
|
||
})
|
||
}
|
||
|
||
function toggleWindow(): void {
|
||
logWindow?.isVisible() ? logWindow?.hide() : (logWindow?.show(), logWindow?.focus())
|
||
}
|
||
|
||
/* ===== Log window HTML ===== */
|
||
const LOG_HTML = `<!DOCTYPE html>
|
||
<html><head><meta charset="utf-8">
|
||
<style>
|
||
*{margin:0;padding:0;box-sizing:border-box}
|
||
body{background:#1e1e2e;color:#cdd6f4;font:13px/1.5 'Consolas','Cascadia Code',monospace;padding:8px}
|
||
#log{white-space:pre-wrap;word-break:break-all;height:100vh;overflow-y:auto}
|
||
.d{color:#6c7086}.i{color:#cdd6f4}.w{color:#f9e2af}.e{color:#f38ba8}
|
||
</style></head><body><div id="log"></div>
|
||
<script>
|
||
const el=document.getElementById('log');
|
||
window.electronAPI.onLog((line)=>{
|
||
var m=line.match(/^.{21}(\[.\])\[/);
|
||
var c=m?{D:'d',I:'i',W:'w',E:'e'}[m[1]]:'i';
|
||
el.innerHTML+='<span class="'+c+'">'+line.replace(/&/g,'&').replace(/</g,'<')+'</span>\\n';
|
||
el.scrollTop=el.scrollHeight;
|
||
});
|
||
window.electronAPI.getLogBuffer().then(buf=>{for(var l of buf){
|
||
var m=l.match(/^.{21}(\[.\])\[/),c=m?{D:'d',I:'i',W:'w',E:'e'}[m[1]]:'i';
|
||
el.innerHTML+='<span class="'+c+'">'+l.replace(/&/g,'&').replace(/</g,'<')+'</span>\\n';
|
||
}});
|
||
</script></body></html>`
|
||
|
||
/* ===== Tray ===== */
|
||
let tray: Tray | null = null
|
||
|
||
function createTray(): void {
|
||
tray = new Tray(createIcon(32))
|
||
tray.setToolTip('质量追溯系统')
|
||
tray.setContextMenu(Menu.buildFromTemplate([
|
||
{ label: '打开页面', click: () => { try { require('child_process').exec('start http://localhost:3000') } catch {} } },
|
||
{ label: '显示/隐藏 日志', click: toggleWindow },
|
||
{ type: 'separator' },
|
||
{ label: '退出', click: () => { isQuitting = true; stopBackend(); app.quit() } },
|
||
]))
|
||
tray.on('double-click', toggleWindow)
|
||
}
|
||
|
||
/* ===== App lifecycle ===== */
|
||
app.whenReady().then(() => {
|
||
// Ensure data and logs directories exist
|
||
;['data', 'logs'].forEach(d => {
|
||
const p = path.join(PROJECT_DIR, d)
|
||
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true })
|
||
})
|
||
|
||
createTray()
|
||
createLogWindow()
|
||
startBackend()
|
||
|
||
setTimeout(() => logWindow?.show(), 1500)
|
||
})
|
||
|
||
app.on('window-all-closed', () => { /* keep running in tray */ })
|
||
app.on('before-quit', () => { isQuitting = true; stopBackend() })
|
||
|
||
ipcMain.handle('get-log-buffer', () => logBuffer)
|