// 自定义托盘右键菜单:无边框卡片式弹窗,替代系统原生菜单(原生样式跟随系统、不可控)。
// 用法:attach(tray, { onOpen, onQuit }),主进程负责窗口与菜单项动作。
"use strict";
const path = require("path");
const { app, BrowserWindow, ipcMain, screen } = require("electron");
const { makeLogger } = require("./logger");
const logger = makeLogger("tray-menu");
const W = 236;
const H = 178; // 与 buildHTML 里的内容高度一致(头部 44 + 三分隔 + 三菜单项)
const MARGIN = 8; // 与托盘图标 / 屏幕边缘留白
let win = null;
let trayRef = null;
let handlers = { onOpen: null, onQuit: null };
let wired = false;
function buildHTML() {
const version = app.getVersion();
const autoOn = app.getLoginItemSettings().openAtLogin ? "on" : "";
return `
37
37du 自动化工作台
服务运行中 · v${version}
`;
}
function closeMenu() {
if (win && !win.isDestroyed()) win.destroy();
win = null;
}
function openMenu() {
if (win && !win.isDestroyed()) { closeMenu(); return; } // 再次右键 = 收起
if (!trayRef) return;
try {
// 托盘图标可能被折叠进"隐藏的图标"面板(bounds 无效),此时以鼠标位置为锚点
let b = trayRef.getBounds();
if (!b || !b.width) {
const p = screen.getCursorScreenPoint();
b = { x: p.x - 8, y: p.y - 8, width: 16, height: 16 };
}
const pt = { x: b.x + Math.round(b.width / 2), y: b.y + Math.round(b.height / 2) };
const wa = screen.getDisplayNearestPoint(pt).workArea;
// 任务栏在屏幕下半部分时菜单向上弹出,否则向下
let x = Math.round(b.x + b.width / 2 - W / 2);
let y = b.y > wa.y + wa.height / 2 ? b.y - H - MARGIN : b.y + b.height + MARGIN;
x = Math.max(wa.x + MARGIN, Math.min(x, wa.x + wa.width - W - MARGIN));
y = Math.max(wa.y + MARGIN, Math.min(y, wa.y + wa.height - H - MARGIN));
win = new BrowserWindow({
width: W, height: H, x, y,
frame: false, transparent: true, resizable: false, movable: false,
minimizable: false, maximizable: false, fullscreenable: false,
skipTaskbar: true, alwaysOnTop: true, show: false, hasShadow: false,
backgroundColor: "#00000000",
webPreferences: {
preload: path.join(__dirname, "tray-menu-preload.js"),
contextIsolation: true, nodeIntegration: false, sandbox: true,
},
});
win.setAlwaysOnTop(true, "pop-up-menu");
win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML()));
win.once("ready-to-show", () => {
if (win && !win.isDestroyed()) { win.show(); win.focus(); }
});
win.on("blur", () => closeMenu());
win.on("closed", () => { win = null; });
} catch (e) {
logger.warning(`托盘菜单打开失败:${e.message}`);
closeMenu();
}
}
function wire() {
if (wired) return;
wired = true;
ipcMain.on("tray-menu:action", (_e, act) => {
if (act === "open") {
closeMenu();
if (handlers.onOpen) handlers.onOpen();
} else if (act === "quit") {
closeMenu();
if (handlers.onQuit) handlers.onQuit();
} else {
closeMenu();
}
});
ipcMain.handle("tray-menu:toggle-autostart", () => {
const next = !app.getLoginItemSettings().openAtLogin;
app.setLoginItemSettings({ openAtLogin: next });
return next;
});
}
function attach(tray, opts) {
trayRef = tray;
handlers = opts || { onOpen: null, onQuit: null };
wire();
tray.on("right-click", openMenu);
}
module.exports = { attach, close: closeMenu };