feat(keybinding): several shortcuts per action, mouse buttons, searchable picker

Shortcuts were defined in four places that drifted apart: per-action IPC channel
pairs, a hand-written VK table in the service, a second one in the renderer, and
three copies of the keycap styling. Adding an action meant editing all of them,
so two shortcuts stayed hardcoded in bootstrap and one had no settings entry at
all.

packages/core/src/keybinding.ts is now the single source for the binding type,
the selectable key catalog, the action catalog, normalization, validation,
conflict detection, display labels, search and deserialization. Main, preload
and renderer all read from it; nothing redefines keys or rules locally.

- Each action holds a list of bindings instead of one. AppConfig's four
  *Shortcut fields collapse into a single keyBindings map, migrated on launch.
- Mouse buttons can be bound. Left click is refused, right/middle need a
  modifier, side buttons are free. uiohook cannot swallow events, so the
  original click still fires and the UI says so.
- Keys can be picked from a grouped dropdown with a search box, not only by
  recording a keypress.
- HOTKEY's 14 channels become KEYBINDING's 9, taking the action as a parameter,
  so actions no longer multiply channels. The history and command popups moved
  out of bootstrap into ordinary actions.
- displayLabel is gone; labels derive from the binding and follow the app
  language and platform.

Fixes found on the way:
- Double-press hands-free was unreachable: lookup returned only the first
  matching action, and dictation shares its default binding.
- Reserved-combination checks compared joined key names, so a different modifier
  order let Ctrl+C through.
- Disabling shortcuts released every global registration in the process,
  including the popup ones, and never restored them.
- Enabling shortcuts after starting disabled left nothing registered.
- The dashboard stored the caption event payload instead of the state in it.
This commit is contained in:
Yun Chan 2026-09-21 13:41:47 +09:00
parent 0ca9e242fa
commit 4ad1ae6ed4
49 changed files with 5901 additions and 1792 deletions

View file

@ -3,7 +3,7 @@
import { app, dialog, globalShortcut, ipcMain as ipcMainRef } from 'electron'
import { initLoggerService, getLogger } from './services/LoggerService'
import { initConfigService, configGet, configSet } from './services/ConfigService'
import { getHotkeyService } from './services/HotkeyService'
import { getKeyBindingService } from './services/KeyBindingService'
import { getVoiceModeService } from './services/VoiceModeService'
import { startLocalLLMAvailability } from './services/LocalLLMService'
import { getHistoryService } from './services/HistoryService'
@ -61,7 +61,7 @@ export async function bootstrap(): Promise<void> {
{ name: 'sound-effects', critical: false, fn: initSoundEffects },
{ name: 'auto-launch', critical: false, fn: initAutoLaunch },
{ name: 'popup-preload', critical: false, fn: initPopupWindows },
{ name: 'hotkey', critical: false, fn: initHotkey },
{ name: 'key-bindings', critical: false, fn: initKeyBindings },
{ name: 'voice-mode', critical: false, fn: initVoiceMode },
{ name: 'stt-warmup', critical: false, fn: initSTTWarmup },
{ name: 'llm-polling', critical: false, fn: initLLMPolling },
@ -119,10 +119,10 @@ async function initIpcHandlers(): Promise<void> {
registerAllIpcHandlers()
}
async function initHotkey(): Promise<void> {
const hotkey = getHotkeyService()
hotkey.loadFromConfig()
hotkey.start()
async function initKeyBindings(): Promise<void> {
const keyBindings = getKeyBindingService()
keyBindings.loadFromConfig()
keyBindings.start()
}
async function initCustomInstructions(): Promise<void> {
@ -155,34 +155,42 @@ async function initPopupWindows(): Promise<void> {
// 오디오 디바이스 미리 캐싱 (Settings 열 때 즉시 반환)
getAudioCaptureService().getDevices().catch(() => { /* 실패해도 무시 */ })
// Ctrl+Shift+V → 히스토리 팝업 토글
globalShortcut.register('Ctrl+Shift+V', () => {
if (isHistoryPopupVisible()) {
hideHistoryPopup()
unregisterPopupNavKeys()
} else {
const entries = getHistoryService().list({ page: 0, pageSize: 10 }).entries
showHistoryPopup(entries as unknown as Array<Record<string, unknown>>)
registerPopupNavKeys()
}
})
// Ctrl+Shift+C → 커맨드 선택 팝업 토글
globalShortcut.register('Ctrl+Shift+C', () => {
if (isCommandPopupVisible()) {
hideCommandPopup()
unregisterPopupNavKeys()
} else {
const instructions = getCustomInstructionService().getAll()
const activeId = configGet('activeInstructionId') as string | null
showCommandPopup(instructions as unknown as Array<Record<string, unknown>>, activeId || null)
registerPopupNavKeys('command')
// 팝업 토글도 재바인딩 가능한 액션이다 — 하드코딩 accelerator 대신 KeyBindingService를 구독한다.
getKeyBindingService().on('triggered', (payload) => {
if (payload.type !== 'pressed') return
if (payload.actionId === 'history-popup') {
toggleHistoryPopup()
} else if (payload.actionId === 'command-popup') {
toggleCommandPopup()
}
})
setupCommandPopupIPC()
}
function toggleHistoryPopup(): void {
if (isHistoryPopupVisible()) {
hideHistoryPopup()
unregisterPopupNavKeys()
return
}
const entries = getHistoryService().list({ page: 0, pageSize: 10 }).entries
showHistoryPopup(entries as unknown as Array<Record<string, unknown>>)
registerPopupNavKeys()
}
function toggleCommandPopup(): void {
if (isCommandPopupVisible()) {
hideCommandPopup()
unregisterPopupNavKeys()
return
}
const instructions = getCustomInstructionService().getAll()
const activeId = configGet('activeInstructionId') as string | null
showCommandPopup(instructions as unknown as Array<Record<string, unknown>>, activeId || null)
registerPopupNavKeys('command')
}
// 히스토리 팝업 키 네비게이션 등록/해제
const POPUP_NAV_KEYS: Array<{ accel: string; key: string }> = [
{ accel: 'Up', key: 'ArrowUp' },
@ -222,7 +230,7 @@ function unregisterPopupNavKeys(): void {
async function initVoiceMode(): Promise<void> {
const voiceMode = getVoiceModeService()
voiceMode.connectHotkey()
voiceMode.connectKeyBindings()
const soundEffect = getSoundEffectService()

View file

@ -1,85 +0,0 @@
// src/main/ipc/hotkey-handlers.ts
import { ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
import { getHotkeyService } from '../services/HotkeyService'
import { configGet, configSet } from '../services/ConfigService'
import type { SetHotkeyParams, SetEnabledParams } from '@d3ro/core/types'
export function registerHotkeyHandlers(): void {
ipcMain.handle(IPC_CHANNELS.HOTKEY.GET_DICTATION_SHORTCUT, async () => {
return ipcSuccess(configGet('dictationShortcut'))
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.SET_DICTATION_SHORTCUT, async (_event, params: SetHotkeyParams) => {
try {
configSet('dictationShortcut', params.binding)
getHotkeyService().loadFromConfig()
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(ErrorCode.HotkeyRegistrationFailed, `Failed to set dictation shortcut: ${message}`)
}
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.GET_HANDS_FREE_SHORTCUT, async () => {
return ipcSuccess(configGet('handsFreeShortcut'))
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.SET_HANDS_FREE_SHORTCUT, async (_event, params: SetHotkeyParams) => {
try {
configSet('handsFreeShortcut', params.binding)
getHotkeyService().loadFromConfig()
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(ErrorCode.HotkeyRegistrationFailed, `Failed to set hands-free shortcut: ${message}`)
}
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.GET_COMMAND_SHORTCUT, async () => {
return ipcSuccess(configGet('commandShortcut'))
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.SET_COMMAND_SHORTCUT, async (_event, params: SetHotkeyParams) => {
try {
configSet('commandShortcut', params.binding)
getHotkeyService().loadFromConfig()
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(ErrorCode.HotkeyRegistrationFailed, `Failed to set command shortcut: ${message}`)
}
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.GET_CAPTION_SHORTCUT, async () => {
return ipcSuccess(configGet('captionShortcut'))
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.SET_CAPTION_SHORTCUT, async (_event, params: SetHotkeyParams) => {
try {
configSet('captionShortcut', params.binding)
getHotkeyService().loadFromConfig()
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(ErrorCode.HotkeyRegistrationFailed, `Failed to set caption shortcut: ${message}`)
}
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.IS_ENABLED, async () => {
return ipcSuccess(configGet('hotkeyEnabled'))
})
ipcMain.handle(IPC_CHANNELS.HOTKEY.SET_ENABLED, async (_event, params: SetEnabledParams) => {
configSet('hotkeyEnabled', params.enabled)
const hotkey = getHotkeyService()
if (params.enabled) {
hotkey.start()
} else {
hotkey.stop()
}
return ipcSuccess(undefined)
})
}

View file

@ -6,7 +6,7 @@ import { registerWindowHandlers } from './window-handlers'
import { registerSystemHandlers } from './system-handlers'
import { registerVoiceHandlers } from './voice-handlers'
import { registerSTTHandlers } from './stt-handlers'
import { registerHotkeyHandlers } from './hotkey-handlers'
import { registerKeyBindingHandlers } from './keybinding-handlers'
import { registerLLMHandlers } from './llm-handlers'
import { registerHistoryHandlers } from './history-handlers'
import { registerDictionaryHandlers } from './dictionary-handlers'
@ -40,7 +40,7 @@ export function registerAllIpcHandlers(): void {
registerSystemHandlers()
registerVoiceHandlers()
registerSTTHandlers()
registerHotkeyHandlers()
registerKeyBindingHandlers()
registerLLMHandlers()
registerHistoryHandlers()
registerDictionaryHandlers()

View file

@ -0,0 +1,238 @@
// src/main/ipc/keybinding-handlers.ts
//
// 키바인딩 IPC. 액션을 파라미터로 받는 단일 채널 집합이며,
// 검증·충돌 판정은 전부 `packages/core/src/keybinding.ts` 의 함수를 쓴다.
import { ipcMain, BrowserWindow } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
import {
bindingKey,
createDefaultBindingMap,
detectBindingConflicts,
findActionSpec,
isKeyBinding,
isKeyBindingActionId,
normalizeBinding,
parseBindingMap,
validateBinding
} from '@d3ro/core/keybinding'
import { getKeyBindingService } from '../services/KeyBindingService'
import type { KeyBindingTriggerPayload } from '../services/KeyBindingService'
import { configGet, configSet } from '../services/ConfigService'
import type {
KeyBinding,
KeyBindingChangedEvent,
KeyBindingMap,
KeyBindingTriggeredEvent,
KeyBindingValidationResult,
ResetKeyBindingParams,
SetEnabledParams,
SetKeyBindingsParams,
ValidateKeyBindingParams
} from '@d3ro/core/types'
function broadcast(channel: string, payload: unknown): void {
for (const win of BrowserWindow.getAllWindows()) {
win.webContents.send(channel, payload)
}
}
/** 바인딩 맵 변경을 모든 창에 알린다 (창 간 동기화). */
function broadcastChanged(map: KeyBindingMap): void {
const event: KeyBindingChangedEvent = { map }
broadcast(IPC_CHANNELS.KEYBINDING.CHANGED, event)
}
/** 저장된 맵을 읽는다. 손상·누락 항목은 기본값으로 복원한다. */
function readMap(): KeyBindingMap {
return parseBindingMap(configGet('keyBindings'))
}
/** 맵을 저장하고 후킹 서비스에 다시 태운 뒤 창에 알린다. */
function applyMap(map: KeyBindingMap): void {
configSet('keyBindings', map)
getKeyBindingService().loadFromConfig()
broadcastChanged(map)
}
/** uiohook 트리거를 렌더러로 중계한다. 재등록 시 리스너가 중복되지 않게 이전 것을 떼어낸다. */
let triggerRelay: ((payload: KeyBindingTriggerPayload) => void) | null = null
function connectTriggerRelay(): void {
const service = getKeyBindingService()
if (triggerRelay !== null) {
service.off('triggered', triggerRelay)
}
triggerRelay = (payload: KeyBindingTriggerPayload) => {
const event: KeyBindingTriggeredEvent = {
actionId: payload.actionId,
type: payload.type,
isDoublePress: payload.isDoublePress
}
broadcast(IPC_CHANNELS.KEYBINDING.TRIGGERED, event)
}
service.on('triggered', triggerRelay)
}
export function registerKeyBindingHandlers(): void {
connectTriggerRelay()
ipcMain.handle(IPC_CHANNELS.KEYBINDING.GET_MAP, async () => {
return ipcSuccess(readMap())
})
ipcMain.handle(
IPC_CHANNELS.KEYBINDING.SET_BINDINGS,
async (_event, params: SetKeyBindingsParams) => {
if (!isKeyBindingActionId(params.actionId)) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Unknown key binding action: ${String(params.actionId)}`
)
}
if (!Array.isArray(params.bindings)) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Bindings for "${params.actionId}" must be an array`
)
}
const map = readMap()
const next: KeyBinding[] = []
const seen = new Set<string>()
for (const candidate of params.bindings) {
if (!isKeyBinding(candidate)) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Malformed binding for "${params.actionId}"`
)
}
const binding = normalizeBinding(candidate)
const validation = validateBinding(binding)
if (!validation.valid) {
return ipcError(
ErrorCode.HotkeySystemReserved,
`Binding rejected for "${params.actionId}": ${validation.reason}`,
{ reason: validation.reason, reasonKey: validation.reasonKey }
)
}
const conflicts = detectBindingConflicts(params.actionId, binding, map)
if (conflicts.length > 0) {
return ipcError(
ErrorCode.HotkeyConflict,
`Binding for "${params.actionId}" conflicts with ` +
conflicts.map((c) => c.actionId).join(', '),
{ conflicts: conflicts.map((c) => c.actionId) }
)
}
const key = bindingKey(binding)
if (seen.has(key)) continue
seen.add(key)
next.push(binding)
}
map[params.actionId] = next
try {
applyMap(map)
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Failed to set bindings for "${params.actionId}": ${message}`
)
}
}
)
ipcMain.handle(
IPC_CHANNELS.KEYBINDING.RESET_ACTION,
async (_event, params: ResetKeyBindingParams) => {
const spec = isKeyBindingActionId(params.actionId)
? findActionSpec(params.actionId)
: null
if (spec === null) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Unknown key binding action: ${String(params.actionId)}`
)
}
try {
const map = readMap()
map[spec.id] = spec.defaultBindings.map((binding) => ({ ...binding }))
applyMap(map)
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Failed to reset "${spec.id}": ${message}`
)
}
}
)
ipcMain.handle(IPC_CHANNELS.KEYBINDING.RESET_ALL, async () => {
try {
applyMap(createDefaultBindingMap())
return ipcSuccess(undefined)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Failed to reset key bindings: ${message}`
)
}
})
ipcMain.handle(
IPC_CHANNELS.KEYBINDING.VALIDATE,
async (_event, params: ValidateKeyBindingParams) => {
if (!isKeyBindingActionId(params.actionId)) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Unknown key binding action: ${String(params.actionId)}`
)
}
if (!isKeyBinding(params.binding)) {
return ipcError(
ErrorCode.HotkeyRegistrationFailed,
`Malformed binding for "${params.actionId}"`
)
}
const binding = normalizeBinding(params.binding)
const result: KeyBindingValidationResult = {
validation: validateBinding(binding),
conflicts: detectBindingConflicts(params.actionId, binding, readMap())
}
return ipcSuccess(result)
}
)
ipcMain.handle(IPC_CHANNELS.KEYBINDING.IS_ENABLED, async () => {
return ipcSuccess(configGet('hotkeyEnabled'))
})
ipcMain.handle(
IPC_CHANNELS.KEYBINDING.SET_ENABLED,
async (_event, params: SetEnabledParams) => {
configSet('hotkeyEnabled', params.enabled)
const service = getKeyBindingService()
if (params.enabled) {
// 비활성 상태로 부팅한 뒤 켜는 경로 — 등록이 비어 있으므로 먼저 다시 읽는다.
service.loadFromConfig()
service.start()
} else {
service.stop()
}
return ipcSuccess(undefined)
}
)
}

View file

@ -2,7 +2,8 @@
// electron-store 기반 설정 관리. 설계서 02의 AppConfig 타입 사용.
import { EventEmitter } from 'events'
import type { AppConfig, ConfigChangedEvent } from '@d3ro/core/types'
import type { AppConfig, ConfigChangedEvent, KeyBindingActionId, KeyBindingMap } from '@d3ro/core/types'
import { createDefaultBindingMap, normalizeBinding, parseBindingMap } from '@d3ro/core/keybinding'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { getLogger } from './LoggerService'
@ -12,6 +13,7 @@ const logger = getLogger('ConfigService')
interface ElectronStore<T> {
get<K extends keyof T>(key: K): T[K]
set<K extends keyof T>(key: K, value: T[K]): void
delete(key: string): void
store: T
}
@ -51,38 +53,7 @@ const CONFIG_DEFAULTS: AppConfig = {
// 라이브 음성 대화 백엔드 — 'realtime'은 로그인+구독 필요 (OpenAI Realtime WebRTC)
conversationBackend: 'local' as const,
defaultLLMAction: 'refine',
dictationShortcut: {
keyCode: 0xa5, // Right Alt
ctrl: false,
alt: false,
shift: false,
meta: false,
displayLabel: 'Right Alt'
},
handsFreeShortcut: {
keyCode: 0xa5,
ctrl: false,
alt: false,
shift: false,
meta: false,
displayLabel: 'Right Alt (double)'
},
commandShortcut: {
keyCode: 0xa5,
ctrl: true,
alt: false,
shift: false,
meta: false,
displayLabel: 'Ctrl + Right Alt'
},
captionShortcut: {
keyCode: 0xa5,
ctrl: true,
alt: false,
shift: true,
meta: false,
displayLabel: 'Ctrl + Shift + Right Alt'
},
keyBindings: createDefaultBindingMap(),
hotkeyEnabled: true,
insertMethod: 'clipboard',
autoInsert: true,
@ -125,6 +96,9 @@ function createMemoryStore(initial: AppConfig): ElectronStore<AppConfig> {
set<K extends keyof AppConfig>(key: K, value: AppConfig[K]): void {
data[key] = value
},
delete(key: string): void {
delete (data as unknown as Record<string, unknown>)[key]
},
get store(): AppConfig {
return data
},
@ -134,6 +108,77 @@ function createMemoryStore(initial: AppConfig): ElectronStore<AppConfig> {
}
}
// ── 키바인딩 마이그레이션 (구 *Shortcut 4개 → keyBindings) ──
/** 0.x 저장 형태. 구조·라벨 정본이 keybinding.ts 로 옮겨지기 전의 값이다. */
interface LegacyShortcut {
keyCode: number
ctrl: boolean
alt: boolean
shift: boolean
meta: boolean
}
const LEGACY_SHORTCUT_ACTIONS: Readonly<Record<string, KeyBindingActionId>> = {
dictationShortcut: 'dictation',
handsFreeShortcut: 'hands-free',
commandShortcut: 'command',
captionShortcut: 'caption',
}
function isLegacyShortcut(value: unknown): value is LegacyShortcut {
if (typeof value !== 'object' || value === null) return false
const v = value as Record<string, unknown>
return (
typeof v.keyCode === 'number' &&
typeof v.ctrl === 'boolean' &&
typeof v.alt === 'boolean' &&
typeof v.shift === 'boolean' &&
typeof v.meta === 'boolean'
)
}
/**
* 저장된 keyBindings 를 복원하고, 남아 있는 구 `*Shortcut` 값을 1회만 이관한다.
*
* 구 필드는 이관 직후 삭제하므로 다시 읽히지 않는다.
* `displayLabel` 은 폐기한다 — 라벨은 formatBindingSegments() 로 파생시킨다.
*/
function migrateKeyBindings(activeStore: ElectronStore<AppConfig>): void {
const raw = activeStore.store as unknown as Record<string, unknown>
const restored: KeyBindingMap = parseBindingMap(raw.keyBindings)
const legacyKeys = Object.keys(LEGACY_SHORTCUT_ACTIONS).filter((key) =>
isLegacyShortcut(raw[key]),
)
if (legacyKeys.length === 0) {
activeStore.set('keyBindings', restored)
return
}
for (const key of legacyKeys) {
const legacy = raw[key] as LegacyShortcut
const actionId = LEGACY_SHORTCUT_ACTIONS[key]
if (actionId === undefined) continue
restored[actionId] = [
normalizeBinding({
device: 'keyboard',
code: legacy.keyCode,
ctrl: legacy.ctrl,
alt: legacy.alt,
shift: legacy.shift,
meta: legacy.meta,
}),
]
}
activeStore.set('keyBindings', restored)
for (const key of legacyKeys) {
activeStore.delete(key)
}
logger.info(`Migrated ${legacyKeys.length} legacy shortcut(s) to keyBindings`)
}
/** electron-store 없이 설정 CRUD를 가능하게 한다 (테스트 + 초기화 전 안전망). */
export function initInMemoryConfig(overrides?: Partial<AppConfig>): void {
store = createMemoryStore({ ...CONFIG_DEFAULTS, ...overrides })
@ -149,6 +194,7 @@ export async function initConfigService(): Promise<void> {
name: 'd3ro-voice-config',
defaults: CONFIG_DEFAULTS
})
migrateKeyBindings(store)
logger.info('ConfigService initialized')
}

View file

@ -1,709 +0,0 @@
// src/main/services/HotkeyService.ts
// uiohook-napi 기반 글로벌 키보드 후킹 서비스.
// 설계서 01의 IHotkeyService 구현. Speakly HotkeyService + HotkeyConfig 패턴 참조.
import { EventEmitter } from 'events'
import { globalShortcut } from 'electron'
import { uIOhook, UiohookKey } from 'uiohook-napi'
import type { UiohookKeyboardEvent } from 'uiohook-napi'
import { getLogger } from './LoggerService'
import { configGet } from './ConfigService'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { TIMING } from '@d3ro/core/constants'
import type { HotkeyBinding } from '@d3ro/core/types'
const logger = getLogger('HotkeyService')
// ============================================================
// 내부 타입
// ============================================================
export interface HotkeyConfig {
/** 핫키 식별자 (예: 'voice-dictation', 'voice-handsfree') */
id: string
/** uiohook 키코드 */
keyCode: number
/** 수정자 키 목록 */
modifiers: HotkeyModifier[]
/** true=hold-to-talk (누르고 있는 동안 활성), false=toggle */
holdMode: boolean
/** 더블프레스 감지 활성화 여부 */
doublePressEnabled: boolean
/** 활성화 여부 */
enabled: boolean
/**
* Electron globalShortcut accelerator (예: 'Shift+Cmd+1').
* macOS에서 OS 시스템 beep을 막기 위해 함께 register하고
* callback은 noop으로 둔다 (실제 hold/release는 uiohook이 처리).
* 변환 실패 시 null.
*/
acceleratorString: string | null
}
export type HotkeyModifier = 'ctrl' | 'alt' | 'shift' | 'meta'
interface HotkeyServiceEvents {
'hotkey-pressed': (payload: { config: HotkeyConfig; timestamp: number }) => void
'hotkey-released': (payload: {
config: HotkeyConfig
durationMs: number
timestamp: number
}) => void
'double-press': (payload: {
config: HotkeyConfig
intervalMs: number
timestamp: number
}) => void
error: (payload: { error: D3ROError }) => void
}
// ============================================================
// Windows VK 코드 → uiohook 키코드 매핑
// ============================================================
/**
* Windows Virtual-Key 코드를 uiohook-napi 키코드로 변환한다.
* ConfigService에 저장된 HotkeyBinding.keyCode는 Windows VK 코드이므로
* uiohook 이벤트와 비교하려면 변환이 필요하다.
*/
const VK_TO_UIOHOOK: ReadonlyMap<number, number> = new Map([
// 수정자 키
[0xa0, UiohookKey.Shift], // VK_LSHIFT
[0xa1, UiohookKey.ShiftRight], // VK_RSHIFT
[0xa2, UiohookKey.Ctrl], // VK_LCONTROL
[0xa3, UiohookKey.CtrlRight], // VK_RCONTROL
[0xa4, UiohookKey.Alt], // VK_LMENU
[0xa5, UiohookKey.AltRight], // VK_RMENU (Right Alt)
[0x5b, UiohookKey.Meta], // VK_LWIN
[0x5c, UiohookKey.MetaRight], // VK_RWIN
// 기능 키
[0x70, UiohookKey.F1],
[0x71, UiohookKey.F2],
[0x72, UiohookKey.F3],
[0x73, UiohookKey.F4],
[0x74, UiohookKey.F5],
[0x75, UiohookKey.F6],
[0x76, UiohookKey.F7],
[0x77, UiohookKey.F8],
[0x78, UiohookKey.F9],
[0x79, UiohookKey.F10],
[0x7a, UiohookKey.F11],
[0x7b, UiohookKey.F12],
// 일반 키
[0x20, UiohookKey.Space],
[0x0d, UiohookKey.Enter],
[0x1b, UiohookKey.Escape],
[0x08, UiohookKey.Backspace],
[0x09, UiohookKey.Tab],
[0x2d, UiohookKey.Insert],
[0x2e, UiohookKey.Delete],
[0x24, UiohookKey.Home],
[0x23, UiohookKey.End],
[0x21, UiohookKey.PageUp],
[0x22, UiohookKey.PageDown],
[0x25, UiohookKey.ArrowLeft],
[0x26, UiohookKey.ArrowUp],
[0x27, UiohookKey.ArrowRight],
[0x28, UiohookKey.ArrowDown],
// 알파벳 (VK_A=0x41 ~ VK_Z=0x5A)
[0x41, UiohookKey.A],
[0x42, UiohookKey.B],
[0x43, UiohookKey.C],
[0x44, UiohookKey.D],
[0x45, UiohookKey.E],
[0x46, UiohookKey.F],
[0x47, UiohookKey.G],
[0x48, UiohookKey.H],
[0x49, UiohookKey.I],
[0x4a, UiohookKey.J],
[0x4b, UiohookKey.K],
[0x4c, UiohookKey.L],
[0x4d, UiohookKey.M],
[0x4e, UiohookKey.N],
[0x4f, UiohookKey.O],
[0x50, UiohookKey.P],
[0x51, UiohookKey.Q],
[0x52, UiohookKey.R],
[0x53, UiohookKey.S],
[0x54, UiohookKey.T],
[0x55, UiohookKey.U],
[0x56, UiohookKey.V],
[0x57, UiohookKey.W],
[0x58, UiohookKey.X],
[0x59, UiohookKey.Y],
[0x5a, UiohookKey.Z],
// 숫자 (VK_0=0x30 ~ VK_9=0x39)
[0x30, UiohookKey['0']],
[0x31, UiohookKey['1']],
[0x32, UiohookKey['2']],
[0x33, UiohookKey['3']],
[0x34, UiohookKey['4']],
[0x35, UiohookKey['5']],
[0x36, UiohookKey['6']],
[0x37, UiohookKey['7']],
[0x38, UiohookKey['8']],
[0x39, UiohookKey['9']]
])
// Windows VK → Electron Accelerator key string
function vkToAcceleratorKey(vk: number): string | null {
// 0~9
if (vk >= 0x30 && vk <= 0x39) return String.fromCharCode(vk)
// A~Z
if (vk >= 0x41 && vk <= 0x5a) return String.fromCharCode(vk)
// F1~F24
if (vk >= 0x70 && vk <= 0x87) return `F${vk - 0x6f}`
switch (vk) {
case 0x20: return 'Space'
case 0x0d: return 'Return'
case 0x1b: return 'Esc'
case 0x08: return 'Backspace'
case 0x09: return 'Tab'
case 0x2d: return 'Insert'
case 0x2e: return 'Delete'
case 0x24: return 'Home'
case 0x23: return 'End'
case 0x21: return 'PageUp'
case 0x22: return 'PageDown'
case 0x25: return 'Left'
case 0x26: return 'Up'
case 0x27: return 'Right'
case 0x28: return 'Down'
case 0xba: return ';'
case 0xbb: return '='
case 0xbc: return ','
case 0xbd: return '-'
case 0xbe: return '.'
case 0xbf: return '/'
case 0xc0: return '`'
case 0xdb: return '['
case 0xdc: return '\\'
case 0xdd: return ']'
case 0xde: return "'"
default: return null
}
}
/**
* HotkeyBinding을 Electron globalShortcut accelerator로 변환.
* macOS Cmd → 'Cmd', Windows Win key → 'Super'.
*/
function bindingToAccelerator(binding: HotkeyBinding): string | null {
const key = vkToAcceleratorKey(binding.keyCode)
if (!key) return null
// 단일 modifier 키 자체를 단축키로 쓰는 경우 (예: Right Alt 단독) — accelerator 등록 불가.
// 일반 키와 modifier가 함께일 때만 등록.
const hasModifier = binding.ctrl || binding.alt || binding.shift || binding.meta
if (!hasModifier) {
// F1~F24, Esc 등 단일키는 등록 가능. 단 modifier 키 자체는 제외.
const isModifierKey =
binding.keyCode === 0x10 ||
binding.keyCode === 0x11 ||
binding.keyCode === 0x12 ||
binding.keyCode === 0x5b ||
binding.keyCode === 0x5c ||
(binding.keyCode >= 0xa0 && binding.keyCode <= 0xa5)
if (isModifierKey) return null
}
const parts: string[] = []
if (binding.ctrl) parts.push('Control')
if (binding.alt) parts.push('Alt')
if (binding.shift) parts.push('Shift')
if (binding.meta) parts.push(process.platform === 'darwin' ? 'Cmd' : 'Super')
parts.push(key)
return parts.join('+')
}
/**
* HotkeyBinding(Windows VK 코드)을 HotkeyConfig(uiohook 키코드)로 변환한다.
*/
function bindingToConfig(
id: string,
binding: HotkeyBinding,
holdMode: boolean,
doublePressEnabled: boolean
): HotkeyConfig {
const uiohookKeyCode = VK_TO_UIOHOOK.get(binding.keyCode)
if (uiohookKeyCode === undefined) {
logger.warn(
`Unknown VK code 0x${binding.keyCode.toString(16)} for hotkey "${id}", ` +
`using raw value ${binding.keyCode}`
)
}
const modifiers: HotkeyModifier[] = []
if (binding.ctrl) modifiers.push('ctrl')
if (binding.alt) modifiers.push('alt')
if (binding.shift) modifiers.push('shift')
if (binding.meta) modifiers.push('meta')
return {
id,
keyCode: uiohookKeyCode ?? binding.keyCode,
modifiers,
holdMode,
doublePressEnabled,
enabled: true,
acceleratorString: bindingToAccelerator(binding)
}
}
// ============================================================
// HotkeyService 클래스
// ============================================================
class HotkeyService extends EventEmitter {
private _isRunning = false
private _registeredHotkeys: Map<string, HotkeyConfig> = new Map()
/** 더블프레스 감지용: 마지막 press 시각 */
private _lastPressTime: Map<string, number> = new Map()
/** hold duration 계산용: press 시작 시각 */
private _pressStartTime: Map<string, number> = new Map()
/** 키 반복(auto-repeat) 방지: 현재 눌려있는 키 */
private _isKeyDown: Map<string, boolean> = new Map()
/** uiohook 이벤트 핸들러 (바인딩 해제용) */
private _onKeyDown: ((e: UiohookKeyboardEvent) => void) | null = null
private _onKeyUp: ((e: UiohookKeyboardEvent) => void) | null = null
get isRunning(): boolean {
return this._isRunning
}
get registeredHotkeys(): ReadonlyMap<string, HotkeyConfig> {
return this._registeredHotkeys
}
/**
* uiohook 글로벌 키보드 후킹을 시작한다.
* 이미 실행 중이면 무시.
*/
start(): void {
if (this._isRunning) {
logger.warn('HotkeyService already running')
return
}
try {
this._onKeyDown = (e: UiohookKeyboardEvent) => this._handleKeyDown(e)
this._onKeyUp = (e: UiohookKeyboardEvent) => this._handleKeyUp(e)
uIOhook.on('keydown', this._onKeyDown)
uIOhook.on('keyup', this._onKeyUp)
uIOhook.start()
this._isRunning = true
logger.info('uiohook started, global keyboard hook active')
} catch (error) {
const d3roError = new D3ROError(
ErrorCode.HotkeyHookInitFailed,
`Failed to start uiohook: ${error instanceof Error ? error.message : String(error)}`
)
this.emit('error', { error: d3roError })
logger.error(d3roError.message)
}
}
/**
* uiohook 글로벌 키보드 후킹을 중지한다.
*/
stop(): void {
if (!this._isRunning) {
return
}
try {
uIOhook.stop()
if (this._onKeyDown) {
uIOhook.removeListener('keydown', this._onKeyDown)
this._onKeyDown = null
}
if (this._onKeyUp) {
uIOhook.removeListener('keyup', this._onKeyUp)
this._onKeyUp = null
}
this._isRunning = false
this._isKeyDown.clear()
this._pressStartTime.clear()
// 등록된 모든 globalShortcut 해제
try {
globalShortcut.unregisterAll()
} catch (err) {
logger.warn(
`globalShortcut.unregisterAll failed: ${err instanceof Error ? err.message : String(err)}`
)
}
logger.info('uiohook stopped')
} catch (error) {
logger.error(
`Failed to stop uiohook: ${error instanceof Error ? error.message : String(error)}`
)
}
}
/**
* 핫키를 등록한다. 동일 ID가 이미 등록되어 있으면 갱신한다.
*
* macOS에서 hold 모드 핫키는 uiohook이 처리하지만, OS가 키를 swallow하지 않아
* focused app/desktop으로 전달되어 시스템 beep이 나는 경우가 있다.
* Electron globalShortcut을 noop callback과 함께 등록하면 OS가 키를 swallow하므로
* uiohook은 그대로 keydown/keyup을 받으면서 beep만 차단된다.
*/
registerHotkey(config: HotkeyConfig): void {
if (!config.enabled) {
logger.debug(`Hotkey "${config.id}" is disabled, skipping registration`)
return
}
// 기존 등록이 있으면 globalShortcut도 한 번 해제 (accelerator 변경 가능성)
const existing = this._registeredHotkeys.get(config.id)
if (existing?.acceleratorString) {
try {
if (globalShortcut.isRegistered(existing.acceleratorString)) {
globalShortcut.unregister(existing.acceleratorString)
}
} catch (err) {
logger.warn(
`globalShortcut unregister (existing) failed for "${config.id}": ${err instanceof Error ? err.message : String(err)}`
)
}
}
this._registeredHotkeys.set(config.id, config)
// macOS beep 차단용 globalShortcut 등록 (callback은 noop, 실제 처리는 uiohook)
if (config.acceleratorString) {
try {
const ok = globalShortcut.register(config.acceleratorString, () => {
// noop — uiohook이 hold/release를 책임진다.
})
if (!ok) {
logger.warn(
`globalShortcut.register returned false for "${config.id}" (${config.acceleratorString}) — beep 차단 실패`
)
}
} catch (err) {
logger.warn(
`globalShortcut.register failed for "${config.id}": ${err instanceof Error ? err.message : String(err)}`
)
}
}
logger.info(
`Hotkey registered: "${config.id}" ` +
`(keyCode=${config.keyCode}, modifiers=[${config.modifiers.join(',')}], ` +
`holdMode=${config.holdMode}, doublePress=${config.doublePressEnabled}, ` +
`accelerator=${config.acceleratorString ?? 'N/A'})`
)
}
/**
* 핫키 등록을 해제한다.
*/
unregisterHotkey(id: string): void {
const existing = this._registeredHotkeys.get(id)
if (existing?.acceleratorString) {
try {
if (globalShortcut.isRegistered(existing.acceleratorString)) {
globalShortcut.unregister(existing.acceleratorString)
}
} catch (err) {
logger.warn(
`globalShortcut unregister failed for "${id}": ${err instanceof Error ? err.message : String(err)}`
)
}
}
if (this._registeredHotkeys.delete(id)) {
this._lastPressTime.delete(id)
this._pressStartTime.delete(id)
this._isKeyDown.delete(id)
logger.info(`Hotkey unregistered: "${id}"`)
}
}
/**
* ConfigService에서 핫키 설정을 로드하여 등록한다.
*/
loadFromConfig(): void {
const hotkeyEnabled = configGet('hotkeyEnabled')
if (!hotkeyEnabled) {
logger.info('Hotkeys disabled in config')
return
}
const dictationBinding = configGet('dictationShortcut')
const handsFreeBinding = configGet('handsFreeShortcut')
const commandBinding = configGet('commandShortcut')
const captionBinding = configGet('captionShortcut')
// 기존 핫키 초기화
this._registeredHotkeys.clear()
// Dictation: hold-to-talk, 더블프레스 비활성
this.registerHotkey(
bindingToConfig('voice-dictation', dictationBinding, true, false)
)
// Hands-free: toggle, 더블프레스 활성
this.registerHotkey(
bindingToConfig('voice-handsfree', handsFreeBinding, false, true)
)
// Command: toggle, 더블프레스 비활성
this.registerHotkey(
bindingToConfig('voice-command', commandBinding, false, false)
)
// Caption: toggle (자막 모드 시작/정지), 더블프레스 비활성
this.registerHotkey(
bindingToConfig('voice-caption', captionBinding, false, false)
)
logger.info(
`Loaded ${this._registeredHotkeys.size} hotkeys from config`
)
}
/**
* 서비스 리소스를 정리한다.
*/
dispose(): void {
this.stop()
this._registeredHotkeys.clear()
this._lastPressTime.clear()
this._pressStartTime.clear()
this._isKeyDown.clear()
this.removeAllListeners()
logger.info('HotkeyService disposed')
}
// ============================================================
// 내부: 키 이벤트 처리
// ============================================================
/**
* 키 다운 이벤트를 처리한다.
* 등록된 핫키 중 매칭되는 것을 찾아 적절한 이벤트를 발행한다.
*/
private _handleKeyDown(e: UiohookKeyboardEvent): void {
const matched = this._findMatchingHotkey(e)
if (!matched) return
const { id } = matched
// 키 반복(auto-repeat) 무시: 이미 눌려있으면 건너뜀
if (this._isKeyDown.get(id)) {
return
}
this._isKeyDown.set(id, true)
const now = Date.now()
// press 시작 시각 기록 (hold duration 계산용)
this._pressStartTime.set(id, now)
// 더블프레스 감지
if (matched.doublePressEnabled) {
const lastPress = this._lastPressTime.get(id)
if (lastPress !== undefined && now - lastPress < TIMING.DOUBLE_PRESS_DURATION) {
// 300ms 이내 연속 두 번 press = 더블프레스
this._lastPressTime.delete(id)
logger.debug(`Double-press detected: "${id}" (interval=${now - lastPress}ms)`)
this.emit('double-press', {
config: matched,
intervalMs: now - lastPress,
timestamp: now
})
return
}
this._lastPressTime.set(id, now)
}
logger.debug(`Hotkey pressed: "${id}"`)
this.emit('hotkey-pressed', {
config: matched,
timestamp: now
})
}
/**
* 키 업 이벤트를 처리한다.
* Alt+1 같은 조합에서 Alt를 먼저 놓아도 release 감지해야 한다.
* 전략: pressed 상태인 핫키 중 구성 키(main key 또는 modifier)가 놓아지면 release.
*/
private _handleKeyUp(e: UiohookKeyboardEvent): void {
// 방법 1: 정확한 매칭 시도
const matched = this._findMatchingHotkey(e)
if (matched && this._isKeyDown.get(matched.id)) {
this._fireRelease(matched)
return
}
// 방법 2: 현재 pressed인 핫키 중 구성 키가 놓아진 경우 (modifier 먼저 놓기 대응)
for (const config of this._registeredHotkeys.values()) {
if (!this._isKeyDown.get(config.id)) continue
// 놓아진 키가 이 핫키의 main key인가?
const isMainKey = e.keycode === config.keyCode
// 놓아진 키가 이 핫키의 modifier 중 하나인가?
const isModifier = this._isEventModifierOf(e, config)
if (isMainKey || isModifier) {
this._fireRelease(config)
return
}
}
}
/** pressed 핫키의 release 이벤트 발행 */
private _fireRelease(config: HotkeyConfig): void {
const { id } = config
this._isKeyDown.set(id, false)
const now = Date.now()
const pressStart = this._pressStartTime.get(id)
const durationMs = pressStart !== undefined ? now - pressStart : 0
this._pressStartTime.delete(id)
logger.debug(`Hotkey released: "${id}" (duration=${durationMs}ms)`)
this.emit('hotkey-released', {
config,
durationMs,
timestamp: now
})
}
/** 키 이벤트가 핫키의 modifier 구성요소인지 확인 */
private _isEventModifierOf(e: UiohookKeyboardEvent, config: HotkeyConfig): boolean {
const modifiers = config.modifiers ?? []
for (const mod of modifiers) {
if (mod === 'ctrl' && (this._isCtrlKeyCode(e.keycode))) return true
if (mod === 'alt' && (this._isAltKeyCode(e.keycode))) return true
if (mod === 'shift' && (this._isShiftKeyCode(e.keycode))) return true
if (mod === 'meta' && (this._isMetaKeyCode(e.keycode))) return true
}
return false
}
/**
* uiohook 키 이벤트와 등록된 핫키를 매칭한다.
* 키코드와 수정자 키가 모두 일치해야 매칭 성공.
*/
private _findMatchingHotkey(e: UiohookKeyboardEvent): HotkeyConfig | null {
for (const config of this._registeredHotkeys.values()) {
if (!config.enabled) continue
// 키코드 일치 확인
if (e.keycode !== config.keyCode) continue
// 수정자 키 일치 확인
// 핫키에 지정된 수정자가 모두 눌려 있어야 하고,
// 지정되지 않은 수정자는 눌려 있으면 안 된다.
//
// 단, 핫키의 주 키 자체가 수정자 키인 경우(예: Right Alt 단독):
// - 해당 수정자의 altKey 등이 true로 올 수 있으므로,
// modifiers에 해당 modifier가 **없을 때만** 이벤트의 해당 플래그를 무시한다.
// - modifiers에 해당 modifier가 **있으면** (예: Alt+Right Alt은 불가하므로)
// 해당 플래그가 true여야 매칭 성공.
//
// 예: Right Alt 단독 (keyCode=AltRight, modifiers=[])
// → e.altKey가 true여도 wantsAlt=false이므로 bypass → match
// 예: Ctrl+Right Alt (keyCode=AltRight, modifiers=['ctrl'])
// → e.altKey bypass, e.ctrlKey===true 체크 → match only with Ctrl held
const wantsCtrl = config.modifiers.includes('ctrl')
const wantsAlt = config.modifiers.includes('alt')
const wantsShift = config.modifiers.includes('shift')
const wantsMeta = config.modifiers.includes('meta')
// 주 키 자체가 해당 modifier인 경우, 그 modifier의 이벤트 플래그는 무시
const skipCtrl = this._isCtrlKeyCode(config.keyCode) && !wantsCtrl
const skipAlt = this._isAltKeyCode(config.keyCode) && !wantsAlt
const skipShift = this._isShiftKeyCode(config.keyCode) && !wantsShift
const skipMeta = this._isMetaKeyCode(config.keyCode) && !wantsMeta
const ctrlMatch = skipCtrl || (e.ctrlKey === wantsCtrl)
const altMatch = skipAlt || (e.altKey === wantsAlt)
const shiftMatch = skipShift || (e.shiftKey === wantsShift)
const metaMatch = skipMeta || (e.metaKey === wantsMeta)
if (ctrlMatch && altMatch && shiftMatch && metaMatch) {
return config
}
}
return null
}
private _isCtrlKeyCode(keyCode: number): boolean {
return keyCode === UiohookKey.Ctrl || keyCode === UiohookKey.CtrlRight
}
private _isAltKeyCode(keyCode: number): boolean {
return keyCode === UiohookKey.Alt || keyCode === UiohookKey.AltRight
}
private _isShiftKeyCode(keyCode: number): boolean {
return keyCode === UiohookKey.Shift || keyCode === UiohookKey.ShiftRight
}
private _isMetaKeyCode(keyCode: number): boolean {
return keyCode === UiohookKey.Meta || keyCode === UiohookKey.MetaRight
}
// ============================================================
// EventEmitter 타입 오버라이드
// ============================================================
override on<K extends keyof HotkeyServiceEvents>(
event: K,
listener: HotkeyServiceEvents[K]
): this {
return super.on(event, listener)
}
override off<K extends keyof HotkeyServiceEvents>(
event: K,
listener: HotkeyServiceEvents[K]
): this {
return super.off(event, listener)
}
override emit<K extends keyof HotkeyServiceEvents>(
event: K,
...args: Parameters<HotkeyServiceEvents[K]>
): boolean {
return super.emit(event, ...args)
}
}
// ============================================================
// 싱글톤
// ============================================================
let instance: HotkeyService | null = null
export function getHotkeyService(): HotkeyService {
if (!instance) {
instance = new HotkeyService()
}
return instance
}

View file

@ -0,0 +1,766 @@
// src/main/services/KeyBindingService.ts
// uiohook-napi 기반 글로벌 키바인딩 후킹 서비스.
//
// 바인딩 계약(키 목록·기본값·정규화·검증·충돌 판정)의 정본은 `packages/core/src/keybinding.ts` 다.
// 이 파일은 두 가지만 책임진다:
// 1) 정본 좌표계(Windows VK / MouseButton) ↔ uiohook 이벤트 좌표계 변환
// 2) press / release · 더블프레스 · auto-repeat 런타임 상태 머신
//
// 런타임 상태는 액션 id 가 아니라 bindingKey() 로 키잉한다 —
// 한 액션에 여러 바인딩이 붙고, 여러 액션이 한 바인딩을 공유하기 때문이다.
import { EventEmitter } from 'events'
import { globalShortcut } from 'electron'
import { uIOhook, UiohookKey } from 'uiohook-napi'
import type { UiohookKeyboardEvent, UiohookMouseEvent } from 'uiohook-napi'
import { getLogger } from './LoggerService'
import { configGet } from './ConfigService'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { TIMING } from '@d3ro/core/constants'
import {
KEYBINDING_ACTIONS,
MouseButton,
VK,
bindingKey,
normalizeBinding
} from '@d3ro/core/keybinding'
import type {
KeyBinding,
KeyBindingActionId,
KeyBindingActionSpec,
MouseButtonCode
} from '@d3ro/core/types'
const logger = getLogger('KeyBindingService')
// ============================================================
// 이벤트 페이로드
// ============================================================
export interface KeyBindingTriggerPayload {
actionId: KeyBindingActionId
type: 'pressed' | 'released'
/** 더블프레스로 트리거된 누름인지 */
isDoublePress: boolean
/** KEYBINDING_ACTIONS 의 holdMode — 소비자가 hold-to-talk / 토글을 분기하는 데 쓴다 */
holdMode: boolean
timestamp: number
/** type === 'released' 일 때의 누름 유지 시간 (pressed 는 0) */
durationMs: number
}
interface KeyBindingServiceEvents {
triggered: (payload: KeyBindingTriggerPayload) => void
error: (payload: { error: D3ROError }) => void
}
// ============================================================
// Windows VK ↔ uiohook 키코드
// ============================================================
/**
* Windows Virtual-Key 코드 → uiohook-napi 키코드.
* 저장·IPC 의 KeyBinding.code 는 VK 이므로 uiohook 이벤트와 비교하려면 변환이 필요하다.
* 여기에 없는 키는 uiohook 이벤트로 관측할 수 없으므로 등록 시점에 건너뛴다.
*/
const VK_TO_UIOHOOK: ReadonlyMap<number, number> = new Map([
// 수정자 키
[VK.ShiftLeft, UiohookKey.Shift],
[VK.ShiftRight, UiohookKey.ShiftRight],
[VK.CtrlLeft, UiohookKey.Ctrl],
[VK.CtrlRight, UiohookKey.CtrlRight],
[VK.AltLeft, UiohookKey.Alt],
[VK.AltRight, UiohookKey.AltRight],
[VK.MetaLeft, UiohookKey.Meta],
[VK.MetaRight, UiohookKey.MetaRight],
// 기능 키 F1~F24
[0x70, UiohookKey.F1],
[0x71, UiohookKey.F2],
[0x72, UiohookKey.F3],
[0x73, UiohookKey.F4],
[0x74, UiohookKey.F5],
[0x75, UiohookKey.F6],
[0x76, UiohookKey.F7],
[0x77, UiohookKey.F8],
[0x78, UiohookKey.F9],
[0x79, UiohookKey.F10],
[0x7a, UiohookKey.F11],
[0x7b, UiohookKey.F12],
[0x7c, UiohookKey.F13],
[0x7d, UiohookKey.F14],
[0x7e, UiohookKey.F15],
[0x7f, UiohookKey.F16],
[0x80, UiohookKey.F17],
[0x81, UiohookKey.F18],
[0x82, UiohookKey.F19],
[0x83, UiohookKey.F20],
[0x84, UiohookKey.F21],
[0x85, UiohookKey.F22],
[0x86, UiohookKey.F23],
[0x87, UiohookKey.F24],
// 편집 키
[VK.Space, UiohookKey.Space],
[VK.Enter, UiohookKey.Enter],
[VK.Escape, UiohookKey.Escape],
[VK.Backspace, UiohookKey.Backspace],
[VK.Tab, UiohookKey.Tab],
[VK.CapsLock, UiohookKey.CapsLock],
// 내비게이션 키
[VK.Insert, UiohookKey.Insert],
[VK.Delete, UiohookKey.Delete],
[VK.Home, UiohookKey.Home],
[VK.End, UiohookKey.End],
[VK.PageUp, UiohookKey.PageUp],
[VK.PageDown, UiohookKey.PageDown],
[VK.ArrowLeft, UiohookKey.ArrowLeft],
[VK.ArrowUp, UiohookKey.ArrowUp],
[VK.ArrowRight, UiohookKey.ArrowRight],
[VK.ArrowDown, UiohookKey.ArrowDown],
// 알파벳 (VK_A=0x41 ~ VK_Z=0x5A)
[0x41, UiohookKey.A],
[0x42, UiohookKey.B],
[0x43, UiohookKey.C],
[0x44, UiohookKey.D],
[0x45, UiohookKey.E],
[0x46, UiohookKey.F],
[0x47, UiohookKey.G],
[0x48, UiohookKey.H],
[0x49, UiohookKey.I],
[0x4a, UiohookKey.J],
[0x4b, UiohookKey.K],
[0x4c, UiohookKey.L],
[0x4d, UiohookKey.M],
[0x4e, UiohookKey.N],
[0x4f, UiohookKey.O],
[0x50, UiohookKey.P],
[0x51, UiohookKey.Q],
[0x52, UiohookKey.R],
[0x53, UiohookKey.S],
[0x54, UiohookKey.T],
[0x55, UiohookKey.U],
[0x56, UiohookKey.V],
[0x57, UiohookKey.W],
[0x58, UiohookKey.X],
[0x59, UiohookKey.Y],
[0x5a, UiohookKey.Z],
// 숫자 (VK_0=0x30 ~ VK_9=0x39)
[0x30, UiohookKey['0']],
[0x31, UiohookKey['1']],
[0x32, UiohookKey['2']],
[0x33, UiohookKey['3']],
[0x34, UiohookKey['4']],
[0x35, UiohookKey['5']],
[0x36, UiohookKey['6']],
[0x37, UiohookKey['7']],
[0x38, UiohookKey['8']],
[0x39, UiohookKey['9']],
// 넘패드
[VK.Numpad0, UiohookKey.Numpad0],
[0x61, UiohookKey.Numpad1],
[0x62, UiohookKey.Numpad2],
[0x63, UiohookKey.Numpad3],
[0x64, UiohookKey.Numpad4],
[0x65, UiohookKey.Numpad5],
[0x66, UiohookKey.Numpad6],
[0x67, UiohookKey.Numpad7],
[0x68, UiohookKey.Numpad8],
[VK.Numpad9, UiohookKey.Numpad9],
[VK.NumpadMultiply, UiohookKey.NumpadMultiply],
[VK.NumpadAdd, UiohookKey.NumpadAdd],
[VK.NumpadSubtract, UiohookKey.NumpadSubtract],
[VK.NumpadDecimal, UiohookKey.NumpadDecimal],
[VK.NumpadDivide, UiohookKey.NumpadDivide],
// 문장부호
[VK.Semicolon, UiohookKey.Semicolon],
[VK.Equal, UiohookKey.Equal],
[VK.Comma, UiohookKey.Comma],
[VK.Minus, UiohookKey.Minus],
[VK.Period, UiohookKey.Period],
[VK.Slash, UiohookKey.Slash],
[VK.Backquote, UiohookKey.Backquote],
[VK.BracketLeft, UiohookKey.BracketLeft],
[VK.Backslash, UiohookKey.Backslash],
[VK.BracketRight, UiohookKey.BracketRight],
[VK.Quote, UiohookKey.Quote],
// 시스템 키
[VK.PrintScreen, UiohookKey.PrintScreen],
[VK.ScrollLock, UiohookKey.ScrollLock],
[VK.NumLock, UiohookKey.NumLock]
])
const UIOHOOK_TO_VK: ReadonlyMap<number, number> = new Map(
Array.from(VK_TO_UIOHOOK, ([vk, uiohookCode]) => [uiohookCode, vk] as const)
)
function isCtrlCode(code: number): boolean {
return code === UiohookKey.Ctrl || code === UiohookKey.CtrlRight
}
function isAltCode(code: number): boolean {
return code === UiohookKey.Alt || code === UiohookKey.AltRight
}
function isShiftCode(code: number): boolean {
return code === UiohookKey.Shift || code === UiohookKey.ShiftRight
}
function isMetaCode(code: number): boolean {
return code === UiohookKey.Meta || code === UiohookKey.MetaRight
}
// ============================================================
// 마우스 버튼 좁히기
// ============================================================
const MOUSE_BUTTON_CODES: readonly MouseButtonCode[] = [
MouseButton.Left,
MouseButton.Right,
MouseButton.Middle,
MouseButton.Back,
MouseButton.Forward
]
/**
* uiohook-napi 의 `UiohookMouseEvent.button` 은 타입이 `unknown` 이다.
* libuiohook 은 MOUSE_BUTTON1..5 를 숫자로 싣고 보내므로 여기서 좁힌다.
*/
function readMouseButton(event: UiohookMouseEvent): MouseButtonCode | null {
const raw: unknown = event.button
if (typeof raw !== 'number' || !Number.isInteger(raw)) return null
const found = MOUSE_BUTTON_CODES.find((code) => code === raw)
return found ?? null
}
// ============================================================
// Electron accelerator 변환 (macOS beep 차단 전용)
// ============================================================
function vkToAcceleratorKey(vk: number): string | null {
if (vk >= VK.Digit0 && vk <= VK.Digit9) return String.fromCharCode(vk)
if (vk >= VK.A && vk <= VK.Z) return String.fromCharCode(vk)
if (vk >= VK.F1 && vk <= VK.F24) return `F${vk - VK.F1 + 1}`
switch (vk) {
case VK.Space: return 'Space'
case VK.Enter: return 'Return'
case VK.Escape: return 'Esc'
case VK.Backspace: return 'Backspace'
case VK.Tab: return 'Tab'
case VK.Insert: return 'Insert'
case VK.Delete: return 'Delete'
case VK.Home: return 'Home'
case VK.End: return 'End'
case VK.PageUp: return 'PageUp'
case VK.PageDown: return 'PageDown'
case VK.ArrowLeft: return 'Left'
case VK.ArrowUp: return 'Up'
case VK.ArrowRight: return 'Right'
case VK.ArrowDown: return 'Down'
case VK.PrintScreen: return 'PrintScreen'
case VK.NumLock: return 'Numlock'
case VK.ScrollLock: return 'Scrolllock'
case VK.Semicolon: return ';'
case VK.Equal: return '='
case VK.Comma: return ','
case VK.Minus: return '-'
case VK.Period: return '.'
case VK.Slash: return '/'
case VK.Backquote: return '`'
case VK.BracketLeft: return '['
case VK.Backslash: return '\\'
case VK.BracketRight: return ']'
case VK.Quote: return "'"
default: return null
}
}
/**
* 키보드 바인딩 → Electron globalShortcut accelerator.
*
* globalShortcut 은 **macOS 시스템 beep 차단 용도로만** 쓴다.
* OS 가 키를 swallow 하게 만들어 focused app 으로 전달되지 않게 하고,
* 실제 press/release 처리는 uiohook 이 그대로 담당한다.
* 수정자 키 자체를 주 키로 쓰는 바인딩(예: Right Alt 단독)은 accelerator 로 표현할 수 없다.
*/
function bindingToAccelerator(binding: KeyBinding): string | null {
const key = vkToAcceleratorKey(binding.code)
if (key === null) return null
const parts: string[] = []
if (binding.ctrl) parts.push('Control')
if (binding.alt) parts.push('Alt')
if (binding.shift) parts.push('Shift')
if (binding.meta) parts.push(process.platform === 'darwin' ? 'Cmd' : 'Super')
parts.push(key)
return parts.join('+')
}
// ============================================================
// 내부 타입
// ============================================================
interface RegisteredBinding {
actionId: KeyBindingActionId
spec: KeyBindingActionSpec
/** 정본 좌표계 바인딩 (정규화 완료) */
binding: KeyBinding
/** keyboard → uiohook 키코드 / mouse → MouseButton 코드 */
eventCode: number
/** macOS beep 차단용 accelerator. 마우스 바인딩과 변환 불가 키는 null */
accelerator: string | null
}
interface ActiveTrigger {
actionId: KeyBindingActionId
isDoublePress: boolean
holdMode: boolean
}
// ============================================================
// KeyBindingService
// ============================================================
class KeyBindingService extends EventEmitter {
private _isRunning = false
/** bindingKey → 그 바인딩을 쓰는 액션들. 매칭은 이 역인덱스 조회로 끝난다. */
private _byBindingKey: Map<string, RegisteredBinding[]> = new Map()
/** 이 서비스가 직접 등록한 accelerator만 추적한다 (다른 곳의 등록을 해제하지 않기 위해) */
private _ownedAccelerators: Set<string> = new Set()
/** 키 반복(auto-repeat) 방지: 현재 눌려있는 바인딩 */
private _isKeyDown: Map<string, boolean> = new Map()
/** hold duration 계산용: press 시작 시각 */
private _pressStartTime: Map<string, number> = new Map()
/** 더블프레스 감지용: 마지막 press 시각 */
private _lastPressTime: Map<string, number> = new Map()
/** 현재 누름에서 실제로 트리거된 액션 — release 를 같은 대상에게만 보낸다 */
private _activeTriggers: Map<string, ActiveTrigger[]> = new Map()
private _onKeyDown: ((e: UiohookKeyboardEvent) => void) | null = null
private _onKeyUp: ((e: UiohookKeyboardEvent) => void) | null = null
private _onMouseDown: ((e: UiohookMouseEvent) => void) | null = null
private _onMouseUp: ((e: UiohookMouseEvent) => void) | null = null
get isRunning(): boolean {
return this._isRunning
}
/** 등록된 바인딩 수 (bindingKey 기준) */
get registeredBindingCount(): number {
return this._byBindingKey.size
}
// ── 수명 주기 ──────────────────────────────────────────
/**
* uiohook 글로벌 후킹을 시작한다. 이미 실행 중이면 무시.
*
* mousemove / wheel / click 은 구독하지 않는다 — 고빈도이고 바인딩 대상이 아니다.
*/
start(): void {
if (this._isRunning) {
logger.warn('KeyBindingService already running')
return
}
try {
this._onKeyDown = (e: UiohookKeyboardEvent) => this._handleKeyDown(e)
this._onKeyUp = (e: UiohookKeyboardEvent) => this._handleKeyUp(e)
this._onMouseDown = (e: UiohookMouseEvent) => this._handleMouseDown(e)
this._onMouseUp = (e: UiohookMouseEvent) => this._handleMouseUp(e)
uIOhook.on('keydown', this._onKeyDown)
uIOhook.on('keyup', this._onKeyUp)
uIOhook.on('mousedown', this._onMouseDown)
uIOhook.on('mouseup', this._onMouseUp)
uIOhook.start()
this._isRunning = true
this._syncAccelerators()
logger.info('uiohook started, global keyboard/mouse hook active')
} catch (error) {
const d3roError = new D3ROError(
ErrorCode.HotkeyHookInitFailed,
`Failed to start uiohook: ${error instanceof Error ? error.message : String(error)}`
)
this.emit('error', { error: d3roError })
logger.error(d3roError.message)
}
}
/** uiohook 글로벌 후킹을 중지한다. 이 서비스가 등록한 accelerator만 해제한다. */
stop(): void {
if (!this._isRunning) return
try {
uIOhook.stop()
if (this._onKeyDown) {
uIOhook.removeListener('keydown', this._onKeyDown)
this._onKeyDown = null
}
if (this._onKeyUp) {
uIOhook.removeListener('keyup', this._onKeyUp)
this._onKeyUp = null
}
if (this._onMouseDown) {
uIOhook.removeListener('mousedown', this._onMouseDown)
this._onMouseDown = null
}
if (this._onMouseUp) {
uIOhook.removeListener('mouseup', this._onMouseUp)
this._onMouseUp = null
}
this._isRunning = false
this._clearRuntimeState()
this._unregisterOwnedAccelerators()
logger.info('uiohook stopped')
} catch (error) {
logger.error(
`Failed to stop uiohook: ${error instanceof Error ? error.message : String(error)}`
)
}
}
dispose(): void {
this.stop()
this._byBindingKey.clear()
this._unregisterOwnedAccelerators()
this._clearRuntimeState()
this.removeAllListeners()
logger.info('KeyBindingService disposed')
}
// ── 등록 ───────────────────────────────────────────────
/** ConfigService 의 keyBindings 를 읽어 역인덱스를 다시 만든다. */
loadFromConfig(): void {
this._byBindingKey.clear()
this._clearRuntimeState()
if (!configGet('hotkeyEnabled')) {
this._unregisterOwnedAccelerators()
logger.info('Key bindings disabled in config')
return
}
const map = configGet('keyBindings')
for (const spec of KEYBINDING_ACTIONS) {
for (const raw of map[spec.id] ?? []) {
this._register(spec, raw)
}
}
this._syncAccelerators()
logger.info(
`Loaded ${this._byBindingKey.size} key binding(s) from config ` +
`for ${KEYBINDING_ACTIONS.length} action(s)`
)
}
private _register(spec: KeyBindingActionSpec, raw: KeyBinding): void {
const binding = normalizeBinding(raw)
let eventCode: number | null
if (binding.device === 'mouse') {
eventCode = binding.code
} else {
eventCode = VK_TO_UIOHOOK.get(binding.code) ?? null
}
if (eventCode === null) {
logger.warn(
`Key code 0x${binding.code.toString(16)} has no uiohook equivalent ` +
`— binding for action "${spec.id}" is not registered`
)
return
}
const key = bindingKey(binding)
const entry: RegisteredBinding = {
actionId: spec.id,
spec,
binding,
eventCode,
accelerator: binding.device === 'keyboard' ? bindingToAccelerator(binding) : null
}
const existing = this._byBindingKey.get(key)
if (existing === undefined) {
this._byBindingKey.set(key, [entry])
return
}
// 같은 액션이 같은 바인딩을 두 번 들고 있으면 한 번 누를 때 두 번 트리거된다.
if (existing.some((registered) => registered.actionId === spec.id)) return
existing.push(entry)
}
// ── accelerator (macOS beep 차단) ──────────────────────
private _syncAccelerators(): void {
this._unregisterOwnedAccelerators()
if (!this._isRunning) return
for (const entries of this._byBindingKey.values()) {
// 같은 bindingKey 를 공유하는 엔트리는 바인딩이 동일하므로 accelerator 도 같다.
const accelerator = entries[0]?.accelerator
if (accelerator === undefined || accelerator === null) continue
if (this._ownedAccelerators.has(accelerator)) continue
try {
const ok = globalShortcut.register(accelerator, () => {
// noop — press/release 는 uiohook 이 책임진다. 등록 목적은 OS 의 키 swallow 다.
})
if (ok) {
this._ownedAccelerators.add(accelerator)
} else {
logger.warn(`globalShortcut.register returned false for "${accelerator}"`)
}
} catch (err) {
logger.warn(
`globalShortcut.register failed for "${accelerator}": ${err instanceof Error ? err.message : String(err)}`
)
}
}
}
private _unregisterOwnedAccelerators(): void {
for (const accelerator of this._ownedAccelerators) {
try {
globalShortcut.unregister(accelerator)
} catch (err) {
logger.warn(
`globalShortcut.unregister failed for "${accelerator}": ${err instanceof Error ? err.message : String(err)}`
)
}
}
this._ownedAccelerators.clear()
}
private _clearRuntimeState(): void {
this._isKeyDown.clear()
this._pressStartTime.clear()
this._lastPressTime.clear()
this._activeTriggers.clear()
}
// ── 이벤트 → 바인딩 매칭 ───────────────────────────────
/**
* uiohook 이벤트를 정본 좌표계 bindingKey 로 옮긴다.
* normalizeBinding 이 "주 키가 수정자 자신"인 경우를 정리하므로
* Right Alt 단독 바인딩도 그대로 매칭된다.
*/
private _keyboardEventKey(e: UiohookKeyboardEvent): string | null {
const vk = UIOHOOK_TO_VK.get(e.keycode)
if (vk === undefined) return null
return bindingKey({
device: 'keyboard',
code: vk,
ctrl: e.ctrlKey,
alt: e.altKey,
shift: e.shiftKey,
meta: e.metaKey
})
}
private _mouseEventKey(e: UiohookMouseEvent): string | null {
const button = readMouseButton(e)
if (button === null) return null
return bindingKey({
device: 'mouse',
code: button,
ctrl: e.ctrlKey,
alt: e.altKey,
shift: e.shiftKey,
meta: e.metaKey
})
}
private _handleKeyDown(e: UiohookKeyboardEvent): void {
const key = this._keyboardEventKey(e)
if (key === null) return
this._handlePress(key)
}
private _handleMouseDown(e: UiohookMouseEvent): void {
const key = this._mouseEventKey(e)
if (key === null) return
this._handlePress(key)
}
/**
* 키 업.
* Alt+1 같은 조합에서 수정자를 먼저 놓아도 release 를 놓치지 않아야 하므로,
* 정확 매칭이 실패하면 눌림 상태인 바인딩의 구성 키가 놓였는지도 확인한다.
*/
private _handleKeyUp(e: UiohookKeyboardEvent): void {
const key = this._keyboardEventKey(e)
if (key !== null && this._isKeyDown.get(key) === true) {
this._fireRelease(key)
return
}
this._releaseByComponentKey(e.keycode)
}
private _handleMouseUp(e: UiohookMouseEvent): void {
const key = this._mouseEventKey(e)
if (key !== null && this._isKeyDown.get(key) === true) {
this._fireRelease(key)
}
}
/** 눌림 상태인 바인딩 중 놓인 키가 주 키/수정자인 것을 release 시킨다. */
private _releaseByComponentKey(uiohookCode: number): void {
for (const [key, entries] of this._byBindingKey) {
if (this._isKeyDown.get(key) !== true) continue
const entry = entries[0]
if (entry === undefined) continue
const isMainKey =
entry.binding.device === 'keyboard' && entry.eventCode === uiohookCode
if (isMainKey || this._isModifierComponent(uiohookCode, entry.binding)) {
this._fireRelease(key)
return
}
}
}
private _isModifierComponent(uiohookCode: number, binding: KeyBinding): boolean {
if (binding.ctrl && isCtrlCode(uiohookCode)) return true
if (binding.alt && isAltCode(uiohookCode)) return true
if (binding.shift && isShiftCode(uiohookCode)) return true
if (binding.meta && isMetaCode(uiohookCode)) return true
return false
}
// ── press / release ────────────────────────────────────
private _handlePress(key: string): void {
const entries = this._byBindingKey.get(key)
if (entries === undefined || entries.length === 0) return
// 키 반복(auto-repeat) 무시
if (this._isKeyDown.get(key) === true) return
this._isKeyDown.set(key, true)
const now = Date.now()
this._pressStartTime.set(key, now)
// 더블프레스 감지는 이 바인딩을 쓰는 액션 중 하나라도 doublePress 일 때만 한다.
// 그렇지 않으면 단일프레스 액션을 빠르게 두 번 누를 때 두 번째가 삼켜진다.
let isDoublePress = false
if (entries.some((entry) => entry.spec.doublePress)) {
const lastPress = this._lastPressTime.get(key)
isDoublePress =
lastPress !== undefined && now - lastPress < TIMING.DOUBLE_PRESS_DURATION
if (isDoublePress) {
this._lastPressTime.delete(key)
} else {
this._lastPressTime.set(key, now)
}
}
// dictation(단일) 과 hands-free(더블) 는 같은 바인딩을 공유한다 —
// 첫 매치만 반환하지 않고 doublePress 여부로 갈라 해당하는 액션을 모두 트리거한다.
const triggers: ActiveTrigger[] = []
for (const entry of entries) {
if (entry.spec.doublePress !== isDoublePress) continue
triggers.push({
actionId: entry.actionId,
isDoublePress,
holdMode: entry.spec.holdMode
})
}
this._activeTriggers.set(key, triggers)
for (const trigger of triggers) {
logger.debug(`Key binding pressed: "${trigger.actionId}" (double=${isDoublePress})`)
this.emit('triggered', {
actionId: trigger.actionId,
type: 'pressed',
isDoublePress: trigger.isDoublePress,
holdMode: trigger.holdMode,
timestamp: now,
durationMs: 0
})
}
}
private _fireRelease(key: string): void {
this._isKeyDown.set(key, false)
const now = Date.now()
const pressStart = this._pressStartTime.get(key)
const durationMs = pressStart !== undefined ? now - pressStart : 0
this._pressStartTime.delete(key)
const triggers = this._activeTriggers.get(key) ?? []
this._activeTriggers.delete(key)
for (const trigger of triggers) {
logger.debug(
`Key binding released: "${trigger.actionId}" (duration=${durationMs}ms)`
)
this.emit('triggered', {
actionId: trigger.actionId,
type: 'released',
isDoublePress: trigger.isDoublePress,
holdMode: trigger.holdMode,
timestamp: now,
durationMs
})
}
}
// ── EventEmitter 타입 오버라이드 ───────────────────────
override on<K extends keyof KeyBindingServiceEvents>(
event: K,
listener: KeyBindingServiceEvents[K]
): this {
return super.on(event, listener)
}
override off<K extends keyof KeyBindingServiceEvents>(
event: K,
listener: KeyBindingServiceEvents[K]
): this {
return super.off(event, listener)
}
override emit<K extends keyof KeyBindingServiceEvents>(
event: K,
...args: Parameters<KeyBindingServiceEvents[K]>
): boolean {
return super.emit(event, ...args)
}
}
// ============================================================
// 싱글톤
// ============================================================
let instance: KeyBindingService | null = null
export function getKeyBindingService(): KeyBindingService {
if (!instance) {
instance = new KeyBindingService()
}
return instance
}

View file

@ -13,15 +13,15 @@ import { getAudioCaptureService } from './AudioCaptureService'
import { getLocalSTTService } from './LocalSTTService'
import type { TranscriptionResult } from './LocalSTTService'
import { getSTTManager } from './stt/STTManager'
import { getHotkeyService } from './HotkeyService'
import type { HotkeyConfig } from './HotkeyService'
import { getKeyBindingService } from './KeyBindingService'
import type { KeyBindingTriggerPayload } from './KeyBindingService'
import { configGet } from './ConfigService'
import { getTextInsertService } from './TextInsertService'
import { getLocalLLMService } from './LocalLLMService'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { TIMING } from '@d3ro/core/constants'
import { RecognitionState, AudioState } from '@d3ro/core/types'
import type { VoiceMode, VoiceState, LLMAction } from '@d3ro/core/types'
import type { KeyBindingActionId, VoiceMode, VoiceState, LLMAction } from '@d3ro/core/types'
import {
showRecordingTip,
hideRecordingTip,
@ -55,7 +55,9 @@ interface VoiceAction {
type: 'press' | 'release' | 'escape'
timestamp: number
mode: VoiceMode
hotkeyId: string
actionId: KeyBindingActionId
/** hold-to-talk 여부 — release 에서 세션을 끊을지 결정한다 */
holdMode: boolean
}
interface VoiceModeEvents {
@ -147,9 +149,7 @@ class VoiceModeService extends EventEmitter {
// 리스너 해제용 참조
private _audioDataHandler: ((payload: { buffer: Buffer }) => void) | null = null
private _audioLevelHandler: ((payload: { level: number }) => void) | null = null
private _hotkeyPressHandler: ((payload: { config: HotkeyConfig; timestamp: number }) => void) | null = null
private _hotkeyReleaseHandler: ((payload: { config: HotkeyConfig; durationMs: number; timestamp: number }) => void) | null = null
private _doublePressHandler: ((payload: { config: HotkeyConfig }) => void) | null = null
private _keyBindingHandler: ((payload: KeyBindingTriggerPayload) => void) | null = null
private _disposed = false
@ -174,39 +174,39 @@ class VoiceModeService extends EventEmitter {
// ── 초기화 ──────────────────────────────────────────────
/**
* HotkeyService 이벤트를 구독하여 핫키 → 세션 제어를 연결한다.
* KeyBindingService 이벤트를 구독하여 키바인딩 → 세션 제어를 연결한다.
* bootstrap에서 호출한다.
*/
connectHotkey(): void {
const hotkey = getHotkeyService()
this._hotkeyPressHandler = (payload) => {
// Phase 10.1: caption 핫키는 VoiceModeService가 아닌 CaptionService로 라우팅
if (payload.config.id === 'voice-caption') {
this._toggleCaption()
return
connectKeyBindings(): void {
this._keyBindingHandler = (payload) => {
switch (payload.actionId) {
case 'caption':
// Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅.
// 토글이므로 press만 처리하고 release는 버린다.
if (payload.type === 'pressed') this._toggleCaption()
return
case 'history-popup':
case 'command-popup':
// 팝업 액션은 bootstrap이 직접 구독한다.
return
default:
break
}
const mode = this._resolveMode(payload.config)
this._enqueueAction({ type: 'press', timestamp: payload.timestamp, mode, hotkeyId: payload.config.id })
const holdMode = this._resolveHoldMode(payload.actionId, payload.holdMode)
const action: VoiceAction = {
type: payload.type === 'pressed' ? 'press' : 'release',
timestamp: payload.timestamp,
mode: this._resolveMode(payload.actionId, payload.isDoublePress),
actionId: payload.actionId,
holdMode
}
this._enqueueAction(action)
}
this._hotkeyReleaseHandler = (payload) => {
// caption 핫키의 release는 무시 (토글 방식)
if (payload.config.id === 'voice-caption') return
const mode = this._resolveMode(payload.config)
this._enqueueAction({ type: 'release', timestamp: payload.timestamp, mode, hotkeyId: payload.config.id })
}
getKeyBindingService().on('triggered', this._keyBindingHandler)
this._doublePressHandler = (payload) => {
// 더블프레스 → hands-free 모드 토글
this._enqueueAction({ type: 'press', timestamp: Date.now(), mode: 'hands-free', hotkeyId: payload.config.id })
}
hotkey.on('hotkey-pressed', this._hotkeyPressHandler)
hotkey.on('hotkey-released', this._hotkeyReleaseHandler)
hotkey.on('double-press', this._doublePressHandler)
logger.info('Hotkey events connected')
logger.info('Key binding events connected')
}
// ── 세션 제어 ──────────────────────────────────────────
@ -1050,24 +1050,34 @@ class VoiceModeService extends EventEmitter {
}
}
private async _handleRelease(_action: VoiceAction): Promise<void> {
if (_action.mode === 'dictation' && this.isActive) {
private async _handleRelease(action: VoiceAction): Promise<void> {
if (action.holdMode && action.mode === 'dictation' && this.isActive) {
// Dictation: hold-to-talk — release로 즉시 종료
// Speakly 패턴: 딜레이 없이 즉시 stop (딜레이가 race condition 유발)
await this.stopSession()
}
// HandsFree: release 무시
// HandsFree(토글): release 무시
}
// ── 유틸리티 ───────────────────────────────────────────
private _resolveMode(config: HotkeyConfig): VoiceMode {
if (config.id === 'voice-handsfree' || config.doublePressEnabled) {
private _resolveMode(actionId: KeyBindingActionId, isDoublePress: boolean): VoiceMode {
if (actionId === 'hands-free' || isDoublePress) {
return 'hands-free'
}
return 'dictation'
}
/**
* 'command' 액션에는 아직 전용 핸들러가 없다.
* 현행 동작대로 dictation 파이프라인으로 fallback 하며, 그 경로는 hold-to-talk 이므로
* KEYBINDING_ACTIONS 의 holdMode(false)가 아니라 dictation 과 같은 값을 쓴다.
*/
private _resolveHoldMode(actionId: KeyBindingActionId, specHoldMode: boolean): boolean {
if (actionId === 'command') return true
return specHoldMode
}
// ── 자막 모드 토글 (Phase 10.1) ─────────────────────────
private async _toggleCaption(): Promise<void> {
@ -1111,16 +1121,10 @@ class VoiceModeService extends EventEmitter {
this._cancelSession('user')
}
// 핫키 리스너 해제
const hotkey = getHotkeyService()
if (this._hotkeyPressHandler) {
hotkey.off('hotkey-pressed', this._hotkeyPressHandler)
}
if (this._hotkeyReleaseHandler) {
hotkey.off('hotkey-released', this._hotkeyReleaseHandler)
}
if (this._doublePressHandler) {
hotkey.off('double-press', this._doublePressHandler)
// 키바인딩 리스너 해제
if (this._keyBindingHandler) {
getKeyBindingService().off('triggered', this._keyBindingHandler)
this._keyBindingHandler = null
}
// 오디오 리스너 해제