import { app, BrowserWindow, ipcMain, screen } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { placeOnDisplay, simulatedDisplays, } from "../shared/display"; import { assertDisplayIdReq, assertModeReq, CH, } from "../shared/ipc"; app.setName("Display Frame Lab"); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const tempData = isSmoke || isShots ? path.join(os.tmpdir(), `display-lab-${isSmoke ? "smoke" : "shots"}-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); let win = null; let displays = []; let primaryId = 0; let lastPlacement = null; let events = []; let restoreBounds = null; let moveTimer = null; let resizeTimer = null; function log(kind, detail) { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); if (win && !win.isDestroyed()) { win.webContents.send("display:event", { kind, detail, at: Date.now() }); } } function toDisplayInfo(display, primary) { return { id: display.id, label: display.label || `显示器 ${display.id}`, primary: display.id === primary, internal: display.internal, scaleFactor: display.scaleFactor, rotation: display.rotation, bounds: { ...display.bounds }, workArea: { ...display.workArea }, simulated: false, }; } function refreshDisplays() { const primary = screen.getPrimaryDisplay(); primaryId = primary.id; displays = screen .getAllDisplays() .map((display) => toDisplayInfo(display, primaryId)) .sort((a, b) => a.bounds.x - b.bounds.x || a.bounds.y - b.bounds.y); } function currentMode(window) { if (window.isKiosk()) return "kiosk"; if (window.isSimpleFullScreen()) return "simple"; if (window.isFullScreen()) return "fullscreen"; if (window.isMaximized()) return "maximized"; return "normal"; } function rememberBounds(window) { if (!restoreBounds && currentMode(window) === "normal") { restoreBounds = window.getBounds(); } } function leaveSpecial(window) { if (window.isKiosk()) window.setKiosk(false); if (window.isSimpleFullScreen()) window.setSimpleFullScreen(false); if (window.isFullScreen()) window.setFullScreen(false); } function applyMode(window, mode) { if (mode === "normal") { leaveSpecial(window); if (window.isMaximized()) window.unmaximize(); if (restoreBounds) { window.setBounds(restoreBounds); restoreBounds = null; } log("mode", "normal"); return; } rememberBounds(window); if (mode === "maximized") { leaveSpecial(window); if (!window.isMaximized()) window.maximize(); } else if (mode === "simple") { if (process.platform !== "darwin") { throw new Error("UNSUPPORTED_SIMPLE_FULLSCREEN"); } if (window.isKiosk()) window.setKiosk(false); if (window.isFullScreen()) window.setFullScreen(false); window.setSimpleFullScreen(true); } else if (mode === "kiosk") { if (window.isSimpleFullScreen()) window.setSimpleFullScreen(false); if (window.isFullScreen()) window.setFullScreen(false); window.setKiosk(true); } else { if (window.isSimpleFullScreen()) window.setSimpleFullScreen(false); if (window.isKiosk()) window.setKiosk(false); window.setFullScreen(true); } log("mode", mode); } function moveToDisplay(window, displayId) { const display = displays.find((item) => item.id === displayId); if (!display) throw new Error("DISPLAY_NOT_FOUND"); const size = window.getBounds(); const bounds = placeOnDisplay(display, { width: size.width, height: size.height, }); window.setBounds(bounds, true); lastPlacement = { displayId, bounds, reason: "居中放置在工作区", at: Date.now(), }; log("placement", `display ${displayId} @ ${bounds.x},${bounds.y}`); } function centerWindow(window) { const display = screen.getDisplayMatching(window.getBounds()); const bounds = placeOnDisplay(toDisplayInfo(display, primaryId), { width: window.getBounds().width, height: window.getBounds().height, }); window.setBounds(bounds, true); lastPlacement = { displayId: display.id, bounds, reason: "按当前显示器居中", at: Date.now(), }; log("placement", `center ${display.id} @ ${bounds.x},${bounds.y}`); } function snapshot() { const window = win; const bounds = window?.getBounds() ?? { x: 0, y: 0, width: 0, height: 0 }; const matching = screen.getDisplayMatching(bounds); const cursor = screen.getCursorScreenPoint(); const nearest = screen.getDisplayNearestPoint(cursor); return { platform: process.platform, electronVersion: process.versions.electron, displays: displays.map((display) => ({ ...display })), simulated: simulatedDisplays(), primaryId, cursor, nearestId: nearest.id, matchingId: matching.id, window: { bounds, contentBounds: window?.getContentBounds() ?? bounds, mode: window ? currentMode(window) : "normal", isMaximized: window?.isMaximized() ?? false, isFullScreen: window?.isFullScreen() ?? false, isSimpleFullScreen: window?.isSimpleFullScreen() ?? false, isKiosk: window?.isKiosk() ?? false, isResizable: window?.isResizable() ?? false, isFocused: window?.isFocused() ?? false, scaleFactor: matching.scaleFactor, }, lastPlacement, events: events.map((event) => ({ ...event })), }; } function resolvePreload() { 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() { const window = new BrowserWindow({ width: 1100, height: 860, minWidth: 880, minHeight: 600, show: false, frame: false, title: "多显示器与无边框工作台", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); const debounced = (timer, kind, detail) => { if (timer) clearTimeout(timer); return setTimeout(() => log(kind, detail()), 160); }; window.on("move", () => { moveTimer = debounced(moveTimer, "move", () => JSON.stringify(window.getBounds())); }); window.on("resize", () => { resizeTimer = debounced(resizeTimer, "resize", () => JSON.stringify(window.getBounds())); }); window.on("maximize", () => log("window", "maximize")); window.on("unmaximize", () => log("window", "unmaximize")); window.on("enter-full-screen", () => log("window", "enter-full-screen")); window.on("leave-full-screen", () => log("window", "leave-full-screen")); window.on("minimize", () => log("window", "minimize")); window.on("restore", () => log("window", "restore")); window.once("ready-to-show", () => window.show()); window.webContents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); log("ready", "renderer loaded"); }); window.on("closed", () => { if (moveTimer) clearTimeout(moveTimer); if (resizeTimer) clearTimeout(resizeTimer); win = null; }); 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 delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer(window, code) { let lastError = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)); } catch (error) { lastError = error; await delay(200); } } throw lastError instanceof Error ? lastError : new Error(String(lastError)); } async function waitForRenderer(window) { 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"); } async function runSmoke(window) { 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.displays >= 1 && result.primaryScale >= 1 && result.moveInside && result.centerInside && result.dragCss === "drag" && result.noDragCss === "no-drag" && result.maximizeOn && result.maximizeOff && result.simpleOn && result.simpleOff && result.kioskOn && result.kioskOff && result.clampNegOk && result.clampBigOk && result.pickLeft && result.pickPortrait && result.centerPortraitOk && result.physicalOk && result.simulated === 3 && result.events >= 5, ...result, })}\n`); applyMode(window, "normal"); app.quit(); } catch (error) { process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`); app.exit(1); } } async function capture(window, dir, file) { 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) { try { const dir = path.resolve(process.cwd(), "../../../docs/assets/images/35-multi-display-frameless"); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(700); await waitForRenderer(window); applyMode(window, "normal"); moveToDisplay(window, primaryId); await delay(300); await evalRenderer(window, `window.__prepareShots("displays")`); await delay(400); await capture(window, dir, "35-01-displays.png"); await evalRenderer(window, `window.__prepareShots("frameless")`); await delay(300); await capture(window, dir, "35-02-frameless.png"); await evalRenderer(window, `window.__prepareShots("bounds")`); await delay(300); await capture(window, dir, "35-03-bounds.png"); 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.moveTo, (_event, raw) => { assertDisplayIdReq(raw); if (!win) throw new Error("NO_WINDOW"); moveToDisplay(win, raw.displayId); return snapshot(); }); ipcMain.handle(CH.center, () => { if (!win) throw new Error("NO_WINDOW"); centerWindow(win); return snapshot(); }); ipcMain.handle(CH.setMode, (_event, raw) => { assertModeReq(raw); if (!win) throw new Error("NO_WINDOW"); applyMode(win, raw.mode); return snapshot(); }); ipcMain.handle(CH.minimize, () => { win?.minimize(); return snapshot(); }); ipcMain.handle(CH.toggleMaximize, () => { if (!win) throw new Error("NO_WINDOW"); if (win.isMaximized()) { win.unmaximize(); restoreBounds = null; } else { rememberBounds(win); win.maximize(); } return snapshot(); }); ipcMain.handle(CH.closeWindow, () => { win?.close(); return snapshot(); }); ipcMain.handle(CH.refresh, () => { refreshDisplays(); log("refresh", "刷新显示器与窗口状态"); return snapshot(); }); app.whenReady().then(() => { refreshDisplays(); const window = createWindow(); for (const display of screen.getAllDisplays()) { log("display", `${display.id} ${display.label} ${display.bounds.width}x${display.bounds.height}@${display.scaleFactor}x`); } screen.on("display-added", (_event, display) => { refreshDisplays(); log("display-added", `${display.id} ${display.label}`); }); screen.on("display-removed", (_event, display) => { refreshDisplays(); log("display-removed", `${display.id} ${display.label}`); }); screen.on("display-metrics-changed", (_event, display, changed) => { refreshDisplays(); log("display-metrics", `${display.id}: ${changed.join(",")}`); }); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { win?.show(); win?.focus(); } }); }); app.on("will-quit", () => { if (moveTimer) clearTimeout(moveTimer); if (resizeTimer) clearTimeout(resizeTimer); if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (!isSmoke && !isShots && process.platform !== "darwin") app.quit(); }); //# sourceMappingURL=index.js.map