refactor: Electron desktop app with tray + log window

This commit is contained in:
zlm committed 2026-06-10 13:28:43 +08:00
1 parent ecec178400
commit 13aead949b
7 files changed
+187 -168

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
appId: com.scanner-record.desktop
productName: 质量追溯系统
copyright: Copyright 2026
win:
target:
- target: portable
arch:
- x64
portable:
artifactName: ScannerRecord-${version}-win64.exe
+9 -3
View File
@@ -2,9 +2,15 @@
"name": "scanner-record-desktop", "name": "scanner-record-desktop",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"description": "Windows 系统托盘 + 日志窗口", "main": "dist/main.js",
"scripts": { "scripts": {
"install": "pip install -r requirements.txt", "dev": "tsc && electron dist/main.js",
"start": "python tray.py" "build": "tsc && electron-builder --win portable",
"pack": "tsc && electron-builder --win portable --dir"
},
"devDependencies": {
"electron": "^34.0.0",
"electron-builder": "^25.0.0",
"typescript": "^5.7.0"
} }
} }
-2
View File
@@ -1,2 +0,0 @@
pystray>=0.19.0
Pillow>=10.0.0
+143
View File
@@ -0,0 +1,143 @@
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')
/* ===== 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 (!app.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,'&amp;').replace(/</g,'&lt;')+'</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,'&amp;').replace(/</g,'&lt;')+'</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: () => { app.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', () => { app.isQuitting = true; stopBackend() })
ipcMain.handle('get-log-buffer', () => logBuffer)
+8
View File
@@ -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'),
})
-163
View File
@@ -1,163 +0,0 @@
"""
质量追溯系统 - Windows 系统托盘
双击 tray.py 启动:
1. 启动后端(隐藏子进程,无控制台窗口)
2. 系统托盘图标(蓝色)
3. 双击图标 → 打开浏览器查看前端
4. 右键图标 → 退出
依赖:
pip install pystray Pillow
"""
import sys
import os
import subprocess
import threading
import time
import webbrowser
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from pathlib import Path
# ── Paths ──────────────────────────────────────────────
SCRIPT_DIR = Path(__file__).parent.resolve()
PROJECT_DIR = (SCRIPT_DIR / '..' / 'project').resolve()
LOG_DIR = PROJECT_DIR / 'logs'
# ── Backend process ────────────────────────────────────
backend = None
def start_backend():
global backend
env = os.environ.copy()
env['PORT'] = '3000'
env['SKIP_PLC'] = '1'
if sys.platform == 'win32':
# Windows: npx.cmd needs shell=True; hide console
backend = subprocess.Popen(
'npx tsx src/index.ts',
cwd=str(PROJECT_DIR),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
shell=True,
creationflags=0x08000000,
)
else:
backend = subprocess.Popen(
['npx', 'tsx', 'src/index.ts'],
cwd=str(PROJECT_DIR),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
)
# Read stdout/stderr in background for log window
def read_stream(stream, prefix=''):
for line in iter(stream.readline, b''):
text = line.decode('utf-8', errors='replace').rstrip()
if text:
append_log(f'{prefix}{text}')
stream.close()
threading.Thread(target=read_stream, args=(backend.stdout, ''), daemon=True).start()
threading.Thread(target=read_stream, args=(backend.stderr, '[E] '), daemon=True).start()
def stop_backend():
if backend and backend.poll() is None:
backend.terminate()
backend.wait(timeout=5)
# ── Log window ─────────────────────────────────────────
log_window = None
log_text = None
def append_log(line):
if log_text:
log_text.after(0, lambda: _do_append(line))
def _do_append(line):
log_text.insert(tk.END, line + '\n')
log_text.see(tk.END)
def toggle_log_window():
global log_window
if log_window and log_window.winfo_exists():
log_window.deiconify()
log_window.lift()
else:
create_log_window()
def create_log_window():
global log_window, log_text
log_window = tk.Toplevel()
log_window.title('质量追溯系统 - 日志')
log_window.geometry('850x500')
log_window.protocol('WM_DELETE_WINDOW', lambda: log_window.withdraw())
log_text = ScrolledText(log_window, font=('Consolas', 10), bg='#1e1e2e',
fg='#cdd6f4', insertbackground='white', state='normal')
log_text.pack(fill=tk.BOTH, expand=True)
# Colour tags
log_text.tag_configure('i', foreground='#cdd6f4')
log_text.tag_configure('w', foreground='#f9e2af')
log_text.tag_configure('e', foreground='#f38ba8')
log_text.tag_configure('d', foreground='#6c7086')
# ── System tray ────────────────────────────────────────
def create_tray():
try:
from PIL import Image, ImageDraw
except ImportError:
print('[tray] 请安装依赖: pip install pystray Pillow')
sys.exit(1)
import pystray
# Create a simple blue circle icon
img = Image.new('RGBA', (32, 32), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.ellipse([4, 4, 28, 28], fill=(0x1a, 0x23, 0x7e, 255))
def on_show(_):
webbrowser.open('http://localhost:3000')
def on_quit(_):
stop_backend()
icon.stop()
sys.exit(0)
menu = (
pystray.MenuItem('打开页面', on_show, default=True),
pystray.MenuItem('退出', on_quit),
)
icon = pystray.Icon('scanner-record', img, '质量追溯系统', menu)
# Start backend after tray is running
threading.Thread(target=start_backend, daemon=True).start()
icon.run()
if __name__ == '__main__':
# Check dependencies
try:
import pystray
from PIL import Image
except ImportError:
print('请先安装依赖: pip install pystray Pillow')
input('按 Enter 键退出...')
sys.exit(1)
try:
create_tray()
except KeyboardInterrupt:
stop_backend()
except Exception as e:
print(f'错误: {e}')
input('按 Enter 键退出...')
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}