refactor: replace Electron with Python system tray (pystray)
This commit is contained in:
1 parent
6aa2320ece
commit
59320571a7
6 files changed
+165
-250
No files matched your search
@@ -2,15 +2,9 @@
|
|||||||
"name": "scanner-record-desktop",
|
"name": "scanner-record-desktop",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist/main.js",
|
"description": "Windows 系统托盘 + 日志窗口",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsc && electron dist/main.js",
|
"install": "pip install -r requirements.txt",
|
||||||
"build": "tsc",
|
"start": "python tray.py"
|
||||||
"start": "electron dist/main.js"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"electron": "^34.0.0",
|
|
||||||
"tsx": "^4.19.0",
|
|
||||||
"typescript": "^5.7.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pystray>=0.19.0
|
||||||
|
Pillow>=10.0.0
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
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 = `<!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 'Cascadia Code', 'Consolas', monospace; padding: 8px; }
|
|
||||||
#log { white-space: pre-wrap; word-break: break-all; }
|
|
||||||
.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) => {
|
|
||||||
const prefix = line.match(/^.{21}(\[.\])\[/);
|
|
||||||
const level = prefix ? prefix[1] : '[I]';
|
|
||||||
const cls = { '[D]': 'd', '[I]': 'i', '[W]': 'w', '[E]': 'e' }[level] || 'i';
|
|
||||||
el.innerHTML += '<span class="' + cls + '">' + escapeHtml(line) + '</span>\\n';
|
|
||||||
el.scrollTop = el.scrollHeight;
|
|
||||||
});
|
|
||||||
function escapeHtml(s) {
|
|
||||||
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</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)
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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'),
|
|
||||||
})
|
|
||||||
+160
@@ -0,0 +1,160 @@
|
|||||||
|
"""
|
||||||
|
质量追溯系统 - 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'
|
||||||
|
|
||||||
|
# Use npx to run tsx, regardless of OS
|
||||||
|
cmd = ['npx', 'tsx', 'src/index.ts']
|
||||||
|
|
||||||
|
# Windows: hide console window
|
||||||
|
extra = {}
|
||||||
|
if sys.platform == 'win32':
|
||||||
|
extra['creationflags'] = 0x08000000 # CREATE_NO_WINDOW
|
||||||
|
|
||||||
|
backend = subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
cwd=str(PROJECT_DIR),
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
env=env,
|
||||||
|
**extra,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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 键退出...')
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"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"]
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user