feat(desktop): screen text capture (OCR) overlay with selectable text
A rebindable screen-ocr action (default Ctrl+Alt+O) freezes the monitor under the cursor and covers it with a focusable overlay. Text is selected by flow drag, rectangle drag, double/triple click, Shift+click or Ctrl+A, then copied, saved as PNG or searchable PDF, translated, summarized, read aloud, opened as a link or searched. - Selection, text assembly and the PDF document are pure functions in @d3ro/core/screen-ocr, shared by the main process and the overlay. - Recognition uses Windows.Media.Ocr through powershell.exe -EncodedCommand with 2x upscaling; the capture reaches disk only as a temp PNG that is removed right after recognition. - Capture uses GDI BitBlt for the target monitor (39 ms) because desktopCapturer captured all three monitors and took 2.9 s when DXGI duplication timed out. - The accelerator is reserved only where the feature is available, so macOS does not swallow the key for a feature it cannot run (fails closed with a message). Map: CAP-17 [~], GAP-OCR-01 (live hotkey journey not yet driven in the running app), GAP-OCR-02 (macOS engine, mixed-language accuracy).
This commit is contained in:
parent
6791e29f27
commit
03cd8bf890
41 changed files with 4561 additions and 17 deletions
246
apps/desktop/src/main/services/screen-ocr/electron-adapters.ts
Normal file
246
apps/desktop/src/main/services/screen-ocr/electron-adapters.ts
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
// src/main/services/screen-ocr/electron-adapters.ts
|
||||
//
|
||||
// ScreenOcrService 포트의 Electron 어댑터 — 화면 캡처 · 파일 · PDF · 클립보드 · LLM · TTS.
|
||||
// 정책은 서비스(ScreenOcrService)와 core(@d3ro/core/screen-ocr)에 있고, 여기는 OS/Electron 호출만 한다.
|
||||
|
||||
import { promises as fs } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { app, BrowserWindow, clipboard, desktopCapturer, dialog, nativeImage, screen } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import type { OcrRect } from '@d3ro/core/screen-ocr'
|
||||
import { configGet, configSet } from '../ConfigService'
|
||||
import { getLlmGateway } from '../llm/LlmGateway'
|
||||
import { getTTSPlaybackService } from '../TTSPlaybackService'
|
||||
import { getLogger } from '../LoggerService'
|
||||
import { openExternalSafe } from '../../windows/web-contents-hardening'
|
||||
import { captureScreenRegion } from '../../utils/win32-screen-capture'
|
||||
import {
|
||||
hideScreenOcrOverlay,
|
||||
peekScreenOcrOverlayWindow,
|
||||
getScreenOcrOverlayWindow,
|
||||
sendToScreenOcrOverlay,
|
||||
showScreenOcrOverlay
|
||||
} from '../../windows/screen-ocr-overlay'
|
||||
import type {
|
||||
ScreenOcrDeps,
|
||||
ScreenOcrFilesPort,
|
||||
ScreenOcrOverlayPort,
|
||||
ScreenShot
|
||||
} from '../ScreenOcrService'
|
||||
import { createWindowsOcrEngine } from './windows-ocr-engine'
|
||||
|
||||
const logger = getLogger('ScreenOcrAdapters')
|
||||
|
||||
/** 오버레이가 그림을 다 그렸다고 알리기를 기다리는 최대 시간 — 넘으면 그냥 보인다. */
|
||||
const OVERLAY_READY_TIMEOUT_MS = 500
|
||||
|
||||
// ── 화면 캡처 ─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 커서가 있는 모니터를 물리 해상도로 캡처한다.
|
||||
* Windows 는 GDI 로 그 모니터 한 장만 읽고(수십 ms), 안 되면 desktopCapturer 로 넘어간다.
|
||||
*/
|
||||
export async function captureDisplayAtCursor(): Promise<ScreenShot> {
|
||||
const display = screen.getDisplayNearestPoint(screen.getCursorScreenPoint())
|
||||
const image = captureWithGdi(display) ?? (await captureWithDesktopCapturer(display))
|
||||
const size = image.getSize()
|
||||
return {
|
||||
png: image.toPNG(),
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
scaleFactor: display.scaleFactor,
|
||||
displayBounds: { ...display.bounds },
|
||||
crop: (rect: OcrRect): Buffer => image.crop(rect).toPNG()
|
||||
}
|
||||
}
|
||||
|
||||
function captureWithGdi(display: Electron.Display): Electron.NativeImage | null {
|
||||
if (process.platform !== 'win32') return null
|
||||
// 모니터 영역(DIP) → 가상 화면의 물리 픽셀. 배율이 섞인 다중 모니터에서도 OS 가 준 값을 그대로 쓴다.
|
||||
const pixels = captureScreenRegion(screen.dipToScreenRect(null, display.bounds))
|
||||
if (!pixels) return null
|
||||
const image = nativeImage.createFromBitmap(pixels.bgra, { width: pixels.width, height: pixels.height })
|
||||
return image.isEmpty() ? null : image
|
||||
}
|
||||
|
||||
async function captureWithDesktopCapturer(display: Electron.Display): Promise<Electron.NativeImage> {
|
||||
const width = Math.round(display.size.width * display.scaleFactor)
|
||||
const height = Math.round(display.size.height * display.scaleFactor)
|
||||
|
||||
const sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width, height } })
|
||||
// display_id 가 비는 환경(드라이버·원격 세션)이 있다 — 모니터가 하나뿐이면 그 하나를 쓴다.
|
||||
const source =
|
||||
sources.find((candidate) => candidate.display_id === String(display.id)) ??
|
||||
(sources.length === 1 ? sources[0] : undefined)
|
||||
if (!source || source.thumbnail.isEmpty()) {
|
||||
throw new Error(`no capture source for display ${display.id} (${sources.length} source(s))`)
|
||||
}
|
||||
return source.thumbnail
|
||||
}
|
||||
|
||||
// ── 오버레이 창 ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 오버레이 표시는 2단계다: 숨긴 창에 그림을 먼저 보내고, 다 그렸다는 신호(READY)가 오면 보인다.
|
||||
* 곧바로 보이면 이전 캡처나 빈 바탕이 한 프레임 비친다.
|
||||
*/
|
||||
export function createOverlayPort(): ScreenOcrOverlayPort & { notifyReady(sessionId: string): void } {
|
||||
let pending: { sessionId: string; bounds: Electron.Rectangle; timer: NodeJS.Timeout } | null = null
|
||||
|
||||
const reveal = (): void => {
|
||||
if (!pending) return
|
||||
clearTimeout(pending.timer)
|
||||
const { bounds } = pending
|
||||
pending = null
|
||||
showScreenOcrOverlay(bounds)
|
||||
}
|
||||
|
||||
return {
|
||||
show(bounds, payload) {
|
||||
if (pending) clearTimeout(pending.timer)
|
||||
const win = getScreenOcrOverlayWindow()
|
||||
// 숨긴 채로 크기를 먼저 맞춘다 — 렌더러가 보이기 전에 최종 크기로 배치를 끝내게.
|
||||
win.setBounds(bounds)
|
||||
pending = {
|
||||
sessionId: payload.sessionId,
|
||||
bounds,
|
||||
timer: setTimeout(() => {
|
||||
logger.warn('Screen OCR overlay did not report ready in time — showing anyway')
|
||||
reveal()
|
||||
}, OVERLAY_READY_TIMEOUT_MS)
|
||||
}
|
||||
sendToScreenOcrOverlay(IPC_CHANNELS.POPUP_SCREEN_OCR.SESSION, payload)
|
||||
},
|
||||
notifyReady(sessionId) {
|
||||
if (pending?.sessionId === sessionId) reveal()
|
||||
},
|
||||
sendRecognized(payload) {
|
||||
sendToScreenOcrOverlay(IPC_CHANNELS.POPUP_SCREEN_OCR.RECOGNIZED, payload)
|
||||
},
|
||||
respond(payload) {
|
||||
sendToScreenOcrOverlay(IPC_CHANNELS.POPUP_SCREEN_OCR.RESPONSE, payload)
|
||||
},
|
||||
hide() {
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer)
|
||||
pending = null
|
||||
}
|
||||
// 그림을 놓게 한다(닫힌 뒤에도 캡처가 렌더러 메모리에 남지 않게).
|
||||
sendToScreenOcrOverlay(IPC_CHANNELS.POPUP_SCREEN_OCR.SESSION, null)
|
||||
hideScreenOcrOverlay()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 파일 ──────────────────────────────────────────────
|
||||
|
||||
function tempDir(): string {
|
||||
return join(app.getPath('temp'), 'd3ro-voice-screen-ocr')
|
||||
}
|
||||
|
||||
/** 저장 대화상자가 떠 있는 동안을 알린다 — 그동안은 전역 Esc 잡기를 풀어 대화상자의 Esc 가 살아 있게 한다. */
|
||||
export interface DialogGuard {
|
||||
enter(): void
|
||||
leave(): void
|
||||
}
|
||||
|
||||
export function createFilesPort(dialogTitle: (kind: 'pdf' | 'png') => string, guard: DialogGuard): ScreenOcrFilesPort {
|
||||
return {
|
||||
async writeTemp(name, data) {
|
||||
const dir = tempDir()
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
const path = join(dir, name)
|
||||
await fs.writeFile(path, data)
|
||||
return path
|
||||
},
|
||||
async remove(path) {
|
||||
await fs.rm(path, { force: true })
|
||||
},
|
||||
async askSavePath(kind, defaultName) {
|
||||
const options: Electron.SaveDialogOptions = {
|
||||
title: dialogTitle(kind),
|
||||
defaultPath: join(app.getPath('documents'), defaultName),
|
||||
filters: [kind === 'pdf' ? { name: 'PDF', extensions: ['pdf'] } : { name: 'PNG', extensions: ['png'] }]
|
||||
}
|
||||
// 오버레이가 최상위 단계라 부모 없이 띄우면 대화상자가 그 뒤에 깔린다.
|
||||
const parent = peekScreenOcrOverlayWindow()
|
||||
guard.enter()
|
||||
try {
|
||||
const { canceled, filePath } = parent
|
||||
? await dialog.showSaveDialog(parent, options)
|
||||
: await dialog.showSaveDialog(options)
|
||||
return canceled || !filePath ? null : filePath
|
||||
} finally {
|
||||
guard.leave()
|
||||
}
|
||||
},
|
||||
async write(path, data) {
|
||||
await fs.writeFile(path, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 임시 HTML 한 쪽을 숨긴 창에서 PDF 로 찍는다 (쪽 크기는 문서의 @page 를 따른다). */
|
||||
export async function renderHtmlFileToPdf(htmlPath: string): Promise<Buffer> {
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
width: 800,
|
||||
height: 600,
|
||||
webPreferences: { javascript: false, sandbox: true, contextIsolation: true, nodeIntegration: false }
|
||||
})
|
||||
try {
|
||||
win.webContents.on('will-navigate', (event) => event.preventDefault())
|
||||
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
||||
await win.loadFile(htmlPath)
|
||||
return await win.webContents.printToPDF({
|
||||
printBackground: true,
|
||||
preferCSSPageSize: true,
|
||||
margins: { top: 0, bottom: 0, left: 0, right: 0 }
|
||||
})
|
||||
} finally {
|
||||
win.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
// ── 조립 ──────────────────────────────────────────────
|
||||
|
||||
export function createScreenOcrDeps(
|
||||
overlay: ScreenOcrOverlayPort,
|
||||
dialogTitle: (kind: 'pdf' | 'png') => string,
|
||||
strings: () => Record<string, string>,
|
||||
guard: DialogGuard
|
||||
): ScreenOcrDeps {
|
||||
return {
|
||||
capture: captureDisplayAtCursor,
|
||||
engine: createWindowsOcrEngine(),
|
||||
overlay,
|
||||
files: createFilesPort(dialogTitle, guard),
|
||||
renderPdf: renderHtmlFileToPdf,
|
||||
clipboard: {
|
||||
writeText: async (text) => {
|
||||
await clipboard.writeText(text)
|
||||
},
|
||||
writeImage: async (png) => {
|
||||
await clipboard.writeImage(nativeImage.createFromBuffer(png))
|
||||
}
|
||||
},
|
||||
llm: {
|
||||
translate: (text, targetLanguage, signal, timeoutMs) =>
|
||||
getLlmGateway().processText(text, 'translate', targetLanguage, undefined, { signal, timeoutMs }),
|
||||
summarize: (text, signal, timeoutMs) =>
|
||||
getLlmGateway().processText(text, 'summarize', undefined, undefined, { signal, timeoutMs })
|
||||
},
|
||||
tts: {
|
||||
speak: (text) => getTTSPlaybackService().speak(text),
|
||||
stop: () => getTTSPlaybackService().stop()
|
||||
},
|
||||
openExternal: (url) => openExternalSafe(url),
|
||||
config: {
|
||||
getOcrLanguage: () => configGet('screenOcrLanguage') || 'auto',
|
||||
setOcrLanguage: (language) => configSet('screenOcrLanguage', language),
|
||||
getAppLocale: () => (configGet('language') as string) || 'ko',
|
||||
getTranslationTarget: () => configGet('targetLanguage') || 'English'
|
||||
},
|
||||
strings
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue