示例工程 34-global-shortcuts-autostart

34-global-shortcuts-autostart/app/main/index.ts

typescript · 19 KB

import {
  app,
  BrowserWindow,
  globalShortcut,
  ipcMain,
  powerMonitor,
  powerSaveBlocker,
} from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  classifyAttempt,
  parseAccelerator,
  type AttemptVerdict,
} from "../shared/accelerator";
import {
  assertActionReq,
  assertAutostartReq,
  assertBlockerIdReq,
  assertBlockerReq,
  assertRegisterReq,
  assertResidencyReq,
  CH,
  type AutostartInfo,
  type EventRow,
  type PowerInfo,
  type RegisterRow,
  type ResidencyInfo,
  type ShortcutId,
  type ShortcutRow,
  type Snapshot,
} from "../shared/ipc";
import {
  decideBlocker,
  parseAutostartArgs,
  planAutostart,
  type BlockerKind,
} from "../shared/power-policy";

app.setName("Shortcut Energy 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(),
        `shortcut-lab-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

type ShortcutDef = {
  id: ShortcutId;
  label: string;
  accelerator: string;
  fallbacks: string[];
};

const DEFAULTS: ShortcutDef[] = [
  {
    id: "toggle-window",
    label: "显示 / 隐藏主窗口",
    accelerator: "CommandOrControl+Shift+Alt+K",
    fallbacks: ["CommandOrControl+Shift+Alt+1"],
  },
  {
    id: "quick-note",
    label: "快速记一条",
    accelerator: "CommandOrControl+Shift+Alt+J",
    fallbacks: ["CommandOrControl+Shift+Alt+2"],
  },
  {
    id: "focus-search",
    label: "唤回并聚焦搜索",
    accelerator: "CommandOrControl+Shift+Alt+L",
    fallbacks: ["CommandOrControl+Shift+Alt+3"],
  },
];

type BlockerRow = {
  id: number;
  kind: BlockerKind;
  startedAt: number;
};

let win: BrowserWindow | null = null;
let forceQuit = false;
let shortcutsReady = false;
const shortcuts: ShortcutRow[] = DEFAULTS.map((def) => ({
  id: def.id,
  label: def.label,
  accelerator: def.accelerator,
  registered: false,
  status: "spare",
  detail: "尚未注册",
}));
let attempts: RegisterRow[] = [];
let lastAttempt: RegisterRow | null = null;
let events: EventRow[] = [];
let notes: string[] = [];
const residency: ResidencyInfo = {
  enabled: true,
  hiddenCount: 0,
  showCount: 0,
  visible: true,
};
let blockers: BlockerRow[] = [];
let planOpenAtLogin = false;
let lastDecision = "尚未计算";

function logEvent(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  if (win && !win.isDestroyed()) {
    win.webContents.send("hub:action", { kind, detail, at: Date.now() });
  }
}

function note(text: string): void {
  notes = [text, ...notes].slice(0, 20);
}

function currentShortcut(id: ShortcutId): ShortcutRow | undefined {
  return shortcuts.find((row) => row.id === id);
}

function onShortcut(id: ShortcutId): void {
  const row = currentShortcut(id);
  logEvent("shortcut", `${id} · ${row?.accelerator ?? "?"}`);
  if (id === "toggle-window") {
    if (!win || win.isDestroyed()) return;
    if (win.isVisible()) {
      win.hide();
      residency.visible = false;
      residency.hiddenCount += 1;
      logEvent("residency", "快捷键隐藏窗口");
    } else {
      win.show();
      win.focus();
      residency.visible = true;
      residency.showCount += 1;
      logEvent("residency", "快捷键唤回窗口");
    }
    return;
  }
  if (!win || win.isDestroyed()) return;
  win.show();
  win.focus();
  residency.visible = true;
  residency.showCount += 1;
  if (id === "quick-note") {
    const at = new Date().toLocaleTimeString("zh-CN", { hour12: false });
    note(`${at} 来自全局快捷键 ${row?.accelerator ?? ""}`);
    logEvent("note", "已记录一条快速笔记");
  } else {
    logEvent("focus", "已请求聚焦搜索框");
  }
}

function tryRegister(
  row: ShortcutRow,
  accelerator: string,
): { ok: boolean; detail: string; verdict: AttemptVerdict } {
  const parsed = parseAccelerator(accelerator);
  if (!parsed.ok) {
    return { ok: false, detail: parsed.detail, verdict: "INVALID" };
  }
  const owner = shortcuts.find(
    (item) => item.id !== row.id && item.accelerator === parsed.accelerator,
  );
  if (owner) {
    return {
      ok: false,
      detail: `已由「${owner.label}」占用`,
      verdict: "ALREADY_OWNED",
    };
  }
  let thrown = false;
  let returned = false;
  let message = "";
  try {
    returned = globalShortcut.register(parsed.accelerator, () =>
      onShortcut(row.id),
    );
  } catch (error) {
    thrown = true;
    message = error instanceof Error ? error.message : String(error);
  }
  const verdict = classifyAttempt({
    threw: thrown,
    ownedByThisApp: false,
    registerReturned: returned,
  });
  if (verdict === "OK") {
    return { ok: true, detail: `${parsed.accelerator} 已注册`, verdict };
  }
  return {
    ok: false,
    detail: thrown
      ? message
      : "系统拒绝注册,可能已被其它应用占用(或组合受系统保留)",
    verdict,
  };
}

function registerDefaults(): void {
  if (shortcutsReady) return;
  shortcutsReady = true;
  for (const def of DEFAULTS) {
    const row = currentShortcut(def.id);
    if (!row) continue;
    let done = false;
    for (const candidate of [def.accelerator, ...def.fallbacks]) {
      if (done) break;
      const result = tryRegister(row, candidate);
      if (result.ok) {
        row.accelerator = parseAccelerator(candidate).ok
          ? (parseAccelerator(candidate) as { accelerator: string }).accelerator
          : candidate;
        row.registered = true;
        row.status = "registered";
        row.detail = "";
        done = true;
      } else {
        row.registered = false;
        row.status = result.verdict === "INVALID" ? "invalid" : "conflict";
        row.detail = result.detail;
      }
    }
    logEvent(
      "register",
      `${def.label} → ${row.accelerator} · ${row.registered ? "已注册" : row.status}`,
    );
  }
}

function attemptRegister(id: ShortcutId, accelerator: string): void {
  const row = currentShortcut(id);
  if (!row) throw new Error("BAD_ACTION");
  const existingAccelerator = row.accelerator;
  const result = tryRegister(row, accelerator);
  let finalAccelerator = accelerator;
  if (result.ok) {
    const parsed = parseAccelerator(accelerator);
    if (parsed.ok) finalAccelerator = parsed.accelerator;
    if (row.registered && existingAccelerator !== finalAccelerator) {
      globalShortcut.unregister(existingAccelerator);
      logEvent("unregister", `${existingAccelerator} 已释放`);
    }
    row.accelerator = finalAccelerator;
    row.registered = true;
    row.status = "registered";
    row.detail = "";
  } else if (row.registered) {
    row.detail = `保留原快捷键 ${existingAccelerator};本次失败:${result.detail}`;
    row.status = "registered";
  } else {
    row.detail = result.detail;
    row.status = result.verdict === "INVALID" ? "invalid" : "conflict";
    row.registered = false;
  }
  const attempt: RegisterRow = {
    at: Date.now(),
    accelerator: finalAccelerator,
    verdict: result.verdict,
    detail: result.detail,
  };
  attempts = [attempt, ...attempts].slice(0, 12);
  lastAttempt = attempt;
  logEvent("attempt", `${finalAccelerator} → ${result.verdict}`);
}

function readAutostart(): AutostartInfo {
  const settings = app.getLoginItemSettings();
  const args = parseAutostartArgs(process.argv);
  return {
    platform: process.platform,
    openAtLogin: Boolean(settings.openAtLogin),
    wasOpenedAtLogin: Boolean(settings.wasOpenedAtLogin),
    executableWillLaunchAtLogin: Boolean(settings.executableWillLaunchAtLogin),
    status: String(settings.status ?? ""),
    launchArgs: args.args,
    isAutostartLaunch: args.isAutostart,
    isHiddenLaunch: args.isHidden,
    packaged: app.isPackaged,
  };
}

function powerInfo(): PowerInfo {
  const onBattery = powerMonitor.isOnBatteryPower();
  const displayBlocked = blockers.some(
    (item) => item.kind === "prevent-display-sleep",
  );
  const jobBlocked = blockers.some(
    (item) => item.kind === "prevent-app-suspension",
  );
  const decision = decideBlocker({
    activeJobs: jobBlocked ? 1 : 0,
    mediaPlaying: displayBlocked,
    userWantsAwake: false,
    onBattery,
  });
  lastDecision = `${decision.kind} · ${decision.reason}`;
  return {
    idleSeconds: powerMonitor.getSystemIdleTime(),
    onBattery,
    blockers: blockers.map((item) => ({ ...item })),
    lastDecision,
  };
}

function snapshot(): Snapshot {
  const autostart = readAutostart();
  const plan = planAutostart({
    currentOpenAtLogin: autostart.openAtLogin,
    desiredOpenAtLogin: planOpenAtLogin,
    packaged: autostart.packaged,
    platform: autostart.platform,
  });
  return {
    platform: process.platform,
    shortcuts: shortcuts.map((row) => ({ ...row })),
    attempts: attempts.map((row) => ({ ...row })),
    lastAttempt: lastAttempt ? { ...lastAttempt } : null,
    events: events.map((row) => ({ ...row })),
    notes: [...notes],
    residency: { ...residency, visible: Boolean(win?.isVisible()) },
    power: powerInfo(),
    autostart,
    plan,
    planOpenAtLogin,
  };
}

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: "全局快捷键与节能工作台",
    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();
    registerDefaults();
  });
  window.webContents.once("did-finish-load", () => {
    if (!window.isDestroyed() && !window.isVisible()) window.show();
    registerDefaults();
    logEvent("ready", "主窗口已加载");
  });
  window.on("close", (event) => {
    if (forceQuit) return;
    if (residency.enabled) {
      event.preventDefault();
      window.hide();
      residency.visible = false;
      residency.hiddenCount += 1;
      logEvent("residency", "关闭被拦截:窗口隐藏,应用继续驻留");
    }
  });
  window.on("show", () => {
    residency.visible = true;
  });
  window.on("hide", () => {
    residency.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 delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

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

type SmokeResult = {
  platform: string;
  registered: number;
  accelerators: string[];
  duplicateVerdict: string;
  invalidVerdict: string;
  newVerdict: string;
  noteCount: number;
  hiddenAfterToggle: boolean;
  shownAfterToggle: boolean;
  residencyHidden: boolean;
  residencyShown: boolean;
  hiddenCount: number;
  blockerStarted: boolean;
  blockerStopped: boolean;
  autostartBefore: boolean;
  autostartAfter: boolean;
  autostartUnchanged: boolean;
  idleSeconds: number;
  onBattery: boolean;
  planAction: string;
  eventCount: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    const result = await evalRenderer<SmokeResult>(window, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.registered === 3 &&
          result.duplicateVerdict === "ALREADY_OWNED" &&
          result.invalidVerdict === "INVALID" &&
          result.newVerdict === "OK" &&
          result.noteCount >= 1 &&
          result.hiddenAfterToggle &&
          result.shownAfterToggle &&
          result.residencyHidden &&
          result.residencyShown &&
          result.hiddenCount >= 1 &&
          result.blockerStarted &&
          result.blockerStopped &&
          result.autostartUnchanged &&
          Number.isInteger(result.idleSeconds) &&
          result.idleSeconds >= 0 &&
          typeof result.onBattery === "boolean" &&
          result.planAction.length > 0 &&
          result.eventCount >= 8,
        ...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(
  window: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  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<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/34-global-shortcuts-autostart",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("shortcuts")`);
    await delay(500);
    await capture(window, dir, "34-01-shortcuts.png");
    await evalRenderer(window, `window.__prepareShots("conflict")`);
    await delay(500);
    await capture(window, dir, "34-02-conflict.png");
    await evalRenderer(window, `window.__prepareShots("energy")`);
    await delay(500);
    await capture(window, dir, "34-03-energy.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.register, (_event, raw: unknown) => {
  assertRegisterReq(raw);
  attemptRegister(raw.id, raw.accelerator);
  return snapshot();
});

ipcMain.handle(CH.trigger, (_event, raw: unknown) => {
  assertActionReq(raw);
  onShortcut(raw.id);
  return snapshot();
});

ipcMain.handle(CH.setResidency, (_event, raw: unknown) => {
  assertResidencyReq(raw);
  residency.enabled = raw.enabled;
  logEvent("residency", raw.enabled ? "已开启后台驻留" : "已关闭后台驻留");
  return snapshot();
});

ipcMain.handle(CH.closeWindow, () => {
  if (!residency.enabled) {
    logEvent("residency", "驻留已关闭,拒绝模拟关闭以免应用退出");
    return snapshot();
  }
  win?.close();
  return snapshot();
});

ipcMain.handle(CH.showWindow, () => {
  if (win && !win.isDestroyed()) {
    win.show();
    win.focus();
    residency.visible = true;
    residency.showCount += 1;
    logEvent("residency", "手动唤回窗口");
  }
  return snapshot();
});

ipcMain.handle(CH.startBlocker, (_event, raw: unknown) => {
  assertBlockerReq(raw);
  const id = powerSaveBlocker.start(raw.kind);
  if (!powerSaveBlocker.isStarted(id)) {
    throw new Error("BLOCKER_START_FAILED");
  }
  blockers = [...blockers, { id, kind: raw.kind, startedAt: Date.now() }];
  logEvent("power", `启动 ${raw.kind}(id ${id})`);
  return snapshot();
});

ipcMain.handle(CH.stopBlocker, (_event, raw: unknown) => {
  assertBlockerIdReq(raw);
  const row = blockers.find((item) => item.id === raw.id);
  if (!row) throw new Error("BLOCKER_NOT_FOUND");
  powerSaveBlocker.stop(raw.id);
  blockers = blockers.filter((item) => item.id !== raw.id);
  logEvent("power", `停止 ${row.kind}(id ${raw.id})`);
  return snapshot();
});

ipcMain.handle(CH.refresh, () => {
  logEvent("refresh", "刷新电源与登录项状态");
  return snapshot();
});

ipcMain.handle(CH.applyAutostart, (_event, raw: unknown) => {
  assertAutostartReq(raw);
  planOpenAtLogin = raw.enabled;
  if (raw.dryRun) {
    logEvent("autostart", `仅预览:目标 openAtLogin=${raw.enabled}`);
    return snapshot();
  }
  const before = app.getLoginItemSettings().openAtLogin;
  try {
    app.setLoginItemSettings({
      openAtLogin: raw.enabled,
      args: raw.enabled ? ["--autostart", "--hidden"] : [],
    });
    const after = app.getLoginItemSettings().openAtLogin;
    logEvent("autostart", `已应用:openAtLogin ${before} → ${after}`);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    logEvent("autostart", `应用失败:${message}`);
    throw new Error("AUTOSTART_APPLY_FAILED");
  }
  return snapshot();
});

ipcMain.handle(CH.quit, () => {
  forceQuit = true;
  logEvent("lifecycle", "真正退出");
  app.quit();
  return snapshot();
});

app.whenReady().then(() => {
  planOpenAtLogin = Boolean(app.getLoginItemSettings().openAtLogin);
  const window = createWindow();
  win = window;
  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("before-quit", () => {
  forceQuit = true;
});

app.on("will-quit", () => {
  globalShortcut.unregisterAll();
  for (const item of blockers) {
    powerSaveBlocker.stop(item.id);
  }
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

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