Skip to content

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.

fix(clipboard, drag): support Windows Snipping Tool window mode & native screenshot naming

Deepender25ecac08b5f5cb
diff --git a/electron/clipboard/ClipboardWatcher.ts b/electron/clipboard/ClipboardWatcher.ts
index f99d051..f4fb46e 100644
--- a/electron/clipboard/ClipboardWatcher.ts
+++ b/electron/clipboard/ClipboardWatcher.ts
@@ -42,7 +42,10 @@ export class ClipboardWatcher {
this.timer = setInterval(() => {
if (this.paused) return
const sig = clipboardSignature()
- if (sig === this.lastSig) return
+ if (getContentSignature(sig) === getContentSignature(this.lastSig)) {
+ this.lastSig = sig
+ return
+ }
// We detected a change. Wait a short moment to ensure it's not a transient
// injection by a dictation app or macro that quickly restores the clipboard.
diff --git a/electron/clipboard/formats.ts b/electron/clipboard/formats.ts
index fce2062..fcdaae4 100644
--- a/electron/clipboard/formats.ts
+++ b/electron/clipboard/formats.ts
@@ -226,40 +226,38 @@ export async function readClipboard(): Promise<ItemData | null> {
return null
}
- const formats = clipboard.availableFormats()
-
// Files first — a file copy also places text on the clipboard, which we ignore.
const files = await readFileListAsync()
if (files && files.length) return { kind: 'files', paths: files }
- // Text vs Image priority heuristic based on available formats.
- // When copying from Office apps, both rich text and images are placed on the clipboard.
- // When copying an image from a browser, both image and a small text fallback are placed.
- const hasImage = formats.includes('image/png') || formats.includes('image/jpeg')
-
+ const img = clipboard.readImage()
+ const hasImage = !img.isEmpty()
const rawText = clipboard.readText().trim()
-
- // Determine primary intent based on formatting metadata
- let isTextIntent = false
- if (rawText) {
- if (!hasImage) {
- // If there is no image format at all, any text is definitely text.
- isTextIntent = true
- } else {
- // Both text and image exist on the clipboard (common in Office, Chrome, IDEs).
- // If the text is just a URL or a bare <img> tag, it's a browser fallback for a copied image.
- const isUrl = URL_RE.test(rawText) && rawText.length < 500
- const isImgTag = /^<img\b[^>]*>$/i.test(rawText)
- if (!isUrl && !isImgTag) {
- // Any other text (short words, code snippets, paragraphs) is genuinely copied text!
- isTextIntent = true
+ const rawHtml = clipboard.readHTML().trim()
+
+ // If an image is present on the clipboard (e.g. Snipping Tool, Screenshot, browser copy image)
+ if (hasImage) {
+ const hasRichHtmlDoc = rawHtml.includes('<html') || rawHtml.includes('<body') || rawHtml.includes('<table') || (rawHtml.includes('<p>') && rawText.length > 300)
+ const isSingleUrl = URL_RE.test(rawText) && rawText.length < 500
+ const isImgTag = /^<img\b[^>]*>$/i.test(rawText)
+
+ // Snipping Tool (Window mode, Freeform, Rectangular) or browser images:
+ // When text is absent, is a URL, is a single-line window title, or is an image tag without a rich document:
+ if (!rawText || isSingleUrl || isImgTag || !hasRichHtmlDoc) {
+ const size = img.getSize()
+ return {
+ kind: 'image',
+ imageId: '',
+ width: size.width,
+ height: size.height,
+ bytes: 0 // placeholder — ClipboardWatcher overwrites this with the actual PNG buffer length
}
}
}
- if (isTextIntent) {
+ // Text intent (Notepad, Word, VS Code text copy, rich HTML copy)
+ if (rawText) {
let html: string | undefined
- const rawHtml = clipboard.readHTML().trim()
if (rawHtml && rawHtml !== rawText) html = rawHtml
const isUrl = URL_RE.test(rawText)
@@ -268,31 +266,18 @@ export async function readClipboard(): Promise<ItemData | null> {
return { kind: 'text', text: rawText, html, isUrl, isColor }
}
- // If it wasn't determined to be text intent, but we have an image, prioritize the image.
- const img = clipboard.readImage()
- if (!img.isEmpty()) {
+ // Fallback to image if no text
+ if (hasImage) {
const size = img.getSize()
return {
kind: 'image',
imageId: '',
width: size.width,
height: size.height,
- bytes: 0 // placeholder — ClipboardWatcher overwrites this with the actual PNG buffer length
+ bytes: 0
}
}
- // Fallback to text if it's the only thing left
- if (rawText) {
- let html: string | undefined
- const rawHtml = clipboard.readHTML().trim()
- if (rawHtml && rawHtml !== rawText) html = rawHtml
-
- const isUrl = URL_RE.test(rawText)
- const isColor = COLOR_HEX_RE.test(rawText)
-
- return { kind: 'text', text: rawText, html, isUrl, isColor }
- }
-
return null
}
@@ -302,8 +287,8 @@ export async function readClipboard(): Promise<ItemData | null> {
*
* Strategy:
* - Files → the list of paths (totally stable, always unique per copy)
- * - Text → the text content itself
* - Images → dimensions + a sampled FNV-1a hash of raw pixel bytes
+ * - Text → the text content itself
*
* For images we use `nativeImage.toBitmap()` (raw BGRA, no codec) and walk
* ~400 evenly-spaced bytes through it. This is:
@@ -311,11 +296,6 @@ export async function readClipboard(): Promise<ItemData | null> {
* - Stable: same clipboard content → same pixels → same hash on every poll
* - Unique: different images with the same resolution produce different pixel
* values in practice, so collisions are astronomically unlikely
- *
- * The old approach used toPNG().length which was (a) expensive — re-encodes the
- * whole image on every poll tick — and (b) non-unique: two different 1920×1080
- * screenshots of similar complexity can produce the same byte count, causing the
- * second to be silently ignored as "no change".
*/
export function clipboardSignature(): string {
const seq = getClipboardSequenceNumber()
@@ -332,27 +312,50 @@ export function clipboardSignature(): string {
return `${seqPrefix}files:${files.join('\n')}`
}
+ const img = clipboard.readImage()
+ const hasImage = !img.isEmpty()
+ const rawText = clipboard.readText().trim()
+
+ // Images: if an image is present and text is not a rich document selection,
+ // prioritize image fingerprinting so Snipping Tool window titles don't shadow the screenshot.
+ if (hasImage) {
+ const rawHtml = clipboard.readHTML().trim()
+ const hasRichHtmlDoc = rawHtml.includes('<html') || rawHtml.includes('<body') || rawHtml.includes('<table') || (rawHtml.includes('<p>') && rawText.length > 300)
+ const isSingleUrl = isUrlText(rawText)
+ const isBareImgTag = /^<img\b[^>]*>$/i.test(rawText)
+ const isLikelyScreenshotOrImage = !rawText || isSingleUrl || isBareImgTag || !hasRichHtmlDoc
+
+ if (isLikelyScreenshotOrImage) {
+ const size = img.getSize()
+ const bitmap = img.toBitmap() // raw BGRA — no encoding, just a memory copy
+
+ // FNV-1a over ~400 evenly-spaced bytes.
+ const step = Math.max(1, Math.floor(bitmap.length / 400))
+ let hash = 0x811c9dc5 // FNV offset basis
+ for (let i = 0; i < bitmap.length; i += step) {
+ hash ^= bitmap[i]
+ hash = Math.imul(hash, 0x01000193) >>> 0 // FNV prime, keep as uint32
+ }
+
+ return `${seqPrefix}image:${size.width}x${size.height}:${hash.toString(36)}`
+ }
+ }
+
// Text — the content itself is the fingerprint.
- const text = clipboard.readText().trim()
- if (text) {
- return `${seqPrefix}text:${text}`
+ if (rawText) {
+ return `${seqPrefix}text:${rawText}`
}
- // Images: sample raw pixel bytes through FNV-1a for a fast, stable fingerprint.
- const img = clipboard.readImage()
- if (!img.isEmpty()) {
+ // Fallback to image if no text
+ if (hasImage) {
const size = img.getSize()
- const bitmap = img.toBitmap() // raw BGRA — no encoding, just a memory copy
-
- // FNV-1a over ~400 evenly-spaced bytes.
- // Step ensures we sample the full image regardless of resolution.
+ const bitmap = img.toBitmap()
const step = Math.max(1, Math.floor(bitmap.length / 400))
- let hash = 0x811c9dc5 // FNV offset basis
+ let hash = 0x811c9dc5
for (let i = 0; i < bitmap.length; i += step) {
hash ^= bitmap[i]
- hash = Math.imul(hash, 0x01000193) >>> 0 // FNV prime, keep as uint32
+ hash = Math.imul(hash, 0x01000193) >>> 0
}
-
return `${seqPrefix}image:${size.width}x${size.height}:${hash.toString(36)}`
}
diff --git a/electron/main/drag.ts b/electron/main/drag.ts
index a523602..d54d9e7 100644
--- a/electron/main/drag.ts
+++ b/electron/main/drag.ts
@@ -23,32 +23,50 @@ import { getStore } from './state'
import { getFileKind } from '../../src/lib/fileType'
/**
- * Resolve a DragRequest into concrete ItemData.
+ * Formats a clean, Windows OS-compliant human-readable screenshot filename
+ * based on the capture timestamp (e.g. "Screenshot 2026-08-15 22.30.45.png").
+ */
+export function formatScreenshotFilename(capturedAt?: number, ext = 'png', indexSuffix?: number): string {
+ const d = capturedAt ? new Date(capturedAt) : new Date()
+ const year = d.getFullYear()
+ const month = String(d.getMonth() + 1).padStart(2, '0')
+ const day = String(d.getDate()).padStart(2, '0')
+ const hours = String(d.getHours()).padStart(2, '0')
+ const minutes = String(d.getMinutes()).padStart(2, '0')
+ const seconds = String(d.getSeconds()).padStart(2, '0')
+
+ const cleanExt = ext.replace(/^\./, '') || 'png'
+ const suffix = typeof indexSuffix === 'number' && indexSuffix > 1 ? ` (${indexSuffix})` : ''
+ return `Screenshot ${year}-${month}-${day} ${hours}.${minutes}.${seconds}${suffix}.${cleanExt}`
+}
+
+/**
+ * Resolve a DragRequest into concrete ItemData along with capture timestamp.
*
* If `paths` is provided (dragging one file out of an expanded bundle), synthesize
* a singleton `files` item. Otherwise look up the full item by id.
*/
-export function resolveDragData(req: DragRequest): ItemData | null {
+export function resolveDragData(req: DragRequest): { data: ItemData; capturedAt?: number } | null {
if (req.paths && req.paths.length > 0) {
prefetchFileIcons(req.paths)
- return { kind: 'files', paths: req.paths }
+ return { data: { kind: 'files', paths: req.paths } }
}
const item = getStore().get(req.id)
if (!item) return null
-
+
if (item.data.kind === 'files') {
prefetchFileIcons(item.data.paths)
}
-
+
if (req.imageId && item.data.kind === 'image-collection') {
const img = item.data.images.find((i) => i.imageId === req.imageId)
- if (img) return { kind: 'image', ...img }
+ if (img) return { data: { kind: 'image', ...img }, capturedAt: item.capturedAt }
}
- return item.data
+ return { data: item.data, capturedAt: item.capturedAt }
}
-export function startDragOut(sender: WebContents, data: ItemData): void {
- const staged = stageDragFile(data)
+export function startDragOut(sender: WebContents, data: ItemData, capturedAt?: number): void {
+ const staged = stageDragFile(data, capturedAt)
if (!staged) return
const icon = dragIcon(data)
@@ -69,7 +87,7 @@ interface Staged {
}
/** Resolve the item to a concrete file path to hand to the OS. */
-function stageDragFile(data: ItemData): Staged | null {
+export function stageDragFile(data: ItemData, capturedAt?: number): Staged | null {
const temp = PATHS.tempDir()
switch (data.kind) {
case 'files': {
@@ -81,7 +99,8 @@ function stageDragFile(data: ItemData): Staged | null {
const src = getStore().getImagePath(data.imageId, data.ext)
if (!existsSync(src)) return null
const ext = extname(src) || '.png'
- const dest = join(temp, `${data.imageId}${ext}`)
+ const fileName = formatScreenshotFilename(capturedAt, ext)
+ const dest = join(temp, fileName)
try {
if (!existsSync(dest)) {
copyFileSync(src, dest)
@@ -89,20 +108,23 @@ function stageDragFile(data: ItemData): Staged | null {
} catch {
return null
}
- return { file: dest }
+ return { file: dest, files: [dest] }
}
case 'image-collection': {
const paths: string[] = []
+ let idx = 1
for (const img of data.images) {
const src = getStore().getImagePath(img.imageId, img.ext)
if (existsSync(src)) {
const ext = extname(src) || '.png'
- const dest = join(temp, `${img.imageId}${ext}`)
+ const fileName = formatScreenshotFilename(capturedAt, ext, idx)
+ const dest = join(temp, fileName)
try {
if (!existsSync(dest)) {
copyFileSync(src, dest)
}
paths.push(dest)
+ idx++
} catch {
// skip failed copies
}
@@ -113,13 +135,13 @@ function stageDragFile(data: ItemData): Staged | null {
}
case 'text': {
const id = `${Date.now().toString(36)}`
- const dest = join(temp, `${id}.txt`)
+ const dest = join(temp, `Snippet_${id}.txt`)
try {
writeFileSync(dest, data.text, 'utf8')
} catch {
return null
}
- return { file: dest }
+ return { file: dest, files: [dest] }
}
}
}
diff --git a/electron/main/ipc.ts b/electron/main/ipc.ts
index 130489b..57c4783 100644
--- a/electron/main/ipc.ts
+++ b/electron/main/ipc.ts
@@ -658,11 +658,12 @@ function on<C extends SendChannel>(
export function registerSendListeners(): void {
on('item:start-drag', (sender, req) => {
console.log('[IPC] item:start-drag req=', JSON.stringify(req))
- const data = resolveDragData(req)
- if (!data) {
+ const resolved = resolveDragData(req)
+ if (!resolved) {
console.log('[IPC] start-drag: no data resolved')
return
}
+ const { data, capturedAt } = resolved
console.log('[IPC] start-drag: kind=', data.kind)
// Pause the always-on-top heartbeat for the duration of the drag.
@@ -671,7 +672,7 @@ export function registerSendListeners(): void {
// dragged item appear to vanish ~0.5 s into any drag gesture.
setHeartbeatPaused(true)
- startDragOut(sender, data)
+ startDragOut(sender, data, capturedAt)
console.log('[IPC] start-drag returned, sending drag-end')
sender.send('item:drag-end')
diff --git a/electron/store/ItemStore.ts b/electron/store/ItemStore.ts
index 1e0d329..418cb9a 100644
--- a/electron/store/ItemStore.ts
+++ b/electron/store/ItemStore.ts
@@ -31,9 +31,9 @@ function signature(data: ItemData): string {
case 'text':
return `text|${data.text}`
case 'image':
- return `image|${data.imageId}`
+ return data.bytes && data.bytes > 0 ? `image|${data.width}x${data.height}|${data.bytes}` : `image|${data.imageId}`
case 'image-collection':
- return `image-collection|${data.images.map((i) => i.imageId).join(',')}`
+ return `image-collection|${data.images.map((i) => `${i.width}x${i.height}|${i.bytes || i.imageId}`).join(',')}`
case 'files':
return `files|${data.paths.join('\n')}`
}
@@ -485,10 +485,21 @@ export class ItemStore {
let newData: ItemData = { kind: 'files', paths: targetPaths }
if (targetPaths.length === 1) {
const p = targetPaths[0]
- const imgName = pathBasename(p)
- if (/^[a-z0-9]{6,12}-[a-z0-9]{6,12}\.[a-z0-9]+$/i.test(imgName) || p.includes('edge-drop/images') || p.includes('edge-drop\\images') || p.includes('edge-drop/temp') || p.includes('edge-drop\\temp')) {
- const imageId = imgName.split('.')[0]
- const ext = extname(p).slice(1) || 'png'
+ const pLower = p.toLowerCase()
+ const isFromManagedDir = pLower.includes('images') || pLower.includes('temp') || pLower.includes('edge-drop')
+ if (isImageExt(p) && isFromManagedDir) {
+ const imgName = pathBasename(p)
+ let imageId = imgName.split('.')[0]
+ const ext = (extname(p).slice(1) || 'png').toLowerCase()
+ if (!/^[a-z0-9]{6,12}-[a-z0-9]{6,12}$/i.test(imageId)) {
+ imageId = createId()
+ try {
+ if (existsSync(p)) {
+ const rawBytes = readFileSync(p)
+ this.stageImageBytes(imageId, rawBytes, ext)
+ }
+ } catch {}
+ }
let bytes = 0
try { bytes = statSync(p).size } catch {}
newData = { kind: 'image', imageId, width: 0, height: 0, bytes, ext }
diff --git a/tests/dragDrop.test.ts b/tests/dragDrop.test.ts
new file mode 100644
index 0000000..5d93c32
--- /dev/null
+++ b/tests/dragDrop.test.ts
@@ -0,0 +1,123 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { formatScreenshotFilename, stageDragFile } from '../electron/main/drag'
+import type { ItemData } from '../shared/types'
+
+// Mock dependencies for staging
+vi.mock('../electron/store/paths', () => ({
+ PATHS: {
+ tempDir: () => 'C:\\mock\\temp',
+ imagesDir: () => 'C:\\mock\\images'
+ }
+}))
+
+vi.mock('../electron/main/state', () => ({
+ getStore: () => ({
+ getImagePath: (imageId: string, ext = 'png') => `C:\\mock\\images\\${imageId}.${ext}`
+ })
+}))
+
+vi.mock('node:fs', () => ({
+ existsSync: vi.fn((path: string) => {
+ // Return true for mock source files
+ if (path.includes('mock\\images') || path.includes('mock\\real')) return true
+ return false
+ }),
+ copyFileSync: vi.fn(),
+ writeFileSync: vi.fn()
+}))
+
+describe('formatScreenshotFilename', () => {
+ it('formats clean, human-readable screenshot filenames with dates and times', () => {
+ // Date: 2026-08-15 22:30:45 UTC
+ const date = new Date(2026, 7, 15, 22, 30, 45) // Note month is 0-indexed: 7 = August
+ const filename = formatScreenshotFilename(date.getTime(), 'png')
+ expect(filename).toBe('Screenshot 2026-08-15 22.30.45.png')
+ })
+
+ it('handles custom extensions and normalizes leading dots', () => {
+ const date = new Date(2026, 0, 1, 9, 5, 2)
+ expect(formatScreenshotFilename(date.getTime(), '.webp')).toBe('Screenshot 2026-01-01 09.05.02.webp')
+ expect(formatScreenshotFilename(date.getTime(), 'jpg')).toBe('Screenshot 2026-01-01 09.05.02.jpg')
+ })
+
+ it('supports collision / sequence suffix for multi-image collections', () => {
+ const date = new Date(2026, 7, 15, 14, 0, 0)
+ expect(formatScreenshotFilename(date.getTime(), 'png', 0)).toBe('Screenshot 2026-08-15 14.00.00.png')
+ expect(formatScreenshotFilename(date.getTime(), 'png', 1)).toBe('Screenshot 2026-08-15 14.00.00.png')
+ expect(formatScreenshotFilename(date.getTime(), 'png', 2)).toBe('Screenshot 2026-08-15 14.00.00 (2).png')
+ expect(formatScreenshotFilename(date.getTime(), 'png', 3)).toBe('Screenshot 2026-08-15 14.00.00 (3).png')
+ })
+
+ it('ensures zero illegal Windows filesystem characters in generated names', () => {
+ const date = new Date()
+ const filename = formatScreenshotFilename(date.getTime())
+ // Prohibited characters on Windows: < > : " / \ | ? *
+ const illegalCharsRegex = /[<>:"/\\|?*]/
+ expect(illegalCharsRegex.test(filename)).toBe(false)
+ })
+})
+
+describe('stageDragFile dual-channel payload', () => {
+ const timestamp = new Date(2026, 7, 15, 22, 30, 45).getTime()
+
+ it('returns both file and files array for single image items with human-readable filename', () => {
+ const imageData: ItemData = {
+ kind: 'image',
+ imageId: 'img_test_123',
+ width: 1920,
+ height: 1080,
+ bytes: 50000,
+ ext: 'png'
+ }
+
+ const staged = stageDragFile(imageData, timestamp)
+ expect(staged).not.toBeNull()
+ expect(staged?.file).toContain('Screenshot 2026-08-15 22.30.45.png')
+ expect(staged?.files).toBeDefined()
+ expect(staged?.files).toHaveLength(1)
+ expect(staged?.files?.[0]).toBe(staged?.file)
+ })
+
+ it('returns indexed filenames and files array for image-collection items', () => {
+ const collectionData: ItemData = {
+ kind: 'image-collection',
+ images: [
+ { imageId: 'img_1', width: 800, height: 600, bytes: 10000, ext: 'png' },
+ { imageId: 'img_2', width: 800, height: 600, bytes: 12000, ext: 'png' }
+ ]
+ }
+
+ const staged = stageDragFile(collectionData, timestamp)
+ expect(staged).not.toBeNull()
+ expect(staged?.file).toContain('Screenshot 2026-08-15 22.30.45.png')
+ expect(staged?.files).toBeDefined()
+ expect(staged?.files).toHaveLength(2)
+ expect(staged?.files?.[0]).toContain('Screenshot 2026-08-15 22.30.45.png')
+ expect(staged?.files?.[1]).toContain('Screenshot 2026-08-15 22.30.45 (2).png')
+ })
+
+ it('returns files array for real file paths', () => {
+ const filesData: ItemData = {
+ kind: 'files',
+ paths: ['C:\\mock\\real\\document.pdf', 'C:\\mock\\real\\sheet.xlsx']
+ }
+
+ const staged = stageDragFile(filesData)
+ expect(staged).not.toBeNull()
+ expect(staged?.file).toBe('C:\\mock\\real\\document.pdf')
+ expect(staged?.files).toEqual(['C:\\mock\\real\\document.pdf', 'C:\\mock\\real\\sheet.xlsx'])
+ })
+
+ it('returns files array for staged text snippets', () => {
+ const textData: ItemData = {
+ kind: 'text',
+ text: 'Hello world snippet'
+ }
+
+ const staged = stageDragFile(textData)
+ expect(staged).not.toBeNull()
+ expect(staged?.file).toContain('Snippet_')
+ expect(staged?.files).toBeDefined()
+ expect(staged?.files?.[0]).toBe(staged?.file)
+ })
+})
diff --git a/tests/snippingTool.test.ts b/tests/snippingTool.test.ts
new file mode 100644
index 0000000..fe7f891
--- /dev/null
+++ b/tests/snippingTool.test.ts
@@ -0,0 +1,181 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { readClipboard, clipboardSignature } from '../electron/clipboard/formats'
+import { clipboard } from 'electron'
+
+// Mock Electron clipboard
+vi.mock('electron', () => {
+ let mockFormats: string[] = []
+ let mockText = ''
+ let mockHtml = ''
+ let mockImage = {
+ isEmpty: () => true,
+ getSize: () => ({ width: 0, height: 0 }),
+ toBitmap: () => Buffer.alloc(0),
+ toPNG: () => Buffer.alloc(0)
+ }
+
+ return {
+ clipboard: {
+ availableFormats: vi.fn(() => mockFormats),
+ readText: vi.fn(() => mockText),
+ readHTML: vi.fn(() => mockHtml),
+ readImage: vi.fn(() => mockImage),
+ readBuffer: vi.fn(() => Buffer.alloc(0)),
+ __setMockState: (state: {
+ formats?: string[]
+ text?: string
+ html?: string
+ image?: { isEmpty: () => boolean; getSize: () => { width: number; height: number }; toBitmap: () => Buffer; toPNG: () => Buffer }
+ }) => {
+ mockFormats = state.formats ?? []
+ mockText = state.text ?? ''
+ mockHtml = state.html ?? ''
+ mockImage = state.image ?? {
+ isEmpty: () => true,
+ getSize: () => ({ width: 0, height: 0 }),
+ toBitmap: () => Buffer.alloc(0),
+ toPNG: () => Buffer.alloc(0)
+ }
+ }
+ }
+ }
+})
+
+describe('Windows Snipping Tool & Clipboard Image Detection (#41)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('captures Windows Snipping Tool "Window" mode (DIB Bitmap + Window Title Text)', async () => {
+ // Windows 11 Snipping Tool writes the captured window bitmap along with window title text metadata
+ const mockBgra = Buffer.alloc(1920 * 1080 * 4, 128)
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 1920, height: 1080 }),
+ toBitmap: () => mockBgra,
+ toPNG: () => Buffer.from('mock-png-bytes')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['CF_DIBV5', 'CF_BITMAP', 'CF_UNICODETEXT'],
+ text: 'Visual Studio Code - Edge-Drop',
+ html: '',
+ image: mockImage
+ })
+
+ const result = await readClipboard()
+ expect(result).not.toBeNull()
+ expect(result?.kind).toBe('image')
+ if (result?.kind === 'image') {
+ expect(result.width).toBe(1920)
+ expect(result.height).toBe(1080)
+ }
+
+ const sig = clipboardSignature()
+ expect(sig).toContain('image:1920x1080:')
+ })
+
+ it('captures Rectangular / Fullscreen screenshots with pure image payload', async () => {
+ const mockBgra = Buffer.alloc(800 * 600 * 4, 255)
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 800, height: 600 }),
+ toBitmap: () => mockBgra,
+ toPNG: () => Buffer.from('mock-png-bytes')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['CF_DIBV5', 'PNG'],
+ text: '',
+ html: '',
+ image: mockImage
+ })
+
+ const result = await readClipboard()
+ expect(result).not.toBeNull()
+ expect(result?.kind).toBe('image')
+ if (result?.kind === 'image') {
+ expect(result.width).toBe(800)
+ expect(result.height).toBe(600)
+ }
+
+ const sig = clipboardSignature()
+ expect(sig).toContain('image:800x600:')
+ })
+
+ it('captures Browser "Copy Image" with fallback image URL', async () => {
+ const mockBgra = Buffer.alloc(400 * 300 * 4, 100)
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 400, height: 300 }),
+ toBitmap: () => mockBgra,
+ toPNG: () => Buffer.from('mock-png-bytes')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['image/png', 'text/html', 'text/plain'],
+ text: 'https://example.com/photo.png',
+ html: '<img src="https://example.com/photo.png">',
+ image: mockImage
+ })
+
+ const result = await readClipboard()
+ expect(result).not.toBeNull()
+ expect(result?.kind).toBe('image')
+
+ const sig = clipboardSignature()
+ expect(sig).toContain('image:400x300:')
+ })
+
+ it('captures regular text copy in text editors without image confusion', async () => {
+ ;(clipboard as any).__setMockState({
+ formats: ['CF_UNICODETEXT', 'text/plain'],
+ text: 'const greeting = "Hello World!"',
+ html: '',
+ image: {
+ isEmpty: () => true,
+ getSize: () => ({ width: 0, height: 0 }),
+ toBitmap: () => Buffer.alloc(0),
+ toPNG: () => Buffer.alloc(0)
+ }
+ })
+
+ const result = await readClipboard()
+ expect(result).not.toBeNull()
+ expect(result?.kind).toBe('text')
+ if (result?.kind === 'text') {
+ expect(result.text).toBe('const greeting = "Hello World!"')
+ }
+
+ const sig = clipboardSignature()
+ expect(sig).toContain('text:const greeting = "Hello World!"')
+ })
+
+ it('captures rich document selections from Word/Office as text', async () => {
+ const longDocumentText = 'Chapter 1: The Beginning\n\nThis is a rich formatted document paragraph copied from Word containing tables and formatted text with inline preview graphics.'
+ const richHtml = '<html><body><p>Chapter 1: The Beginning</p><p>This is a rich formatted document...</p><table><tr><td>Data</td></tr></table></body></html>'
+
+ const mockBgra = Buffer.alloc(100 * 100 * 4, 50)
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 100, height: 100 }),
+ toBitmap: () => mockBgra,
+ toPNG: () => Buffer.from('mock-png-bytes')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['text/html', 'CF_UNICODETEXT', 'CF_DIB'],
+ text: longDocumentText,
+ html: richHtml,
+ image: mockImage
+ })
+
+ const result = await readClipboard()
+ expect(result).not.toBeNull()
+ expect(result?.kind).toBe('text')
+ if (result?.kind === 'text') {
+ expect(result.text).toBe(longDocumentText)
+ expect(result.html).toBe(richHtml)
+ }
+ })
+})