Files
37duAutomation/desktop/electron-shell/electron/electron-main.js
T
puddy dbb05e6ab3 feat(electron-shell): 启动链路修复与执行/配置收口插件侧
- 启动链路 P1-P7 修复:预算对齐、完成事件推送、端口占用提示、前端阶段文案接管
- 静态缓存按 IS_FROZEN 区分开发/打包态,bootPhaseOwned 竞态修复
- 一键执行与参数配置统一收口到插件界面,定时任务引用 config_id
- 环境包迁移到 %LOCALAPPDATA%\37duAutomation\python-env,重装零解压
- shell-updater:缓存包 sha256 校验、静默升级后自动拉起新版、自动清理旧安装包
- after-pack 钩子生成 shell.version 修复打包态版本识别
- 插件 xq0031/xq0045 迁移至 plugins/XQ0001-0100/ 号段分桶中文目录
2026-09-28 14:20:35 +08:00

200 lines
6.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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;
let isQuitting = false; // 托盘「退出」/系统退出时置真,放行真正关闭;否则关闭窗口 = 收托盘
// 单实例锁:重复启动聚焦已有窗口
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,
// 与启动页默认皮肤底色一致(style.css --bg #F9F7F2),避免冷启动色跳
backgroundColor: "#F9F7F2",
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", (e) => {
if (isQuitting) {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
return; // 真正退出:放行关闭
}
// 关闭按钮 → 收托盘(隐藏窗口,服务/插件继续运行),从托盘菜单「退出」才真正退出
e.preventDefault();
mainWindow.hide();
});
mainWindow.on("closed", () => {
mainWindow = null;
});
}
function trayIconImage() {
// 优先用官方图标(Windows 托盘/窗口均正常渲染);缺失时 SVG 兜底。
// 打包态:resources/assets/icon.ico(extraResources 真实文件);开发态:本模块 assets/
const ico = config.IS_FROZEN
? path.join(process.resourcesPath, "assets", "icon.ico")
: path.join(__dirname, "..", "assets", "icon.ico");
if (fs.existsSync(ico)) {
const img = nativeImage.createFromPath(ico);
if (!img.isEmpty()) return img;
}
// 16x16 蓝色圆点占位图标(正式打包时替换为 tools/icon.ico 生成的 png)
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="4" fill="#3b6cf6"/><text x="8" y="12" font-size="10" text-anchor="middle" fill="#fff" font-family="sans-serif">37</text></svg>`;
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: () => {
// 关闭窗口只是收托盘(窗口仍存在),此处复用已有窗口而非重复新建
if (!mainWindow) createWindow();
else { mainWindow.show(); mainWindow.focus(); }
},
},
{ 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()` 里 resolveAllowed/凭证/授权等串行网络调用在中心机不可达时会逐个
// 超时,窗口迟迟不出 —— 表现为"后台静默加载、毫无提示、像卡死"。
server = listen(() => {
createWindow();
createTray();
logger.info("Electron 壳就绪");
});
void init().catch((e) => logger.error(`后台初始化异常:${e.stack || e}`));
} catch (e) {
logger.error(`启动失败:${e.stack || e}`);
dialog.showErrorBox("37du 自动化工作台", `启动失败:${e.message}`);
app.quit();
}
});
app.on("window-all-closed", () => {
// 关闭窗口默认收托盘(close 已拦截),只有真正退出路径才会走到这里
app.quit();
});
app.on("before-quit", () => {
isQuitting = true; // 放行主窗口真正关闭
try {
if (server) server.close();
} catch (e) {
/* 忽略 */
}
});
}