示例工程 04-lifecycle-and-windows

04-lifecycle-and-windows/app/main/index.ts

typescript · 6.9 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import {
  CH,
  type LifecycleEvent,
  type LifecycleInfo,
  type WindowSnapshot,
} from "../shared/ipc";

const gotLock = app.requestSingleInstanceLock();

function runMain(): void {
  const isSmoke =
    process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
  const isShots = process.argv.includes("--shots");

  let primary: BrowserWindow | null = null;
  let started = false;
  const events: LifecycleEvent[] = [];

  function log(record: Record<string, unknown>): void {
    process.stdout.write(`${JSON.stringify(record)}\n`);
  }

  function record(name: string, detail?: string): void {
    events.push({ at: Date.now(), name, detail });
    if (events.length > 100) events.shift();
    log({ evt: "lifecycle", name, detail });
  }

  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 load(window: BrowserWindow): void {
    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`),
      );
    }
  }

  function snapshot(window: BrowserWindow): WindowSnapshot {
    return {
      id: window.id,
      bounds: window.getBounds(),
      focused: window.isFocused(),
      minimized: window.isMinimized(),
      maximized: window.isMaximized(),
    };
  }

  function collectInfo(): LifecycleInfo {
    return {
      events: events.slice(-30),
      windows: BrowserWindow.getAllWindows()
        .filter((window) => !window.isDestroyed())
        .map(snapshot),
      singleInstance: gotLock,
      ready: app.isReady(),
    };
  }

  function focusPrimary(): void {
    if (!primary || primary.isDestroyed()) return;
    if (primary.isMinimized()) primary.restore();
    primary.show();
    primary.focus();
  }

  function openWindow(): BrowserWindow {
    const window = new BrowserWindow({
      width: 900,
      height: 640,
      show: false,
      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", () => {
      window.show();
    });
    window.on("focus", () => record("window-focus", String(window.id)));
    window.on("blur", () => record("window-blur", String(window.id)));
    window.on("minimize", () => record("window-minimize", String(window.id)));
    window.on("maximize", () => record("window-maximize", String(window.id)));
    window.on("unmaximize", () =>
      record("window-unmaximize", String(window.id)),
    );
    window.on("closed", () => {
      record("window-closed", String(window.id));
      if (primary === window) primary = null;
    });

    load(window);
    return window;
  }

  async function runSmoke(): Promise<void> {
    try {
      openWindow();
      await new Promise((resolve) => setTimeout(resolve, 600));
      const info = collectInfo();
      log({
        evt: "smoke",
        ok: info.windows.length >= 2 && info.events.length > 0,
        windows: info.windows.length,
        events: info.events.length,
        singleInstance: info.singleInstance,
      });
      app.quit();
    } catch (error) {
      log({ evt: "error", message: String(error) });
      app.exit(1);
    }
  }

  async function runShots(): Promise<void> {
    try {
      const dir = path.resolve(
        process.cwd(),
        "../../../docs/assets/images/04-lifecycle-and-windows",
      );
      await fs.mkdir(path.join(dir, "raw"), { recursive: true });
      await primary?.webContents.executeJavaScript(
        `new Promise((resolve) => {
          const started = Date.now();
          const tick = () => {
            if (typeof window.__setTab === "function") resolve(true);
            else if (Date.now() - started > 3000) resolve(false);
            else setTimeout(tick, 20);
          };
          tick();
        })`,
      );
      const shots = [
        { tab: "lifecycle", file: "04-01-lifecycle.png" },
        { tab: "windows", file: "04-02-windows.png" },
        { tab: "single", file: "04-03-single.png" },
      ];
      for (const shot of shots) {
        await primary?.webContents.executeJavaScript(
          `window.__setTab(${JSON.stringify(shot.tab)})`,
        );
        await new Promise((resolve) => setTimeout(resolve, 120));
        const image = await primary?.webContents.capturePage();
        if (!image) throw new Error("capturePage returned null");
        const png = image.toPNG();
        await fs.writeFile(path.join(dir, shot.file), png);
        await fs.writeFile(path.join(dir, "raw", shot.file), png);
        log({ evt: "shot", file: shot.file, bytes: png.byteLength });
      }
      app.quit();
    } catch (error) {
      log({ evt: "error", message: String(error) });
      app.exit(1);
    }
  }

  ipcMain.handle(CH.info, () => collectInfo());
  ipcMain.handle(CH.open, () => {
    openWindow();
    return { ok: true };
  });
  ipcMain.handle(CH.minimize, () => {
    primary?.minimize();
    return { ok: Boolean(primary) };
  });
  ipcMain.handle(CH.maximize, () => {
    if (!primary) return { ok: false };
    if (primary.isMaximized()) primary.unmaximize();
    else primary.maximize();
    return { ok: true };
  });
  ipcMain.handle(CH.close, () => {
    primary?.close();
    return { ok: Boolean(primary) };
  });

  app.on("second-instance", (_event, argv) => {
    record("second-instance", argv.slice(1).join(" "));
    focusPrimary();
  });
  app.on("activate", () => {
    record("activate");
    if (BrowserWindow.getAllWindows().length === 0) createPrimary();
  });
  app.on("before-quit", () => record("before-quit"));
  app.on("will-quit", () => record("will-quit"));
  app.on("window-all-closed", () => {
    record("window-all-closed");
    if (process.platform !== "darwin") app.quit();
  });

  function createPrimary(): void {
    primary = openWindow();
    primary.webContents.on("did-finish-load", () => {
      if (started) return;
      started = true;
      record("window-created", String(primary?.id ?? -1));
      if (isSmoke) {
        void runSmoke();
      } else if (isShots) {
        void runShots();
      }
    });
  }

  app.whenReady().then(() => {
    log({ evt: "app-ready", electron: process.versions.electron });
    record("ready");
    createPrimary();
  });
}

if (!gotLock) {
  app.quit();
} else {
  runMain();
}