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
169
apps/desktop/src/main/screen-ocr-wiring.ts
Normal file
169
apps/desktop/src/main/screen-ocr-wiring.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
// src/main/screen-ocr-wiring.ts
|
||||
//
|
||||
// 화면 OCR 조립 — 서비스에 Electron 어댑터를 꽂고, 단축키 · 오버레이 IPC · Esc 를 잇는다.
|
||||
// 정책은 ScreenOcrService 에 있다. 여기는 얇은 어댑터만 둔다.
|
||||
|
||||
import { globalShortcut, ipcMain, type IpcMainEvent } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import { getLogger } from './services/LoggerService'
|
||||
import { getKeyBindingService } from './services/KeyBindingService'
|
||||
import { initScreenOcrService, type ScreenOcrRequest } from './services/ScreenOcrService'
|
||||
import { createOverlayPort, createScreenOcrDeps } from './services/screen-ocr/electron-adapters'
|
||||
import { getPopupTranslator, showResultPopup } from './windows/WindowManager'
|
||||
import { peekScreenOcrOverlayWindow } from './windows/screen-ocr-overlay'
|
||||
|
||||
const logger = getLogger('ScreenOcrWiring')
|
||||
|
||||
/** 오버레이(Vanilla JS)가 쓰는 문구 — 키 이름은 popups/screen-ocr/script.js 와 짝이다. */
|
||||
const OVERLAY_STRING_KEYS = [
|
||||
'modeText',
|
||||
'modeRect',
|
||||
'copy',
|
||||
'copyLine',
|
||||
'copyImage',
|
||||
'saveImage',
|
||||
'savePdf',
|
||||
'translate',
|
||||
'summarize',
|
||||
'speak',
|
||||
'stopSpeak',
|
||||
'openLink',
|
||||
'search',
|
||||
'selectAll',
|
||||
'close',
|
||||
'language',
|
||||
'languageAuto',
|
||||
'statusRecognizing',
|
||||
'statusReady',
|
||||
'statusEmpty',
|
||||
'statusSelected',
|
||||
'hint',
|
||||
'toastCopied',
|
||||
'toastImageCopied',
|
||||
'toastSaved',
|
||||
'working',
|
||||
'resultTranslate',
|
||||
'resultSummary',
|
||||
'errorRecognition',
|
||||
'errorUnavailable',
|
||||
'errorExport',
|
||||
'errorLlm',
|
||||
'errorTts',
|
||||
'errorLink',
|
||||
'errorInvalid',
|
||||
'errorEmpty'
|
||||
] as const
|
||||
|
||||
export function screenOcrOverlayStrings(): Record<string, string> {
|
||||
const t = getPopupTranslator()
|
||||
const out: Record<string, string> = {}
|
||||
for (const key of OVERLAY_STRING_KEYS) out[key] = t(`screenOcr.${key}`)
|
||||
return out
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** 화면 OCR 을 조립한다. 돌려주는 함수는 종료 시 정리한다. */
|
||||
export function initScreenOcr(): () => void {
|
||||
const overlay = createOverlayPort()
|
||||
|
||||
// 오버레이가 포커스를 못 얻은 경우(Windows 전경 잠금)에도 Esc 로 닫히게 열려 있는 동안만 잡는다.
|
||||
// 저장 대화상자가 떠 있는 동안은 푼다 — 대화상자의 Esc(취소)가 오버레이까지 닫지 않게.
|
||||
const ESCAPE = 'Escape'
|
||||
let escapeHeld = false
|
||||
let overlayOpen = false
|
||||
let dialogDepth = 0
|
||||
const syncEscape = (): void => {
|
||||
const wanted = overlayOpen && dialogDepth === 0
|
||||
if (wanted === escapeHeld) return
|
||||
if (wanted) {
|
||||
try {
|
||||
escapeHeld = globalShortcut.register(ESCAPE, () => service.close())
|
||||
} catch (error) {
|
||||
logger.warn(`Escape capture failed: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
} else {
|
||||
escapeHeld = false
|
||||
globalShortcut.unregister(ESCAPE)
|
||||
}
|
||||
}
|
||||
|
||||
const service = initScreenOcrService(
|
||||
createScreenOcrDeps(
|
||||
overlay,
|
||||
(kind) => getPopupTranslator()(kind === 'pdf' ? 'screenOcr.dialog.savePdf' : 'screenOcr.dialog.saveImage'),
|
||||
screenOcrOverlayStrings,
|
||||
{
|
||||
enter: () => {
|
||||
dialogDepth += 1
|
||||
syncEscape()
|
||||
},
|
||||
leave: () => {
|
||||
dialogDepth = Math.max(0, dialogDepth - 1)
|
||||
syncEscape()
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
const start = (): void => {
|
||||
service.toggle().catch((error: unknown) => {
|
||||
logger.error(`Screen OCR start failed: ${error instanceof Error ? error.message : String(error)}`)
|
||||
// 쓸 수 없는 환경 · 캡처 실패를 조용히 삼키지 않는다 — 왜 아무 일도 안 일어났는지 알린다.
|
||||
const unavailable = error instanceof D3ROError && error.code === ErrorCode.ScreenOcrUnavailable
|
||||
const t = getPopupTranslator()
|
||||
showResultPopup(t(unavailable ? 'screenOcr.errorUnavailable' : 'screenOcr.errorCapture'))
|
||||
})
|
||||
}
|
||||
|
||||
const onTriggered = (payload: { type: string; actionId: string }): void => {
|
||||
if (payload.type === 'pressed' && payload.actionId === 'screen-ocr') start()
|
||||
}
|
||||
getKeyBindingService().on('triggered', onTriggered)
|
||||
|
||||
service.on('opened', () => {
|
||||
overlayOpen = true
|
||||
syncEscape()
|
||||
})
|
||||
service.on('closed', () => {
|
||||
overlayOpen = false
|
||||
syncEscape()
|
||||
})
|
||||
|
||||
/** 오버레이 창이 보낸 것만 받는다. */
|
||||
const fromOverlay = (event: IpcMainEvent): boolean => {
|
||||
const win = peekScreenOcrOverlayWindow()
|
||||
return win !== null && event.sender === win.webContents
|
||||
}
|
||||
|
||||
const onReady = (event: IpcMainEvent, data: unknown): void => {
|
||||
if (!fromOverlay(event) || !isRecord(data) || typeof data.sessionId !== 'string') return
|
||||
overlay.notifyReady(data.sessionId)
|
||||
}
|
||||
const onDismiss = (event: IpcMainEvent): void => {
|
||||
if (fromOverlay(event)) service.close()
|
||||
}
|
||||
const onRequest = (event: IpcMainEvent, data: unknown): void => {
|
||||
if (!fromOverlay(event) || !isRecord(data)) return
|
||||
const { sessionId, requestId, request } = data
|
||||
if (typeof sessionId !== 'string' || typeof requestId !== 'number' || !isRecord(request)) return
|
||||
if (typeof request.type !== 'string') return
|
||||
// 모양 검증은 서비스가 한다(글 · 영역 · 언어) — 여기서는 봉투만 확인한다.
|
||||
void service.handleRequest(sessionId, requestId, request as unknown as ScreenOcrRequest)
|
||||
}
|
||||
|
||||
ipcMain.on(IPC_CHANNELS.POPUP_SCREEN_OCR.READY, onReady)
|
||||
ipcMain.on(IPC_CHANNELS.POPUP_SCREEN_OCR.DISMISS, onDismiss)
|
||||
ipcMain.on(IPC_CHANNELS.POPUP_SCREEN_OCR.REQUEST, onRequest)
|
||||
|
||||
return () => {
|
||||
getKeyBindingService().off('triggered', onTriggered)
|
||||
ipcMain.removeListener(IPC_CHANNELS.POPUP_SCREEN_OCR.READY, onReady)
|
||||
ipcMain.removeListener(IPC_CHANNELS.POPUP_SCREEN_OCR.DISMISS, onDismiss)
|
||||
ipcMain.removeListener(IPC_CHANNELS.POPUP_SCREEN_OCR.REQUEST, onRequest)
|
||||
service.dispose()
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue