Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
perf(capture): read copied file lists in-process and keep thumbnail decodes off panel motion
Deepender25636f77616f07
diff --git a/electron/clipboard/formats.ts b/electron/clipboard/formats.tsindex 1e101c4..9571c7f 100644--- a/electron/clipboard/formats.ts+++ b/electron/clipboard/formats.ts@@ -14,10 +14,33 @@ import koffi from 'koffi'import type { ClipboardImageSource, ItemData } from '../../shared/types'let getSeqNum: (() => number) | null = null++/** Win32 calls for reading CF_HDROP in-process (see readFileDropListNative). */+interface HdropApi {+ open: (hWnd: number) => boolean+ close: () => boolean+ isAvailable: (format: number) => boolean+ getData: (format: number) => unknown+ dragQuery: (hDrop: unknown, index: number, buf: Buffer | null, cch: number) => number+}+let hdropApi: HdropApi | null = null+if (process.platform === 'win32') {try {const user32 = koffi.load('user32.dll')getSeqNum = user32.func('uint32 GetClipboardSequenceNumber()')+ try {+ const shell32 = koffi.load('shell32.dll')+ hdropApi = {+ open: user32.func('bool OpenClipboard(uintptr_t hWndNewOwner)'),+ close: user32.func('bool CloseClipboard()'),+ isAvailable: user32.func('bool IsClipboardFormatAvailable(uint32 format)'),+ getData: user32.func('void *GetClipboardData(uint32 uFormat)'),+ dragQuery: shell32.func('uint32 DragQueryFileW(void *hDrop, uint32 iFile, _Out_ uint16_t *lpszFile, uint32 cch)')+ }+ } catch (err) {+ console.error('[formats] Failed to load CF_HDROP APIs; file lists will use PowerShell:', err)+ }} catch (err) {console.error('[formats] Failed to load GetClipboardSequenceNumber from user32.dll:', err)}@@ -42,23 +65,69 @@ const execFileAsync = promisify(execFile)/** Windows clipboard format name for a copied-file list. */export const CF_FILE_LIST = 'FileNameW'+const CF_HDROP = 15+/**- * Async version: reads the full list of copied file paths via PowerShell- * GetFileDropList(), which is the only reliable way to retrieve ALL selected- * files from a multi-file Explorer copy (CF_HDROP / FileNameW only carries- * the first file as a legacy single-path fallback).+ * Read every path of CF_HDROP in-process — the same data PowerShell's+ * GetFileDropList() returns, without spawning powershell.exe (measured+ * 250–300ms per copy, which is what made copied files appear late).+ * Returns null whenever the native read cannot answer, so the caller falls+ * back to the PowerShell path unchanged.+ */+async function readFileDropListNative(): Promise<string[] | null> {+ const api = hdropApi+ if (!api) return null+ for (let attempt = 0; attempt < 3; attempt++) {+ if (api.open(0)) {+ try {+ if (!api.isAvailable(CF_HDROP)) return null+ const hDrop = api.getData(CF_HDROP)+ if (!hDrop) return null+ const count = api.dragQuery(hDrop, 0xffffffff, null, 0)+ const paths: string[] = []+ for (let i = 0; i < count; i++) {+ const len = api.dragQuery(hDrop, i, null, 0)+ if (!len) continue+ const out = Buffer.alloc((len + 1) * 2)+ if (!api.dragQuery(hDrop, i, out, len + 1)) continue+ paths.push(out.toString('utf16le', 0, len * 2))+ }+ return paths.length ? paths : null+ } catch {+ return null+ } finally {+ try { api.close() } catch { /* ignore */ }+ }+ }+ // Another process holds the clipboard open (often Explorer finishing a+ // delayed render). Back off briefly without blocking the main thread.+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+ return null+}++/**+ * Async version: reads the full list of copied file paths. CF_HDROP is read+ * in-process first; PowerShell GetFileDropList() remains the fallback. Both+ * return ALL selected files from a multi-file Explorer copy (FileNameW only+ * carries the first file as a legacy single-path fallback).*- * Falls back to parsing the FileNameW UTF-16LE buffer directly if PowerShell- * is unavailable or times out.+ * Falls back to parsing the FileNameW UTF-16LE buffer directly if both are+ * unavailable or PowerShell times out.*/async function readFileListAsync(): Promise<string[] | null> {try {// First, confirm there is actually a file list on the clipboard before- // spawning a process. FileNameW being present is sufficient signal.+ // reading it. FileNameW being present is sufficient signal.const buf = clipboard.readBuffer(CF_FILE_LIST)if (!buf || buf.length < 4) return nullif (process.platform === 'win32') {+ const native = await readFileDropListNative()+ if (native) {+ const paths = filterValidPaths(native)+ if (paths.length > 0) return paths+ }try {const psPath = getSystemPowerShellPath()// Await the result so we actually get all paths — the previousdiff --git a/electron/main/index.ts b/electron/main/index.tsindex d00d845..e448b21 100644--- a/electron/main/index.ts+++ b/electron/main/index.ts@@ -26,7 +26,7 @@ import { extname, join, normalize } from 'node:path'import { existsSync, createReadStream } from 'node:fs'import { createHash } from 'node:crypto'import { resolveStoredImage, resolveEmojiAsset, resolveIconAsset, emojiAssetDir } from './imageProtocol'-import { getThumbnailPayload, thumbnailCacheControl } from './thumbnailCache'+import { getThumbnailPayloadScheduled, thumbnailCacheControl } from './thumbnailCache'// Edge-Drop renders a small, mostly static transparent panel. Chromium's GPU// process costs substantially more memory (~150–250 MB) than the iGPU compositing@@ -215,7 +215,7 @@ function registerImageProtocol(): void {: resolveStoredImage(PATHS.imagesDir(), rawTarget)?.filePathif (!filePath || !existsSync(filePath)) return new Response('Not found', { status: 404 })- return createThumbnailResponse(filePath, !isFileThumb, request)+ return await createThumbnailResponse(filePath, !isFileThumb, request)}// Support streaming full-resolution local image files: edgelocal://file/<encodedPath>@@ -273,9 +273,10 @@ function registerImageProtocol(): void {* Serve a bounded thumbnail with proper HTTP caching: long immutable freshness* for content-addressed captures, short freshness + ETag/304 for external* files. Payloads come from the LRU thumbnail engine so repeated requests do- * zero decode work in the main process.+ * zero decode work in the main process; misses decode via its motion-aware+ * queue so they never land inside a panel transition.*/-function createThumbnailResponse(filePath: string, isStoredCapture: boolean, request?: Request): Response {+async function createThumbnailResponse(filePath: string, isStoredCapture: boolean, request?: Request): Promise<Response> {const ext = extname(filePath).toLowerCase()// SVG files are vector XML documents; stream them directly with correct MIME type// rather than failing inside nativeImage.createFromPath (which only supports raster bitmaps).@@ -291,7 +292,7 @@ function createThumbnailResponse(filePath: string, isStoredCapture: boolean, req})}- const payload = getThumbnailPayload(filePath)+ const payload = await getThumbnailPayloadScheduled(filePath)if (!payload) return new Response('Unsupported image', { status: 415 })const headers = new Headers({diff --git a/electron/main/thumbnailCache.ts b/electron/main/thumbnailCache.tsindex 2db94e2..80d0c99 100644--- a/electron/main/thumbnailCache.ts+++ b/electron/main/thumbnailCache.ts@@ -78,11 +78,15 @@ function readFacts(filePath: string): FileFacts | null {* Produce (or fetch from LRU) the encoded 240 px PNG for a raster image.* Returns null when the source cannot be read or decoded.*/+function cacheKey(filePath: string, facts: FileFacts): string {+ return `${filePath}|${facts.mtimeMs}:${facts.size}`+}+export function getThumbnailPayload(filePath: string): ThumbnailPayload | null {const facts = readFacts(filePath)if (!facts) return null- const key = `${filePath}|${facts.mtimeMs}:${facts.size}`+ const key = cacheKey(filePath, facts)const cached = lruGet(key)if (cached) return cached@@ -116,6 +120,80 @@ export function getThumbnailPayload(filePath: string): ThumbnailPayload | null {}}+/* ------------------------------------------------------------------ */+/* Motion-aware scheduling */+/* ------------------------------------------------------------------ */+//+// A decode blocks the main thread for 40–125ms per photo (measured), and+// with a transparent window on software compositing every presented frame+// passes through the main thread — a decode during the open/close/flyout+// motion freezes those frames for its whole duration. Cache misses are+// therefore queued, decoded one per macrotask so frames and IPC get through+// in between, and held while UI motion is in progress. Hits stay immediate.++/** How long a motion notice holds decodes (open/close/flyout run ≤ 320ms). */+const MOTION_QUIET_MS = 450++let motionQuietUntil = 0+const inflight = new Map<string, Promise<ThumbnailPayload | null>>()+const queue: Array<() => void> = []+let pumping = false++/** Main process signals that a panel/flyout transition is starting now. */+export function noteUiMotion(durationMs = MOTION_QUIET_MS): void {+ motionQuietUntil = Math.max(motionQuietUntil, Date.now() + durationMs)+}++function pump(): void {+ if (pumping) return+ pumping = true+ const step = (): void => {+ const wait = motionQuietUntil - Date.now()+ if (wait > 0) {+ setTimeout(step, wait)+ return+ }+ const job = queue.shift()+ if (!job) {+ pumping = false+ return+ }+ job()+ setTimeout(step, 0)+ }+ setTimeout(step, 0)+}++/**+ * Same result as getThumbnailPayload, but cache misses are decoded through+ * the motion-aware queue instead of synchronously inside the request.+ */+export function getThumbnailPayloadScheduled(filePath: string): Promise<ThumbnailPayload | null> {+ const facts = readFacts(filePath)+ if (!facts) return Promise.resolve(null)++ const key = cacheKey(filePath, facts)+ const cached = lruGet(key)+ if (cached) return Promise.resolve(cached)++ const pending = inflight.get(key)+ if (pending) return pending++ const job = new Promise<ThumbnailPayload | null>((resolve) => {+ queue.push(() => {+ try {+ resolve(getThumbnailPayload(filePath))+ } catch {+ resolve(null)+ }+ })+ pump()+ })+ inflight.set(key, job)+ void job.then(() => inflight.delete(key))+ return job+}+/*** Cache policy for a thumbnail response.* - Stored captures (`edgelocal://thumb/<imageId>`) are content-addressed:diff --git a/electron/main/window.ts b/electron/main/window.tsindex 08c5b4d..bc2cc60 100644--- a/electron/main/window.ts+++ b/electron/main/window.ts@@ -24,6 +24,7 @@ import { WorkAreaCache } from './workAreaCache'import { probeSeamAware, isNearProximity, type SeamTickState } from './stickProbe'import { loadSettings, saveSettings } from '../store/settings'import { isFullscreenAppActive, registerFullscreenActiveListener } from './fullscreen'+import { noteUiMotion } from './thumbnailCache'type RegisterWindowMessageFn = (lpString: string) => numbertype SetWindowLongPtrFn = (hWnd: number | bigint, nIndex: number, dwNewLong: number | bigint) => number | bigint@@ -342,6 +343,8 @@ let gcTimer: ReturnType<typeof setTimeout> | null = nullexport function setInteractive(value: boolean): void {if (!mainWindow || value === interactive) returninteractive = value+ // Open starts here; hold main-thread thumbnail decodes off its frames.+ noteUiMotion()if (value) {// Panel is open: disable click-through so user can interact.// Remember who is in front BEFORE any search typing can steal focus.@@ -379,6 +382,9 @@ export function setInteractive(value: boolean): void {}export function setPreviewMode(active: boolean): void {+ // Before the guard: the renderer sends setPreviewMode(false) at the start+ // of every close (setOpen(false)), so this is also the close-motion signal.+ noteUiMotion()if (previewActive === active) returnpreviewActive = activerepositionWindow()diff --git a/tests/fileDropNative.test.ts b/tests/fileDropNative.test.tsnew file mode 100644index 0000000..ee576c8--- /dev/null+++ b/tests/fileDropNative.test.ts@@ -0,0 +1,128 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdirSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'++/**+ * Explorer file copies: the CF_HDROP list is read in-process; PowerShell is+ * only the fallback. Win32 calls are simulated through a koffi mock.+ */+const win = vi.hoisted(() => ({+ paths: [] as string[],+ hasHdrop: true,+ openFails: 0,+ opens: 0,+ closes: 0,+ psStdout: '',+ psCalls: 0+}))++vi.mock('koffi', () => {+ const impl: Record<string, (...args: any[]) => unknown> = {+ GetClipboardSequenceNumber: () => 1,+ OpenClipboard: () => {+ win.opens+++ if (win.openFails > 0) {+ win.openFails--+ return false+ }+ return true+ },+ CloseClipboard: () => {+ win.closes+++ return true+ },+ IsClipboardFormatAvailable: (format: number) => format === 15 && win.hasHdrop,+ GetClipboardData: () => (win.hasHdrop ? { hdrop: true } : null),+ DragQueryFileW: (_h: unknown, index: number, buf: Buffer | null, cch: number) => {+ if (index === 0xffffffff) return win.paths.length+ const p = win.paths[index]+ if (!buf) return p.length+ buf.write(p.slice(0, cch - 1), 0, 'utf16le')+ return Math.min(p.length, cch - 1)+ }+ }+ const lib = { func: (sig: string) => impl[sig.match(/(\w+)\(/)![1]] }+ return { default: { load: () => lib } }+})++vi.mock('node:child_process', () => ({+ execFile: (_file: string, _args: string[], _opts: unknown, cb: (err: unknown, out: unknown) => void) => {+ win.psCalls+++ cb(null, { stdout: win.psStdout, stderr: '' })+ }+}))++vi.mock('electron', () => ({+ clipboard: {+ availableFormats: () => ['FileNameW', 'CF_HDROP'],+ readBuffer: (format: string) =>+ format === 'FileNameW' && win.paths.length ? Buffer.from(`${win.paths[0]}\0`, 'utf16le') : Buffer.alloc(0),+ readText: () => '',+ readHTML: () => '',+ readImage: () => ({ isEmpty: () => true, getSize: () => ({ width: 0, height: 0 }) })+ },+ app: { isPackaged: false, getAppPath: () => 'C:\\mock', getPath: () => 'C:\\mock' }+}))++import { readClipboard } from '../electron/clipboard/formats'++describe.skipIf(process.platform !== 'win32')('Explorer file copy — native CF_HDROP read', () => {+ let dir: string+ let files: string[]++ beforeEach(() => {+ dir = join(tmpdir(), `ed-hdrop-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ mkdirSync(dir, { recursive: true })+ files = ['a b.jpg', 'Ünïcödé 报告.pdf', 'c.docx', 'd.png', 'e.zip'].map((n) => {+ const p = join(dir, n)+ writeFileSync(p, 'x')+ return p+ })+ Object.assign(win, { paths: files, hasHdrop: true, openFails: 0, opens: 0, closes: 0, psStdout: '', psCalls: 0 })+ })++ afterEach(() => {+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }+ })++ it('returns every selected file without spawning PowerShell', async () => {+ const item = await readClipboard()+ expect(item).toEqual({ kind: 'files', paths: files })+ expect(win.psCalls).toBe(0)+ expect(win.closes).toBe(win.opens)+ })++ it('retries when another process holds the clipboard, still without PowerShell', async () => {+ win.openFails = 2+ const item = await readClipboard()+ expect(item).toEqual({ kind: 'files', paths: files })+ expect(win.psCalls).toBe(0)+ expect(win.closes).toBe(1)+ })++ it('falls back to PowerShell when the clipboard stays locked', async () => {+ win.openFails = 99+ win.psStdout = files.join('\r\n')+ const item = await readClipboard()+ expect(item).toEqual({ kind: 'files', paths: files })+ expect(win.psCalls).toBe(1)+ expect(win.closes).toBe(0)+ })++ it('falls back to PowerShell when CF_HDROP is absent', async () => {+ win.hasHdrop = false+ win.psStdout = files.join('\r\n')+ const item = await readClipboard()+ expect(item).toEqual({ kind: 'files', paths: files })+ expect(win.psCalls).toBe(1)+ expect(win.closes).toBe(win.opens)+ })++ it('drops paths that no longer exist, exactly like the PowerShell path', async () => {+ win.paths = [...files, join(dir, 'gone.txt')]+ const item = await readClipboard()+ expect(item).toEqual({ kind: 'files', paths: files })+ expect(win.psCalls).toBe(0)+ })+})diff --git a/tests/thumbnailCache.test.ts b/tests/thumbnailCache.test.tsindex b1c56b2..e794e17 100644--- a/tests/thumbnailCache.test.ts+++ b/tests/thumbnailCache.test.ts@@ -22,10 +22,81 @@ vi.mock('electron', () => ({import {clearThumbnailCache,getThumbnailPayload,+ getThumbnailPayloadScheduled,+ noteUiMotion,thumbnailCacheControl,thumbnailCacheSize} from '../electron/main/thumbnailCache'+describe('thumbnailCache — motion-aware scheduling', () => {+ let dir: string++ beforeEach(() => {+ vi.useFakeTimers()+ dir = join(tmpdir(), `ed-thumbsched-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ mkdirSync(dir, { recursive: true })+ clearThumbnailCache()+ calls.createFromPath = 0+ })++ afterEach(async () => {+ // Let the queue pump finish so it does not stay parked on a fake timer.+ await vi.runAllTimersAsync()+ vi.useRealTimers()+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }+ })++ function makeFile(name: string): string {+ const p = join(dir, name)+ writeFileSync(p, Buffer.from('fake-image-bytes'))+ return p+ }++ it('never decodes inside the request: one decode per macrotask', async () => {+ const a = getThumbnailPayloadScheduled(makeFile('a.jpg'))+ const b = getThumbnailPayloadScheduled(makeFile('b.jpg'))+ expect(calls.createFromPath).toBe(0)+ await vi.advanceTimersToNextTimerAsync()+ expect(calls.createFromPath).toBe(1)+ await vi.advanceTimersToNextTimerAsync()+ expect(calls.createFromPath).toBe(2)+ expect((await a)!.contentType).toBe('image/png')+ expect((await b)!.contentType).toBe('image/png')+ })++ it('holds decodes while UI motion is in progress, then runs them', async () => {+ noteUiMotion(450)+ const p = getThumbnailPayloadScheduled(makeFile('a.jpg'))+ await vi.advanceTimersByTimeAsync(400)+ expect(calls.createFromPath).toBe(0)+ await vi.advanceTimersByTimeAsync(100)+ expect(calls.createFromPath).toBe(1)+ expect(await p).not.toBeNull()+ })++ it('returns cached thumbnails immediately, even during motion', async () => {+ const f = makeFile('a.jpg')+ const first = getThumbnailPayload(f)+ noteUiMotion(450)+ expect(await getThumbnailPayloadScheduled(f)).toBe(first)+ expect(calls.createFromPath).toBe(1)+ })++ it('shares one decode between concurrent requests for the same file', async () => {+ const f = makeFile('a.jpg')+ const a = getThumbnailPayloadScheduled(f)+ const b = getThumbnailPayloadScheduled(f)+ await vi.runAllTimersAsync()+ expect(await a).toBe(await b)+ expect(calls.createFromPath).toBe(1)+ })++ it('resolves null for a missing file without queueing', async () => {+ expect(await getThumbnailPayloadScheduled(join(dir, 'missing.jpg'))).toBeNull()+ expect(calls.createFromPath).toBe(0)+ })+})+describe('thumbnailCache — bounded LRU + validators', () => {let dir: string