示例工程 30-multi-window-state

30-multi-window-state/app/main/index.ts

typescript · 18 KB

import { app, BrowserWindow, ipcMain, screen, type Rectangle } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  assertIdReq,
  assertMessageReq,
  assertMoveReq,
  assertRoleReq,
  CH,
  type AuxRole,
  type DisplayInfo,
  type PersistedState,
  type Rect,
  type WindowEvent,
  type WindowInfo,
  type WindowRole,
  type WindowsSnapshot,
} from "../shared/ipc";
import { clampToArea, pickArea } from "../shared/bounds";

app.setName("Window State Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const isolated = isSmoke || isShots;
const tempData = isolated
  ? path.join(
      os.tmpdir(),
      `window-state-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
    )
  : "";
if (tempData) app.setPath("userData", tempData);

type Meta = {
  title: string;
  width: number;
  height: number;
};

const META: Record<WindowRole, Meta> = {
  main: { title: "主窗口", width: 1100, height: 780 },
  settings: { title: "设置", width: 560, height: 460 },
  inspector: { title: "检查器", width: 620, height: 560 },
  note: { title: "便签", width: 420, height: 460 },
};

const AUX_ROLES: AuxRole[] = ["settings", "inspector", "note"];

let mainWindow: BrowserWindow | null = null;
const aux = new Map<number, { win: BrowserWindow; role: AuxRole }>();
let events: WindowEvent[] = [];
let lastMessage = "";
let restoredCount = 0;
let saveTimer: ReturnType<typeof setTimeout> | null = null;
let skipSave = false;

function storeFile(): string {
  return path.join(app.getPath("userData"), "windows.json");
}

function sanitizeRect(value: unknown): Rect | null {
  if (typeof value !== "object" || value === null) return null;
  const { x, y, width, height } = value as Record<string, unknown>;
  if (
    typeof x !== "number" ||
    typeof y !== "number" ||
    typeof width !== "number" ||
    typeof height !== "number" ||
    !Number.isFinite(x) ||
    !Number.isFinite(y) ||
    !Number.isFinite(width) ||
    !Number.isFinite(height) ||
    width < 200 ||
    height < 150
  ) {
    return null;
  }
  return { x, y, width, height };
}

function loadStore(): PersistedState {
  try {
    const raw: unknown = JSON.parse(fsSync.readFileSync(storeFile(), "utf8"));
    if (typeof raw !== "object" || raw === null)
      return { bounds: {}, open: [] };
    const bounds: Partial<Record<WindowRole, Rect>> = {};
    const rawBounds = (raw as { bounds?: unknown }).bounds;
    if (typeof rawBounds === "object" && rawBounds !== null) {
      for (const role of ["main", ...AUX_ROLES] as WindowRole[]) {
        const rect = sanitizeRect((rawBounds as Record<string, unknown>)[role]);
        if (rect) bounds[role] = rect;
      }
    }
    const rawOpen = (raw as { open?: unknown }).open;
    const open = Array.isArray(rawOpen)
      ? rawOpen.filter((role): role is WindowRole =>
          ["main", ...AUX_ROLES].includes(role as WindowRole),
        )
      : [];
    return { bounds, open };
  } catch {
    return { bounds: {}, open: [] };
  }
}

function currentBounds(role: WindowRole): Rect | undefined {
  if (role === "main") {
    if (!mainWindow || mainWindow.isDestroyed()) return undefined;
    const bounds = mainWindow.getBounds();
    return { ...bounds };
  }
  for (const entry of aux.values()) {
    if (entry.role === role && !entry.win.isDestroyed()) {
      return { ...entry.win.getBounds() };
    }
  }
  return undefined;
}

function collectPersisted(): PersistedState {
  const bounds: Partial<Record<WindowRole, Rect>> = {};
  const main = currentBounds("main");
  if (main) bounds.main = main;
  for (const entry of aux.values()) {
    if (!entry.win.isDestroyed()) {
      bounds[entry.role] = { ...entry.win.getBounds() };
    }
  }
  return {
    bounds,
    open: [...aux.values()].map((entry) => entry.role),
  };
}

function saveNow(): void {
  if (saveTimer) {
    clearTimeout(saveTimer);
    saveTimer = null;
  }
  try {
    const dir = path.dirname(storeFile());
    fsSync.mkdirSync(dir, { recursive: true });
    const temp = `${storeFile()}.tmp`;
    fsSync.writeFileSync(
      temp,
      `${JSON.stringify(collectPersisted(), null, 2)}\n`,
      "utf8",
    );
    fsSync.renameSync(temp, storeFile());
  } catch {
    // 存储失败不影响窗口继续工作。
  }
}

function scheduleSave(): void {
  if (skipSave) return;
  if (saveTimer) clearTimeout(saveTimer);
  saveTimer = setTimeout(() => {
    saveTimer = null;
    saveNow();
  }, 250);
}

function addEvent(source: WindowEvent["source"], text: string): void {
  events = [{ at: Date.now(), source, text }, ...events].slice(0, 20);
}

function displayInfo(): DisplayInfo[] {
  const primary = screen.getPrimaryDisplay();
  return screen.getAllDisplays().map((display) => ({
    id: display.id,
    workArea: { ...display.workArea },
    scaleFactor: display.scaleFactor,
    primary: display.id === primary.id,
  }));
}

function windowInfo(win: BrowserWindow, role: WindowRole): WindowInfo {
  const bounds = win.getBounds();
  return {
    id: win.id,
    role,
    title: META[role].title,
    bounds: { ...bounds },
    visible: win.isVisible(),
    focused: win.isFocused(),
    displayId: screen.getDisplayMatching(bounds).id,
  };
}

function snapshot(): WindowsSnapshot {
  const windows: WindowInfo[] = [];
  if (mainWindow && !mainWindow.isDestroyed()) {
    windows.push(windowInfo(mainWindow, "main"));
  }
  for (const entry of aux.values()) {
    if (!entry.win.isDestroyed()) {
      windows.push(windowInfo(entry.win, entry.role));
    }
  }
  return {
    windows,
    storePath: "userData/windows.json",
    persisted: collectPersisted(),
    displays: displayInfo(),
    events: [...events],
    lastMessage,
    restoredCount,
  };
}

function broadcast(): void {
  const state = snapshot();
  for (const win of BrowserWindow.getAllWindows()) {
    if (!win.isDestroyed()) win.webContents.send(CH.changed, state);
  }
}

function placeBounds(role: WindowRole, saved?: Rect, offsetIndex = 0): Rect {
  const displays = screen.getAllDisplays();
  const fallback: Rect = {
    x: 80 + offsetIndex * 36,
    y: 60 + offsetIndex * 36,
    width: META[role].width,
    height: META[role].height,
  };
  const desired = saved ?? fallback;
  const area = pickArea(
    desired,
    displays.map((display) => display.workArea),
  );
  return clampToArea(desired, area);
}

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 loadRenderer(win: BrowserWindow, role: WindowRole): void {
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
    url.searchParams.set("role", role);
    url.searchParams.set("id", String(win.id));
    void win.loadURL(url.toString());
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
      { query: { role, id: String(win.id) } },
    );
  }
}

function roleOf(win: BrowserWindow): WindowRole {
  if (win === mainWindow) return "main";
  for (const entry of aux.values()) {
    if (entry.win === win) return entry.role;
  }
  return "main";
}

function createMain(saved?: Rect): BrowserWindow {
  const bounds = placeBounds("main", saved);
  const win = new BrowserWindow({
    ...bounds,
    show: false,
    title: META.main.title,
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  win.once("ready-to-show", () => win.show());
  win.webContents.once("did-finish-load", () => {
    if (!win.isDestroyed() && !win.isVisible()) win.show();
  });
  win.on("move", scheduleSave);
  win.on("resize", scheduleSave);
  win.on("focus", broadcast);
  win.on("blur", broadcast);
  win.on("show", broadcast);
  win.on("hide", broadcast);
  win.on("closed", () => {
    if (mainWindow === win) mainWindow = null;
    scheduleSave();
    broadcast();
  });
  loadRenderer(win, "main");
  win.show();
  mainWindow = win;
  return win;
}

function findAux(role: AuxRole): BrowserWindow | undefined {
  for (const entry of aux.values()) {
    if (entry.role === role && !entry.win.isDestroyed()) return entry.win;
  }
  return undefined;
}

function createAux(role: AuxRole, saved?: Rect): BrowserWindow {
  const existing = findAux(role);
  if (existing) {
    existing.focus();
    addEvent("system", `${META[role].title} 已存在,聚焦`);
    broadcast();
    return existing;
  }
  const index = aux.size + 1;
  const bounds = placeBounds(role, saved, index);
  const win = new BrowserWindow({
    ...bounds,
    show: false,
    title: META[role].title,
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  win.once("ready-to-show", () => win.show());
  win.webContents.once("did-finish-load", () => {
    if (!win.isDestroyed() && !win.isVisible()) win.show();
  });
  win.on("move", scheduleSave);
  win.on("resize", scheduleSave);
  win.on("focus", broadcast);
  win.on("blur", broadcast);
  win.on("closed", () => {
    aux.delete(win.id);
    addEvent("system", `关闭 ${META[role].title}`);
    scheduleSave();
    broadcast();
  });
  loadRenderer(win, role);
  win.show();
  aux.set(win.id, { win, role });
  addEvent("system", `创建 ${META[role].title}`);
  scheduleSave();
  broadcast();
  return win;
}

function findWindow(id: number): BrowserWindow | undefined {
  if (mainWindow?.id === id) return mainWindow;
  return aux.get(id)?.win;
}

function destroyAux(): void {
  for (const entry of [...aux.values()]) {
    if (!entry.win.isDestroyed()) entry.win.destroy();
  }
  aux.clear();
}

function resetAll(): WindowsSnapshot {
  skipSave = true;
  destroyAux();
  skipSave = false;
  try {
    fsSync.rmSync(storeFile(), { force: true });
  } catch {
    // 忽略删除失败。
  }
  events = [];
  lastMessage = "";
  restoredCount = 0;
  addEvent("system", "已重置窗口布局");
  saveNow();
  broadcast();
  return snapshot();
}

function restoreFromStore(): WindowsSnapshot {
  const saved = loadStore();
  skipSave = true;
  destroyAux();
  skipSave = false;
  for (const role of saved.open) {
    if (AUX_ROLES.includes(role as AuxRole)) {
      createAux(role as AuxRole, saved.bounds[role]);
    }
  }
  restoredCount = aux.size;
  addEvent(
    "system",
    restoredCount > 0
      ? `从磁盘恢复 ${restoredCount} 个窗口`
      : "没有可恢复的窗口",
  );
  saveNow();
  broadcast();
  return snapshot();
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(win: BrowserWindow, code: string): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await win.webContents.executeJavaScript(code)) as T;
    } catch (error) {
      lastError = error;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(win: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (win.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        win,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  roles: string[];
  singletonCount: number;
  moved: boolean;
  messageSeen: boolean;
  persistedOpen: number;
  restoredRoles: string[];
  restoredIdsChanged: boolean;
  clamped: boolean;
  lastEvent: string;
};

async function runSmoke(win: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
    const stored: unknown = JSON.parse(
      fsSync.readFileSync(storeFile(), "utf8"),
    );
    const storedOpen = Array.isArray((stored as { open?: unknown }).open)
      ? (stored as { open: unknown[] }).open.length
      : -1;
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.roles.includes("main") &&
          result.roles.includes("settings") &&
          result.roles.includes("note") &&
          result.roles.includes("inspector") &&
          result.singletonCount === 1 &&
          result.moved &&
          result.messageSeen &&
          result.persistedOpen === 3 &&
          result.restoredRoles.length === 3 &&
          result.restoredIdsChanged &&
          result.clamped &&
          storedOpen === 3 &&
          mainWindow?.isVisible() === true &&
          aux.size === 3,
        storedOpen,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  win: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await win.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(win: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/30-multi-window-state",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    await evalRenderer(win, `window.__prepareShots("hub")`);
    await delay(1200);
    await capture(win, dir, "30-01-hub.png");
    const note = findAux("note");
    if (note) {
      note.show();
      await delay(200);
      await capture(note, dir, "30-02-note.png");
    }
    await evalRenderer(win, `window.__prepareShots("restore")`);
    await delay(900);
    await capture(win, dir, "30-03-restore.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.get, () => snapshot());

ipcMain.handle(CH.create, (_event, raw: unknown) => {
  try {
    assertRoleReq(raw);
    createAux(raw.role);
    return snapshot();
  } catch {
    throw new Error("WINDOW_CREATE_FAILED");
  }
});

ipcMain.handle(CH.focus, (_event, raw: unknown) => {
  try {
    assertIdReq(raw);
    const win = findWindow(raw.id);
    if (win && !win.isDestroyed()) {
      win.show();
      win.focus();
      addEvent("hub", `聚焦 ${META[roleOf(win)].title}`);
    }
    broadcast();
    return snapshot();
  } catch {
    throw new Error("WINDOW_FOCUS_FAILED");
  }
});

ipcMain.handle(CH.close, (_event, raw: unknown) => {
  try {
    assertIdReq(raw);
    const win = findWindow(raw.id);
    if (win && win !== mainWindow && !win.isDestroyed()) win.close();
    return snapshot();
  } catch {
    throw new Error("WINDOW_CLOSE_FAILED");
  }
});

ipcMain.handle(CH.move, (_event, raw: unknown) => {
  try {
    assertMoveReq(raw);
    const win = findWindow(raw.id);
    if (win && !win.isDestroyed()) {
      const current = win.getBounds();
      const desired: Rectangle = {
        ...current,
        x: current.x + raw.dx,
        y: current.y + raw.dy,
      };
      const area = pickArea(
        desired,
        screen.getAllDisplays().map((display) => display.workArea),
      );
      win.setBounds(clampToArea(desired, area));
      addEvent("hub", `移动 ${META[roleOf(win)].title}`);
    }
    scheduleSave();
    broadcast();
    return snapshot();
  } catch {
    throw new Error("WINDOW_MOVE_FAILED");
  }
});

ipcMain.handle(CH.message, (_event, raw: unknown) => {
  try {
    assertMessageReq(raw);
    lastMessage = raw.text;
    addEvent("aux", raw.text);
    broadcast();
    return snapshot();
  } catch {
    throw new Error("WINDOW_MESSAGE_FAILED");
  }
});

ipcMain.handle(CH.restore, () => restoreFromStore());
ipcMain.handle(CH.reset, () => resetAll());

app.whenReady().then(() => {
  const saved = loadStore();
  const win = createMain(saved.bounds.main);
  let restored = 0;
  for (const role of saved.open) {
    if (AUX_ROLES.includes(role as AuxRole)) {
      createAux(role as AuxRole, saved.bounds[role]);
      restored += 1;
    }
  }
  restoredCount = restored;
  if (restored > 0) addEvent("system", `启动时恢复 ${restored} 个窗口`);
  broadcast();
  if (isSmoke) {
    void runSmoke(win);
  } else if (isShots) {
    void runShots(win);
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMain(loadStore().bounds.main);
    } else {
      mainWindow?.show();
    }
  });
});

app.on("will-quit", () => {
  if (saveTimer) clearTimeout(saveTimer);
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (!isSmoke && !isShots && process.platform !== "darwin") app.quit();
});