import { app, BrowserWindow, clipboard, dialog, ipcMain } from "electron"; import electron from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { assertHtmlReq, assertPathReq, assertTextReq, CH, type ClipboardInfo, type FilePreview, type RecentEntry, type Samples, type Snapshot, } from "../shared/ipc"; app.setName("Clipboard DnD 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(), `clipboard-lab-${isSmoke ? "smoke" : "shots"}-${process.pid}`, ) : ""; if (tempData) app.setPath("userData", tempData); const MAX_SIZE = 1024 * 1024; const ALLOWED = [".md", ".txt", ".json", ".log"]; const MAX_CONTENT = 20_000; let win: BrowserWindow | null = null; let clipboardInfo: ClipboardInfo = { formats: [], text: "", html: "", error: "", }; let lastFile: FilePreview | null = null; let recent: RecentEntry[] = []; let samples: Samples = { notes: "", config: "", big: "", wrong: "", missing: "", }; function ensureSamples(): Samples { const dir = path.join(app.getPath("userData"), "samples"); fsSync.mkdirSync(dir, { recursive: true }); const notes = path.join(dir, "notes.md"); const config = path.join(dir, "config.json"); const big = path.join(dir, "big.txt"); const wrong = path.join(dir, "notes.png"); const missing = path.join(dir, "missing.md"); fsSync.writeFileSync( notes, "# 剪贴板与拖放\n\n这是通过文件读取打开的示例 Markdown。\n", "utf8", ); fsSync.writeFileSync( config, `${JSON.stringify({ theme: "light", recent: 10 }, null, 2)}\n`, "utf8", ); fsSync.writeFileSync(big, "a".repeat(MAX_SIZE + 1024), "utf8"); return { notes, config, big, wrong, missing }; } async function refreshClipboard(): Promise { try { const items = await clipboard.read(); const formats = [...new Set(items.flatMap((item) => item.types))]; const text = (await clipboard.readText()).slice(0, 100_000); let html = ""; const htmlItem = items.find((item) => item.types.includes("text/html")); if (htmlItem) { const value = await htmlItem.getType("text/html"); if (value instanceof Blob) { html = (await value.text()).slice(0, 100_000); } } clipboardInfo = { formats, text, html, error: "" }; } catch { clipboardInfo = { ...clipboardInfo, error: "CLIPBOARD_READ_FAILED" }; } } function addRecent(entry: RecentEntry): void { recent = [entry, ...recent.filter((item) => item.path !== entry.path)].slice( 0, 10, ); } function filePreview(filePath: string, error = ""): FilePreview { return { ok: false, path: filePath, name: path.basename(filePath), ext: path.extname(filePath).toLowerCase(), size: 0, content: "", error, }; } function readPath(filePath: string): FilePreview { const ext = path.extname(filePath).toLowerCase(); const name = path.basename(filePath); if (!ALLOWED.includes(ext)) { const preview = filePreview(filePath, "BAD_EXTENSION"); lastFile = preview; return preview; } let size = 0; let exists = true; try { const stat = fsSync.statSync(filePath); size = stat.size; if (!stat.isFile()) throw new Error("NOT_FILE"); if (size > MAX_SIZE) throw new Error("TOO_LARGE"); const text = fsSync.readFileSync(filePath, "utf8"); const preview: FilePreview = { ok: true, path: filePath, name, ext, size, content: text.slice(0, MAX_CONTENT), error: "", }; lastFile = preview; addRecent({ path: filePath, name, ext, size, exists: true, at: Date.now(), error: "", }); return preview; } catch (error) { const code = error instanceof Error && error.message === "TOO_LARGE" ? "TOO_LARGE" : error instanceof Error && error.message === "NOT_FILE" ? "NOT_FILE" : "READ_FAILED"; if (code === "READ_FAILED") exists = false; const preview = filePreview(filePath, code); preview.size = size; lastFile = preview; addRecent({ path: filePath, name, ext, size, exists, at: Date.now(), error: code, }); return preview; } } function snapshot(): Snapshot { return { platform: process.platform, clipboard: { ...clipboardInfo }, lastFile, recent: [...recent], samples, }; } 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()); window.webContents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); }); 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 { 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; clipboardText: string; formats: string[]; formatsHasHtml: boolean; notesOk: boolean; notesContent: string; missingError: string; wrongError: string; bigError: string; refreshedMissing: boolean; recentBeforeClear: number; cleared: boolean; samples: Samples; }; async function runSmoke(window: BrowserWindow): Promise { try { await waitForRenderer(window); await delay(500); await waitForRenderer(window); const result = await evalRenderer(window, "window.__smoke()"); process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: result.clipboardText.includes("剪贴板测试") && result.formats.length > 0 && result.notesOk && result.notesContent.includes("示例 Markdown") && result.missingError === "READ_FAILED" && result.wrongError === "BAD_EXTENSION" && result.bigError === "TOO_LARGE" && result.refreshedMissing && result.recentBeforeClear >= 3 && result.cleared && fsSync.existsSync(result.samples.notes) && fsSync.existsSync(result.samples.config) && fsSync.existsSync(result.samples.big) && !fsSync.existsSync(result.samples.missing), ...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 { 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/33-clipboard-dnd-fs", ); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(500); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("clipboard")`); await delay(400); await capture(window, dir, "33-01-clipboard.png"); await evalRenderer(window, `window.__prepareShots("file")`); await delay(400); await capture(window, dir, "33-02-drop-file.png"); await evalRenderer(window, `window.__prepareShots("missing")`); await delay(400); await capture(window, dir, "33-03-recent-missing.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.readClipboard, async () => { await refreshClipboard(); return snapshot(); }); ipcMain.handle(CH.writeText, async (_event, raw: unknown) => { try { assertTextReq(raw); await clipboard.writeText(raw.text); await refreshClipboard(); return snapshot(); } catch { throw new Error("CLIPBOARD_WRITE_TEXT_FAILED"); } }); ipcMain.handle(CH.writeHtml, async (_event, raw: unknown) => { try { assertHtmlReq(raw); const plain = raw.html.replace(/<[^>]*>/g, ""); const item = new electron.ClipboardItem({ "text/plain": plain, "text/html": raw.html, }); await clipboard.write([item]); await refreshClipboard(); return snapshot(); } catch { throw new Error("CLIPBOARD_WRITE_HTML_FAILED"); } }); ipcMain.handle(CH.readPath, (_event, raw: unknown) => { try { assertPathReq(raw); readPath(raw.path); return snapshot(); } catch { throw new Error("FS_READ_PATH_FAILED"); } }); ipcMain.handle(CH.pickFile, async () => { const result = await dialog.showOpenDialog({ properties: ["openFile"], filters: [{ name: "文本文件", extensions: ["md", "txt", "json", "log"] }], }); const chosen = result.filePaths[0]; if (!result.canceled && chosen) readPath(chosen); return snapshot(); }); ipcMain.handle(CH.refreshRecent, () => { recent = recent.map((entry) => ({ ...entry, exists: fsSync.existsSync(entry.path), error: fsSync.existsSync(entry.path) ? entry.error : "READ_FAILED", })); return snapshot(); }); ipcMain.handle(CH.clearRecent, () => { recent = []; return snapshot(); }); app.whenReady().then(() => { samples = ensureSamples(); void refreshClipboard(); const window = createWindow(); 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 (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (!isSmoke && !isShots && process.platform !== "darwin") app.quit(); });