import { app, BrowserWindow, globalShortcut, ipcMain, Menu, nativeImage, Notification, Tray, type MenuItemConstructorOptions, } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { assertAutostartReq, assertLinkReq, assertNotifyReq, assertViewReq, CH, type ActivityRow, type Integration, type LastLink, type LinkSource, type Snapshot, type TrayMenuItemView, } from "../shared/ipc"; import { hubLinkFromArgv, parseHubLink, type HubView, } from "../shared/deep-link"; import { initialHubState, reduceHub, type HubState } from "../shared/hub-state"; import { TRAY_ICON_DATA_URL } from "../shared/tray-icon"; app.setName("XWRT Hub"); const SHORTCUT = "CommandOrControl+Shift+Alt+H"; const gotLock = app.requestSingleInstanceLock(); if (!gotLock) app.quit(); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const startHidden = process.argv.includes("--hidden"); const tempData = isSmoke || isShots ? path.join( os.tmpdir(), `hub-${isSmoke ? "smoke" : "shots"}-${process.pid}`, ) : ""; if (tempData) app.setPath("userData", tempData); let win: BrowserWindow | null = null; let tray: Tray | null = null; let forceQuit = false; let state: HubState = initialHubState(); let activeView: HubView = "inbox"; let lastLink: LastLink | null = null; let activity: ActivityRow[] = []; let protocolRegistered = false; const counts: Record = { inbox: 3, tasks: 4, settings: 0, }; const integration: Integration = { trayCreated: false, trayMenuItems: 0, shortcutAccelerator: SHORTCUT, shortcutRegistered: false, notificationSupported: Notification.isSupported(), singleInstance: gotLock, protocolRegistered: false, packaged: app.isPackaged, openAtLogin: false, autostartStatus: "", lastNotification: "", }; function log(kind: string, detail: string): void { activity = [{ at: Date.now(), kind, detail }, ...activity].slice(0, 40); if (win && !win.isDestroyed()) { win.webContents.send("hub:event", { kind, detail, at: Date.now() }); } } function readAutostart(): void { const settings = app.getLoginItemSettings(); integration.openAtLogin = Boolean(settings.openAtLogin); integration.autostartStatus = String(settings.status ?? ""); } function broadcast(): void { if (win && !win.isDestroyed()) { win.webContents.send("hub:event", { kind: "snapshot", detail: "refresh", at: Date.now(), }); } } function showWindow(): void { if (!win || win.isDestroyed()) return; win.show(); win.focus(); state = reduceHub(state, "show"); } function toggleWindow(): void { if (!win || win.isDestroyed()) return; if (win.isVisible()) { win.hide(); state = reduceHub(state, "hide"); log("shortcut", "全局快捷键隐藏窗口"); } else { showWindow(); log("shortcut", "全局快捷键唤回窗口"); } broadcast(); } function openView(view: HubView, source: string): void { activeView = view; showWindow(); log("view", `${source} → ${view}`); broadcast(); } function applyLink(raw: string, source: LinkSource): LastLink { const parsed = parseHubLink(raw); const entry: LastLink = parsed.ok ? { raw, ok: true, view: parsed.view, id: parsed.id, reason: "", source, at: Date.now(), } : { raw, ok: false, view: null, id: null, reason: parsed.reason, source, at: Date.now(), }; lastLink = entry; if (parsed.ok) { activeView = parsed.view; log( "link", `${source} → ${parsed.view}${parsed.id ? ` · ${parsed.id}` : ""}`, ); } else { log("link-error", `${source} → ${parsed.reason}`); } showWindow(); broadcast(); return entry; } function sendNotification(title: string, body: string): boolean { if (!Notification.isSupported()) { integration.lastNotification = "unsupported"; log("notification", "系统不支持通知"); broadcast(); return false; } try { const notification = new Notification({ title, body }); notification.on("click", () => { showWindow(); log("notification-click", title); broadcast(); }); notification.show(); integration.lastNotification = `${title} · ${body}`; log("notification", title); broadcast(); return true; } catch (error) { const message = error instanceof Error ? error.message : String(error); integration.lastNotification = `failed: ${message}`; log("notification-error", message); broadcast(); return false; } } function setAutostart(enabled: boolean, dryRun: boolean): void { if (dryRun) { log("autostart", `预览:openAtLogin=${enabled}(未写入)`); broadcast(); return; } const before = app.getLoginItemSettings().openAtLogin; try { app.setLoginItemSettings({ openAtLogin: enabled, args: enabled ? ["--autostart", "--hidden"] : [], }); readAutostart(); log( "autostart", `应用:openAtLogin ${before} → ${integration.openAtLogin}`, ); if (tray) tray.setContextMenu(Menu.buildFromTemplate(trayTemplate())); } catch (error) { const message = error instanceof Error ? error.message : String(error); log("autostart-error", message); broadcast(); throw new Error("AUTOSTART_APPLY_FAILED"); } broadcast(); } function quitApp(): void { forceQuit = true; state = reduceHub(state, "quit"); log("lifecycle", "真正退出"); app.quit(); } function trayTemplate(): MenuItemConstructorOptions[] { return [ { id: "hub.show", label: "显示指挥台", accelerator: "CommandOrControl+Shift+Alt+H", click: () => { showWindow(); broadcast(); }, }, { id: "hub.inbox", label: "打开收件箱", click: () => openView("inbox", "tray"), }, { id: "hub.tasks", label: "打开任务", click: () => openView("tasks", "tray"), }, { id: "hub.settings", label: "打开设置", click: () => openView("settings", "tray"), }, { type: "separator" }, { id: "hub.autostart", label: "开机自启", type: "checkbox", checked: app.getLoginItemSettings().openAtLogin, click: (item) => { try { setAutostart(item.checked, false); } catch { // 失败已写进活动日志。 } }, }, { id: "hub.notify", label: "发送测试通知", click: () => { sendNotification("XWRT 指挥台", "这是一条来自托盘的测试通知"); }, }, { type: "separator" }, { id: "hub.quit", label: "真正退出", click: () => quitApp(), }, ]; } function trayMenuView(): TrayMenuItemView[] { return trayTemplate() .filter((item) => item.id && item.type !== "separator") .map((item) => ({ id: String(item.id), label: String(item.label ?? item.id), type: item.type === "checkbox" ? "checkbox" : "normal", checked: Boolean(item.checked), enabled: item.enabled !== false, })); } function snapshot(): Snapshot { readAutostart(); return { platform: process.platform, electronVersion: process.versions.electron, activeView, counts, lastLink, activity: activity.map((row) => ({ ...row })), integration: { ...integration, trayCreated: tray !== null, trayMenuItems: trayMenuView().length, protocolRegistered, packaged: app.isPackaged, singleInstance: gotLock, shortcutRegistered: integration.shortcutRegistered, }, trayMenu: trayMenuView(), window: { visible: win?.isVisible() ?? false, focused: win?.isFocused() ?? false, bounds: win?.getBounds() ?? { x: 0, y: 0, width: 0, height: 0 }, }, }; } function resolvePreload(): string { const candidates = [ path.join(__dirname, "preload.cjs"), path.join(__dirname, "../preload/index.cjs"), path.join(__dirname, "preload.js"), ]; return ( candidates.find((candidate) => fsSync.existsSync(candidate)) ?? candidates[0] ?? "" ); } function createWindow(): BrowserWindow { const window = new BrowserWindow({ width: 1100, height: 860, show: false, title: "XWRT 指挥台", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); window.once("ready-to-show", () => { if (!startHidden || isSmoke || isShots) window.show(); }); window.webContents.once("did-finish-load", () => { broadcast(); }); window.on("close", (event) => { if (forceQuit) return; event.preventDefault(); window.hide(); state = reduceHub(state, "close"); log("window", "关闭被拦截:隐藏到托盘"); broadcast(); }); window.on("show", () => { state = { ...state, visible: true }; }); window.on("hide", () => { state = { ...state, visible: false }; }); if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); } else { void window.loadFile( path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), ); } win = window; return window; } function createTray(): void { if (tray) return; const image = nativeImage.createFromDataURL(TRAY_ICON_DATA_URL); if (process.platform === "darwin") image.setTemplateImage(true); tray = new Tray(image); tray.setToolTip("XWRT 指挥台"); tray.on("click", () => toggleWindow()); tray.setContextMenu(Menu.buildFromTemplate(trayTemplate())); integration.trayCreated = true; integration.trayMenuItems = trayMenuView().length; log("tray", `托盘已创建 · ${integration.trayMenuItems} 个菜单项`); } function registerShortcut(): void { try { integration.shortcutRegistered = globalShortcutRegister(); } catch (error) { const message = error instanceof Error ? error.message : String(error); integration.shortcutRegistered = false; log("shortcut-error", message); } log( "shortcut", `${SHORTCUT} · ${integration.shortcutRegistered ? "已注册" : "注册失败"}`, ); } function globalShortcutRegister(): boolean { return globalShortcut.register(SHORTCUT, () => toggleWindow()); } function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer( window: BrowserWindow, code: string, ): Promise { let lastError: unknown = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)) as T; } catch (error) { lastError = error; await delay(200); } } throw lastError instanceof Error ? lastError : new Error(String(lastError)); } async function waitForRenderer(window: BrowserWindow): Promise { for (let attempt = 0; attempt < 160; attempt += 1) { if (window.isDestroyed()) return; try { const ready = await evalRenderer( window, "typeof window.__smoke === 'function'", ); if (ready) return; } catch { // 页面仍在加载。 } await delay(100); } throw new Error("renderer did not become ready"); } type SmokeResult = { platform: string; singleInstance: boolean; tray: boolean; trayItems: number; shortcut: boolean; notificationSupported: boolean; notification: string; validView: string; validId: string; validSource: string; badScheme: string; badView: string; hidden: boolean; shown: boolean; closedToTray: boolean; restored: boolean; autostartBefore: boolean; autostartAfter: boolean; autostartUnchanged: boolean; events: number; counts: number; }; async function runSmoke(window: BrowserWindow): Promise { try { await waitForRenderer(window); await delay(700); await waitForRenderer(window); const result = await evalRenderer(window, "window.__smoke()"); process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: result.singleInstance && result.tray && result.trayItems >= 6 && result.shortcut && typeof result.notificationSupported === "boolean" && result.notification.length > 0 && result.validView === "tasks" && result.validId === "42" && result.validSource === "second-instance" && result.badScheme === "BAD_SCHEME" && result.badView === "BAD_VIEW" && result.hidden && result.shown && result.closedToTray && result.restored && result.autostartUnchanged && result.events >= 6 && result.counts === 7, ...result, })}\n`, ); forceQuit = true; app.quit(); } catch (error) { process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`, ); app.exit(1); } } async function capture( window: BrowserWindow, dir: string, file: string, ): Promise { const image = await window.webContents.capturePage(); if (image.isEmpty()) throw new Error(`empty capture: ${file}`); const png = image.toPNG(); fsSync.writeFileSync(path.join(dir, file), png); fsSync.writeFileSync(path.join(dir, "raw", file), png); } async function runShots(window: BrowserWindow): Promise { try { const dir = path.resolve( process.cwd(), "../../../docs/assets/images/36-project-desktop-hub", ); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(700); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("hub")`); await delay(400); await capture(window, dir, "36-01-hub.png"); await evalRenderer(window, `window.__prepareShots("deeplink")`); await delay(400); await capture(window, dir, "36-02-deeplink.png"); await evalRenderer(window, `window.__prepareShots("tray")`); await delay(400); await capture(window, dir, "36-03-tray.png"); forceQuit = true; app.quit(); } catch (error) { process.stdout.write( `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`, ); app.exit(1); } } ipcMain.handle(CH.snapshot, () => snapshot()); ipcMain.handle(CH.setView, (_event, raw: unknown) => { assertViewReq(raw); activeView = raw.view; log("view", `切换到 ${raw.view}`); broadcast(); return snapshot(); }); ipcMain.handle(CH.openLink, (_event, raw: unknown) => { assertLinkReq(raw); applyLink(raw.url, raw.source); return snapshot(); }); ipcMain.handle(CH.notify, (_event, raw: unknown) => { assertNotifyReq(raw); sendNotification(raw.title, raw.body); return snapshot(); }); ipcMain.handle(CH.setAutostart, (_event, raw: unknown) => { assertAutostartReq(raw); setAutostart(raw.enabled, raw.dryRun); return snapshot(); }); ipcMain.handle(CH.hide, () => { win?.hide(); state = reduceHub(state, "hide"); log("window", "隐藏到托盘"); return snapshot(); }); ipcMain.handle(CH.show, () => { showWindow(); log("window", "从托盘唤回"); return snapshot(); }); ipcMain.handle(CH.closeToTray, () => { win?.close(); return snapshot(); }); ipcMain.handle(CH.quit, () => { quitApp(); return snapshot(); }); ipcMain.handle(CH.refresh, () => { readAutostart(); log("refresh", "刷新系统集成状态"); return snapshot(); }); app.on("second-instance", (_event, argv) => { const url = hubLinkFromArgv(argv); if (url) { applyLink(url, "second-instance"); } else { showWindow(); log("second-instance", "第二实例已转发到当前窗口"); broadcast(); } }); app.on("open-url", (event, url) => { event.preventDefault(); applyLink(url, "open-url"); }); app.whenReady().then(() => { if (!gotLock) return; readAutostart(); if (app.isPackaged) { protocolRegistered = app.setAsDefaultProtocolClient("xwrt-hub"); } else { protocolRegistered = false; } log( "ready", `XWRT 指挥台启动 · ${app.isPackaged ? "打包" : "开发态"}${startHidden ? " · 隐藏启动" : ""}`, ); const window = createWindow(); createTray(); registerShortcut(); const initialUrl = hubLinkFromArgv(process.argv); if (initialUrl) { applyLink(initialUrl, "open-url"); } broadcast(); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { showWindow(); } broadcast(); }); }); app.on("before-quit", () => { forceQuit = true; }); app.on("will-quit", () => { globalShortcut.unregisterAll(); tray?.destroy(); tray = null; if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { // 托盘驻留:窗口关闭不代表退出;只有托盘不存在时才退回默认行为。 if (!tray) app.quit(); });