From de1eb1f92f80e523bd262227576b5e3f2beb5cde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:44:30 +0800 Subject: [PATCH] feat(input,guesttools,ui): add per-VM Windows modifier key remapping and Win-to-Command support --- frontend/scripts/test-i18n.mjs | 74 ++++++ frontend/src/components/SettingsModal.tsx | 99 ++++++++ frontend/src/i18n/domains/settings.gen.ts | 60 +++++ frontend/src/i18n/keys.gen.ts | 30 +++ frontend/src/types.ts | 19 ++ frontend/src/wails.ts | 4 +- frontend/wailsjs/go/app/App.d.ts | 4 + frontend/wailsjs/go/app/App.js | 8 + frontend/wailsjs/go/models.ts | 47 ++++ internal/app/app.go | 14 +- internal/app/guesttools_flow.go | 4 + internal/app/keymap_flow.go | 141 +++++++++++ internal/app/keymap_flow_test.go | 32 +++ internal/app/plugins_flow.go | 50 ++-- internal/guesttools/clipboard_agent_test.go | 2 +- internal/guesttools/image.go | 102 +++++++- internal/guesttools/keymap_agent_test.go | 179 ++++++++++++++ internal/guesttools/server.go | 95 +++++--- internal/host/ime_hook_windows.go | 23 +- internal/host/input_service.go | 122 ++++++++-- internal/host/input_service_windows.go | 13 +- internal/host/keymap.go | 249 ++++++++++++++++++++ internal/host/keymap_other.go | 9 + internal/host/keymap_test.go | 192 +++++++++++++++ internal/host/keymap_windows.go | 225 ++++++++++++++++++ internal/vmstart/keymap.go | 159 +++++++++++++ internal/vmstart/keymap_test.go | 60 +++++ locales/en-US/settings.json | 30 +++ locales/zh-CN/settings.json | 30 +++ 29 files changed, 1988 insertions(+), 88 deletions(-) create mode 100644 internal/app/keymap_flow.go create mode 100644 internal/app/keymap_flow_test.go create mode 100644 internal/guesttools/keymap_agent_test.go create mode 100644 internal/host/keymap.go create mode 100644 internal/host/keymap_other.go create mode 100644 internal/host/keymap_test.go create mode 100644 internal/host/keymap_windows.go create mode 100644 internal/vmstart/keymap.go create mode 100644 internal/vmstart/keymap_test.go diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 6539187..07dabb8 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -250,3 +250,77 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr assert.equal(appleBlue['--accent-text'], '#ffffff') assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`) }) + + +test('VM keymap preserves preset bindings and isolates pending writes by VM', async () => { + const source = fs.readFileSync(path.join(srcDir, 'components/SettingsModal.tsx'), 'utf8') + const normalized = source.replaceAll('\r\n', '\n') + const effects = normalized.slice( + normalized.indexOf(' useEffect(() => {\n setKeymap(null)'), + normalized.indexOf(' const updateDriveShares'), + ) + const preset = normalized.match(/onChange=\{(\(preset\) => \{\n\s+if \(preset === keymap\.preset\)[\s\S]*?\n\s+\})\} \/>/)?.[1] + assert.ok(effects.includes('const updateKeymap') && preset) + const { render } = await loadBundledTS(` + export function render({ detail, api, useEffect, window, activeVMNameRef, keymapWrite, + keymapRevision, setKeymap, setKeymapErr, setKeymapBusy, parseAppError, keymap }) { + const cat = 'input' + const running = true + ${effects} + return ${preset} + } + `) + let finishWrite + const writes = [] + const reads = [] + const state = {} + let failRead = true + const context = { + api: { + SetVMKeymap(name, req) { + writes.push([name, req]) + return new Promise((resolve) => { finishWrite = resolve }) + }, + async GetVMKeymap(name) { + reads.push(name) + if (name === 'b' && failRead) throw Error('temporary') + return { preset: 'off', bindings: {} } + }, + }, + useEffect(effect) { + const cleanup = effect() + if (cleanup) this.cleanups.push(cleanup) + }, + cleanups: [], + window: { setInterval(refresh) { this.refresh = refresh }, clearInterval() {} }, + activeVMNameRef: { current: 'a' }, + keymapWrite: { current: new Set() }, + keymapRevision: { current: new Map() }, + setKeymap(value) { state.keymap = value }, + setKeymapErr(value) { state.error = value }, + setKeymapBusy(value) { state.busy = value }, + parseAppError: (error) => ({ summary: error.message }), + } + context.useEffect = context.useEffect.bind(context) + const bindings = { lwin: 'lcmd' } + const change = render({ ...context, detail: { name: 'a' }, keymap: { preset: 'win_to_cmd', bindings } }) + change('win_to_cmd') + assert.deepEqual(writes, []) + change('custom') + assert.deepEqual(writes, [['a', { preset: 'custom', bindings }]]) + context.cleanups.pop()() + context.activeVMNameRef.current = 'b' + const changeB = render({ ...context, detail: { name: 'b' }, keymap: { preset: 'custom', bindings } }) + changeB('custom') + assert.equal(writes.length, 1) + assert.deepEqual(reads, ['a', 'b']) + assert.equal(state.busy, false) + await new Promise(setImmediate) + assert.equal(state.error, 'temporary') + failRead = false + await context.window.refresh() + assert.equal(state.error, '') + finishWrite({ preset: 'custom', bindings }) + await new Promise(setImmediate) + assert.deepEqual(state.keymap, { preset: 'off', bindings: {} }) +}) diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 7eaee4d..fe19874 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -31,6 +31,7 @@ import { Modal } from '../ui/dialog' import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings' import { api } from '../wails' import { formatAffinitySummary } from './AffinityDialog' +import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier, VMKeymapStatus, VMKeymapUpdate } from '../types' const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) @@ -159,6 +160,11 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op activeVMNameRef.current = detail.name const [driveErr, setDriveErr] = useState('') const [affinityStatus, setAffinityStatus] = useState(null) + const [keymap, setKeymap] = useState(null) + const [keymapErr, setKeymapErr] = useState('') + const [keymapBusy, setKeymapBusy] = useState(false) + const keymapWrite = useRef(new Set()) + const keymapRevision = useRef(new Map()) const [vmPlugins, setVmPlugins] = useState([]) const [vmPluginVals, setVmPluginVals] = useState>>({}) const pane = useRef(null) @@ -281,6 +287,53 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op return () => { active = false } }, [detail.name, running, affinityVersion]) + useEffect(() => { + setKeymap(null) + setKeymapBusy(keymapWrite.current.has(detail.name)) + setKeymapErr('') + }, [detail.name]) + + useEffect(() => { + if (cat !== 'input') return + let active = true + let pending = false + const refresh = async () => { + if (pending || keymapWrite.current.has(detail.name)) return + const revision = keymapRevision.current.get(detail.name) + pending = true + try { + const next = await api.GetVMKeymap(detail.name) + if (active && revision === keymapRevision.current.get(detail.name)) { + setKeymap(next) + setKeymapErr('') + } + } catch (e) { + if (active && revision === keymapRevision.current.get(detail.name)) setKeymapErr(parseAppError(e).summary) + } finally { + pending = false + } + } + void refresh() + const timer = window.setInterval(refresh, 3000) + return () => { active = false; window.clearInterval(timer) } + }, [cat, detail.name, running]) + + const updateKeymap = (req: VMKeymapUpdate) => { + const name = detail.name + if (keymapWrite.current.has(name)) return + keymapRevision.current.set(name, (keymapRevision.current.get(name) ?? 0) + 1) + keymapWrite.current.add(name) + setKeymapBusy(true) + setKeymapErr('') + void api.SetVMKeymap(name, req) + .then((next) => { if (activeVMNameRef.current === name) setKeymap(next) }) + .catch((e) => { if (activeVMNameRef.current === name) setKeymapErr(parseAppError(e).summary) }) + .finally(() => { + keymapWrite.current.delete(name) + if (activeVMNameRef.current === name) setKeymapBusy(false) + }) + } + const updateDriveShares = async (enabled: boolean, selected: string[]) => { if (driveBusyRef.current || !driveSettings) return driveBusyRef.current = true @@ -916,6 +969,52 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op control={ set({ capture })} />} /> + + {keymapErr &&
{keymapErr}
} + {keymap && <> + label={tr('keymapPresetTitle')} value={keymap.preset} + options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]} + onChange={(preset) => { + if (preset === keymap.preset) return + updateKeymap({ preset, bindings: preset === 'custom' && keymap.preset !== 'off' ? keymap.bindings : {} }) + }} />} + /> + {keymap.preset === 'custom' && ([ + ['lwin', 'keymapHostLwin'], + ['rwin', 'keymapHostRwin'], + ['lalt', 'keymapHostLalt'], + ['ralt', 'keymapHostRalt'], + ['lctrl', 'keymapHostLctrl'], + ['rctrl', 'keymapHostRctrl'], + ['capslock', 'keymapHostCapslock'], + ] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => ( + label={tr(label)} value={keymap.bindings[modifier] ?? 'default'} + options={[ + { value: 'default', label: tr('keymapGuestDefault') }, + { value: 'lcmd', label: tr('keymapGuestLcmd') }, + { value: 'rcmd', label: tr('keymapGuestRcmd') }, + { value: 'lopt', label: tr('keymapGuestLopt') }, + { value: 'ropt', label: tr('keymapGuestRopt') }, + { value: 'lctrl', label: tr('keymapGuestLctrl') }, + { value: 'rctrl', label: tr('keymapGuestRctrl') }, + { value: 'esc', label: tr('keymapGuestEsc') }, + { value: 'disabled', label: tr('keymapGuestDisabled') }, + ]} + onChange={(target) => updateKeymap({ preset: 'custom', bindings: { ...keymap.bindings, [modifier]: target } })} />} + /> + ))} + } +
{renderVMPluginGroup('keyboard')} = { "kernelIrqchipLabel": "中断加速", "kernelIrqchipOff": "关闭", "kernelIrqchipOn": "开启", + "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。", + "keymapGroupTitle": "修饰键映射", + "keymapGuestDefault": "默认", + "keymapGuestDisabled": "禁用", + "keymapGuestEsc": "Esc", + "keymapGuestLcmd": "左 ⌘ Command", + "keymapGuestLctrl": "左 ⌃ Control", + "keymapGuestLopt": "左 ⌥ Option", + "keymapGuestRcmd": "右 ⌘ Command", + "keymapGuestRctrl": "右 ⌃ Control", + "keymapGuestRopt": "右 ⌥ Option", + "keymapHostCapslock": "Caps Lock", + "keymapHostLalt": "左 Alt", + "keymapHostLctrl": "左 Ctrl", + "keymapHostLwin": "左 Win", + "keymapHostRalt": "右 Alt", + "keymapHostRctrl": "右 Ctrl", + "keymapHostRwin": "右 Win", + "keymapInactive": "修饰键映射未启用", + "keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射", + "keymapPending": "等待 Guest Tools 启用修饰键映射", + "keymapPresetCustom": "自定义", + "keymapPresetOff": "关闭", + "keymapPresetSwapAltWin": "Alt ↔ Win", + "keymapPresetTitle": "映射预设", + "keymapPresetWinToCmd": "Win → ⌘", + "keymapRunning": "虚拟机获得焦点时生效", + "keymapStopped": "虚拟机启动后生效", + "keymapUpgrade": "请将 Guest Tools 更新到版本 {version}", + "keymapWaiting": "等待 Guest Tools 连接", "language": "语言", "languageSub": "内置简体中文与英语,可通过插件扩展更多语言", "logLevel": "日志级别", @@ -535,6 +565,36 @@ export const settingsEn: Record = { "kernelIrqchipLabel": "Interrupt acceleration", "kernelIrqchipOff": "Off", "kernelIrqchipOn": "On", + "keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.", + "keymapGroupTitle": "Modifier keys", + "keymapGuestDefault": "Default", + "keymapGuestDisabled": "Disabled", + "keymapGuestEsc": "Esc", + "keymapGuestLcmd": "Left ⌘ Command", + "keymapGuestLctrl": "Left ⌃ Control", + "keymapGuestLopt": "Left ⌥ Option", + "keymapGuestRcmd": "Right ⌘ Command", + "keymapGuestRctrl": "Right ⌃ Control", + "keymapGuestRopt": "Right ⌥ Option", + "keymapHostCapslock": "Caps Lock", + "keymapHostLalt": "Left Alt", + "keymapHostLctrl": "Left Ctrl", + "keymapHostLwin": "Left Win", + "keymapHostRalt": "Right Alt", + "keymapHostRctrl": "Right Ctrl", + "keymapHostRwin": "Right Win", + "keymapInactive": "Modifier mapping is inactive", + "keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping", + "keymapPending": "Waiting for Guest Tools to activate modifier mapping", + "keymapPresetCustom": "Custom", + "keymapPresetOff": "Off", + "keymapPresetSwapAltWin": "Alt ↔ Win", + "keymapPresetTitle": "Preset", + "keymapPresetWinToCmd": "Win → ⌘", + "keymapRunning": "Active while this VM is focused", + "keymapStopped": "Applies when this VM is running", + "keymapUpgrade": "Update Guest Tools to version {version}", + "keymapWaiting": "Waiting for Guest Tools to connect", "language": "Language", "languageSub": "Simplified Chinese and English built in; add more via plugins", "logLevel": "Log level", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..7897ab7 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -397,6 +397,36 @@ export type I18nKey = | "kernelIrqchipLabel" | "kernelIrqchipOff" | "kernelIrqchipOn" + | "keymapGroupNote" + | "keymapGroupTitle" + | "keymapGuestDefault" + | "keymapGuestDisabled" + | "keymapGuestEsc" + | "keymapGuestLcmd" + | "keymapGuestLctrl" + | "keymapGuestLopt" + | "keymapGuestRcmd" + | "keymapGuestRctrl" + | "keymapGuestRopt" + | "keymapHostCapslock" + | "keymapHostLalt" + | "keymapHostLctrl" + | "keymapHostLwin" + | "keymapHostRalt" + | "keymapHostRctrl" + | "keymapHostRwin" + | "keymapInactive" + | "keymapInputServiceRequired" + | "keymapPending" + | "keymapPresetCustom" + | "keymapPresetOff" + | "keymapPresetSwapAltWin" + | "keymapPresetTitle" + | "keymapPresetWinToCmd" + | "keymapRunning" + | "keymapStopped" + | "keymapUpgrade" + | "keymapWaiting" | "language" | "languageSub" | "localeAuto" diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 92b48b5..76aa784 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -171,3 +171,22 @@ export interface LogEntry { source: string line: string } +export type VMKeymapPreset = 'off' | 'win_to_cmd' | 'swap_alt_win' | 'custom' +export type VMKeymapHostModifier = 'lwin' | 'rwin' | 'lalt' | 'ralt' | 'lctrl' | 'rctrl' | 'capslock' +export type VMKeymapGuestModifier = 'default' | 'lcmd' | 'rcmd' | 'lopt' | 'ropt' | 'lctrl' | 'rctrl' | 'esc' | 'disabled' + +export interface VMKeymapUpdate { + preset: VMKeymapPreset + bindings: Partial> +} + +export interface VMKeymapStatus extends VMKeymapUpdate { + needs_guest_tools: boolean + guest_connected: boolean + guest_agent_version?: number + required_agent_version: number + input_service_available: boolean + guest_keymap_active: boolean + hook_active: boolean + running: boolean +} diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 182aaa8..059d489 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -17,7 +17,7 @@ import { import type { ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary, LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime, - RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, + RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMKeymapStatus, VMKeymapUpdate, } from './types' type AnyFn = (...args: never[]) => unknown @@ -149,6 +149,8 @@ export const api = { GetTasks: boundGo.GetTasks as () => Promise, GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise, SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise, + GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise, + SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise, ListInstallers: boundGo.ListInstallers as () => Promise, ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise, SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise, diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ded8dce..409c9da 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -97,6 +97,8 @@ export function GetTasks():Promise>; export function GetVMAffinity(arg1:string):Promise; +export function GetVMKeymap(arg1:string):Promise; + export function GetVMDetail(arg1:string):Promise; export function GetVMDriveShareSettings(arg1:string):Promise; @@ -213,6 +215,8 @@ export function SetRuntimeChannel(arg1:string):Promise; export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise; +export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise; + export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array):Promise; export function SetVMNote(arg1:string,arg2:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index da78976..5d9f8be 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -178,6 +178,10 @@ export function GetVMAffinity(arg1) { return window['go']['app']['App']['GetVMAffinity'](arg1); } +export function GetVMKeymap(arg1) { + return window['go']['app']['App']['GetVMKeymap'](arg1); +} + export function GetVMDetail(arg1) { return window['go']['app']['App']['GetVMDetail'](arg1); } @@ -410,6 +414,10 @@ export function SetVMAffinity(arg1, arg2) { return window['go']['app']['App']['SetVMAffinity'](arg1, arg2); } +export function SetVMKeymap(arg1, arg2) { + return window['go']['app']['App']['SetVMKeymap'](arg1, arg2); +} + export function SetVMDriveShareSettings(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 7d181bf..6bea82c 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1,4 +1,51 @@ export namespace app { + + export class VMKeymapUpdate { + preset: string; + bindings: Record; + + static createFrom(source: object | string = {}) { + return new VMKeymapUpdate(source); + } + + constructor(source: Partial | string = {}) { + if (typeof source === "string") source = JSON.parse(source) as Partial; + this.preset = source.preset ?? "off"; + this.bindings = source.bindings ?? {}; + } + } + + export class VMKeymapStatus { + preset: string; + bindings: Record; + needs_guest_tools: boolean; + guest_connected: boolean; + guest_agent_version?: number; + required_agent_version: number; + input_service_available: boolean; + guest_keymap_active: boolean; + hook_active: boolean; + running: boolean; + + static createFrom(source: object | string = {}) { + return new VMKeymapStatus(source); + } + + constructor(source: Partial | string = {}) { + if (typeof source === "string") source = JSON.parse(source) as Partial; + this.preset = source.preset ?? "off"; + this.bindings = source.bindings ?? {}; + this.needs_guest_tools = source.needs_guest_tools ?? false; + this.guest_connected = source.guest_connected ?? false; + this.guest_agent_version = source.guest_agent_version; + this.required_agent_version = source.required_agent_version ?? 0; + this.input_service_available = source.input_service_available ?? false; + this.guest_keymap_active = source.guest_keymap_active ?? false; + this.hook_active = source.hook_active ?? false; + this.running = source.running ?? false; + } + } + export class AppState { config?: config.Config; diff --git a/internal/app/app.go b/internal/app/app.go index 9c035eb..9d180fd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -94,6 +94,11 @@ type App struct { runtimeKinds *rt.KindRegistry uiHealth uiHealthState themeMode installguide.Theme + + keymapMu sync.Mutex + keymapPIDs map[string]int + fallbackInputSvc *host.InputService + inputShuttingDown bool } // Lifecycle exposes Wails lifecycle callbacks without exporting them as @@ -191,6 +196,13 @@ func (a *App) shutdown(ctx context.Context) { } tasks.cancelAll() stopAllVMMonitors() + a.mu.Lock() + a.inputShuttingDown = true + fallback := a.fallbackInputSvc + a.mu.Unlock() + if fallback != nil { + fallback.Close() + } a.shutdownPlugins() a.mu.Lock() for name, entry := range a.rebootWatchers { @@ -381,7 +393,7 @@ func (a *App) pollVMs(ctx context.Context) { if ib != nil { ib.SetTargets(imeTargets) } - a.syncInputTargets(imeTargets) + a.syncKeymapRules() if tm != nil { effLoc := i18n.EffectiveLocale(loc) if runningCount >= 1 { diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 2f3da20..8bc1768 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -55,6 +55,7 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created a.injectRemoteText(vmName, "", text) }) a.guestTools = srv + srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() }) created = true } a.mu.Unlock() @@ -110,6 +111,8 @@ func (a *App) inputBridgeEnv(name, vmDir string) []string { return nil } srv.RegisterVM(validatedDriveConfig(cfg)) + srv.SetKeymapCarrier(name, false) + a.syncKeymapRules() return []string{ fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port), "REIMS_GO_INPUT_TOKEN=" + cfg.Token, @@ -128,6 +131,7 @@ func (a *App) registerExistingGuestTools(ctx context.Context) { // guest agent that is already running reconnects after reims-go restarts or // the Guest Tools plugin is switched back on. func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) { + defer a.syncKeymapRules() c, err := a.client() if err != nil { return diff --git a/internal/app/keymap_flow.go b/internal/app/keymap_flow.go new file mode 100644 index 0000000..89fac1e --- /dev/null +++ b/internal/app/keymap_flow.go @@ -0,0 +1,141 @@ +package app + +import ( + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +const KeymapRequiredAgentVersion = 8 +const keymapStatusMaxAge = 30 * time.Second + +type VMKeymapUpdate struct { + Preset string `json:"preset"` + Bindings map[string]string `json:"bindings"` +} + +type VMKeymapStatus struct { + Preset string `json:"preset"` + Bindings map[string]string `json:"bindings"` + NeedsGuestTools bool `json:"needs_guest_tools"` + GuestConnected bool `json:"guest_connected"` + GuestAgentVersion int `json:"guest_agent_version,omitempty"` + RequiredAgentVersion int `json:"required_agent_version"` + GuestKeymapActive bool `json:"guest_keymap_active"` + InputServiceAvailable bool `json:"input_service_available"` + HookActive bool `json:"hook_active"` + Running bool `json:"running"` +} + +func (a *App) GetVMKeymap(name string) (VMKeymapStatus, error) { + if vm, ok := a.polledVM(name); ok && vm.Dir != "" { + return a.keymapStatus(name, vm.State == "running", vmstart.ReadVMKeymap(vm.Dir)), nil + } + detail, err := a.GetVMDetail(name) + if err != nil { + return VMKeymapStatus{}, err + } + return a.keymapStatus(name, detail.State == "running", vmstart.ReadVMKeymap(detail.Directory)), nil +} + +func (a *App) SetVMKeymap(name string, req VMKeymapUpdate) (VMKeymapStatus, error) { + detail, err := a.GetVMDetail(name) + if err != nil { + return VMKeymapStatus{}, err + } + cfg := vmstart.VMKeymapConfig{ + Preset: vmstart.KeymapPreset(req.Preset), + Bindings: make(map[vmstart.HostModifier]vmstart.GuestModifier, len(req.Bindings)), + } + for k, v := range req.Bindings { + cfg.Bindings[vmstart.HostModifier(k)] = vmstart.GuestModifier(v) + } + cfg, err = vmstart.SaveVMKeymap(detail.Directory, cfg) + if err != nil { + return VMKeymapStatus{}, err + } + a.syncKeymapRules() + return a.keymapStatus(name, detail.State == "running", cfg), nil +} + +func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig) VMKeymapStatus { + bindings := vmstart.ResolveKeymapBindings(cfg) + status := VMKeymapStatus{ + Preset: string(cfg.Preset), + Bindings: keymapBindingStrings(bindings), + NeedsGuestTools: vmstart.NeedsGuestCarrier(bindings), + RequiredAgentVersion: KeymapRequiredAgentVersion, + Running: running, + } + a.mu.Lock() + srv := a.guestTools + a.mu.Unlock() + if srv != nil && running { + guest := srv.Status(name, keymapStatusMaxAge) + status.GuestConnected = guest.Connected + status.GuestAgentVersion = guest.AgentVersion + status.GuestKeymapActive = guest.KeymapActive && guest.AgentVersion >= KeymapRequiredAgentVersion + } + svc := a.getInputService() + status.InputServiceAvailable = svc != nil + if svc != nil && running { + status.HookActive = svc.IsKeymapActiveForVM(name) + } + return status +} + +func keymapBindingStrings(bindings map[vmstart.HostModifier]vmstart.GuestModifier) map[string]string { + out := make(map[string]string, len(bindings)) + for k, v := range bindings { + out[string(k)] = string(v) + } + return out +} + +func (a *App) syncKeymapRules() { + a.keymapMu.Lock() + defer a.keymapMu.Unlock() + a.mu.Lock() + vms := append([]reims.VMListItem(nil), a.lastVMs...) + srv := a.guestTools + a.mu.Unlock() + svc := a.getInputService() + var rules []host.KeymapRule + var targets []host.IMETarget + pids := make(map[string]int) + for _, vm := range vms { + if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + if srv != nil { + srv.SetKeymapCarrier(vm.Name, false) + } + continue + } + dir := vm.Dir + if dir == "" { + if detail, err := a.GetVMDetail(vm.Name); err == nil { + dir = detail.Directory + } + } + targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: dir, PID: uint32(*vm.PID)}) + pids[vm.Name] = *vm.PID + bindings := vmstart.ResolveKeymapBindings(vmstart.ReadVMKeymap(dir)) + rule := host.KeymapRule{VMName: vm.Name, Bindings: keymapBindingStrings(bindings)} + if srv != nil { + if oldPID := a.keymapPIDs[vm.Name]; oldPID != 0 && oldPID != *vm.PID { + srv.SetKeymapCarrier(vm.Name, false) + } + srv.SetKeymapCarrier(vm.Name, svc != nil && vmstart.NeedsGuestCarrier(bindings)) + status := srv.Status(vm.Name, keymapStatusMaxAge) + rule.CarrierReady = status.Connected && status.KeymapActive && status.AgentVersion >= KeymapRequiredAgentVersion + } + if len(bindings) != 0 { + rules = append(rules, rule) + } + } + a.keymapPIDs = pids + if svc != nil { + svc.SetTargetsAndKeymapRules(targets, rules) + } +} diff --git a/internal/app/keymap_flow_test.go b/internal/app/keymap_flow_test.go new file mode 100644 index 0000000..d784c4a --- /dev/null +++ b/internal/app/keymap_flow_test.go @@ -0,0 +1,32 @@ +package app + +import ( + "testing" + + "github.com/Nwflower/reims-go/internal/vmstart" +) + +func TestKeymapStatusWithoutPluginManager(t *testing.T) { + a := &App{} + t.Cleanup(func() { a.getInputService().Close() }) + a.syncKeymapRules() + cfg := vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd} + got := a.keymapStatus("mac", true, cfg) + if got.Preset != "win_to_cmd" || got.Bindings["lwin"] != "lcmd" || + !got.NeedsGuestTools || !got.InputServiceAvailable || !got.Running || got.RequiredAgentVersion != 8 || + got.GuestConnected || got.GuestKeymapActive || got.HookActive { + t.Fatalf("unexpected status: %+v", got) + } + got = a.keymapStatus("mac", false, vmstart.DefaultVMKeymapConfig()) + if got.Preset != "off" || got.Running || got.NeedsGuestTools || got.Bindings == nil || len(got.Bindings) != 0 { + t.Fatalf("unexpected defaults: %+v", got) + } +} + +func TestKeymapStatusWithoutInputService(t *testing.T) { + a := &App{inputShuttingDown: true} + status := a.keymapStatus("mac", true, vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd}) + if status.InputServiceAvailable || status.HookActive || !status.NeedsGuestTools { + t.Fatalf("unexpected status: %+v", status) + } +} diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index ec50073..389f398 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -31,20 +31,20 @@ import ( // PluginUIContributions aggregates all active declarative plugin UI contributions // for the frontend in a single round-trip (§4.2, §10). type PluginUIContributions struct { - SafeMode bool `json:"safe_mode"` - CrashDetected bool `json:"crash_detected"` - Menus []plugin.MenuContribution `json:"menus,omitempty"` - VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"` - SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"` - StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"` - Panels []plugin.PanelContribution `json:"panels,omitempty"` + SafeMode bool `json:"safe_mode"` + CrashDetected bool `json:"crash_detected"` + Menus []plugin.MenuContribution `json:"menus,omitempty"` + VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"` + SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"` + StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"` + Panels []plugin.PanelContribution `json:"panels,omitempty"` VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"` Themes []plugin.ThemeContribution `json:"themes,omitempty"` Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"` RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"` - RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"` - Drivers []driver.DriverSummary `json:"drivers,omitempty"` - AssetToken string `json:"asset_token,omitempty"` + RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"` + Drivers []driver.DriverSummary `json:"drivers,omitempty"` + AssetToken string `json:"asset_token,omitempty"` } func (a *App) initPlugins() { @@ -189,6 +189,7 @@ func (a *App) initPlugins() { mgr.Registry().OnChange(func() { a.syncRuntimeKinds(kindReg, mgr.Registry()) a.syncInputFilters() + a.syncKeymapRules() a.syncClipboardPolicies() a.syncLocales() if a.ctx != nil { @@ -196,15 +197,23 @@ func (a *App) initPlugins() { } }) + a.keymapMu.Lock() a.mu.Lock() + fallback := a.fallbackInputSvc + a.fallbackInputSvc = nil a.pluginMgr = mgr a.driverRouter = drvRouter a.runtimeKinds = kindReg a.mu.Unlock() + if fallback != nil { + fallback.Close() + } + a.keymapMu.Unlock() mgr.Registry().Reconcile(context.Background()) mgr.MarkBootComplete() a.syncInputFilters() + a.syncKeymapRules() a.syncClipboardPolicies() a.syncLocales() } @@ -327,11 +336,20 @@ func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) { func (a *App) getInputService() *host.InputService { a.mu.Lock() - mgr := a.pluginMgr - a.mu.Unlock() - if mgr == nil { + if a.inputShuttingDown { + a.mu.Unlock() return nil } + mgr := a.pluginMgr + if mgr == nil { + if a.fallbackInputSvc == nil { + a.fallbackInputSvc = host.NewInputService(nil) + } + svc := a.fallbackInputSvc + a.mu.Unlock() + return svc + } + a.mu.Unlock() raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput) if !ok { return nil @@ -340,12 +358,6 @@ func (a *App) getInputService() *host.InputService { return svc } -func (a *App) syncInputTargets(targets []host.IMETarget) { - if svc := a.getInputService(); svc != nil { - svc.SetTargets(targets) - } -} - func (a *App) syncInputFilters() { a.mu.Lock() mgr := a.pluginMgr diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index cf5fd8f..98b920a 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -23,7 +23,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { if start < 0 || end <= start { t.Fatal("missing generated clipboard code") } - if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) { + if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)[,\}]`).MatchString(agent) { t.Fatal("clipboard sync requires agent version 6 or newer") } if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 2415203..a821d90 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -100,8 +100,15 @@ rm -f "$INJECT_LOCK" 2>/dev/null || true CAFFEINATE_PID="" TEXT_INPUT_PID="" +keymap_active="false" +keymap_applied="false" +` + guestKeymapCarrier + ` cleanup() { + if [ "$keymap_applied" = "true" ]; then + apply_hidutil_carrier disable + report_status 1 + fi if [ -n "$CAFFEINATE_PID" ]; then kill "$CAFFEINATE_PID" 2>/dev/null || true fi @@ -110,7 +117,8 @@ cleanup() { fi rm -f "$INJECT_LOCK" 2>/dev/null || true } -trap cleanup EXIT INT TERM +trap cleanup EXIT +trap 'exit 0' INT TERM load_conf() { if [ -f "/Volumes/REIMSTOOLS/config" ]; then @@ -282,6 +290,7 @@ apply_host_config() { cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true) [ -n "$cfg_json" ] || return 0 sync_drive_mounts "$cfg_json" + sync_keymap_carrier "$cfg_json" if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then clip_enabled="0" else @@ -310,10 +319,10 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - curl -fsS -m 3 -X POST \ + curl -fsS -m "${1:-3}" -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":8,\"keymap_active\":$keymap_active}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -638,6 +647,8 @@ DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true umount "$SHARE_MOUNT" 2>/dev/null || true +` + guestKeymapCarrier + ` +apply_hidutil_carrier disable ` + guestDriveCleanup + ` unmount_unused_drives "" rm -f "$PLIST" @@ -646,10 +657,93 @@ echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept." `) } +const guestKeymapCarrier = ` +apply_hidutil_carrier() { + keymap_active="false" + mappings=$(/usr/bin/hidutil property --get UserKeyMapping 2>/dev/null) || return 0 + [ -n "$mappings" ] || return 0 + plan=$(printf '%s\n' "$mappings" | LC_ALL=C awk -v mode="$1" ' + function number(value, i, n, digit) { + if (value ~ /^[0-9]+$/) return value + 0 + if (value !~ /^0[xX][0-9a-fA-F]+$/) { invalid = 1; return 0 } + for (i = 3; i <= length(value); i++) { + digit = index("0123456789abcdef", tolower(substr(value, i, 1))) - 1 + n = 16 * n + digit + } + return n + } + function append(src, dst) { + if (entries != "") entries = entries "," + entries = entries sprintf("{\"HIDKeyboardModifierMappingSrc\":%.0f,\"HIDKeyboardModifierMappingDst\":%.0f}", src, dst) + } + BEGIN { + carrier["30064771183"] = 30064771298 + carrier["30064771184"] = 30064771299 + carrier["30064771185"] = 30064771303 + carrier["30064771187"] = 30064771302 + RS = "}" + } + { + n = split($0, fields, /[[:space:]=;{}(),]+/) + have_src = have_dst = 0 + for (i = 1; i <= n; i++) { + if (fields[i] == "HIDKeyboardModifierMappingSrc") { + src = number(fields[++i]) + have_src++ + } else if (fields[i] == "HIDKeyboardModifierMappingDst") { + dst = number(fields[++i]) + have_dst++ + } else if (fields[i] != "" && fields[i] != "null" && fields[i] != "UserKeyMapping") { + invalid = 1 + } + } + if (!have_src && !have_dst) next + if (have_src != 1 || have_dst != 1) { invalid = 1; next } + id = sprintf("%.0f", src) + if (id in carrier) { + found++ + if (!seen[id]++ && dst == carrier[id]) correct++ + } else { + append(src, dst) + } + } + END { + if (invalid) exit 1 + if ((mode == "disable" && !found) || (mode == "enable" && found == 4 && correct == 4)) { + print "unchanged" + exit + } + if (mode == "enable") { + for (src in carrier) append(src, carrier[src]) + } + printf "{\"UserKeyMapping\":[%s]}\n", entries + } + ') || return 0 + if [ "$plan" != "unchanged" ]; then + /usr/bin/hidutil property --set "$plan" >/dev/null 2>&1 || return 0 + fi + if [ "$1" = "enable" ]; then + keymap_active="true" + else + keymap_carrier_clean="1" + fi + keymap_applied="$keymap_active" +} + +sync_keymap_carrier() { + if printf '%s' "$1" | grep -q '"keymap_carrier_enabled"[[:space:]]*:[[:space:]]*true'; then + keymap_carrier_clean="0" + apply_hidutil_carrier enable + elif [ "${keymap_carrier_clean:-0}" != "1" ]; then + apply_hidutil_carrier disable + fi +} +` + const guestDriveCleanup = ` drive_mount_type() { [ ! -L "$1" ] || return 0 - mount 2>/dev/null | awk -v target=" on $1 (" ' + mount 2>/dev/null | LC_ALL=C awk -v target=" on $1 (" ' pos = index($0, target) { split(substr($0, pos + length(target)), options, /[,)]/) print options[1] diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go new file mode 100644 index 0000000..01cb117 --- /dev/null +++ b/internal/guesttools/keymap_agent_test.go @@ -0,0 +1,179 @@ +package guesttools + +import ( + "encoding/json" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestGuestAgentKeymapScript(t *testing.T) { + sh, err := exec.LookPath("sh") + if err != nil { + sh = "C:/Program Files/Git/bin/sh.exe" + if _, err := os.Stat(sh); err != nil { + t.Skip("POSIX sh is unavailable") + } + } + agent := string(GuestAgentScript()) + start := strings.Index(agent, "apply_hidutil_carrier() {") + end := strings.Index(agent, "load_conf() {") + if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":8,\"keymap_active\":$keymap_active`) { + t.Fatal("missing guest keymap script or version 8 status") + } + for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { + t.Run(input, func(t *testing.T) { + dir := t.TempDir() + fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + fixture += "\nprintf '%s\\n' \"$1\" > state\nsync_keymap_carrier '{}'\n" + fixture += "[ \"$keymap_carrier_clean\" = 1 ]\nrm state\nsync_keymap_carrier '{}'\n[ ! -f state ]\n" + cmd := exec.Command(sh, "-c", fixture, "fixture", input) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("shell fixture: %v\n%s", err, out) + } + gets, err := os.ReadFile(filepath.Join(dir, "get.log")) + if err != nil || strings.TrimSpace(string(gets)) != "get" { + t.Fatalf("expected exactly one hidutil read: %q, %v", gets, err) + } + got, err := os.ReadFile(filepath.Join(dir, "set.log")) + if strings.Contains(input, "30064771184") { + if err != nil || strings.TrimSpace(string(got)) != `{"UserKeyMapping":[]}` { + t.Fatalf("disable output = %q, %v", got, err) + } + } else if !os.IsNotExist(err) { + t.Fatalf("empty input should require no write: %q, %v", got, err) + } + }) + } + for _, teardown := range []string{"disable", "exit", "uninstall"} { + t.Run(teardown, func(t *testing.T) { + dir := t.TempDir() + fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + keymapShellExercise + if teardown == "uninstall" { + uninstall := string(GuestUninstallScript()) + start := strings.Index(uninstall, "apply_hidutil_carrier() {") + end := strings.Index(uninstall, "drive_mount_type() {") + if start < 0 || end <= start { + t.Fatal("missing uninstall carrier cleanup") + } + fixture += strings.ReplaceAll(uninstall[start:end], "/usr/bin/hidutil", "hidutil") + fixture += "\ntrap - EXIT\n" + } + script := filepath.Join(dir, "keymap.sh") + if err := os.WriteFile(script, []byte(fixture), 0o600); err != nil { + t.Fatal(err) + } + cmd := exec.Command(sh, script, teardown) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("shell fixture: %v\n%s", err, out) + } + data, err := os.ReadFile(filepath.Join(dir, "set.log")) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(data)), "\n") + if len(lines) != 2 { + t.Fatalf("expected one enable and one removal, got %s", data) + } + for i, line := range lines { + var result struct { + Mappings []struct { + Src uint64 `json:"HIDKeyboardModifierMappingSrc"` + Dst uint64 `json:"HIDKeyboardModifierMappingDst"` + } `json:"UserKeyMapping"` + } + if err := json.Unmarshal([]byte(line), &result); err != nil { + t.Fatal(err) + } + want := map[uint64]uint64{0x700000039: 0x7000000E0} + if i == 0 { + want[0x70000006F] = 0x7000000E2 + want[0x700000070] = 0x7000000E3 + want[0x700000071] = 0x7000000E7 + want[0x700000073] = 0x7000000E6 + } + for _, pair := range result.Mappings { + if want[pair.Src] != pair.Dst || pair.Dst == 0 { + t.Fatalf("unexpected pair %+v", pair) + } + delete(want, pair.Src) + } + if len(want) != 0 { + t.Fatalf("missing mappings: %v", want) + } + } + }) + } +} + +const keymapShellFixture = `set -eu +PATH="/usr/bin:/bin:$PATH" +CAFFEINATE_PID= +TEXT_INPUT_PID= +INJECT_LOCK=./injecting +keymap_active=false +keymap_applied=false +report_status() { [ "$1" = "1" ] && [ "$keymap_active" = "false" ]; } +hidutil() { + case "$2" in + --get) printf "get\n" >> get.log; cat state ;; + --set) + printf '%s\n' "$3" >> set.log + printf '%s\n' "$3" | sed 's/{"UserKeyMapping":\[/(/; s/\]}$/)/; s/"HIDKeyboardModifierMappingSrc":/HIDKeyboardModifierMappingSrc = /g; s/,"HIDKeyboardModifierMappingDst":/; HIDKeyboardModifierMappingDst = /g' > state + ;; + *) return 1 ;; + esac +} +printf '%s\n' '({' 'HIDKeyboardModifierMappingSrc = 0x700000039;' 'HIDKeyboardModifierMappingDst = 0x7000000E0;' '})' > state +` + +const keymapShellExercise = ` +sync_keymap_carrier '{"keymap_carrier_enabled": true}' +[ "$keymap_active" = "true" ] +sync_keymap_carrier '{"keymap_carrier_enabled":true}' +[ "$keymap_active" = "true" ] +if [ "$1" = "disable" ]; then + sync_keymap_carrier '{"keymap_carrier_enabled":false}' + [ "$keymap_active" = "false" ] +fi +` + +func TestKeymapCarrierStatusHandshake(t *testing.T) { + srv := NewTransportServer(nil) + srv.RegisterVM(VMConfig{VMName: "mac", Token: "token"}) + srv.SetKeymapCarrier("mac", true) + var statuses []bool + srv.SetStatusChangeHandler(func(name string) { + statuses = append(statuses, srv.Status(name, time.Minute).KeymapActive) + }) + config := httptest.NewRequest("GET", "/v1/config", nil) + config.Header.Set("Authorization", "Bearer token") + w := httptest.NewRecorder() + srv.handleConfig(w, config) + if !strings.Contains(w.Body.String(), `"keymap_carrier_enabled":true`) { + t.Fatalf("guest config = %s", w.Body) + } + for _, body := range []string{ + `{"agent_version":7,"keymap_active":true}`, + `{"agent_version":8,"keymap_active":true}`, + `{"agent_version":8,"keymap_active":true}`, + `{"agent_version":8,"keymap_active":false}`, + } { + req := httptest.NewRequest("POST", "/v1/status", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer token") + w := httptest.NewRecorder() + srv.handleStatus(w, req) + if w.Code != 200 { + t.Fatalf("status = %d: %s", w.Code, w.Body) + } + } + if len(statuses) != 3 || statuses[0] || !statuses[1] || statuses[2] { + t.Fatalf("callbacks = %v", statuses) + } +} diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 910b480..14bcef0 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -85,6 +85,7 @@ type VMConfig struct { // GuestStatus summarizes live Guest Tools connection and capability state. type GuestStatus struct { + KeymapActive bool `json:"keymap_active"` Connected bool `json:"connected"` MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" PreventSleep bool `json:"prevent_sleep"` @@ -173,16 +174,19 @@ type pendingClipOverride struct { } type registeredVM struct { - name string - token string - sharedDir string - preventSleep bool - driveSharingEnabled bool - sharedDriveRoots map[string]string - mountMode string - sleepActive bool - agentVersion int - lastSeen time.Time + keymapCarrierEnabled bool + keymapActive bool + lastStatus time.Time + name string + token string + sharedDir string + preventSleep bool + driveSharingEnabled bool + sharedDriveRoots map[string]string + mountMode string + sleepActive bool + agentVersion int + lastSeen time.Time injectMu sync.Mutex textSeq uint64 @@ -218,6 +222,7 @@ type Server struct { watchCancel context.CancelFunc clipNotify chan struct{} onHostText func(vmName, text string) + onStatusChange func(vmName string) } // NewServer constructs a Guest Tools HTTP bridge with clipboard active by default. @@ -603,6 +608,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge return GuestStatus{ + KeymapActive: connected && vm.keymapCarrierEnabled && vm.keymapActive && time.Since(vm.lastStatus) <= maxAge, Connected: connected, MountMode: vm.mountMode, PreventSleep: vm.preventSleep, @@ -612,6 +618,21 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { } } +func (s *Server) SetKeymapCarrier(vmName string, enabled bool) { + s.mu.Lock() + defer s.mu.Unlock() + if vm := s.vms[vmName]; vm != nil && vm.keymapCarrierEnabled != enabled { + vm.keymapCarrierEnabled = enabled + vm.keymapActive = false + } +} + +func (s *Server) SetStatusChangeHandler(fn func(vmName string)) { + s.mu.Lock() + defer s.mu.Unlock() + s.onStatusChange = fn +} + func (s *Server) touchLastSeen(vmName string) { s.mu.Lock() if vm := s.vms[vmName]; vm != nil { @@ -641,16 +662,17 @@ func (s *Server) authenticate(r *http.Request) *registeredVM { // injectMu and alias the text queues. Handlers that need the // queues look the live VM up again by name under s.mu. cp := registeredVM{ - name: vm.name, - token: vm.token, - sharedDir: vm.sharedDir, - preventSleep: vm.preventSleep, - driveSharingEnabled: vm.driveSharingEnabled, - sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), - mountMode: vm.mountMode, - sleepActive: vm.sleepActive, - agentVersion: vm.agentVersion, - lastSeen: vm.lastSeen, + keymapCarrierEnabled: vm.keymapCarrierEnabled, + name: vm.name, + token: vm.token, + sharedDir: vm.sharedDir, + preventSleep: vm.preventSleep, + driveSharingEnabled: vm.driveSharingEnabled, + sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), + mountMode: vm.mountMode, + sleepActive: vm.sleepActive, + agentVersion: vm.agentVersion, + lastSeen: vm.lastSeen, } return &cp } @@ -683,7 +705,7 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) { http.Error(w, "unauthorized", http.StatusUnauthorized) return } - caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly"} + caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "keymap-carrier"} if policy := s.EffectiveClipboardPolicy(vm.name); policy.Enabled { caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...) if policy.SyncImages { @@ -712,14 +734,15 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { policy := s.EffectiveClipboardPolicy(vm.name) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ - "vm": vm.name, - "prevent_sleep": vm.preventSleep, - "webdav_path": "/dav/" + vm.name + "/", - "shared_drives": enabledDriveLetters(vm), - "clipboard_enabled": policy.Enabled, - "clipboard_direction": policy.Direction, - "clipboard_sync_images": policy.SyncImages, - "clipboard_max_bytes": policy.MaxImageBytes, + "vm": vm.name, + "keymap_carrier_enabled": vm.keymapCarrierEnabled, + "prevent_sleep": vm.preventSleep, + "webdav_path": "/dav/" + vm.name + "/", + "shared_drives": enabledDriveLetters(vm), + "clipboard_enabled": policy.Enabled, + "clipboard_direction": policy.Direction, + "clipboard_sync_images": policy.SyncImages, + "clipboard_max_bytes": policy.MaxImageBytes, }) } @@ -734,6 +757,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { return } var req struct { + KeymapActive bool `json:"keymap_active"` MountMode string `json:"mount_mode"` SleepActive bool `json:"sleep_active"` AgentVersion int `json:"agent_version"` @@ -747,7 +771,15 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { mode = "" } s.mu.Lock() - if cur := s.vms[vm.name]; cur != nil { + var notify func(string) + if cur := s.vms[vm.name]; cur != nil && cur.token == vm.token { + now := time.Now() + active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= 8 + if cur.keymapActive != active || now.Sub(cur.lastStatus) > 30*time.Second { + notify = s.onStatusChange + } + cur.keymapActive = active + cur.lastStatus = now if mode != "" { cur.mountMode = mode } @@ -759,6 +791,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { } s.mu.Unlock() w.WriteHeader(http.StatusOK) + if notify != nil { + notify(vm.name) + } } func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) { diff --git a/internal/host/ime_hook_windows.go b/internal/host/ime_hook_windows.go index 7b192e6..fc16ed9 100644 --- a/internal/host/ime_hook_windows.go +++ b/internal/host/ime_hook_windows.go @@ -12,17 +12,17 @@ import ( ) var ( - procSetWindowsHookExW = user32.NewProc("SetWindowsHookExW") - procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx") - procCallNextHookEx = user32.NewProc("CallNextHookEx") - procGetMessageW = user32.NewProc("GetMessageW") - procPeekMessageW = user32.NewProc("PeekMessageW") - procPostThreadMessageW = user32.NewProc("PostThreadMessageW") - procGetForegroundWindow = user32.NewProc("GetForegroundWindow") - procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId") - imeKernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetModuleHandleW = imeKernel32.NewProc("GetModuleHandleW") - procGetCurrentThreadId = imeKernel32.NewProc("GetCurrentThreadId") + procSetWindowsHookExW = user32.NewProc("SetWindowsHookExW") + procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx") + procCallNextHookEx = user32.NewProc("CallNextHookEx") + procGetMessageW = user32.NewProc("GetMessageW") + procPeekMessageW = user32.NewProc("PeekMessageW") + procPostThreadMessageW = user32.NewProc("PostThreadMessageW") + procGetForegroundWindow = user32.NewProc("GetForegroundWindow") + procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId") + imeKernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetModuleHandleW = imeKernel32.NewProc("GetModuleHandleW") + procGetCurrentThreadId = imeKernel32.NewProc("GetCurrentThreadId") ) const ( @@ -53,6 +53,7 @@ type winMsg struct { time uint32 ptX int32 ptY int32 + private uint32 } var ( diff --git a/internal/host/input_service.go b/internal/host/input_service.go index 40793ca..4d4e35b 100644 --- a/internal/host/input_service.go +++ b/internal/host/input_service.go @@ -1,6 +1,8 @@ package host import ( + "maps" + "reflect" "strings" "sync" "sync/atomic" @@ -11,11 +13,11 @@ import ( type InputFilterRule struct { ID string `json:"id"` PluginID string `json:"plugin_id"` - Event string `json:"event"` // "mouse_wheel" - Axis string `json:"axis"` // "vertical" | "horizontal" | "both" - Transform string `json:"transform"` // "invert" - Scope string `json:"scope"` // "vm_foreground" - VMNames map[string]bool `json:"vm_names,omitempty"` // empty = all VMs; non-empty = targeted VMs + Event string `json:"event"` // "mouse_wheel" + Axis string `json:"axis"` // "vertical" | "horizontal" | "both" + Transform string `json:"transform"` // "invert" + Scope string `json:"scope"` // "vm_foreground" + VMNames map[string]bool `json:"vm_names,omitempty"` // empty = all VMs; non-empty = targeted VMs Vertical bool `json:"vertical"` Horizontal bool `json:"horizontal"` } @@ -79,15 +81,18 @@ func hasMatchingWheelTarget(rules []InputFilterRule, targets []IMETarget) bool { // InputService unifies low-level keyboard (IME bridge) and on-demand low-level // mouse (declarative inputFilters) hooks behind one reversible host service (§5.4). type InputService struct { - mu sync.Mutex - onIMEText func(target IMETarget, text string) - imeEnabled bool - imeBridge *IMEBridge - targets []IMETarget - targetByPID atomic.Pointer[map[uint32]IMETarget] - rules atomic.Pointer[[]InputFilterRule] - mouseHook *mouseWheelHook - closed bool + mu sync.Mutex + onIMEText func(target IMETarget, text string) + imeEnabled bool + imeBridge *IMEBridge + targets []IMETarget + targetByPID atomic.Pointer[map[uint32]IMETarget] + rules atomic.Pointer[[]InputFilterRule] + mouseHook *mouseWheelHook + keymapRules []KeymapRule + keymapState atomic.Pointer[keymapSnapshot] + keymapHook *keymapHook + closed bool } // NewInputService constructs an inactive InputService. No OS hooks are installed @@ -137,6 +142,11 @@ func (s *InputService) SetTargets(targets []IMETarget) { if s.closed { return } + s.setTargetsLocked(targets) + s.reconcileKeymapLocked() +} + +func (s *InputService) setTargetsLocked(targets []IMETarget) { cp := append([]IMETarget(nil), targets...) s.targets = cp m := make(map[uint32]IMETarget, len(cp)) @@ -152,6 +162,85 @@ func (s *InputService) SetTargets(targets []IMETarget) { s.reconcileMouseHookLocked() } +type keymapSnapshot struct { + rules []KeymapRule + targets map[uint32]string +} + +func (s *InputService) SetKeymapRules(rules []KeymapRule) { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return + } + s.setKeymapRulesLocked(rules) + s.reconcileKeymapLocked() +} + +func (s *InputService) SetTargetsAndKeymapRules(targets []IMETarget, rules []KeymapRule) { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return + } + s.setTargetsLocked(targets) + s.setKeymapRulesLocked(rules) + s.reconcileKeymapLocked() +} + +func (s *InputService) setKeymapRulesLocked(rules []KeymapRule) { + s.keymapRules = make([]KeymapRule, len(rules)) + for i, rule := range rules { + rule.Bindings = maps.Clone(rule.Bindings) + s.keymapRules[i] = rule + } +} + +func (s *InputService) IsKeymapHookInstalled() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.keymapHook != nil +} + +func (s *InputService) IsKeymapActiveForVM(vmName string) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.keymapHook == nil { + return false + } + for _, name := range s.keymapState.Load().targets { + if name == vmName { + return true + } + } + return false +} + +func (s *InputService) reconcileKeymapLocked() { + active := make(map[string]bool) + for _, rule := range s.keymapRules { + active[rule.VMName] = rule.active() + } + next := &keymapSnapshot{rules: s.keymapRules, targets: make(map[uint32]string)} + for _, target := range s.targets { + if target.PID != 0 && active[target.VMName] { + next.targets[target.PID] = target.VMName + } + } + if !reflect.DeepEqual(next, s.keymapState.Load()) { + s.keymapState.Store(next) + if s.keymapHook != nil { + s.keymapHook.refresh() + } + } + if len(next.targets) == 0 && s.keymapHook != nil { + s.keymapHook.Close() + s.keymapHook = nil + } else if len(next.targets) != 0 && s.keymapHook == nil { + s.keymapHook = startKeymapHook(s) + } +} + // SetFilterRules replaces the active declarative input filters and installs or // uninstalls the low-level mouse hook on demand (§5.4). func (s *InputService) SetFilterRules(rules []InputFilterRule) { @@ -206,6 +295,8 @@ func (s *InputService) Close() { s.closed = true ib := s.imeBridge mh := s.mouseHook + kh := s.keymapHook + s.keymapHook = nil s.imeBridge = nil s.mouseHook = nil s.mu.Unlock() @@ -216,4 +307,7 @@ func (s *InputService) Close() { if mh != nil { mh.Close() } + if kh != nil { + kh.Close() + } } diff --git a/internal/host/input_service_windows.go b/internal/host/input_service_windows.go index 3d15f42..08fa787 100644 --- a/internal/host/input_service_windows.go +++ b/internal/host/input_service_windows.go @@ -16,11 +16,11 @@ const ( wmMouseWheel = 0x020A wmMouseHWheel = 0x020E - inputMouse = 0 - mouseEventfWheel = 0x0800 - mouseEventfHWheel = 0x01000 - llmhfInjected = 0x00000001 - gaRoot = 2 + inputMouse = 0 + mouseEventfWheel = 0x0800 + mouseEventfHWheel = 0x01000 + llmhfInjected = 0x00000001 + gaRoot = 2 // reimsInjectedInputMagic tags re-emitted wheel events so the hook ignores // its own inverted events and never loops (§5.4). reimsInjectedInputMagic uintptr = 0x5245494D // "REIM" @@ -52,13 +52,12 @@ type msLLHookStruct struct { // winMouseInput mirrors Win32 INPUT for INPUT_MOUSE on amd64 (40 bytes total). type winMouseInput struct { inputType uint32 - _pad uint32 + _ [0]uintptr // Align the INPUT union on both 32-bit and 64-bit. dx int32 dy int32 mouseData uint32 dwFlags uint32 time uint32 - _pad2 uint32 dwExtraInfo uintptr } diff --git a/internal/host/keymap.go b/internal/host/keymap.go new file mode 100644 index 0000000..2289cf0 --- /dev/null +++ b/internal/host/keymap.go @@ -0,0 +1,249 @@ +package host + +import "maps" + +const ( + vkLWin = 0x5B + vkRWin = 0x5C + vkLCtrl = 0xA2 + vkRCtrl = 0xA3 + vkLAlt = 0xA4 + vkRAlt = 0xA5 +) + +type KeymapRule struct { + VMName string + Bindings map[string]string + CarrierReady bool +} + +type KeyEvent struct { + VK uint32 + ScanCode uint32 + Up bool +} + +type EmittedKey struct { + VK uint16 + Scan uint16 + Extended bool + Up bool +} + +var hostModifiers = map[uint32]string{ + vkLWin: "lwin", vkRWin: "rwin", vkLCtrl: "lctrl", vkRCtrl: "rctrl", + vkLAlt: "lalt", vkRAlt: "ralt", 0x14: "capslock", +} + +var keymapTargets = map[string]EmittedKey{ + "lcmd": {VK: 0x84, Scan: 0x6C}, "rcmd": {VK: 0x85, Scan: 0x6D}, + "lopt": {VK: 0x83, Scan: 0x6B}, "ropt": {VK: 0x87, Scan: 0x76}, + "lctrl": {VK: vkLCtrl, Scan: 0x1D}, "rctrl": {VK: vkRCtrl, Scan: 0x1D, Extended: true}, + "esc": {VK: 0x1B, Scan: 0x01}, "disabled": {}, +} + +func (r KeymapRule) target(vk uint32) (EmittedKey, bool) { + key, ok := keymapTargets[r.Bindings[hostModifiers[vk]]] + return key, ok && (r.CarrierReady || key.VK < 0x83 || key.VK > 0x87) +} + +func (r KeymapRule) active() bool { + for vk := range hostModifiers { + if _, ok := r.target(vk); ok { + return true + } + } + return false +} + +type KeymapEngine struct { + rules map[string]KeymapRule + physical map[uint32]bool + stalePhysical map[uint32]bool + activeMapped map[uint32]EmittedKey + heldVM string + altGrCtrlDown bool + altGrCtrlSuppressed bool +} + +func NewKeymapEngine(rules []KeymapRule) *KeymapEngine { + e := &KeymapEngine{ + physical: make(map[uint32]bool), + stalePhysical: make(map[uint32]bool), + activeMapped: make(map[uint32]EmittedKey), + } + e.SetRules(rules) + return e +} + +func (e *KeymapEngine) SetRules(rules []KeymapRule) []EmittedKey { + previous := e.rules[e.heldVM] + e.rules = make(map[string]KeymapRule, len(rules)) + for _, rule := range rules { + rule.Bindings = maps.Clone(rule.Bindings) + e.rules[rule.VMName] = rule + } + current := e.rules[e.heldVM] + if e.heldVM != "" && (previous.CarrierReady != current.CarrierReady || !maps.Equal(previous.Bindings, current.Bindings)) { + return e.ReleaseAll() + } + return nil +} + +func (e *KeymapEngine) ProcessEvent(ev KeyEvent, vmName string, foregroundMatch bool) (bool, []EmittedKey) { + vk := ev.VK + if vk == vkLCtrl && ev.ScanCode&0x200 != 0 { + // Decide suppression once on the initial press so cross-focus auto-repeat + // never orphans Windows' synthetic AltGr Ctrl key-up. + if ev.Up { + suppress := e.altGrCtrlSuppressed + e.altGrCtrlDown = false + e.altGrCtrlSuppressed = false + return suppress, nil + } + if e.altGrCtrlDown { + return e.altGrCtrlSuppressed, nil + } + e.altGrCtrlDown = true + _, mapped := e.rules[vmName].target(vkRAlt) + e.altGrCtrlSuppressed = foregroundMatch && mapped + return e.altGrCtrlSuppressed, nil + } + if hostModifiers[vk] == "" { + return false, nil + } + wasDown := e.physical[vk] + delete(e.stalePhysical, vk) + if ev.Up { + delete(e.physical, vk) + if key, suppressed := e.activeMapped[vk]; suppressed { + delete(e.activeMapped, vk) + if key.VK != 0 && !e.targetHeld(key) { + key.Up = true + return true, []EmittedKey{key} + } + return true, nil + } + return false, nil + } + e.physical[vk] = true + if _, suppressed := e.activeMapped[vk]; suppressed { + return true, nil + } + if wasDown || !foregroundMatch { + return false, nil + } + if (vk == vkLWin || vk == vkRWin) && + (e.physical[vkLCtrl] || e.physical[vkRCtrl]) && + (e.physical[vkLAlt] || e.physical[vkRAlt]) { + return false, e.restoreCaptureModifiers(vmName) + } + key, ok := e.rules[vmName].target(vk) + if !ok { + return false, nil + } + alreadyHeld := e.targetHeld(key) + e.activeMapped[vk] = key + e.heldVM = vmName + if key.VK == 0 || alreadyHeld { + return true, nil + } + return true, []EmittedKey{key} +} + +func (e *KeymapEngine) restoreCaptureModifiers(vmName string) []EmittedKey { + var emit []EmittedKey + for _, original := range [...]EmittedKey{ + {VK: vkLCtrl, Scan: 0x1D}, {VK: vkRCtrl, Scan: 0x1D, Extended: true}, + {VK: vkLAlt, Scan: 0x38}, {VK: vkRAlt, Scan: 0x38, Extended: true}, + } { + vk := uint32(original.VK) + mapped, suppressed := e.activeMapped[vk] + if !suppressed || mapped == original { + continue + } + e.activeMapped[vk] = original + e.heldVM = vmName + _, targetMapped := e.activeMapped[uint32(mapped.VK)] + if mapped.VK != 0 && !e.targetHeld(mapped) && (targetMapped || !e.physical[uint32(mapped.VK)]) { + mapped.Up = true + emit = append(emit, mapped) + } + emit = append(emit, original) + } + return emit +} + +// ReconcilePhysical clears unsuppressed physical modifiers whose KEYUP was +// missed (e.g., after Ctrl+Alt+Del or UAC), using a two-tick grace so a key +// pressed right before Windows updates GetAsyncKeyState is never cleared early. +// Keys in activeMapped were swallowed by WH_KEYBOARD_LL and never set +// GetAsyncKeyState, so they are intentionally skipped here and cleared via +// Reset() on secure-desktop transitions. +func (e *KeymapEngine) ReconcilePhysical(isDown func(vk uint32) bool) []EmittedKey { + for vk := range e.physical { + if _, suppressed := e.activeMapped[vk]; suppressed { + delete(e.stalePhysical, vk) + continue + } + if isDown(vk) { + delete(e.stalePhysical, vk) + continue + } + if !e.stalePhysical[vk] { + e.stalePhysical[vk] = true + continue + } + delete(e.physical, vk) + delete(e.stalePhysical, vk) + } + return nil +} + +// Reset releases every active mapped target key and clears all tracked physical +// and suppressed key state (used when switching to a Windows Secure Desktop +// where user-mode WH_KEYBOARD_LL cannot observe key-up events). +func (e *KeymapEngine) Reset() []EmittedKey { + emit := e.ReleaseAll() + clear(e.physical) + clear(e.stalePhysical) + clear(e.activeMapped) + e.heldVM = "" + e.altGrCtrlDown = false + e.altGrCtrlSuppressed = false + return emit +} + +func (e *KeymapEngine) HasTrackedKeys() bool { + return len(e.physical) != 0 || len(e.activeMapped) != 0 || e.altGrCtrlDown || e.altGrCtrlSuppressed +} + +func (e *KeymapEngine) targetHeld(key EmittedKey) bool { + for _, mapped := range e.activeMapped { + if mapped == key { + return true + } + } + return false +} + +func (e *KeymapEngine) ReleaseAll() []EmittedKey { + var emit []EmittedKey + for vk, key := range e.activeMapped { + // Keep swallowing the physical key until its matching key-up. + e.activeMapped[vk] = EmittedKey{} + if key.VK != 0 && !e.targetHeld(key) { + key.Up = true + emit = append(emit, key) + } + } + e.heldVM = "" + return emit +} + +func (e *KeymapEngine) ReleaseIfFocusLost(currentVM string) []EmittedKey { + if e.heldVM != "" && currentVM != e.heldVM { + return e.ReleaseAll() + } + return nil +} diff --git a/internal/host/keymap_other.go b/internal/host/keymap_other.go new file mode 100644 index 0000000..f499d1f --- /dev/null +++ b/internal/host/keymap_other.go @@ -0,0 +1,9 @@ +//go:build !windows + +package host + +type keymapHook struct{} + +func startKeymapHook(*InputService) *keymapHook { return nil } +func (*keymapHook) refresh() {} +func (*keymapHook) Close() {} diff --git a/internal/host/keymap_test.go b/internal/host/keymap_test.go new file mode 100644 index 0000000..2ce6d71 --- /dev/null +++ b/internal/host/keymap_test.go @@ -0,0 +1,192 @@ +package host + +import ( + "slices" + "testing" +) + +func TestKeymapEngine(t *testing.T) { + rule := KeymapRule{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd", "rwin": "rctrl", "lalt": "disabled"}} + e := NewKeymapEngine([]KeymapRule{rule}) + event := func(vk uint32, up bool, vm string, suppress bool, expected ...EmittedKey) { + t.Helper() + got, emit := e.ProcessEvent(KeyEvent{VK: vk, Up: up}, vm, vm != "") + if got != suppress || !slices.Equal(emit, expected) { + t.Fatalf("event %#x up=%v vm=%q = %v %v, want %v %v", vk, up, vm, got, emit, suppress, expected) + } + } + event(vkLWin, false, "mac", false) + event(vkLWin, true, "mac", false) + rightCtrl := EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true} + event(vkRWin, false, "mac", true, rightCtrl) + event(vkRWin, false, "mac", true) + rightCtrl.Up = true + event(vkRWin, true, "", true, rightCtrl) + event(vkLAlt, false, "mac", true) + event(vkLCtrl, false, "mac", false) + event(vkLWin, false, "mac", false, EmittedKey{VK: vkLAlt, Scan: 0x38}) + event(vkLAlt, true, "mac", true, EmittedKey{VK: vkLAlt, Scan: 0x38, Up: true}) + event(vkLWin, false, "mac", false) + event(vkLWin, true, "mac", false) + event(vkLCtrl, true, "mac", false) + rule.CarrierReady = true + e.SetRules([]KeymapRule{rule}) + event(vkLWin, false, "other", false) + event(vkLWin, false, "mac", false) + event(vkLWin, true, "mac", false) + cmd := EmittedKey{VK: 0x84, Scan: 0x6C} + event(vkLWin, false, "mac", true, cmd) + cmd.Up = true + if got := e.ReleaseIfFocusLost("other"); !slices.Equal(got, []EmittedKey{cmd}) { + t.Fatalf("focus loss = %v", got) + } + event(vkLWin, true, "", true) + event(vkRWin, false, "mac", true, EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true}) + if got := e.SetRules(nil); !slices.Equal(got, []EmittedKey{rightCtrl}) { + t.Fatalf("rule replacement = %v", got) + } + event(vkRWin, true, "mac", true) +} + +func TestKeymapHookStaysOffWithoutReadyTarget(t *testing.T) { + svc := NewInputService(nil) + defer svc.Close() + svc.SetKeymapRules([]KeymapRule{{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd"}}}) + svc.SetTargets([]IMETarget{{VMName: "mac", PID: 42}}) + if svc.IsKeymapHookInstalled() || svc.IsKeymapActiveForVM("mac") { + t.Fatal("hook should stay inactive while the carrier is unavailable") + } + svc.SetKeymapRules([]KeymapRule{{VMName: "other", Bindings: map[string]string{"lwin": "esc"}}}) + if svc.IsKeymapHookInstalled() { + t.Fatal("hook should stay inactive for a nonmatching VM") + } +} + +func TestKeymapReconcilesLostKeyUps(t *testing.T) { + e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}}) + for _, vk := range []uint32{vkLCtrl, vkLAlt} { + e.ProcessEvent(KeyEvent{VK: vk}, "vm", true) + } + isDown := func(uint32) bool { return false } + // First tick arms the two-tick grace so a freshly pressed key is never cleared early. + if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || !e.physical[vkLCtrl] || !e.physical[vkLAlt] { + t.Fatalf("first reconcile tick should retain grace state: keys=%v physical=%v", keys, e.physical) + } + // Second tick clears lost unsuppressed modifiers. + if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || e.physical[vkLCtrl] || e.physical[vkLAlt] { + t.Fatalf("second reconcile tick should clear lost unmapped keys: keys=%v physical=%v", keys, e.physical) + } + // A suppressed mapped key never sets GetAsyncKeyState on Windows, so repeated + // ReconcilePhysical ticks with isDown==false must NEVER release it early. + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] { + t.Fatalf("Win down after reconciliation: %v %v", suppress, keys) + } + for i := 0; i < 5; i++ { + if keys := e.ReconcilePhysical(isDown); len(keys) != 0 { + t.Fatalf("reconcile tick %d prematurely released suppressed key: %v", i, keys) + } + } + if !e.physical[vkLWin] || e.activeMapped[vkLWin] != keymapTargets["lcmd"] { + t.Fatalf("suppressed Win key state lost during reconcile: physical=%v mapped=%v", e.physical, e.activeMapped) + } + // Secure Desktop transition clears both physical and suppressed state via Reset(). + if keys := e.Reset(); len(keys) != 1 || keys[0].VK != keymapTargets["lcmd"].VK || !keys[0].Up { + t.Fatalf("Reset after secure desktop: %v", keys) + } + if e.HasTrackedKeys() { + t.Fatalf("Reset left tracked keys: physical=%v mapped=%v", e.physical, e.activeMapped) + } + // After returning from Secure Desktop, Win works normally again. + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] { + t.Fatalf("Win down after Reset: %v %v", suppress, keys) + } +} + +func TestKeymapAltGrCrossFocusAutoRepeat(t *testing.T) { + e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"ralt": "rcmd"}}}) + fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D} + // Pressed outside the VM -> must not suppress. + if suppress, keys := e.ProcessEvent(fake, "", false); suppress || len(keys) != 0 || !e.HasTrackedKeys() { + t.Fatalf("AltGr down outside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys()) + } + // Auto-repeat after focus enters the VM -> must keep initial non-suppressed decision. + if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 { + t.Fatalf("AltGr repeat inside VM: suppress=%v keys=%v", suppress, keys) + } + // Release inside VM -> must pass through so Windows receives fake LCtrl UP. + fake.Up = true + if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 || e.HasTrackedKeys() { + t.Fatalf("AltGr up inside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys()) + } +} + +func TestKeymapAltGr(t *testing.T) { + for _, mapped := range []bool{false, true} { + bindings := map[string]string{"lctrl": "esc", "lwin": "lcmd"} + if mapped { + bindings["ralt"] = "rcmd" + bindings["lwin"] = "lopt" + } + e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: bindings, CarrierReady: true}}) + fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D} + if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress != mapped || len(keys) != 0 || e.physical[vkLCtrl] { + t.Fatalf("AltGr fake Ctrl down: %v %v", suppress, keys) + } + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkRAlt}, "vm", true); suppress != mapped || (mapped && (len(keys) != 1 || keys[0] != keymapTargets["rcmd"])) { + t.Fatalf("AltGr right Alt: %v %v", suppress, keys) + } + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets[bindings["lwin"]] { + t.Fatalf("Win with AltGr: %v %v", suppress, keys) + } + e.ReleaseIfFocusLost("") + fake.Up = true + if suppress, keys := e.ProcessEvent(fake, "", false); suppress != mapped || len(keys) != 0 || e.altGrCtrlSuppressed { + t.Fatalf("AltGr fake Ctrl up after focus loss: %v %v", suppress, keys) + } + } +} + +func TestKeymapUnrelatedRuleChangeKeepsHeldKey(t *testing.T) { + rule := KeymapRule{VMName: "a", Bindings: map[string]string{"lwin": "lcmd"}, CarrierReady: true} + e := NewKeymapEngine([]KeymapRule{rule}) + e.ProcessEvent(KeyEvent{VK: vkLWin}, "a", true) + if keys := e.SetRules([]KeymapRule{rule, {VMName: "b", Bindings: map[string]string{"lwin": "esc"}}}); len(keys) != 0 { + t.Fatalf("unrelated update released key: %v", keys) + } + if keys := e.SetRules(nil); len(keys) != 1 || !keys[0].Up { + t.Fatalf("removing held rule should release key: %v", keys) + } +} + +func TestKeymapCapturePreservesPhysicalCtrl(t *testing.T) { + e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: map[string]string{"lalt": "lctrl"}}}) + e.ProcessEvent(KeyEvent{VK: vkLCtrl}, "vm", true) + e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true) + suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true) + if suppress || len(keys) != 1 || keys[0] != (EmittedKey{VK: vkLAlt, Scan: 0x38}) { + t.Fatalf("capture release with physical Ctrl: %v %v", suppress, keys) + } +} + +func TestKeymapWinLPassesOrdinaryKey(t *testing.T) { + for _, modifier := range []uint32{0, 0xA0, vkLAlt, vkLCtrl} { + e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}}) + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 { + t.Fatalf("Win in VM: %v %v", suppress, keys) + } + if modifier != 0 { + e.ProcessEvent(KeyEvent{VK: modifier}, "vm", true) + } + for _, up := range []bool{false, true} { + if suppress, keys := e.ProcessEvent(KeyEvent{VK: 'L', Up: up}, "vm", true); suppress || len(keys) != 0 { + t.Fatalf("L with modifier %#x: %v %v", modifier, suppress, keys) + } + } + } + e := NewKeymapEngine(nil) + for _, vk := range []uint32{vkLWin, 'L'} { + if suppress, keys := e.ProcessEvent(KeyEvent{VK: vk}, "", false); suppress || len(keys) != 0 { + t.Fatalf("Win+L outside VM: %v %v", suppress, keys) + } + } +} diff --git a/internal/host/keymap_windows.go b/internal/host/keymap_windows.go new file mode 100644 index 0000000..b415967 --- /dev/null +++ b/internal/host/keymap_windows.go @@ -0,0 +1,225 @@ +//go:build windows + +package host + +import ( + "runtime" + "sync" + "sync/atomic" + "syscall" + "unsafe" +) + +const ( + llkhfInjected = 0x10 + wmKeymapRefresh = 0x8001 + wmTimer = 0x0113 + desktopReadObjects = 0x0001 +) + +var ( + procKeymapSetTimer = user32.NewProc("SetTimer") + procKeymapKillTimer = user32.NewProc("KillTimer") + procKeymapAsyncKeyState = user32.NewProc("GetAsyncKeyState") + procOpenInputDesktop = user32.NewProc("OpenInputDesktop") + procCloseDesktop = user32.NewProc("CloseDesktop") + keymapCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapKeyboardProc) }) + activeKeymapHook atomic.Pointer[keymapHook] +) + +type winKeyboardInput struct { + inputType uint32 + keyboard struct { + vk uint16 + scan uint16 + flags uint32 + time uint32 + extra uintptr + padding [2]uint32 + } +} + +var _ [unsafe.Sizeof(winMouseInput{}) - unsafe.Sizeof(winKeyboardInput{})]byte +var _ [unsafe.Sizeof(winKeyboardInput{}) - unsafe.Sizeof(winMouseInput{})]byte + +type keymapHook struct { + service *InputService + threadID uintptr + done chan struct{} + engine *KeymapEngine + snapshot *keymapSnapshot + timer uintptr + inputDesktopAvailable bool + closeOnce sync.Once +} + +func startKeymapHook(service *InputService) *keymapHook { + h := &keymapHook{service: service, done: make(chan struct{})} + if !activeKeymapHook.CompareAndSwap(nil, h) { + return nil + } + ready := make(chan bool) + go h.run(ready) + if !<-ready { + <-h.done + return nil + } + return h +} + +func (h *keymapHook) run(ready chan<- bool) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + defer close(h.done) + defer activeKeymapHook.CompareAndSwap(h, nil) + h.threadID, _, _ = procGetCurrentThreadId.Call() + var msg winMsg + procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove) + h.snapshot = h.service.keymapState.Load() + h.engine = NewKeymapEngine(h.snapshot.rules) + h.inputDesktopAvailable = keymapInputDesktopAccessible() + for vk := range hostModifiers { + if keymapPhysicalDown(vk) { + h.engine.physical[vk] = true + } + } + module, _, _ := procGetModuleHandleW.Call(0) + hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), module, 0) + if hook == 0 { + ready <- false + return + } + defer procUnhookWindowsHookEx.Call(hook) + defer func() { sendMappedKeys(h.engine.ReleaseAll()) }() + h.syncTimer() + defer func() { + if h.timer != 0 { + procKeymapKillTimer.Call(0, h.timer) + } + }() + ready <- true + for { + result, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(result) <= 0 { + return + } + if msg.message == wmKeymapRefresh || msg.message == wmTimer { + h.syncSnapshot() + if h.inputDesktopAvailable && !keymapInputDesktopAccessible() { + sendMappedKeys(h.engine.Reset()) + } else { + sendMappedKeys(h.engine.ReconcilePhysical(keymapPhysicalDown)) + if h.engine.heldVM != "" { + sendMappedKeys(h.engine.ReleaseIfFocusLost(h.foregroundVM())) + } + } + h.syncTimer() + } + } +} + +func (h *keymapHook) syncSnapshot() { + if next := h.service.keymapState.Load(); next != h.snapshot { + h.snapshot = next + sendMappedKeys(h.engine.SetRules(next.rules)) + } +} + +func (h *keymapHook) foregroundVM() string { + window, _, _ := procGetForegroundWindow.Call() + if window == 0 { + return "" + } + var pid uint32 + procGetWindowThreadProcessId.Call(window, uintptr(unsafe.Pointer(&pid))) + return h.snapshot.targets[pid] +} + +func keymapKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr { + if code == hcAction && kbd != nil && + !(kbd.flags&llkhfInjected != 0 && kbd.dwExtraInfo == reimsInjectedInputMagic) { + switch message { + case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp: + if h := activeKeymapHook.Load(); h != nil { + h.syncSnapshot() + modifier := hostModifiers[kbd.vkCode] != "" + vm := "" + if modifier || h.engine.heldVM != "" { + vm = h.foregroundVM() + sendMappedKeys(h.engine.ReleaseIfFocusLost(vm)) + } + + if !modifier { + break + } + suppress, emit := h.engine.ProcessEvent(KeyEvent{ + VK: kbd.vkCode, ScanCode: kbd.scanCode, Up: message == wmKeyUp || message == wmSysKeyUp, + }, vm, vm != "") + sendMappedKeys(emit) + h.syncTimer() + if suppress { + return 1 + } + } + } + } + result, _, _ := procCallNextHookEx.Call(0, uintptr(code), message, uintptr(unsafe.Pointer(kbd))) + return result +} + +func keymapPhysicalDown(vk uint32) bool { + state, _, _ := procKeymapAsyncKeyState.Call(uintptr(vk)) + return state&0x8000 != 0 +} + +func keymapInputDesktopAccessible() bool { + desk, _, _ := procOpenInputDesktop.Call(0, 0, desktopReadObjects) + if desk == 0 { + return false + } + procCloseDesktop.Call(desk) + return true +} + +func (h *keymapHook) syncTimer() { + if h.engine.HasTrackedKeys() { + if h.timer == 0 { + h.timer, _, _ = procKeymapSetTimer.Call(0, 0, 50, 0) + } + } else if h.timer != 0 { + procKeymapKillTimer.Call(0, h.timer) + h.timer = 0 + } +} + +func sendMappedKeys(keys []EmittedKey) { + if len(keys) == 0 { + return + } + inputs := make([]winKeyboardInput, len(keys)) + for i, key := range keys { + input := &inputs[i] + input.inputType = 1 // INPUT_KEYBOARD + input.keyboard.vk = key.VK + input.keyboard.scan = key.Scan + input.keyboard.extra = reimsInjectedInputMagic + if key.Extended { + input.keyboard.flags |= 1 // KEYEVENTF_EXTENDEDKEY + } + if key.Up { + input.keyboard.flags |= 2 // KEYEVENTF_KEYUP + } + } + procSendInput.Call(uintptr(len(inputs)), uintptr(unsafe.Pointer(&inputs[0])), unsafe.Sizeof(inputs[0])) +} + +func (h *keymapHook) refresh() { + procPostThreadMessageW.Call(h.threadID, wmKeymapRefresh, 0, 0) +} + +func (h *keymapHook) Close() { + h.closeOnce.Do(func() { + procPostThreadMessageW.Call(h.threadID, wmQuit, 0, 0) + <-h.done + }) +} diff --git a/internal/vmstart/keymap.go b/internal/vmstart/keymap.go new file mode 100644 index 0000000..80a644a --- /dev/null +++ b/internal/vmstart/keymap.go @@ -0,0 +1,159 @@ +package vmstart + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +type KeymapPreset string +type HostModifier string +type GuestModifier string + +const ( + KeymapOff KeymapPreset = "off" + KeymapWinToCmd KeymapPreset = "win_to_cmd" + KeymapSwapAltWin KeymapPreset = "swap_alt_win" + KeymapCustom KeymapPreset = "custom" + keymapConfigFile = ".reims-go-keymap.json" +) + +type VMKeymapConfig struct { + Preset KeymapPreset `json:"preset"` + Bindings map[HostModifier]GuestModifier `json:"bindings,omitempty"` +} + +func DefaultVMKeymapConfig() VMKeymapConfig { return VMKeymapConfig{Preset: KeymapOff} } + +func NormalizeKeymapPreset(p KeymapPreset) KeymapPreset { + switch p = KeymapPreset(normalizeKeymapValue(string(p))); p { + case KeymapWinToCmd, KeymapSwapAltWin, KeymapCustom: + return p + default: + return KeymapOff + } +} + +func normalizeKeymapValue(s string) string { return strings.ToLower(strings.TrimSpace(s)) } + +func PresetBindings(p KeymapPreset) map[HostModifier]GuestModifier { + switch NormalizeKeymapPreset(p) { + case KeymapWinToCmd: + return map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd"} + case KeymapSwapAltWin: + return map[HostModifier]GuestModifier{"lalt": "lcmd", "ralt": "rcmd", "lwin": "lopt", "rwin": "ropt"} + default: + return map[HostModifier]GuestModifier{} + } +} + +func validHostModifier(k HostModifier) bool { + switch k { + case "lwin", "rwin", "lalt", "ralt", "lctrl", "rctrl", "capslock": + return true + } + return false +} + +func validGuestModifier(k GuestModifier) bool { + switch k { + case "", "default", "lcmd", "rcmd", "lopt", "ropt", "lctrl", "rctrl", "esc", "disabled": + return true + } + return false +} + +func ResolveKeymapBindings(cfg VMKeymapConfig) map[HostModifier]GuestModifier { + bindings := PresetBindings(cfg.Preset) + if NormalizeKeymapPreset(cfg.Preset) != KeymapCustom { + return bindings + } + for rawHost, rawGuest := range cfg.Bindings { + k := HostModifier(normalizeKeymapValue(string(rawHost))) + v := GuestModifier(normalizeKeymapValue(string(rawGuest))) + if validHostModifier(k) && validGuestModifier(v) && v != "" && v != "default" && string(k) != string(v) { + bindings[k] = v + } + } + return bindings +} + +func NeedsGuestCarrier(bindings map[HostModifier]GuestModifier) bool { + for _, v := range bindings { + switch v { + case "lcmd", "rcmd", "lopt", "ropt": + return true + } + } + return false +} + +func ReadVMKeymap(vmDir string) VMKeymapConfig { + if strings.TrimSpace(vmDir) == "" { + return DefaultVMKeymapConfig() + } + data, err := os.ReadFile(filepath.Join(vmDir, keymapConfigFile)) + var cfg VMKeymapConfig + if err != nil || json.Unmarshal(data, &cfg) != nil { + return DefaultVMKeymapConfig() + } + cfg.Preset = NormalizeKeymapPreset(cfg.Preset) + if cfg.Preset == KeymapCustom { + cfg.Bindings = ResolveKeymapBindings(cfg) + } else { + cfg.Bindings = nil + } + return cfg +} + +func SaveVMKeymap(vmDir string, cfg VMKeymapConfig) (VMKeymapConfig, error) { + if strings.TrimSpace(vmDir) == "" { + return VMKeymapConfig{}, errors.New("VM directory is empty") + } + cfg.Preset = KeymapPreset(normalizeKeymapValue(string(cfg.Preset))) + if cfg.Preset != KeymapOff && NormalizeKeymapPreset(cfg.Preset) == KeymapOff { + return VMKeymapConfig{}, fmt.Errorf("invalid keymap preset %q", cfg.Preset) + } + seen := make(map[HostModifier]bool, len(cfg.Bindings)) + for rawHost, rawGuest := range cfg.Bindings { + k := HostModifier(normalizeKeymapValue(string(rawHost))) + v := GuestModifier(normalizeKeymapValue(string(rawGuest))) + if !validHostModifier(k) || !validGuestModifier(v) || seen[k] { + return VMKeymapConfig{}, fmt.Errorf("invalid keymap binding %q → %q", rawHost, rawGuest) + } + seen[k] = true + } + dst := filepath.Join(vmDir, keymapConfigFile) + if cfg.Preset == KeymapOff { + err := os.Remove(dst) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return VMKeymapConfig{}, err + } + return DefaultVMKeymapConfig(), nil + } + if cfg.Preset == KeymapCustom { + cfg.Bindings = ResolveKeymapBindings(cfg) + } else { + cfg.Bindings = nil + } + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return VMKeymapConfig{}, err + } + tmp, err := os.CreateTemp(vmDir, keymapConfigFile+".*") + if err != nil { + return VMKeymapConfig{}, err + } + defer os.Remove(tmp.Name()) + _, writeErr := tmp.Write(data) + if err := errors.Join(writeErr, tmp.Close()); err != nil { + return VMKeymapConfig{}, err + } + if err := os.Rename(tmp.Name(), dst); err != nil { + return VMKeymapConfig{}, err + } + return cfg, nil +} diff --git a/internal/vmstart/keymap_test.go b/internal/vmstart/keymap_test.go new file mode 100644 index 0000000..d4bbeb3 --- /dev/null +++ b/internal/vmstart/keymap_test.go @@ -0,0 +1,60 @@ +package vmstart + +import ( + "maps" + "os" + "path/filepath" + "testing" +) + +func TestVMKeymapPersistence(t *testing.T) { + dir := t.TempDir() + if got := ReadVMKeymap(dir); got.Preset != KeymapOff { + t.Fatalf("default = %+v", got) + } + cfg := VMKeymapConfig{Preset: " CUSTOM ", Bindings: map[HostModifier]GuestModifier{ + " LWIN ": " LCMD ", "capslock": "esc", "lctrl": "lctrl", "rwin": "default", + }} + want := map[HostModifier]GuestModifier{"lwin": "lcmd", "capslock": "esc"} + for i := 0; i < 2; i++ { + got, err := SaveVMKeymap(dir, cfg) + if err != nil || got.Preset != KeymapCustom || !maps.Equal(got.Bindings, want) { + t.Fatalf("save = %+v, %v", got, err) + } + } + for _, bad := range []VMKeymapConfig{ + {Preset: "bad"}, + {Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"win": "esc"}}, + {Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"lwin": "bad"}}, + {Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"lwin": "lcmd", " LWIN": "esc"}}, + } { + if _, err := SaveVMKeymap(dir, bad); err == nil { + t.Fatalf("accepted %+v", bad) + } + } + if got := ReadVMKeymap(dir); got.Preset != KeymapCustom || !maps.Equal(got.Bindings, want) { + t.Fatalf("read after invalid updates = %+v", got) + } + if _, err := SaveVMKeymap(dir, DefaultVMKeymapConfig()); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, keymapConfigFile)); !os.IsNotExist(err) { + t.Fatalf("disabled config was not removed: %v", err) + } +} + +func TestKeymapPresets(t *testing.T) { + for _, tc := range []struct { + preset KeymapPreset + want map[HostModifier]GuestModifier + }{ + {KeymapOff, nil}, + {KeymapWinToCmd, map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd"}}, + {KeymapSwapAltWin, map[HostModifier]GuestModifier{"lwin": "lopt", "rwin": "ropt", "lalt": "lcmd", "ralt": "rcmd"}}, + } { + bindings := ResolveKeymapBindings(VMKeymapConfig{Preset: tc.preset}) + if !maps.Equal(bindings, tc.want) || NeedsGuestCarrier(bindings) != (len(tc.want) > 0) { + t.Fatalf("%s = %v", tc.preset, bindings) + } + } +} diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index cf32f40..0bf5bd2 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -1,4 +1,34 @@ { + "keymapGroupTitle": "Modifier keys", + "keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.", + "keymapPresetTitle": "Preset", + "keymapRunning": "Active while this VM is focused", + "keymapStopped": "Applies when this VM is running", + "keymapWaiting": "Waiting for Guest Tools to connect", + "keymapUpgrade": "Update Guest Tools to version {version}", + "keymapPending": "Waiting for Guest Tools to activate modifier mapping", + "keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping", + "keymapInactive": "Modifier mapping is inactive", + "keymapPresetOff": "Off", + "keymapPresetWinToCmd": "Win → ⌘", + "keymapPresetSwapAltWin": "Alt ↔ Win", + "keymapPresetCustom": "Custom", + "keymapHostLwin": "Left Win", + "keymapHostRwin": "Right Win", + "keymapHostLalt": "Left Alt", + "keymapHostRalt": "Right Alt", + "keymapHostLctrl": "Left Ctrl", + "keymapHostRctrl": "Right Ctrl", + "keymapHostCapslock": "Caps Lock", + "keymapGuestDefault": "Default", + "keymapGuestLcmd": "Left ⌘ Command", + "keymapGuestRcmd": "Right ⌘ Command", + "keymapGuestLopt": "Left ⌥ Option", + "keymapGuestRopt": "Right ⌥ Option", + "keymapGuestLctrl": "Left ⌃ Control", + "keymapGuestRctrl": "Right ⌃ Control", + "keymapGuestEsc": "Esc", + "keymapGuestDisabled": "Disabled", "installersTitle": "Installers", "installersDownloaded": "Downloaded", "installersAvailable": "Releases from Apple", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index e46c6aa..8dac5ee 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -1,4 +1,34 @@ { + "keymapGroupTitle": "修饰键映射", + "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。", + "keymapPresetTitle": "映射预设", + "keymapRunning": "虚拟机获得焦点时生效", + "keymapStopped": "虚拟机启动后生效", + "keymapWaiting": "等待 Guest Tools 连接", + "keymapUpgrade": "请将 Guest Tools 更新到版本 {version}", + "keymapPending": "等待 Guest Tools 启用修饰键映射", + "keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射", + "keymapInactive": "修饰键映射未启用", + "keymapPresetOff": "关闭", + "keymapPresetWinToCmd": "Win → ⌘", + "keymapPresetSwapAltWin": "Alt ↔ Win", + "keymapPresetCustom": "自定义", + "keymapHostLwin": "左 Win", + "keymapHostRwin": "右 Win", + "keymapHostLalt": "左 Alt", + "keymapHostRalt": "右 Alt", + "keymapHostLctrl": "左 Ctrl", + "keymapHostRctrl": "右 Ctrl", + "keymapHostCapslock": "Caps Lock", + "keymapGuestDefault": "默认", + "keymapGuestLcmd": "左 ⌘ Command", + "keymapGuestRcmd": "右 ⌘ Command", + "keymapGuestLopt": "左 ⌥ Option", + "keymapGuestRopt": "右 ⌥ Option", + "keymapGuestLctrl": "左 ⌃ Control", + "keymapGuestRctrl": "右 ⌃ Control", + "keymapGuestEsc": "Esc", + "keymapGuestDisabled": "禁用", "installersTitle": "安装包", "installersDownloaded": "已下载", "installersAvailable": "Apple 提供的版本",