314 lines
11 KiB
TypeScript
314 lines
11 KiB
TypeScript
// src/main/services/TextInsertService.ts
|
|
// 전사된 텍스트를 현재 활성 앱에 삽입한다.
|
|
// 설계서 01의 ITextInsertService 구현. Speakly ClipboardPaste 패턴.
|
|
// @nut-tree-fork/nut-js + electron clipboard API 사용.
|
|
|
|
import { EventEmitter } from 'events'
|
|
import { getLogger } from './LoggerService'
|
|
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
|
import {
|
|
applyClipboardRestore,
|
|
captureClipboard,
|
|
planClipboardRestore,
|
|
type ClipboardImage,
|
|
type ClipboardPort,
|
|
type ClipboardSnapshot
|
|
} from './text-insert/clipboard-snapshot'
|
|
import { electronClipboardPort } from './text-insert/electron-clipboard-port'
|
|
import { NutKeyboardPort, type KeyboardPort } from './text-insert/nut-keyboard-port'
|
|
|
|
const logger = getLogger('TextInsertService')
|
|
|
|
// ============================================================
|
|
// 타입
|
|
// ============================================================
|
|
|
|
type InsertMethod = 'clipboard' | 'keyboard'
|
|
|
|
interface InsertResult {
|
|
success: boolean
|
|
/** 실제로 쓴 방식 — 클립보드를 되돌릴 수 없으면 'clipboard' 요청도 'keyboard' 가 된다 */
|
|
method: InsertMethod
|
|
textLength: number
|
|
durationMs: number
|
|
}
|
|
|
|
interface TextInsertEvents {
|
|
'insert-started': (payload: { text: string; method: InsertMethod }) => void
|
|
'insert-completed': (payload: { result: InsertResult }) => void
|
|
'insert-failed': (payload: { error: D3ROError; method: InsertMethod }) => void
|
|
'clipboard-saved': (payload: Record<string, never>) => void
|
|
'clipboard-restored': (payload: Record<string, never>) => void
|
|
}
|
|
|
|
/** 의존성 주입 (테스트·다른 플랫폼 어댑터용). 생략하면 Electron + nut-js 를 쓴다. */
|
|
export interface TextInsertDeps {
|
|
clipboard?: ClipboardPort<ClipboardImage>
|
|
keyboard?: KeyboardPort
|
|
sleep?: (ms: number) => Promise<void>
|
|
platform?: NodeJS.Platform
|
|
}
|
|
|
|
// ============================================================
|
|
// TextInsertService
|
|
// ============================================================
|
|
|
|
export class TextInsertService extends EventEmitter {
|
|
private readonly _clipboard: ClipboardPort<ClipboardImage>
|
|
private readonly _keyboard: KeyboardPort
|
|
private readonly _sleep: (ms: number) => Promise<void>
|
|
private readonly _platform: NodeJS.Platform
|
|
/**
|
|
* 삽입 직렬화 꼬리. 받아쓰기·음성 액션·제안 수락이 동시에 삽입하면 서로의
|
|
* save/restore 가 엇갈려 다른 삽입의 텍스트를 "원래 클립보드"로 되돌리게 된다.
|
|
*/
|
|
private _tail: Promise<void> = Promise.resolve()
|
|
|
|
constructor(deps: TextInsertDeps = {}) {
|
|
super()
|
|
this._platform = deps.platform ?? process.platform
|
|
this._clipboard = deps.clipboard ?? electronClipboardPort
|
|
this._keyboard = deps.keyboard ?? new NutKeyboardPort(this._platform)
|
|
this._sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
|
|
}
|
|
|
|
/** 키 입력 모듈을 미리 불러 둔다 (부팅 뒤 백그라운드) — 첫 삽입 지연 제거. */
|
|
async preload(): Promise<void> {
|
|
await this._keyboard.preload?.()
|
|
}
|
|
|
|
/**
|
|
* 텍스트를 현재 활성 앱에 삽입한다.
|
|
* 기본 전략: clipboard save → set → Ctrl+V → restore
|
|
* 동시 호출은 도착 순서대로 하나씩 처리한다.
|
|
*/
|
|
insertText(text: string, method: InsertMethod = 'clipboard'): Promise<InsertResult> {
|
|
const run = this._tail.then(() => this._insertNow(text, method))
|
|
this._tail = run.then(
|
|
() => undefined,
|
|
() => undefined
|
|
)
|
|
return run
|
|
}
|
|
|
|
/**
|
|
* 커서 앞 deleteCount 글자를 지우고 text 를 넣는다 (입력 중 오타 교정).
|
|
*
|
|
* 커서를 옮기지 않고 백스페이스로만 지운다 — 앱마다 다른 단어 이동/선택 동작에 기대지 않는다.
|
|
* 다른 삽입과 같은 직렬화 꼬리를 탄다(클립보드 save/restore 가 엇갈리지 않게).
|
|
*/
|
|
replaceBeforeCaret(
|
|
deleteCount: number,
|
|
text: string,
|
|
method: InsertMethod = 'clipboard',
|
|
options: { commitComposition?: boolean } = {}
|
|
): Promise<InsertResult> {
|
|
const run = this._tail.then(async () => {
|
|
if (method === 'keyboard' && this._keyboard.replaceBeforeCaret) {
|
|
const start = performance.now()
|
|
const handled = await this._keyboard.replaceBeforeCaret(deleteCount, text, options)
|
|
if (handled) {
|
|
this.emit('insert-started', { text, method: 'keyboard' })
|
|
const result: InsertResult = {
|
|
success: true,
|
|
method: 'keyboard',
|
|
textLength: text.length,
|
|
durationMs: performance.now() - start
|
|
}
|
|
this.emit('insert-completed', { result })
|
|
logger.info(
|
|
`Text replaced atomically (-${deleteCount} / +${text.length} chars, ${Math.round(result.durationMs)}ms, keyboard)`
|
|
)
|
|
return result
|
|
}
|
|
}
|
|
try {
|
|
let count = deleteCount
|
|
// 커서 앞 글자가 IME 조합 중이면 먼저 확정한다 (Space → 남은 공백까지 지운다).
|
|
if (options.commitComposition && this._keyboard.commitComposition) {
|
|
await this._keyboard.commitComposition()
|
|
await this._sleep(15)
|
|
count += 1
|
|
}
|
|
await this._keyboard.backspace(count)
|
|
} catch (error) {
|
|
throw error instanceof D3ROError
|
|
? error
|
|
: new D3ROError(
|
|
ErrorCode.TextInsertKeySimulationFailed,
|
|
`Backspace failed: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
}
|
|
// 앱이 지우기를 처리할 시간 — 붙여넣기가 지우기보다 먼저 처리되면 순서가 꼬인다.
|
|
// 긴 문장 교정(예: 30~40자 백스페이스)에서는 대상 앱 메시지 큐가 백스페이스를 소화할 시간을 비례해서 준다.
|
|
const settleMs = Math.min(90, Math.max(20, deleteCount * 2))
|
|
await this._sleep(settleMs)
|
|
return this._insertNow(text, method)
|
|
})
|
|
this._tail = run.then(
|
|
() => undefined,
|
|
() => undefined
|
|
)
|
|
return run
|
|
}
|
|
|
|
private async _insertNow(text: string, method: InsertMethod): Promise<InsertResult> {
|
|
const start = performance.now()
|
|
this.emit('insert-started', { text, method })
|
|
|
|
try {
|
|
const used: InsertMethod =
|
|
method === 'clipboard' ? await this._insertViaClipboard(text) : await this._insertViaKeyboard(text)
|
|
|
|
const result: InsertResult = {
|
|
success: true,
|
|
method: used,
|
|
textLength: text.length,
|
|
durationMs: performance.now() - start
|
|
}
|
|
|
|
this.emit('insert-completed', { result })
|
|
logger.info(`Text inserted (${text.length} chars, ${Math.round(result.durationMs)}ms, ${used})`)
|
|
return result
|
|
} catch (error) {
|
|
const d3roError =
|
|
error instanceof D3ROError
|
|
? error
|
|
: new D3ROError(
|
|
ErrorCode.TextInsertFailed,
|
|
`Text insert failed: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
|
|
this.emit('insert-failed', { error: d3roError, method })
|
|
throw d3roError
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 클립보드 방식: save → set → Cmd/Ctrl+V → restore (Speakly 패턴)
|
|
* macOS는 ⌘+V, Windows/Linux는 Ctrl+V로 분기.
|
|
* 원래 클립보드를 되돌릴 수 없으면(예: 탐색기에서 복사한 파일) 클립보드를 건드리지 않고
|
|
* 키보드 방식으로 넣는다. 실제로 쓴 방식을 돌려준다.
|
|
*/
|
|
private async _insertViaClipboard(text: string): Promise<InsertMethod> {
|
|
// 1. 기존 클립보드 저장 + 복원 가능성 판정
|
|
const snapshot = this.saveClipboard()
|
|
const plan = planClipboardRestore(snapshot)
|
|
if (plan.kind === 'unrestorable') {
|
|
logger.info(
|
|
`Clipboard cannot be restored (formats=${plan.formats.join(',') || '?'}); typing instead`
|
|
)
|
|
return this._insertViaKeyboard(text)
|
|
}
|
|
if (plan.kind === 'write' && plan.dropped.length > 0) {
|
|
logger.debug(`Clipboard formats not restorable alongside text: ${plan.dropped.join(',')}`)
|
|
}
|
|
this.emit('clipboard-saved', {})
|
|
|
|
try {
|
|
// 2. 클립보드에 텍스트 설정
|
|
this._clipboard.writeText(text)
|
|
|
|
// 짧은 지연: 일부 앱이 클립보드 변경을 받아들일 시간 필요
|
|
await this._sleep(20)
|
|
|
|
// 3. Paste 단축키 시뮬레이션 — 플랫폼별 modifier
|
|
await this._keyboard.paste()
|
|
|
|
// 4. 붙여넣기 완료 대기 — 대상 앱의 메시지 큐가 백스페이스 뒤 WM_PASTE(Ctrl+V)에서
|
|
// 클립보드를 읽을 때까지 충분히 기다린 뒤 클립보드를 복원/비운다.
|
|
// (Ctrl+V 키 이벤트는 이미 위에서 전송되었으므로 화면 반영은 즉시 일어난다.)
|
|
await this._sleep(250)
|
|
|
|
// 5. 클립보드 복원 (원래 내용으로 되돌림)
|
|
if (this._restoreIfStillOurs(text, snapshot)) {
|
|
this.emit('clipboard-restored', {})
|
|
}
|
|
return 'clipboard'
|
|
} catch (error) {
|
|
// 실패 시에도 클립보드 복원 시도
|
|
try {
|
|
this._restoreIfStillOurs(text, snapshot)
|
|
} catch {
|
|
logger.warn('Failed to restore clipboard after insert error')
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 클립보드가 아직 우리가 넣은 텍스트일 때만 되돌린다. 그 사이 사용자가 새로 복사했다면
|
|
* 그 내용을 덮어쓰지 않는다 (writeText 자체가 실패한 경우도 여기서 걸러진다).
|
|
*/
|
|
private _restoreIfStillOurs(text: string, snapshot: ClipboardSnapshot<ClipboardImage>): boolean {
|
|
if (this._clipboard.readText() !== text) {
|
|
logger.debug('Clipboard changed during insert; skipping restore')
|
|
return false
|
|
}
|
|
return this.restoreClipboard(snapshot)
|
|
}
|
|
|
|
/**
|
|
* 키보드 방식: 한 글자씩 타이핑 (느리지만 클립보드 비파괴)
|
|
*/
|
|
private async _insertViaKeyboard(text: string): Promise<InsertMethod> {
|
|
await this._keyboard.type(text)
|
|
return 'keyboard'
|
|
}
|
|
|
|
/**
|
|
* 현재 클립보드 상태를 모든 포맷으로 캡처한다.
|
|
*/
|
|
saveClipboard(): ClipboardSnapshot<ClipboardImage> {
|
|
return captureClipboard(this._clipboard)
|
|
}
|
|
|
|
/**
|
|
* 저장된 클립보드 상태를 복원한다. 되돌릴 수 없는 스냅샷이면 아무것도 쓰지 않고 false.
|
|
* 원래 포맷이 있었는데 clear() 하는 일은 없다.
|
|
*/
|
|
restoreClipboard(snapshot: ClipboardSnapshot<ClipboardImage>): boolean {
|
|
const restored = applyClipboardRestore(this._clipboard, planClipboardRestore(snapshot))
|
|
if (!restored) logger.warn('Clipboard snapshot is not restorable; left as is')
|
|
return restored
|
|
}
|
|
|
|
dispose(): void {
|
|
this.removeAllListeners()
|
|
logger.info('TextInsertService disposed')
|
|
}
|
|
|
|
// ── EventEmitter 타입 오버라이드 ───────────────────────
|
|
|
|
override on<K extends keyof TextInsertEvents>(
|
|
event: K,
|
|
listener: TextInsertEvents[K]
|
|
): this {
|
|
return super.on(event, listener)
|
|
}
|
|
|
|
override off<K extends keyof TextInsertEvents>(
|
|
event: K,
|
|
listener: TextInsertEvents[K]
|
|
): this {
|
|
return super.off(event, listener)
|
|
}
|
|
|
|
override emit<K extends keyof TextInsertEvents>(
|
|
event: K,
|
|
...args: Parameters<TextInsertEvents[K]>
|
|
): boolean {
|
|
return super.emit(event, ...args)
|
|
}
|
|
}
|
|
|
|
// ── 싱글톤 ─────────────────────────────────────────────
|
|
|
|
let instance: TextInsertService | null = null
|
|
|
|
export function getTextInsertService(): TextInsertService {
|
|
if (!instance) {
|
|
instance = new TextInsertService()
|
|
}
|
|
return instance
|
|
}
|