Files
37duAutomation/desktop/electron-shell/electron/electron-main.js
T
puddy b8124aa448 feat(electron-shell): 1.8.0 执行队列、流程编排、流程定时与版本回滚
- 执行队列:多任务串行排队,可单独取消,超时自动放弃,异常退出后标记已中断

- 流程编排:画布多场景依赖图,内置确保登录/等待/通知/人工确认节点

- 流程定时:场景与流程统一配置定时(每天/工作日/每周/每月/每隔N小时)

- 流程版本历史:自动留档 20 版,画布一键回滚且回滚可撤销

- 流程配置云备份:随定时任务备份到中心机,换机自动恢复

- 总览页/场景库布局调整,通知浮窗右下角堆叠显示
2026-10-27 13:36:38 +08:00

223 lines
8.5 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, ipcMain } = require("electron");
const path = require("path");
const config = require("./config");
const { makeLogger } = require("./logger");
const trayMenu = require("./tray-menu");
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 && !mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
// 收托盘走的是 hide():隐藏窗口不是 minimized,focus() 也唤不回,必须先 show()
mainWindow.show();
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,
// 无边框窗口:顶栏由渲染层自绘(含窗口控制钮 / 面包屑 / 服务状态)
frame: false,
// 与启动页画布底色一致(style.css --canvas #F2F4F8),避免冷启动色跳
backgroundColor: "#F2F4F8",
title: "37du 自动化工作台",
icon: trayIconImage(),
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
preload: path.join(__dirname, "preload.js"),
},
});
// 渲染层报错转发到主进程日志:白屏时能直接在 shell-dev.log 里看到原因
mainWindow.webContents.on("console-message", (_ev, level, message) => {
if (!message) return;
if (level >= 2) logger.warning(`[renderer] ${message}`);
});
mainWindow.webContents.on("render-process-gone", (_ev, d) => {
logger.error(`渲染进程异常退出:${JSON.stringify(d)}`);
});
mainWindow.loadURL(URL);
// 推送最大化状态变化:渲染层顶栏切换最大化/还原图标
const sendMaxState = () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send("win:maximized", mainWindow.isMaximized());
}
};
mainWindow.on("maximize", sendMaxState);
mainWindow.on("unmaximize", sendMaxState);
// 关闭时保存窗口状态;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;
});
}
// 无边框窗口控制 IPC:渲染层自绘顶栏的窗口控制钮走这里(fire-and-forget)
ipcMain.on("win:min", () => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.minimize(); });
ipcMain.on("win:max", () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
});
// 关闭 = 走 close 拦截逻辑(默认收托盘,托盘「退出」才真正退出)
ipcMain.on("win:close", () => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.close(); });
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 openWorkbench() {
// 关闭窗口只是收托盘(窗口仍存在),此处复用已有窗口而非重复新建
if (!mainWindow) createWindow();
else { mainWindow.show(); mainWindow.focus(); }
}
function createTray() {
tray = new Tray(trayIconImage());
tray.setToolTip("37du 自动化工作台");
// 右键菜单用自绘卡片弹窗(系统原生菜单样式跟随系统、无法统一视觉)
trayMenu.attach(tray, {
onOpen: openWorkbench,
onQuit: () => app.quit(),
});
tray.on("click", openWorkbench);
}
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 {
require("./runner").shutdown();
} catch (e) {
/* 忽略:退出路径不再抛错 */
}
try {
if (server) server.close();
} catch (e) {
/* 忽略 */
}
});
}