fix(text-insert): restore every clipboard format after paste and never wipe non-text clipboards
This commit is contained in:
parent
190b6db284
commit
0adedf5e7b
5 changed files with 704 additions and 113 deletions
|
|
@ -4,9 +4,18 @@
|
|||
// @nut-tree-fork/nut-js + electron clipboard API 사용.
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import { clipboard } from 'electron'
|
||||
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')
|
||||
|
||||
|
|
@ -16,16 +25,9 @@ const logger = getLogger('TextInsertService')
|
|||
|
||||
type InsertMethod = 'clipboard' | 'keyboard'
|
||||
|
||||
interface ClipboardSnapshot {
|
||||
text: string | null
|
||||
html: string | null
|
||||
image: Electron.NativeImage | null
|
||||
rtf: string | null
|
||||
hasContent: boolean
|
||||
}
|
||||
|
||||
interface InsertResult {
|
||||
success: boolean
|
||||
/** 실제로 쓴 방식 — 클립보드를 되돌릴 수 없으면 'clipboard' 요청도 'keyboard' 가 된다 */
|
||||
method: InsertMethod
|
||||
textLength: number
|
||||
durationMs: number
|
||||
|
|
@ -39,72 +41,68 @@ interface TextInsertEvents {
|
|||
'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
|
||||
// ============================================================
|
||||
|
||||
class TextInsertService extends EventEmitter {
|
||||
private _nutKeyboard: NutKeyboard | null = null
|
||||
private _nutLoadPromise: Promise<void> | null = null
|
||||
|
||||
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
|
||||
/**
|
||||
* nut-js는 ESM + 네이티브 모듈이므로 lazy dynamic import 한다.
|
||||
* 삽입 직렬화 꼬리. 받아쓰기·음성 액션·제안 수락이 동시에 삽입하면 서로의
|
||||
* save/restore 가 엇갈려 다른 삽입의 텍스트를 "원래 클립보드"로 되돌리게 된다.
|
||||
*/
|
||||
private async _ensureNut(): Promise<NutKeyboard> {
|
||||
if (this._nutKeyboard) return this._nutKeyboard
|
||||
private _tail: Promise<void> = Promise.resolve()
|
||||
|
||||
if (!this._nutLoadPromise) {
|
||||
this._nutLoadPromise = (async () => {
|
||||
try {
|
||||
const nut = await import('@nut-tree-fork/nut-js')
|
||||
this._nutKeyboard = {
|
||||
pressKey: nut.keyboard.pressKey.bind(nut.keyboard),
|
||||
releaseKey: nut.keyboard.releaseKey.bind(nut.keyboard),
|
||||
type: nut.keyboard.type.bind(nut.keyboard),
|
||||
Key: nut.Key
|
||||
}
|
||||
logger.info('nut-js loaded successfully')
|
||||
} catch (error) {
|
||||
logger.error(`Failed to load nut-js: ${error instanceof Error ? error.message : String(error)}`)
|
||||
throw new D3ROError(
|
||||
ErrorCode.TextInsertKeySimulationFailed,
|
||||
'nut-js 로드 실패. 키보드 시뮬레이션을 사용할 수 없습니다.'
|
||||
)
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
await this._nutLoadPromise
|
||||
if (!this._nutKeyboard) {
|
||||
throw new D3ROError(ErrorCode.TextInsertKeySimulationFailed, 'nut-js not available')
|
||||
}
|
||||
return this._nutKeyboard
|
||||
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)))
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트를 현재 활성 앱에 삽입한다.
|
||||
* 기본 전략: clipboard save → set → Ctrl+V → restore
|
||||
* 동시 호출은 도착 순서대로 하나씩 처리한다.
|
||||
*/
|
||||
async insertText(text: string, method: InsertMethod = 'clipboard'): Promise<InsertResult> {
|
||||
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
|
||||
}
|
||||
|
||||
private async _insertNow(text: string, method: InsertMethod): Promise<InsertResult> {
|
||||
const start = performance.now()
|
||||
this.emit('insert-started', { text, method })
|
||||
|
||||
try {
|
||||
if (method === 'clipboard') {
|
||||
await this._insertViaClipboard(text)
|
||||
} else {
|
||||
await this._insertViaKeyboard(text)
|
||||
}
|
||||
const used: InsertMethod =
|
||||
method === 'clipboard' ? await this._insertViaClipboard(text) : await this._insertViaKeyboard(text)
|
||||
|
||||
const result: InsertResult = {
|
||||
success: true,
|
||||
method,
|
||||
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)`)
|
||||
logger.info(`Text inserted (${text.length} chars, ${Math.round(result.durationMs)}ms, ${used})`)
|
||||
return result
|
||||
} catch (error) {
|
||||
const d3roError =
|
||||
|
|
@ -123,38 +121,47 @@ class TextInsertService extends EventEmitter {
|
|||
/**
|
||||
* 클립보드 방식: save → set → Cmd/Ctrl+V → restore (Speakly 패턴)
|
||||
* macOS는 ⌘+V, Windows/Linux는 Ctrl+V로 분기.
|
||||
* 원래 클립보드를 되돌릴 수 없으면(예: 탐색기에서 복사한 파일) 클립보드를 건드리지 않고
|
||||
* 키보드 방식으로 넣는다. 실제로 쓴 방식을 돌려준다.
|
||||
*/
|
||||
private async _insertViaClipboard(text: string): Promise<void> {
|
||||
// 1. 기존 클립보드 저장
|
||||
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. 클립보드에 텍스트 설정
|
||||
clipboard.writeText(text)
|
||||
this._clipboard.writeText(text)
|
||||
|
||||
// 짧은 지연: 일부 앱이 클립보드 변경을 받아들일 시간 필요
|
||||
await this._sleep(20)
|
||||
|
||||
// 3. Paste 단축키 시뮬레이션 — 플랫폼별 modifier
|
||||
const nut = await this._ensureNut()
|
||||
const pasteModKey =
|
||||
process.platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl
|
||||
|
||||
await nut.pressKey(pasteModKey, nut.Key.V)
|
||||
await nut.releaseKey(nut.Key.V, pasteModKey)
|
||||
await this._keyboard.paste()
|
||||
|
||||
// 4. 붙여넣기 완료 대기 — 앱이 paste 이벤트를 처리할 시간
|
||||
// macOS는 비동기 처리가 좀 더 느린 경우가 있어 250ms로 잡음
|
||||
await this._sleep(process.platform === 'darwin' ? 250 : 150)
|
||||
await this._sleep(this._platform === 'darwin' ? 250 : 150)
|
||||
|
||||
// 5. 클립보드 복원 (원래 내용으로 되돌림)
|
||||
this.restoreClipboard(snapshot)
|
||||
this.emit('clipboard-restored', {})
|
||||
if (this._restoreIfStillOurs(text, snapshot)) {
|
||||
this.emit('clipboard-restored', {})
|
||||
}
|
||||
return 'clipboard'
|
||||
} catch (error) {
|
||||
// 실패 시에도 클립보드 복원 시도
|
||||
try {
|
||||
this.restoreClipboard(snapshot)
|
||||
this._restoreIfStillOurs(text, snapshot)
|
||||
} catch {
|
||||
logger.warn('Failed to restore clipboard after insert error')
|
||||
}
|
||||
|
|
@ -162,52 +169,41 @@ class TextInsertService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 클립보드가 아직 우리가 넣은 텍스트일 때만 되돌린다. 그 사이 사용자가 새로 복사했다면
|
||||
* 그 내용을 덮어쓰지 않는다 (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<void> {
|
||||
const nut = await this._ensureNut()
|
||||
await nut.type(text)
|
||||
private async _insertViaKeyboard(text: string): Promise<InsertMethod> {
|
||||
await this._keyboard.type(text)
|
||||
return 'keyboard'
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 클립보드 상태를 캡처한다.
|
||||
* 현재 클립보드 상태를 모든 포맷으로 캡처한다.
|
||||
*/
|
||||
saveClipboard(): ClipboardSnapshot {
|
||||
const text = clipboard.readText() || null
|
||||
const html = clipboard.readHTML() || null
|
||||
const rtf = clipboard.readRTF() || null
|
||||
const image = clipboard.readImage()
|
||||
const hasImage = image && !image.isEmpty()
|
||||
|
||||
return {
|
||||
text,
|
||||
html,
|
||||
image: hasImage ? image : null,
|
||||
rtf,
|
||||
hasContent: !!(text || html || rtf || hasImage)
|
||||
}
|
||||
saveClipboard(): ClipboardSnapshot<ClipboardImage> {
|
||||
return captureClipboard(this._clipboard)
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장된 클립보드 상태를 복원한다.
|
||||
* 저장된 클립보드 상태를 복원한다. 되돌릴 수 없는 스냅샷이면 아무것도 쓰지 않고 false.
|
||||
* 원래 포맷이 있었는데 clear() 하는 일은 없다.
|
||||
*/
|
||||
restoreClipboard(snapshot: ClipboardSnapshot): void {
|
||||
if (!snapshot.hasContent) {
|
||||
clipboard.clear()
|
||||
return
|
||||
}
|
||||
|
||||
// 텍스트가 있으면 텍스트 우선 복원
|
||||
if (snapshot.text) {
|
||||
clipboard.writeText(snapshot.text)
|
||||
} else if (snapshot.html) {
|
||||
clipboard.writeHTML(snapshot.html)
|
||||
} else if (snapshot.rtf) {
|
||||
clipboard.writeRTF(snapshot.rtf)
|
||||
} else if (snapshot.image) {
|
||||
clipboard.writeImage(snapshot.image)
|
||||
}
|
||||
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 {
|
||||
|
|
@ -215,10 +211,6 @@ class TextInsertService extends EventEmitter {
|
|||
logger.info('TextInsertService disposed')
|
||||
}
|
||||
|
||||
private _sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
// ── EventEmitter 타입 오버라이드 ───────────────────────
|
||||
|
||||
override on<K extends keyof TextInsertEvents>(
|
||||
|
|
@ -243,17 +235,6 @@ class TextInsertService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
// ── nut-js 타입 (lazy import용) ──────────────────────────
|
||||
|
||||
type NutModule = typeof import('@nut-tree-fork/nut-js')
|
||||
|
||||
interface NutKeyboard {
|
||||
pressKey: NutModule['keyboard']['pressKey']
|
||||
releaseKey: NutModule['keyboard']['releaseKey']
|
||||
type: NutModule['keyboard']['type']
|
||||
Key: NutModule['Key']
|
||||
}
|
||||
|
||||
// ── 싱글톤 ─────────────────────────────────────────────
|
||||
|
||||
let instance: TextInsertService | null = null
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue