// packages/core/src/keybinding-runtime.ts // // 전역 키바인딩 런타임 상태 머신 (순수 정책). // // press / release · 더블프레스 · auto-repeat 무시 · 구성 키 release · AltGr 보류를 // 한곳에서 판정한다. 입력 장치 후킹(uiohook)·Electron·시계에 의존하지 않는다 — // 이벤트는 정본 좌표계(bindingKey / Windows VK)로 들어오고, 시간은 주입된 시계로 잰다. // 그래서 가짜 타이머만으로 전 경로를 테스트할 수 있다. // // 어댑터(데스크톱 KeyBindingService)의 책임: // - 장치 이벤트 → bindingKey / VK 변환 // - 관측 불가능한 키 걸러내기(등록 전에) // - macOS beep 차단용 accelerator(플랫폼 · 기능 게이트 포함), 설정 로딩 // // 런타임 상태는 액션 id 가 아니라 bindingKey() 로 키잉한다 — // 한 액션에 여러 바인딩이 붙고, 여러 액션이 한 바인딩을 공유하기 때문이다. import { TIMING } from './constants' import { VK, bindingKey, isModifierKeyCode, normalizeBinding } from './keybinding' import type { BindingDevice, KeyBinding, KeyBindingActionId } from './keybinding' // ============================================================ // 공개 타입 · 포트 // ============================================================ /** 상태 머신이 내보내는 트리거. 데스크톱 `KeyBindingTriggerPayload` 의 정본이다. */ export interface ChordTriggerEvent { actionId: KeyBindingActionId type: 'pressed' | 'released' /** 더블프레스로 트리거된 누름인지 */ isDoublePress: boolean /** 액션 스펙의 holdMode — 소비자가 hold-to-talk / 토글을 분기하는 데 쓴다 */ holdMode: boolean timestamp: number /** type === 'released' 일 때의 누름 유지 시간 (pressed 는 0) */ durationMs: number /** 매칭된 바인딩(정규화 완료)의 주 키 코드와 수정자 상태 */ binding: KeyBinding } /** 상태 머신에 등록하는 바인딩 하나. binding 은 정규화 전이어도 된다. */ export interface ChordBindingEntry { actionId: KeyBindingActionId holdMode: boolean doublePress: boolean binding: KeyBinding } /** * 놓인 물리 키/버튼. keyUp 이 정확 매칭에 실패했을 때 "눌림 상태 바인딩의 구성 요소가 * 놓였는가" 를 판정하는 데 쓴다. 키보드는 Windows VK, 마우스는 MouseButton 코드다. */ export interface ChordReleasedComponent { device: BindingDevice code: number } /** keyDown 의 부가 정보 (어댑터가 관측한 눌림의 성격). */ export interface ChordKeyDownOptions { /** * 이 눌림이 AltGr(가짜 LCtrl + RightAlt)이다 — AltGrPressDetector 판정. * * AltGr 배열(독일어·프랑스어·폴란드어·북유럽 등)에서 오른쪽 Alt 는 문자 입력(@, €, {, \)의 * 시작이다. 바인딩 모양과 무관하게 이 누름으로 발동하는 트리거를 보류해, 이어서 문자 키가 * 눌리면(noteKeyDown) 취소한다. */ altGr?: boolean } /** * 시간 포트. 실제 구현은 Date.now / setTimeout, 테스트는 가짜 타이머를 넣는다. * schedule 은 취소 함수를 돌려준다 — 타이머 핸들 타입을 core 가 알 필요가 없다. */ export interface ChordClock { now(): number schedule(callback: () => void, delayMs: number): () => void } export interface ChordStateMachineOptions { clock: ChordClock onTrigger: (event: ChordTriggerEvent) => void /** 진단 로그. core 는 console 을 쓰지 않으므로 주입받는다. */ debug?: (message: string) => void /** 더블프레스 판정 간격 (기본 TIMING.DOUBLE_PRESS_DURATION) */ doublePressWindowMs?: number /** AltGr 형태 트리거 보류 시간 (기본 ALTGR_CHORD_GRACE_MS) */ altGrGraceMs?: number } /** * AltGr(=Ctrl+Alt) 함정 가드의 보류 시간. * * 오른쪽 Alt 는 Windows 가 Ctrl+Alt 로 보내므로, Ctrl+Alt+화살표 같은 조합을 누르면 * Alt 를 누르는 순간 Ctrl+AltRight 바인딩이 먼저 발동한다(실측 신고: 제안 탐색 대신 * 음성 파이프라인이 돌았다). 수정자만으로 끝나면서 Ctrl+Alt 가 함께 눌린 트리거는 * 이 시간만큼 보류하고, 그 사이 다른 바인딩이 눌리면(=조합을 만들려던 것) 취소한다. */ export const ALTGR_CHORD_GRACE_MS = 280 // ============================================================ // 순수 판정 함수 // ============================================================ type ModifierFlag = 'ctrl' | 'alt' | 'shift' | 'meta' const MODIFIER_FLAGS: readonly ModifierFlag[] = ['ctrl', 'alt', 'shift', 'meta'] /** * 수정자 키 VK 가 켜는 수정자 플래그. 수정자가 아니면 null. * * 정본은 keybinding.ts 의 정규화 규칙(주 키가 수정자 자신이면 그 플래그를 끈다)이다. * 같은 표를 다시 적지 않고, normalizeBinding 이 끄는 플래그로 역산한다. */ export function modifierFlagOfKeyCode(vk: number): ModifierFlag | null { const probe = normalizeBinding({ device: 'keyboard', code: vk, ctrl: true, alt: true, shift: true, meta: true }) return MODIFIER_FLAGS.find((flag) => !probe[flag]) ?? null } /** * AltGr(=Ctrl+Alt) 형태의 수정자 전용 조합인가. * * 정규화는 주 키 자신의 수정자 플래그를 끈다(Ctrl+RightAlt → {AltRight, ctrl}). 그래서 * 저장된 플래그만 보면 기본 바인딩 Ctrl+RightAlt 가 AltGr 형태로 보이지 않는다. * 주 키가 켜는 플래그를 되살려(= 사용자가 실제로 누르는 수정자 집합) 판정한다. */ export function isAltGrShapedBinding(binding: KeyBinding): boolean { if (binding.device !== 'keyboard') return false if (!isModifierKeyCode(binding.code)) return false const self = modifierFlagOfKeyCode(binding.code) const ctrl = binding.ctrl || self === 'ctrl' const alt = binding.alt || self === 'alt' return ctrl && alt } /** * 놓인 키/버튼이 바인딩의 주 키이거나 켜진 수정자의 구성 키인가. * * - 주 키: 장치와 코드가 같으면 수정자 플래그와 무관하게 구성 요소다. 마우스 X1 을 누른 채 * Alt 를 더 누르고 버튼을 놓으면 mouseup 이 `X1+Alt` 로 들어와 정확 매칭이 실패하는데, * 이때도 X1 누름은 놓여야 한다(아니면 hold-to-talk 가 계속 녹음한다). * - 수정자: 키보드 수정자 키만 해당한다. 마우스 바인딩(Ctrl+뒤로 등)도 수정자를 먼저 놓으면 * release 되어야 한다 — 그 뒤의 mouseup 은 수정자 없이 들어와 정확 매칭이 실패하기 때문이다. */ export function isChordComponentOf( component: ChordReleasedComponent, binding: KeyBinding ): boolean { if (binding.device === component.device && binding.code === component.code) return true if (component.device !== 'keyboard') return false const flag = modifierFlagOfKeyCode(component.code) return flag !== null && binding[flag] } /** keyUp 의 두 번째 인자 — 숫자는 키보드 VK(옛 호출 형태)다. */ function toReleasedComponent( component: number | ChordReleasedComponent | null ): ChordReleasedComponent | null { if (component === null) return null if (typeof component === 'number') return { device: 'keyboard', code: component } return component } // ============================================================ // 상태 머신 // ============================================================ type TriggerStatus = 'pending' | 'emitted' | 'cancelled' interface IndexedBinding { actionId: KeyBindingActionId holdMode: boolean doublePress: boolean binding: KeyBinding altGrShaped: boolean } interface ActiveTrigger { entry: IndexedBinding key: string isDoublePress: boolean pressedAt: number /** * pending — AltGr 보류 중 (pressed 미발송) * emitted — pressed 발송됨, released 를 보내야 한다 * cancelled — 보류가 다른 바인딩 눌림으로 취소됨, released 도 보내지 않는다 */ status: TriggerStatus cancelTimer: (() => void) | null } export class ChordStateMachine { private readonly _clock: ChordClock private readonly _onTrigger: (event: ChordTriggerEvent) => void private readonly _debug: (message: string) => void private readonly _doublePressWindowMs: number private readonly _altGrGraceMs: number /** bindingKey → 그 바인딩을 쓰는 액션들 (삽입 순서 유지) */ private _byKey: Map = new Map() /** 눌림 상태 — auto-repeat 무시 · release 매칭 */ private readonly _isDown: Set = new Set() private readonly _pressStart: Map = new Map() private readonly _lastPress: Map = new Map() /** 현재 누름에서 실제로 트리거된 액션 — release 를 같은 대상에게만 보낸다 */ private readonly _active: Map = new Map() /** AltGr 보류 중인 트리거 */ private readonly _pending: Set = new Set() constructor(options: ChordStateMachineOptions) { this._clock = options.clock this._onTrigger = options.onTrigger this._debug = options.debug ?? ((): void => {}) this._doublePressWindowMs = options.doublePressWindowMs ?? TIMING.DOUBLE_PRESS_DURATION this._altGrGraceMs = options.altGrGraceMs ?? ALTGR_CHORD_GRACE_MS } // ── 등록 ─────────────────────────────────────────────── /** 바인딩 목록을 교체한다. 런타임 상태(눌림 · 보류 타이머)도 함께 초기화한다. */ setBindings(entries: readonly ChordBindingEntry[]): void { this.reset() const next = new Map() for (const raw of entries) { const binding = normalizeBinding(raw.binding) const key = bindingKey(binding) const indexed: IndexedBinding = { actionId: raw.actionId, holdMode: raw.holdMode, doublePress: raw.doublePress, binding, altGrShaped: isAltGrShapedBinding(binding) } const existing = next.get(key) if (existing === undefined) { next.set(key, [indexed]) continue } // 같은 액션이 같은 바인딩을 두 번 들고 있으면 한 번 누를 때 두 번 트리거된다. if (existing.some((e) => e.actionId === raw.actionId)) continue existing.push(indexed) } this._byKey = next } /** 등록된 바인딩 수 (bindingKey 기준) */ get registeredBindingCount(): number { return this._byKey.size } /** bindingKey 마다 대표 바인딩 하나 (정규화 완료). accelerator 동기화용. */ registeredBindings(): KeyBinding[] { const out: KeyBinding[] = [] for (const entries of this._byKey.values()) { const first = entries[0] if (first !== undefined) out.push({ ...first.binding }) } return out } /** 눌림 · 더블프레스 · 보류 타이머를 모두 비운다. 보류된 pressed 는 버린다. */ reset(): void { for (const trigger of this._pending) trigger.cancelTimer?.() this._pending.clear() this._isDown.clear() this._pressStart.clear() this._lastPress.clear() this._active.clear() } /** * 떼는 이벤트가 오지 않을 순간(화면 잠금·절전)에 부른다. 이미 보낸 pressed 에는 released 를 보내 * hold 녹음이 끝나게 하고, 보류 중인 트리거는 버린다. 그 뒤 reset 처럼 모두 비운다. * 안 비우면 잠금을 푼 뒤 첫 누름이 auto-repeat 로 버려진다. */ releaseAll(): void { for (const trigger of this._pending) { trigger.cancelTimer?.() trigger.cancelTimer = null trigger.status = 'cancelled' } this._pending.clear() for (const key of [...this._isDown]) this._release(key) this.reset() } // ── 입력 ─────────────────────────────────────────────── /** * 바인딩 여부와 무관하게 모든 키보드 눌림을 알린다 (keyDown 보다 먼저 호출). * * 비수정자 키가 눌렸다 = 보류 중인 AltGr 형태 트리거는 조합이나 문자 입력(AltGr+Q='@')의 * 일부였다 → 취소한다. 바인딩된 키만 보면 바인딩되지 않은 문자 키가 보류를 끝내지 못해, * 문자 하나를 칠 때마다 보류 트리거가 발동한다. * * vk 가 null 이면 어댑터가 정본 좌표계로 옮기지 못한 키다. 수정자 키는 모두 옮길 수 * 있으므로 비수정자로 본다. 수정자 키(가짜 LCtrl · Shift 추가 등)는 보류를 건드리지 않는다. */ noteKeyDown(vk: number | null): void { if (vk !== null && isModifierKeyCode(vk)) return this._cancelPendingExcept(null) } /** 키/버튼 눌림. eventKey 는 이벤트의 bindingKey. */ keyDown(eventKey: string, options: ChordKeyDownOptions = {}): void { const entries = this._byKey.get(eventKey) if (entries === undefined || entries.length === 0) return // 키 반복(auto-repeat) 무시 if (this._isDown.has(eventKey)) return this._isDown.add(eventKey) const now = this._clock.now() this._pressStart.set(eventKey, now) // 다른 바인딩이 이어졌다 = 조합을 만들려던 것 → 보류 중인 AltGr 트리거는 취소. this._cancelPendingExcept(eventKey) // 더블프레스 감지는 이 바인딩을 쓰는 액션 중 하나라도 doublePress 일 때만 한다. // 그렇지 않으면 단일프레스 액션을 빠르게 두 번 누를 때 두 번째가 삼켜진다. let isDoublePress = false if (entries.some((entry) => entry.doublePress)) { const lastPress = this._lastPress.get(eventKey) isDoublePress = lastPress !== undefined && now - lastPress < this._doublePressWindowMs if (isDoublePress) { this._lastPress.delete(eventKey) } else { this._lastPress.set(eventKey, now) } } // dictation(단일) 과 hands-free(더블) 는 같은 바인딩을 공유한다 — // 첫 매치만 반환하지 않고 doublePress 여부로 갈라 해당하는 액션을 모두 트리거한다. const triggers: ActiveTrigger[] = [] for (const entry of entries) { if (entry.doublePress !== isDoublePress) continue triggers.push({ entry, key: eventKey, isDoublePress, pressedAt: now, status: 'emitted', cancelTimer: null }) } this._active.set(eventKey, triggers) for (const trigger of triggers) { this._debug(`Key binding pressed: "${trigger.entry.actionId}" (double=${isDoublePress})`) if (trigger.entry.altGrShaped || options.altGr === true) { this._deferPressed(trigger) } else { this._emitPressed(trigger) } } } /** * 키/버튼 놓임. * * eventKey 가 눌림 상태와 정확히 맞으면 그 바인딩을 놓는다. 아니면 component(놓인 * 키/버튼)가 눌림 상태 바인딩의 주 키/수정자인지 본다 — Alt+1 에서 수정자를 먼저 * 놓거나, 마우스 버튼을 누른 채 수정자를 더 눌러도 release 를 놓치지 않기 위해서다. * * component 가 숫자면 키보드 VK 다(옛 호출 형태). null 이면 정확 매칭만 한다. * 마우스 버튼은 물리적으로 하나이므로 그 버튼을 쓰는 눌림 바인딩을 모두 놓는다. */ keyUp( eventKey: string | null, component: number | ChordReleasedComponent | null ): void { if (eventKey !== null && this._isDown.has(eventKey)) { this._release(eventKey) return } const released = toReleasedComponent(component) if (released === null) return const matches: string[] = [] for (const [key, entries] of this._byKey) { if (!this._isDown.has(key)) continue const first = entries[0] if (first === undefined) continue if (isChordComponentOf(released, first.binding)) { matches.push(key) if (released.device === 'keyboard') break } } for (const key of matches) this._release(key) } // ── 내부 ─────────────────────────────────────────────── private _payload( trigger: ActiveTrigger, type: ChordTriggerEvent['type'], timestamp: number, durationMs: number ): ChordTriggerEvent { return { actionId: trigger.entry.actionId, type, isDoublePress: trigger.isDoublePress, holdMode: trigger.entry.holdMode, timestamp, durationMs, binding: { ...trigger.entry.binding } } } private _emitPressed(trigger: ActiveTrigger): void { trigger.status = 'emitted' this._onTrigger(this._payload(trigger, 'pressed', trigger.pressedAt, 0)) } /** * AltGr 형태 트리거는 곧 다른 키가 이어질 수 있으므로 잠깐 보류한다. * 유예가 끝나거나 그 조합 자체가 놓이면 발송하고, 다른 바인딩이 눌리면 취소한다. */ private _deferPressed(trigger: ActiveTrigger): void { trigger.status = 'pending' this._pending.add(trigger) trigger.cancelTimer = this._clock.schedule(() => { if (!this._pending.delete(trigger)) return trigger.cancelTimer = null this._debug(`AltGr 형태 트리거 유예 후 발동: "${trigger.entry.actionId}"`) this._emitPressed(trigger) }, this._altGrGraceMs) } /** 보류 중인 트리거를 취소한다. eventKey 가 주어지면 그 바인딩의 보류는 남긴다. */ private _cancelPendingExcept(eventKey: string | null): void { for (const trigger of this._pending) { if (trigger.key === eventKey) continue trigger.cancelTimer?.() trigger.cancelTimer = null trigger.status = 'cancelled' this._pending.delete(trigger) // 취소된 누름은 더블프레스의 첫 탭이 아니다 — '@' 를 치고 곧바로 오른쪽 Alt 를 // 탭하면 hands-free 가 켜지는 일을 막는다. if (this._lastPress.get(trigger.key) === trigger.pressedAt) { this._lastPress.delete(trigger.key) } this._debug(`AltGr 형태 보류 트리거 취소 (다른 키가 이어짐): "${trigger.entry.actionId}"`) } } private _release(key: string): void { this._isDown.delete(key) const now = this._clock.now() const pressStart = this._pressStart.get(key) const durationMs = pressStart !== undefined ? now - pressStart : 0 this._pressStart.delete(key) const triggers = this._active.get(key) ?? [] this._active.delete(key) for (const trigger of triggers) { if (trigger.status === 'cancelled') { this._debug( `AltGr 보류가 취소된 바인딩의 released 는 내보내지 않는다: "${trigger.entry.actionId}"` ) continue } if (trigger.status === 'pending') { // 유예 중에 조합 자체가 놓였다 = 다른 키는 오지 않았다. 순서를 지켜 지금 발송한다. trigger.cancelTimer?.() trigger.cancelTimer = null this._pending.delete(trigger) this._emitPressed(trigger) } this._debug(`Key binding released: "${trigger.entry.actionId}" (duration=${durationMs}ms)`) this._onTrigger(this._payload(trigger, 'released', now, durationMs)) } } } // ============================================================ // AltGr 눌림 판별 (Windows) // ============================================================ /** * Windows AltGr 판별기 (순수 정책). * * AltGr 배열에서 오른쪽 Alt 를 누르면 Windows 는 가짜 LCtrl 눌림을 먼저 보내고 곧바로 * RAlt 눌림을 보낸다. 두 이벤트의 타임스탬프는 같다. 후킹 라이브러리(libuiohook)는 이 가짜 * LCtrl 을 걸러내지 않고 Ctrl 수정자를 켜므로, RAlt 눌림이 `Ctrl+RightAlt` 로 보인다 — * 기본 'command' 바인딩과 겹치고 기본 'dictation'(RightAlt 단독)과는 절대 맞지 않는다. * * 판정: RAlt 눌림 직전 이벤트가 같은 타임스탬프의 LCtrl 눌림이고, 그 LCtrl 이 그 전까지 * 놓여 있었다면 AltGr 다. 사용자가 LCtrl 을 먼저 누르고 있었다면(Ctrl+AltGr) 진짜 Ctrl 이다. * AltGr 를 누른 채 반복되는 RAlt 눌림(auto-repeat)도 같은 AltGr 로 본다. * * 후킹 이벤트에 스캔 코드(0x21D)·주입 플래그가 없어 타임스탬프로만 판별한다. 그래서 진짜 * LCtrl 과 RAlt 를 같은 시계 틱 안에 함께 누르면 AltGr 로 오인할 수 있다 — 결과는 보류가 * 붙은 RightAlt 단독 눌림이므로 안전한 쪽으로 틀린다. */ export class AltGrPressDetector { private _ctrlLeftDown = false private _altGrHeld = false /** 직전 키보드 눌림 (가짜 LCtrl 짝 판정용) */ private _last: { vk: number | null; time: number; ctrlLeftWasDown: boolean } | null = null /** * 키보드 눌림을 관측한다. 모든 눌림을 넣어야 한다(좌표계로 옮기지 못한 키는 vk=null). * 반환값: 이 눌림이 AltGr(가짜 LCtrl + RAlt)인가. */ keyDown(vk: number | null, time: number): boolean { const previous = this._last this._last = { vk, time, ctrlLeftWasDown: this._ctrlLeftDown } if (vk === VK.CtrlLeft) { this._ctrlLeftDown = true return false } if (vk !== VK.AltRight) return false if (this._altGrHeld) return true this._altGrHeld = previous !== null && previous.vk === VK.CtrlLeft && previous.time === time && !previous.ctrlLeftWasDown return this._altGrHeld } /** 키보드 놓임을 관측한다. */ keyUp(vk: number | null): void { if (vk === VK.CtrlLeft) this._ctrlLeftDown = false if (vk === VK.AltRight) this._altGrHeld = false } /** 모든 상태를 비운다 (후킹 중지 등). */ reset(): void { this._ctrlLeftDown = false this._altGrHeld = false this._last = null } }