// Electron 壳:窗口 / 托盘 / 单实例 / 自启。渲染层加载本地 8799 兼容层(复用 webhost 前端)。 "use strict"; const fs = require("fs"); const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen } = require("electron"); const path = require("path"); const config = require("./config"); const { makeLogger } = require("./logger"); const logger = makeLogger("electron-main"); // 移除 Electron 默认英文菜单栏(File Edit View Window Help):成品客户端菜单由页面自绘 Menu.setApplicationMenu(null); const PORT = config.PORT; const URL = `http://127.0.0.1:${PORT}`; // 窗口状态持久化:记住位置/尺寸,重启还原(防显示器变更后窗口跑到屏幕外) const WINDOW_STATE_FILE = path.join(config.APP_DATA, "window-state.json"); function loadWindowState() { try { if (!fs.existsSync(WINDOW_STATE_FILE)) return null; const s = JSON.parse(fs.readFileSync(WINDOW_STATE_FILE, "utf-8")); if (!s || typeof s !== "object") return null; const w = Math.max(1000, Math.min(4000, Number(s.width) || 1200)); const h = Math.max(660, Math.min(4000, Number(s.height) || 780)); const x = Number(s.x); const y = Number(s.y); if ( !Number.isFinite(x) || !Number.isFinite(y) || !screen.getAllDisplays().some((d) => { const a = d.workArea; return x < a.x + a.width && x + w > a.x && y < a.y + a.height && y + h > a.y; }) ) { return { width: w, height: h }; // 位置失效:只恢复尺寸 } return { width: w, height: h, x, y }; } catch (e) { return null; } } function saveWindowState(win) { try { const b = win.getBounds(); fs.mkdirSync(config.APP_DATA, { recursive: true }); fs.writeFileSync(WINDOW_STATE_FILE, JSON.stringify(b), "utf-8"); } catch (e) { /* 忽略:状态保存失败不影响运行 */ } } let mainWindow = null; let tray = null; let server = null; // 单实例锁:重复启动聚焦已有窗口 if (!app.requestSingleInstanceLock()) { app.quit(); } else { app.on("second-instance", () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } }); app.setAppUserModelId("37du.Host"); function createWindow() { const st = loadWindowState() || {}; mainWindow = new BrowserWindow({ width: st.width || 1200, height: st.height || 780, x: st.x, y: st.y, minWidth: 1000, minHeight: 660, backgroundColor: "#eef2f9", title: "37du 自动化工作台", icon: trayIconImage(), webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true, preload: path.join(__dirname, "preload.js"), }, }); mainWindow.loadURL(URL); // 关闭时保存窗口状态;resize/move 防抖保存(异常退出也不丢太多) let stateTimer = null; const save = () => { if (stateTimer) clearTimeout(stateTimer); stateTimer = setTimeout(() => { if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow); }, 400); if (stateTimer.unref) stateTimer.unref(); }; mainWindow.on("resize", save); mainWindow.on("move", save); mainWindow.on("close", () => { if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow); }); mainWindow.on("closed", () => { mainWindow = null; }); } function trayIconImage() { // 16x16 蓝色圆点占位图标(正式打包时替换为 tools/icon.ico 生成的 png) const svg = `37`; return nativeImage.createFromDataURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`); } function createTray() { tray = new Tray(trayIconImage()); const ctx = Menu.buildFromTemplate([ { label: "打开工作台", click: () => createWindow() }, { type: "separator" }, { label: "开机自启", type: "checkbox", checked: app.getLoginItemSettings().openAtLogin, click: (item) => { app.setLoginItemSettings({ openAtLogin: item.checked }); }, }, { type: "separator" }, { label: "退出", click: () => app.quit() }, ]); tray.setToolTip("37du 自动化工作台"); tray.setContextMenu(ctx); tray.on("click", () => { if (!mainWindow) createWindow(); else mainWindow.show(); }); } app.whenReady().then(async () => { try { const { init } = require("./app"); const { listen } = require("./server"); await init(); server = listen(() => { createWindow(); createTray(); logger.info("Electron 壳就绪"); }); } catch (e) { logger.error(`启动失败:${e.stack || e}`); dialog.showErrorBox("37du 自动化工作台", `启动失败:${e.message}`); app.quit(); } }); app.on("window-all-closed", () => { app.quit(); // Windows:关闭窗口即退出(服务随主进程结束) }); app.on("before-quit", () => { try { if (server) server.close(); } catch (e) { /* 忽略 */ } }); }