244 lines
7.5 KiB
TypeScript
244 lines
7.5 KiB
TypeScript
// src/main/ipc/keybinding-handlers.ts
|
|
//
|
|
// 키바인딩 IPC. 액션을 파라미터로 받는 단일 채널 집합이며,
|
|
// 검증·충돌 판정은 전부 `packages/core/src/keybinding.ts` 의 함수를 쓴다.
|
|
|
|
import { ipcMain } from 'electron'
|
|
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
|
import { broadcastToAllWindows } from './renderer-broadcast'
|
|
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
|
import {
|
|
bindingKey,
|
|
createDefaultBindingMap,
|
|
detectBindingConflicts,
|
|
findActionSpec,
|
|
isKeyBinding,
|
|
isKeyBindingActionId,
|
|
normalizeBinding,
|
|
validateBinding
|
|
} from '@d3ro/core/keybinding'
|
|
import { getKeyBindingService } from '../services/KeyBindingService'
|
|
import type { KeyBindingTriggerPayload } from '../services/KeyBindingService'
|
|
import {
|
|
configGet,
|
|
configSet,
|
|
loadKeyBindings,
|
|
saveKeyBindings
|
|
} 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 {
|
|
broadcastToAllWindows(channel, payload)
|
|
}
|
|
|
|
/** 바인딩 맵 변경을 모든 창에 알린다 (창 간 동기화). */
|
|
function broadcastChanged(map: KeyBindingMap): void {
|
|
const event: KeyBindingChangedEvent = { map }
|
|
broadcast(IPC_CHANNELS.KEYBINDING.CHANGED, event)
|
|
}
|
|
|
|
/**
|
|
* 저장된 맵을 읽는다. 손상·누락 항목은 기본값으로 복원하고, 사용자가 비운 액션(`[]`)은
|
|
* 비운 그대로 둔다 — 다른 액션을 고칠 때 지운 단축키가 되살아나지 않도록.
|
|
*/
|
|
function readMap(): KeyBindingMap {
|
|
return loadKeyBindings()
|
|
}
|
|
|
|
/** 맵을 저장하고 후킹 서비스에 다시 태운 뒤 창에 알린다. */
|
|
function applyMap(map: KeyBindingMap): void {
|
|
const saved = saveKeyBindings(map)
|
|
getKeyBindingService().loadFromConfig()
|
|
broadcastChanged(saved)
|
|
}
|
|
|
|
/** 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)
|
|
}
|
|
)
|
|
}
|