diff --git a/changes/remove-modifier-key-mapping.json b/changes/remove-modifier-key-mapping.json new file mode 100644 index 0000000..5004fce --- /dev/null +++ b/changes/remove-modifier-key-mapping.json @@ -0,0 +1,7 @@ +{ + "group": "removals", + "order": 0, + "authors": ["Nwflower"], + "zh": "移除按虚拟机设置的修饰键重映射和「拦截宿主机全局热键」。升级后,原有设置停止生效,虚拟机恢复默认按键处理。", + "en": "Remove per-VM modifier-key remapping and host global shortcut blocking. Existing settings stop taking effect after upgrading, and VMs return to default keyboard handling." +} diff --git a/docs/testing.md b/docs/testing.md index c194e2f..34e4f9f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -25,7 +25,7 @@ Go 包并发默认为可用 CPU 数与 4 的较小值,每个包的运行上限 ## 覆盖和后续改进 -- 前端测试直接加载生产模块验证任务排序、过期事件和键位映射。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。 +- 前端测试直接加载生产模块验证任务排序和过期事件。涉及界面交互时优先覆盖用户可观察的状态切换,不按源码行或正则截取组件源码执行。 - Go 单包测试验证领域规则,跨层测试保留桌面桥接、控制套接字、本地 HTTP、子进程与数据迁移等真实接口用例。异步用例通过完成信号控制时序,超时只用于报告卡死。 - 存储层测试使用真实临时目录验证配置、目录锁、版本升级、插件状态备份与损坏恢复。 - 依赖真实便携运行时、磁盘工具、引导镜像与安装包的集成用例仅在传入对应的 `REIMS_GO_TEST_*` 环境变量时运行,常规档位自动跳过。改动涉及虚拟机运行或磁盘操作时须在 Windows 宿主机实测验证。 diff --git a/frontend/scripts/test-keymap.mjs b/frontend/scripts/test-keymap.mjs deleted file mode 100644 index a3bd6a6..0000000 --- a/frontend/scripts/test-keymap.mjs +++ /dev/null @@ -1,150 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { loadTestModule } from './load-test-module.mjs' - -const { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets } = await loadTestModule(`export * from './lib/vmKeymap'`) -const off = { preset: 'off', bindings: {}, capture_host_shortcuts: false } -const custom = { preset: 'custom', bindings: { lwin: 'lcmd' }, capture_host_shortcuts: true } - -test('switching presets preserves shortcut capture and carries bindings into custom', () => { - const preset = { ...custom, preset: 'win_to_cmd' } - assert.equal(keymapPresetUpdate(preset, 'win_to_cmd'), undefined) - assert.deepEqual(keymapPresetUpdate(preset, 'custom'), custom) - assert.deepEqual(keymapPresetUpdate(custom, 'off'), { ...off, capture_host_shortcuts: true }) - assert.deepEqual(keymapPresetUpdate(off, 'custom'), { ...off, preset: 'custom' }) -}) - -test('editing one binding preserves the other bindings, preset, and shortcut capture', () => { - assert.deepEqual(keymapUpdate(custom, { bindings: { lalt: 'disabled' } }), { - ...custom, - bindings: { lwin: 'lcmd', lalt: 'disabled' }, - }) -}) - -test('toggling shortcut capture preserves the preset and bindings', () => { - const captureOff = { ...custom, capture_host_shortcuts: false } - assert.deepEqual(keymapUpdate(captureOff, { capture_host_shortcuts: true }), custom) - assert.deepEqual(keymapUpdate(custom, { capture_host_shortcuts: false }), captureOff) - assert.deepEqual(keymapUpdate(off, { capture_host_shortcuts: true }), { ...off, capture_host_shortcuts: true }) -}) - -test('a pending write for one VM does not block or overwrite another VM', async () => { - const saved = Promise.withResolvers() - const writes = [] - let active = 'a' - let state = {} - const requests = createKeymapRequests({ - async GetVMKeymap(name) { - assert.equal(name, 'b') - return off - }, - SetVMKeymap(name, request) { - writes.push([name, request]) - return saved.promise - }, - }, () => active, (patch) => Object.assign(state, patch)) - - const write = requests.write('a', custom) - await requests.write('a', off) - assert.deepEqual(writes, [['a', custom]]) - assert.equal(state.busy, true) - - active = 'b' - state = requests.initial('b') - await requests.watch('b').refresh() - saved.resolve(custom) - await write - assert.deepEqual(state, { keymap: off, busy: false, error: '' }) - assert.equal(requests.initial('a').busy, false) -}) - -test('a failed keymap read recovers on the next refresh', async () => { - let fail = true - const state = {} - const requests = createKeymapRequests({ - async GetVMKeymap() { - if (fail) throw new Error('temporary') - return off - }, - }, () => 'vm', (patch) => Object.assign(state, patch)) - const watch = requests.watch('vm') - await watch.refresh() - assert.equal(state.error, 'temporary') - fail = false - await watch.refresh() - assert.deepEqual(state, { keymap: off, error: '' }) -}) - -test('a read started before a write cannot restore the old keymap', async () => { - const previousRead = Promise.withResolvers() - const state = {} - const requests = createKeymapRequests({ - GetVMKeymap: () => previousRead.promise, - SetVMKeymap: async () => custom, - }, () => 'vm', (patch) => Object.assign(state, patch)) - - const read = requests.watch('vm').refresh() - await requests.write('vm', custom) - previousRead.resolve(off) - await read - assert.deepEqual(state, { keymap: custom, busy: false, error: '' }) -}) - -test('visibleKeymapPresets hides win_to_cmd on modern runtimes unless already selected', () => { - assert.deepEqual(visibleKeymapPresets('off', false), ['off', 'swap_alt_win', 'custom']) - assert.deepEqual(visibleKeymapPresets('swap_alt_win', false), ['off', 'swap_alt_win', 'custom']) - assert.deepEqual(visibleKeymapPresets('custom', false), ['off', 'swap_alt_win', 'custom']) - assert.deepEqual(visibleKeymapPresets('win_to_cmd', false), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) - assert.deepEqual(visibleKeymapPresets('off', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) - assert.deepEqual(visibleKeymapPresets('swap_alt_win', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom']) -}) - -test('keymapStatusHint returns null when both preset and shortcut capture are off', () => { - const base = { - preset: 'off', - bindings: {}, - capture_host_shortcuts: false, - needs_guest_tools: false, - guest_connected: true, - guest_agent_version: 5, - required_agent_version: 5, - input_service_available: true, - guest_keymap_active: true, - hook_active: true, - running: true, - } - assert.equal(keymapStatusHint(base), null) -}) - -test('keymapStatusHint resolves priority when only capture_host_shortcuts is enabled', () => { - const base = { - preset: 'off', - bindings: {}, - capture_host_shortcuts: true, - needs_guest_tools: false, - guest_connected: false, - guest_agent_version: 0, - required_agent_version: 4, - input_service_available: true, - guest_keymap_active: false, - hook_active: true, - running: true, - } - assert.deepEqual(keymapStatusHint(base), { key: 'keymapRunning' }) - assert.deepEqual(keymapStatusHint({ ...base, hook_active: false }), { key: 'keymapInactive' }) - assert.deepEqual(keymapStatusHint({ ...base, running: false }), { key: 'keymapStopped' }) - assert.deepEqual(keymapStatusHint({ ...base, input_service_available: false, running: false }), { key: 'keymapInputServiceRequired' }) - assert.deepEqual(keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: false }), { key: 'keymapWaiting' }) - assert.deepEqual( - keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 3, required_agent_version: 4 }), - { key: 'keymapUpgrade', vars: { version: 4 } }, - ) - assert.deepEqual( - keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: false }), - { key: 'keymapPending' }, - ) - assert.deepEqual( - keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: true }), - { key: 'keymapRunning' }, - ) -}) diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 8ac3697..91a356f 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -45,7 +45,6 @@ import { formatAffinitySummary } from './AffinityDialog' import { VMNetworkSettings } from './VMNetworkSettings' import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk' import { DiskCacheRow } from './vmSettings/diskCache' -import { KeymapSection, useKeymap } from './vmSettings/keymap' import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins' import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing' import { SMBIOSDialog, SMBIOSSection, useSMBIOS } from './vmSettings/smbios' @@ -183,7 +182,6 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const drives = useDriveShares(detail.name) const folders = useSharedFolders(detail.name, locale) const smbios = useSMBIOS(detail, running) - const keymap = useKeymap(detail.name, running, cat === 'input') const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr) const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged }) const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general') @@ -846,7 +844,6 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats /> )} - = { - off: 'keymapPresetOff', - win_to_cmd: 'keymapPresetWinToCmd', - swap_alt_win: 'keymapPresetSwapAltWin', - custom: 'keymapPresetCustom', -} - -/** The VM's modifier key mapping, refreshed while shown. */ -export function useKeymap(vm: string, running: boolean, shown: boolean) { - const activeVMNameRef = useRef(vm) - activeVMNameRef.current = vm - const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState({ keymap: null, error: '', busy: false }) - const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current, - (patch) => setKeymapState((state) => ({ ...state, ...patch })))) - - useEffect(() => { - setKeymapState(keymapRequests.initial(vm)) - }, [vm, keymapRequests]) - - useEffect(() => { - if (!shown) return - const { refresh, stop } = keymapRequests.watch(vm) - void refresh() - const timer = window.setInterval(refresh, 3000) - return () => { stop(); window.clearInterval(timer) } - }, [shown, vm, running, keymapRequests]) - - return { keymap, keymapErr, keymapBusy, write: keymapRequests.write } -} - -export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType; captureSupported: boolean }> = ({ locale, vm, state, captureSupported }) => { - const tr = (k: I18nKey, v?: Record) => t(locale, k, v) - const { keymap, keymapErr, keymapBusy, write } = state - const statusHint = keymap ? keymapStatusHint(keymap) : null - const presetOptions = keymap - ? visibleKeymapPresets(keymap.preset, captureSupported).map((value) => ({ value, label: tr(PRESET_LABEL[value]) })) - : [] - return ( - - {keymapErr &&
{keymapErr}
} - {keymap && <> - label={tr('keymapPresetTitle')} value={keymap.preset} - options={presetOptions} - onChange={(preset) => { - const request = keymapPresetUpdate(keymap, preset) - if (request) void write(vm, request) - }} />} - /> - { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />} - /> - {statusHint && ( - - )} - {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) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />} - /> - ))} - } -
- ) -} diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index ea58163..75e1652 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -368,40 +368,6 @@ export const settingsZh: Record = { "kernelIrqchipLabel": "中断加速", "kernelIrqchipOff": "关闭", "kernelIrqchipOn": "开启", - "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option", - "keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键", - "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": "自定义", - "keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可", - "keymapPresetOff": "关闭", - "keymapPresetSwapAltWin": "Alt ↔ Win", - "keymapPresetTitle": "映射预设", - "keymapPresetWinToCmd": "Win → ⌘", - "keymapRunning": "虚拟机获得焦点时生效", - "keymapStatusTitle": "生效状态", - "keymapStopped": "虚拟机启动后生效", - "keymapUpgrade": "请将 Guest Tools 更新到版本 {version}", - "keymapWaiting": "等待 Guest Tools 连接", "language": "语言", "languageSub": "内置简体中文与英语,可通过插件扩展更多语言", "logLevel": "日志级别", @@ -918,40 +884,6 @@ export const settingsEn: Record = { "kernelIrqchipLabel": "Interrupt acceleration", "kernelIrqchipOff": "Off", "kernelIrqchipOn": "On", - "keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS", - "keymapCaptureHostShortcutsTitle": "Block host global hotkeys", - "keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard 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", - "keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed", - "keymapPresetOff": "Off", - "keymapPresetSwapAltWin": "Alt ↔ Win", - "keymapPresetTitle": "Preset", - "keymapPresetWinToCmd": "Win → ⌘", - "keymapRunning": "Active while this VM is focused", - "keymapStatusTitle": "Status", - "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 359fa08..6fe552c 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -609,40 +609,6 @@ export type I18nKey = | "kernelIrqchipLabel" | "kernelIrqchipOff" | "kernelIrqchipOn" - | "keymapCaptureHostShortcutsDesc" - | "keymapCaptureHostShortcutsTitle" - | "keymapGroupNote" - | "keymapGroupTitle" - | "keymapGuestDefault" - | "keymapGuestDisabled" - | "keymapGuestEsc" - | "keymapGuestLcmd" - | "keymapGuestLctrl" - | "keymapGuestLopt" - | "keymapGuestRcmd" - | "keymapGuestRctrl" - | "keymapGuestRopt" - | "keymapHostCapslock" - | "keymapHostLalt" - | "keymapHostLctrl" - | "keymapHostLwin" - | "keymapHostRalt" - | "keymapHostRctrl" - | "keymapHostRwin" - | "keymapInactive" - | "keymapInputServiceRequired" - | "keymapPending" - | "keymapPresetCustom" - | "keymapPresetDesc" - | "keymapPresetOff" - | "keymapPresetSwapAltWin" - | "keymapPresetTitle" - | "keymapPresetWinToCmd" - | "keymapRunning" - | "keymapStatusTitle" - | "keymapStopped" - | "keymapUpgrade" - | "keymapWaiting" | "language" | "languageSub" | "localeAuto" diff --git a/frontend/src/lib/vmKeymap.ts b/frontend/src/lib/vmKeymap.ts deleted file mode 100644 index 162a0a1..0000000 --- a/frontend/src/lib/vmKeymap.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { VMKeymapPreset, VMKeymapStatus, VMKeymapUpdate } from '../types' -import { createVMSettingRequests } from './vmSettingRequests' - -type KeymapAPI = { - GetVMKeymap(name: string): Promise - SetVMKeymap(name: string, request: VMKeymapUpdate): Promise -} - -export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean } - -type KeymapStatusKey = - | 'keymapInputServiceRequired' - | 'keymapStopped' - | 'keymapWaiting' - | 'keymapUpgrade' - | 'keymapPending' - | 'keymapRunning' - | 'keymapInactive' - -type KeymapStatusHint = { key: KeymapStatusKey; vars?: { version: number } } - -const ALL_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'win_to_cmd', 'swap_alt_win', 'custom'] -const MODERN_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'swap_alt_win', 'custom'] - -export function visibleKeymapPresets(preset: VMKeymapPreset, captureSupported: boolean): readonly VMKeymapPreset[] { - if (!captureSupported && preset !== 'win_to_cmd') return MODERN_KEYMAP_PRESETS - return ALL_KEYMAP_PRESETS -} - -export function keymapStatusHint(keymap: VMKeymapStatus): KeymapStatusHint | null { - if (keymap.preset === 'off' && !keymap.capture_host_shortcuts) return null - if (!keymap.input_service_available) return { key: 'keymapInputServiceRequired' } - if (!keymap.running) return { key: 'keymapStopped' } - if (keymap.needs_guest_tools && !keymap.guest_connected) return { key: 'keymapWaiting' } - if (keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version) { - return { key: 'keymapUpgrade', vars: { version: keymap.required_agent_version } } - } - if (keymap.needs_guest_tools && !keymap.guest_keymap_active) return { key: 'keymapPending' } - return { key: keymap.hook_active ? 'keymapRunning' : 'keymapInactive' } -} - -type KeymapRequest = Required - -export function keymapUpdate(current: VMKeymapStatus, changes: Partial): KeymapRequest { - const preset = changes.preset ?? current.preset - const bindings = preset === current.preset || (preset === 'custom' && current.preset !== 'off') - ? current.bindings - : {} - return { - preset, - bindings: changes.bindings ? { ...bindings, ...changes.bindings } : bindings, - capture_host_shortcuts: changes.capture_host_shortcuts ?? current.capture_host_shortcuts, - } -} - -export function keymapPresetUpdate(current: VMKeymapStatus, preset: VMKeymapPreset): KeymapRequest | undefined { - if (preset === current.preset) return undefined - return keymapUpdate(current, { preset }) -} - -export function createKeymapRequests(api: KeymapAPI, activeVM: () => string, update: (patch: Partial) => void) { - const requests = createVMSettingRequests(activeVM, ({ value, ...patch }) => { - update(value === undefined ? patch : { ...patch, keymap: value }) - }) - - return { - initial(name: string): KeymapState { - return { keymap: null, error: '', busy: requests.isWriting(name) } - }, - watch(name: string) { - return requests.watch(name, () => api.GetVMKeymap(name)) - }, - write(name: string, request: VMKeymapUpdate) { - return requests.write(name, () => api.SetVMKeymap(name, request)) - }, - } -} diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 8b1a88b..43d6106 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -215,24 +215,3 @@ 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> - capture_host_shortcuts?: boolean -} - -export interface VMKeymapStatus extends VMKeymapUpdate { - capture_host_shortcuts: boolean - 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 09ca831..a4e1ddb 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, - ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate, + ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, } from './types' type AnyFn = (...args: never[]) => unknown @@ -157,9 +157,7 @@ export const api = { GetTasks: boundGo.GetTasks as () => Promise, GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise, SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise, - GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise, GetVMInfo: boundGo.GetVMInfo as (driverID: string, 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 31fdeb3..e066de7 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -122,8 +122,6 @@ export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promis export function GetVMInfo(arg1:string,arg2:string):Promise; -export function GetVMKeymap(arg1:string):Promise; - export function GetVMMacOS(arg1:string):Promise; export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise; @@ -278,8 +276,6 @@ export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise):Promise; -export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise; - export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise; export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 4a70818..eeef3a9 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -222,10 +222,6 @@ export function GetVMInfo(arg1, arg2) { return window['go']['app']['App']['GetVMInfo'](arg1, arg2); } -export function GetVMKeymap(arg1) { - return window['go']['app']['App']['GetVMKeymap'](arg1); -} - export function GetVMMacOS(arg1) { return window['go']['app']['App']['GetVMMacOS'](arg1); } @@ -534,10 +530,6 @@ export function SetVMDriveShareSettings(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3); } -export function SetVMKeymap(arg1, arg2) { - return window['go']['app']['App']['SetVMKeymap'](arg1, arg2); -} - export function SetVMNote(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMNote'](arg1, arg2, arg3); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index d6f54c1..0186a20 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -592,54 +592,6 @@ export namespace app { return a; } } - export class VMKeymapStatus { - preset: string; - bindings: Record; - capture_host_shortcuts: boolean; - needs_guest_tools: boolean; - guest_connected: boolean; - guest_agent_version?: number; - required_agent_version: number; - guest_keymap_active: boolean; - input_service_available: boolean; - hook_active: boolean; - running: boolean; - - static createFrom(source: any = {}) { - return new VMKeymapStatus(source); - } - - constructor(source: any = {}) { - if ('string' === typeof source) source = JSON.parse(source); - this.preset = source["preset"]; - this.bindings = source["bindings"]; - this.capture_host_shortcuts = source["capture_host_shortcuts"]; - this.needs_guest_tools = source["needs_guest_tools"]; - this.guest_connected = source["guest_connected"]; - this.guest_agent_version = source["guest_agent_version"]; - this.required_agent_version = source["required_agent_version"]; - this.guest_keymap_active = source["guest_keymap_active"]; - this.input_service_available = source["input_service_available"]; - this.hook_active = source["hook_active"]; - this.running = source["running"]; - } - } - export class VMKeymapUpdate { - preset: string; - bindings: Record; - capture_host_shortcuts?: boolean; - - static createFrom(source: any = {}) { - return new VMKeymapUpdate(source); - } - - constructor(source: any = {}) { - if ('string' === typeof source) source = JSON.parse(source); - this.preset = source["preset"]; - this.bindings = source["bindings"]; - this.capture_host_shortcuts = source["capture_host_shortcuts"]; - } - } export class VMNetworkPlan { npcap_installed: boolean; running_vms: string[]; diff --git a/internal/app/app.go b/internal/app/app.go index a88d3db..130ba97 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -150,9 +150,6 @@ type App struct { displayPlacements sync.Map - keymapMu sync.Mutex - keymapPIDs map[string]int - fallbackInputSvc *host.InputService inputShuttingDown bool // computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs. computerUseOwnedVMs map[string]map[string]bool @@ -313,12 +310,8 @@ func (a *App) shutdown(ctx context.Context) { a.stopPluginControlServer() a.mu.Lock() a.inputShuttingDown = true - fallback := a.fallbackInputSvc a.mu.Unlock() a.fullscreenHotkey.Close() - if fallback != nil { - fallback.Close() - } a.shutdownPlugins() a.mu.Lock() for name, entry := range a.rebootWatchers { diff --git a/internal/app/app_poll_test.go b/internal/app/app_poll_test.go index 32574e5..b30ece8 100644 --- a/internal/app/app_poll_test.go +++ b/internal/app/app_poll_test.go @@ -18,15 +18,10 @@ func TestPolledVMsReusesFreshPoll(t *testing.T) { a.lastVMs = []reims.VMListItem{{Name: "m0", Dir: `D:\vms\m0`, PID: &pid, State: "running"}} a.lastVMsAt = time.Now() - vm, ok := a.polledVM("m0") - if !ok || vm.State != "running" || vm.Dir != `D:\vms\m0` || *vm.PID != 42 { - t.Fatalf("polledVM = %+v, %v", vm, ok) + vms, err := a.polledVMs(context.Background()) + if err != nil || len(vms) != 1 || vms[0].Name != "m0" { + t.Fatalf("polledVMs = %+v, %v", vms, err) } - if _, ok := a.polledVM("missing"); ok { - t.Fatal("unknown VM should not be found") - } - - vms, _ := a.polledVMs(context.Background()) vms[0].State = "stopped" if a.lastVMs[0].State != "running" { t.Fatal("polledVMs must return a copy, not the cached slice") diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 88bcaba..7f58561 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -161,7 +161,6 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created }) a.guestTools = srv srv.SetHostDNSConfig(a.hostDNSConfigLocked()) - srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() }) created = true } a.syncClipboardStagingLocked() @@ -229,8 +228,6 @@ func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string { if err != nil || cfg.Token == "" { return nil } - 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, @@ -271,7 +268,6 @@ 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 deleted file mode 100644 index f15769d..0000000 --- a/internal/app/keymap_flow.go +++ /dev/null @@ -1,153 +0,0 @@ -package app - -import ( - "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/guesttools" - "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/vmstart" -) - -const KeymapRequiredAgentVersion = guesttools.KeymapAgentVersion - -type VMKeymapUpdate struct { - Preset string `json:"preset"` - Bindings map[string]string `json:"bindings"` - CaptureHostShortcuts *bool `json:"capture_host_shortcuts,omitempty"` -} - -type VMKeymapStatus struct { - Preset string `json:"preset"` - Bindings map[string]string `json:"bindings"` - CaptureHostShortcuts bool `json:"capture_host_shortcuts"` - 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 - } - a.keymapMu.Lock() - capture := vmstart.ReadVMKeymap(detail.Directory).CaptureHostShortcuts - if req.CaptureHostShortcuts != nil { - capture = *req.CaptureHostShortcuts - } - cfg := vmstart.VMKeymapConfig{ - Preset: vmstart.KeymapPreset(req.Preset), - Bindings: make(map[vmstart.HostModifier]vmstart.GuestModifier, len(req.Bindings)), - CaptureHostShortcuts: capture, - } - for k, v := range req.Bindings { - cfg.Bindings[vmstart.HostModifier(k)] = vmstart.GuestModifier(v) - } - cfg, err = vmstart.SaveVMKeymap(detail.Directory, cfg) - if err != nil { - a.keymapMu.Unlock() - return VMKeymapStatus{}, err - } - a.syncKeymapRulesLocked() - a.keymapMu.Unlock() - return a.keymapStatus(name, detail.State == "running", cfg), nil -} - -func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig) VMKeymapStatus { - status := VMKeymapStatus{ - Preset: string(cfg.Preset), - Bindings: keymapBindingStrings(vmstart.ResolveKeymapBindings(cfg)), - CaptureHostShortcuts: cfg.CaptureHostShortcuts, - NeedsGuestTools: vmstart.NeedsGuestCarrier(vmstart.EffectiveKeymapBindings(cfg)), - RequiredAgentVersion: KeymapRequiredAgentVersion, - Running: running, - } - a.mu.Lock() - srv := a.guestTools - a.mu.Unlock() - if srv != nil && running { - guest := srv.Status(name, guesttools.KeymapStatusMaxAge) - status.GuestConnected = guest.Connected - status.GuestAgentVersion = guest.AgentVersion - status.GuestKeymapActive = guest.KeymapActive - } - 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.syncKeymapRulesLocked() -} - -func (a *App) syncKeymapRulesLocked() { - a.mu.Lock() - vms := append([]driver.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.RunningPID() == 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 - cfg := vmstart.ReadVMKeymap(dir) - effective := vmstart.EffectiveKeymapBindings(cfg) - rule := host.KeymapRule{VMName: vm.Name, Bindings: keymapBindingStrings(effective)} - 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(effective)) - rule.CarrierReady = srv.Status(vm.Name, guesttools.KeymapStatusMaxAge).KeymapActive - } - if len(effective) != 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 deleted file mode 100644 index d8241ab..0000000 --- a/internal/app/keymap_flow_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package app - -import ( - "context" - "encoding/json" - "testing" - - "github.com/Nwflower/reims-go/internal/config" - "github.com/Nwflower/reims-go/internal/driver" - vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" - "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/vmstart" -) - -func boolPtr(v bool) *bool { return &v } - -func TestVMKeymapCaptureStatus(t *testing.T) { - dir := t.TempDir() - id := driver.BuiltinReimsMacOSDriverID - drv := &appSecondDriver{id: id, vms: []driver.VMInfo{{Name: "mac", DriverID: id, Directory: dir, State: "running"}}} - reg := plugin.NewRegistry(nil) - if err := reg.Register(plugin.PluginDef{ - Manifest: plugin.Manifest{ID: "test." + id, Version: "1.0.0"}, - Source: plugin.SourceBuiltin, - Desired: true, - Activate: func(_ context.Context, sc *plugin.Scope) error { - reg.RegisterGuestDriver(sc, id, drv) - return nil - }, - }); err != nil { - t.Fatal(err) - } - reg.Reconcile(context.Background()) - a := &App{cfg: &config.Config{DataRoot: dir}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)} - t.Cleanup(func() { a.getInputService().Close() }) - for _, enabled := range []bool{true, false} { - got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(enabled)}) - if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 { - t.Fatalf("SetVMKeymap capture=%v: %+v, %v", enabled, got, err) - } - got, err = a.GetVMKeymap("mac") - if err != nil || got.Preset != "off" || !got.Running || got.CaptureHostShortcuts != enabled || got.NeedsGuestTools != enabled || len(got.Bindings) != 0 { - t.Fatalf("GetVMKeymap capture=%v: %+v, %v", enabled, got, err) - } - } - - // Legacy Wails payloads omitting capture_host_shortcuts must preserve existing setting. - if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)}); err != nil { - t.Fatal(err) - } - for _, raw := range []string{`{"preset":"win_to_cmd","bindings":{}}`, `{"preset":"off","bindings":{}}`} { - var legacy VMKeymapUpdate - if err := json.Unmarshal([]byte(raw), &legacy); err != nil { - t.Fatal(err) - } - if legacy.CaptureHostShortcuts != nil { - t.Fatalf("legacy payload %s unexpectedly set pointer", raw) - } - got, err := a.SetVMKeymap("mac", legacy) - if err != nil || !got.CaptureHostShortcuts || !got.NeedsGuestTools { - t.Fatalf("legacy update %s lost capture flag: %+v, %v", raw, got, err) - } - } - got, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)}) - if err != nil || got.CaptureHostShortcuts || got.NeedsGuestTools { - t.Fatalf("explicit false did not disable capture: %+v, %v", got, err) - } - - // Concurrent explicit enable + legacy update (omitting capture_host_shortcuts) - // must serialize read-merge-save and never clobber capture back to false. - const iterations = 16 - for i := 0; i < iterations; i++ { - if _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(false)}); err != nil { - t.Fatal(err) - } - start := make(chan struct{}) - done := make(chan error, 2) - go func() { - <-start - _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "off", CaptureHostShortcuts: boolPtr(true)}) - done <- err - }() - go func() { - <-start - _, err := a.SetVMKeymap("mac", VMKeymapUpdate{Preset: "win_to_cmd"}) - done <- err - }() - close(start) - for j := 0; j < 2; j++ { - if err := <-done; err != nil { - t.Fatal(err) - } - } - final, err := a.GetVMKeymap("mac") - if err != nil || !final.CaptureHostShortcuts { - t.Fatalf("iter %d: concurrent legacy update clobbered capture flag: %+v, %v", i, final, err) - } - } -} - -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 != KeymapRequiredAgentVersion || - 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 1b495ca..83aac50 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -228,27 +228,19 @@ func (a *App) initPlugins() { stateTable.PruneDrivers(active) a.syncRuntimeKinds(kindReg, mgr.Registry()) a.syncInputFilters() - a.syncKeymapRules() a.syncClipboardPolicies() a.syncLocales() a.wakePoll() a.emitStateChanged() }) - a.keymapMu.Lock() a.mu.Lock() - fallback := a.fallbackInputSvc - a.fallbackInputSvc = nil a.pluginMgr = mgr a.driverRouter = drvRouter a.vmStateTable = stateTable a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload) a.runtimeKinds = kindReg a.mu.Unlock() - if fallback != nil { - fallback.Close() - } - a.keymapMu.Unlock() fetch.SetDefaultDownloader(a.activeDownloader) @@ -258,7 +250,6 @@ func (a *App) initPlugins() { } mgr.MarkBootComplete() a.syncInputFilters() - a.syncKeymapRules() a.syncClipboardPolicies() a.syncLocales() a.startPluginControlServer() @@ -407,15 +398,10 @@ func (a *App) getInputService() *host.InputService { 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() + if mgr == nil { + return nil + } raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput) if !ok { return nil diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index b9c43a0..d9de11b 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -109,9 +109,6 @@ func (a *App) ResumeVM(driverID, name string) error { unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input") windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop") extraEnv, newRegistration, newRegGen = a.registerResumeGuestTools(vm, epoch, unicodeInput, windowDrop) - if unicodeInput && len(extraEnv) > 0 { - a.syncKeymapRules() - } } startAt := time.Now() @@ -199,7 +196,6 @@ func (a *App) registerResumeGuestTools(vm driver.VMInfo, epoch uint64, unicodeIn } var env []string if unicodeInput { - srv.SetKeymapCarrier(ref.Name, false) env = append(env, fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port), "REIMS_GO_INPUT_TOKEN="+cfg.Token, diff --git a/internal/app/vm_poll.go b/internal/app/vm_poll.go index 82d4286..e3b9e97 100644 --- a/internal/app/vm_poll.go +++ b/internal/app/vm_poll.go @@ -117,7 +117,15 @@ func (p *vmPoller) tick(ctx context.Context) { if ib != nil { ib.SetTargets(imeTargets(vms)) } - a.syncKeymapRules() + if svc := a.getInputService(); svc != nil { + var targets []host.IMETarget + for _, vm := range vms { + if pid := vm.RunningPID(); pid > 0 { + targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: vm.Dir, PID: uint32(pid)}) + } + } + svc.SetTargets(targets) + } a.syncFullscreenHotkeyTargets() if tm != nil { tm.UpdateTooltip(trayTooltip(loc, vms)) @@ -410,20 +418,6 @@ func (a *App) polledVMs(ctx context.Context) ([]driver.VMListItem, error) { return a.listVMsInternal(ctx) } -// polledVM looks name up in polledVMs. -func (a *App) polledVM(name string) (driver.VMListItem, bool) { - vms, err := a.polledVMs(context.Background()) - if err != nil { - return driver.VMListItem{}, false - } - for _, vm := range vms { - if vm.Name == name { - return vm, true - } - } - return driver.VMListItem{}, false -} - func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) { vms, err := a.polledVMs(context.Background()) if err != nil { diff --git a/internal/guesttools/control_loop_test.go b/internal/guesttools/control_loop_test.go index deabebb..04f06a2 100644 --- a/internal/guesttools/control_loop_test.go +++ b/internal/guesttools/control_loop_test.go @@ -4,7 +4,7 @@ import "testing" func TestGuestAgentFileSyncControlLoop(t *testing.T) { agent := string(GuestAgentScript()) - state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\nkeymap_active=") + state := scriptSection(t, agent, "\nFILE_SYNC_PID=", "\n\n") cleanup := scriptSection(t, agent, "\ncleanup() {", "\n\n") worker := scriptSection(t, agent, "\nreap_file_sync() {", "\ntext_input_loop &") config := scriptSection(t, agent, "\napply_host_config() {", "\nreport_status() {") @@ -16,7 +16,6 @@ func TestGuestAgentFileSyncControlLoop(t *testing.T) { }) t.Run("cleanup_running_worker", func(t *testing.T) { runShareShell(t, fixture+` -report_status() { [ "$1" = 1 ]; } sync_files() { : > "$TMP_DIR/sync-download.part" sleep 30 >/dev/null 2>&1 & @@ -36,7 +35,7 @@ child_pid=$(cat child.pid) command kill "$child_pid" 2>/dev/null || true [ "$elapsed" -lt 5 ] || fail "cleanup blocked for ${elapsed}s waiting on foreground child" check "$(cat reaped)" "$worker_pid" "cleanup reaped the worker" -check "$(cat parent-cleanup)" disable "parent cleanup disabled the keymap once" +check "$(cat parent-cleanup)" stopped "parent cleanup stopped the window reporter once" [ ! -f "$FILE_SYNC_DONE" ] && [ ! -f "$TMP_DIR/sync-download.part" ] || fail "cleanup left files from the terminated worker" [ ! -f "$INJECT_LOCK" ] || fail "cleanup left the injection lock" @@ -58,7 +57,6 @@ REIMS_TOKEN=token REIMS_VM=guest DROP_MOUNT=./drop_mount mount_mode=webdav -keymap_active=false sleep_active=false timezone_helper_ready=false timezone_error= @@ -125,7 +123,6 @@ CAFFEINATE_PID="" TEXT_INPUT_PID="" DROP_EVENTS_PID="" CLIPBOARD_PID="" -keymap_applied=true tick=0 : > "$INJECT_LOCK" : > parent-cleanup @@ -142,9 +139,8 @@ await_file() { sleep 0.05 done } -stop_window_reporter() { :; } +stop_window_reporter() { printf 'stopped\n' >> parent-cleanup; } sync_window_reporter() { :; } -apply_hidutil_carrier() { printf '%s\n' "$1" >> parent-cleanup; } # Model a completed child that still answers kill -0 until wait. kill() { @@ -177,7 +173,6 @@ ensure_webdav_mount() { } ensure_drop_webdav_mount() { :; } curl() { printf '%s\n' '{"shared_folders_count":2}'; } -sync_keymap_carrier() { printf '%s keymap\n' "$tick" >> config; } sync_drive_mounts() { printf '%s drives\n' "$tick" >> config; } sync_folder_mounts() { printf '%s folders=%s\n' "$tick" "$1" >> config; } sync_timezone() { :; } @@ -199,8 +194,8 @@ sleep() { check "$FILE_SYNC_PID" "$first_pid" "only one worker ran while the first was blocked" check "$(cat started)" 0 "fallback runs before the gate opens" check "$(cat status)" "$(printf '0\n5\n10')" "status ticks while the worker is blocked" - check "$(cat config)" "$(printf '%s\n' '0 keymap' '0 drives' '0 folders=2' \ - '5 keymap' '5 drives' '5 folders=2' '10 keymap' '10 drives' '10 folders=2')" "host config order" + check "$(cat config)" "$(printf '%s\n' '0 drives' '0 folders=2' \ + '5 drives' '5 folders=2' '10 drives' '10 folders=2')" "host config order" : > release-0 await_file "$FILE_SYNC_DONE" [ ! -s parent-cleanup ] && [ -f "$INJECT_LOCK" ] || fail "worker ran parent cleanup" diff --git a/internal/guesttools/drop.go b/internal/guesttools/drop.go index a1a7cc2..35e07cd 100644 --- a/internal/guesttools/drop.go +++ b/internal/guesttools/drop.go @@ -256,8 +256,9 @@ func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) { cur.dropQueue[0] = nil cur.dropQueue = cur.dropQueue[1:] cur.dropActive[item.DropID] = item - cur.markSeen(time.Now()) - cur.lastDropPoll = time.Now() + now := time.Now() + cur.lastSeen = now + cur.lastDropPoll = now s.mu.Unlock() w.Header().Set("Content-Type", "application/json") diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 0bb5fb7..136ea45 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -130,7 +130,6 @@ FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" TMP_DIR="$PWD/tmp" REIMS_HOST_URL=http://stub:19847 -sync_keymap_carrier() { :; } REIMS_TOKEN=token REIMS_VM=mac CAFFEINATE_PID="" diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index b8052fb..8b7f62e 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -14,7 +14,6 @@ import ( ) const SharedFolderAgentVersion = 9 -const KeymapAgentVersion = 10 const TimezoneAgentVersion = 11 const HostDNSAgentVersion = 12 const WindowDropAgentVersion = 13 @@ -28,7 +27,7 @@ const SharedFolderWebDAVAgentVersion = 20 const DropNetworkVolumesAgentVersion = 21 const StableWindowReporterAgentVersion = 22 -const CurrentAgentVersion = StableWindowReporterAgentVersion +const CurrentAgentVersion = 23 type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 9e4d938..4be490a 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -285,25 +285,26 @@ func TestServerAuthClipboardAndSharedFiles(t *testing.T) { t.Fatalf("long-poll timed out instead of waking on change") } - // 5. Config & Status endpoints (prevent-sleep + mount mode). + // 5. A version 22 agent can keep using prevent-sleep and WebDAV after a host upgrade. srv.SetPreventSleep("macos-tahoe", true) r = doReq("GET", "/v1/config", "", nil) var cfgResp struct { - PreventSleep bool `json:"prevent_sleep"` - WebDAVPath string `json:"webdav_path"` + PreventSleep bool `json:"prevent_sleep"` + WebDAVPath string `json:"webdav_path"` + KeymapEnabled bool `json:"keymap_carrier_enabled"` } _ = json.NewDecoder(r.Body).Decode(&cfgResp) r.Body.Close() - if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" { + if !cfgResp.PreventSleep || cfgResp.WebDAVPath != "/dav/macos-tahoe/" || cfgResp.KeymapEnabled { t.Fatalf("unexpected /v1/config: %+v", cfgResp) } - r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":2}`)) + r = doReq("POST", "/v1/status", "application/json", strings.NewReader(`{"mount_mode":"webdav","sleep_active":true,"agent_version":22,"keymap_active":true}`)) r.Body.Close() if r.StatusCode != 200 { t.Fatalf("/v1/status POST: status=%d", r.StatusCode) } st := srv.Status("macos-tahoe", 5*time.Second) - if !st.Connected || st.MountMode != "webdav" || !st.SleepActive || st.AgentVersion != 2 { + if !st.Connected || st.MountMode != "webdav" || !st.SleepActive || st.AgentVersion != 22 { t.Fatalf("unexpected status: %+v", st) } diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index e6a08b2..2f94364 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -172,9 +172,7 @@ WINDOW_REPORTER_PID="" window_report_generation="" FILE_SYNC_PID="" FILE_SYNC_DONE="$TMP_DIR/file-sync.done" -keymap_active="false" -keymap_applied="false" -` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` +` + guestTimezoneAgent + guestTimezoneConfig + ` stop_window_reporter() { if [ -n "${WINDOW_REPORTER_PID:-}" ]; then @@ -186,10 +184,6 @@ stop_window_reporter() { } cleanup() { - if [ "$keymap_applied" = "true" ]; then - apply_hidutil_carrier disable - report_status 1 - fi if [ -n "${FILE_SYNC_PID:-}" ]; then if [ ! -f "$FILE_SYNC_DONE" ]; then pkill -P "$FILE_SYNC_PID" 2>/dev/null || true @@ -643,7 +637,6 @@ apply_host_config() { fi printf '%s %s\n' "$upload_files" "$archive_bytes" > "$TMP_DIR/clip_file_config.tmp" && mv -f "$TMP_DIR/clip_file_config.tmp" "$TMP_DIR/clip_file_config" - sync_keymap_carrier "$cfg_json" sync_drive_mounts "$cfg_json" folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') sync_folder_mounts "${folders_count:-0}" @@ -696,7 +689,7 @@ report_status() { if 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\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale,\"drop_mount_denied\":$drop_mount_denied}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale,\"drop_mount_denied\":$drop_mount_denied}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1; then reported_drop_mount_denied="$drop_mount_denied" fi @@ -1740,8 +1733,6 @@ fi ` + guestURLencode + folderMountHelpers + shareUnmountScript + ` uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true -` + guestKeymapCarrier + ` -apply_hidutil_carrier disable if ! unmount_reims_shares; then echo "Reims Guest Tools shares are busy. Close files using the shares and retry uninstalling." >&2 exit 1 @@ -1827,89 +1818,6 @@ urlencode() { } ` -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 folderMountHelpers = ` is_drive_mounted() { mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1 diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go deleted file mode 100644 index 34c3933..0000000 --- a/internal/guesttools/keymap_agent_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package guesttools - -import ( - "encoding/json" - "net/http/httptest" - "os" - "os/exec" - "path/filepath" - "strconv" - "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\":`+strconv.Itoa(CurrentAgentVersion)+`,\"keymap_active\":$keymap_active`) { - t.Fatal("missing guest keymap script or current agent version in status") - } - for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { - t.Run(input, func(t *testing.T) { - t.Parallel() - lockShellFixture(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) { - t.Parallel() - lockShellFixture(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, "if ! unmount_reims_shares;") - 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= -CLIPBOARD_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":9,"keymap_active":true}`, - `{"agent_version":10,"keymap_active":true}`, - `{"agent_version":10,"keymap_active":true}`, - `{"agent_version":10,"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/keymap_status_test.go b/internal/guesttools/keymap_status_test.go deleted file mode 100644 index 13e0ae7..0000000 --- a/internal/guesttools/keymap_status_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package guesttools - -import ( - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" -) - -func TestKeymapConfirmationFollowsGuestConnection(t *testing.T) { - for _, agentVersion := range []int{14, CurrentAgentVersion} { - t.Run(fmt.Sprintf("agent_%d", agentVersion), func(t *testing.T) { - srv := NewTransportServer(nil) - cfg := VMConfig{VMName: "mac", Token: "token", SharedDir: t.TempDir()} - srv.RegisterVM(cfg) - srv.SetKeymapCarrier(cfg.VMName, true) - - request := func(handler http.HandlerFunc, method, path, body string) { - t.Helper() - req := httptest.NewRequest(method, path, strings.NewReader(body)) - req.Header.Set("Authorization", "Bearer "+cfg.Token) - w := httptest.NewRecorder() - handler(w, req) - if w.Code != http.StatusOK { - t.Fatalf("%s %s: status %d: %s", method, path, w.Code, w.Body) - } - } - report := func(active bool) { - t.Helper() - body := fmt.Sprintf(`{"mount_mode":"sync","agent_version":%d,"keymap_active":%t}`, agentVersion, active) - request(srv.handleStatus, http.MethodPost, "/v1/status", body) - } - check := func(connected, active bool) { - t.Helper() - got := srv.Status(cfg.VMName, KeymapStatusMaxAge) - if got.Connected != connected || got.KeymapActive != active { - t.Fatalf("guest connected/keymap active = %t/%t, want %t/%t", got.Connected, got.KeymapActive, connected, active) - } - } - - report(true) - check(true, true) - - // The guest can still be handling files after its last status report expires. - srv.mu.Lock() - vm := srv.vms[normalizeVMRegistryKey(cfg.VMName)] - vm.lastStatus = time.Now().Add(-2 * KeymapStatusMaxAge) - vm.lastSeen = time.Now().Add(-KeymapStatusMaxAge / 2) - srv.mu.Unlock() - request(srv.handleListFiles, http.MethodGet, "/v1/files", "") - check(true, true) - - // A resumed connection without a fresh report cannot restore the mapping. - srv.mu.Lock() - vm.lastSeen = time.Now().Add(-2 * KeymapStatusMaxAge) - srv.mu.Unlock() - check(false, false) - request(srv.handleConfig, http.MethodGet, "/v1/config", "") - check(true, false) - report(true) - check(true, true) - report(false) - check(true, false) - - report(true) - srv.SetKeymapCarrier(cfg.VMName, false) - srv.SetKeymapCarrier(cfg.VMName, true) - check(true, false) - report(true) - cfg.Token = "replacement" - srv.RegisterVM(cfg) - request(srv.handleConfig, http.MethodGet, "/v1/config", "") - check(true, false) - report(true) - check(true, true) - }) - } -} diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 7bc0436..f4ebcb4 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -46,9 +46,6 @@ const ( const bridgeProtocolVersion = 4 -// KeymapStatusMaxAge is the maximum idle time of a confirmed keymap session. -const KeymapStatusMaxAge = 30 * time.Second - // ErrGuestToolsNotConnected is returned when a guest-assisted operation // requires a live Guest Tools agent inside macOS. var ErrGuestToolsNotConnected = errors.New("guest tools not connected") @@ -124,7 +121,6 @@ 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" DropMountDenied bool `json:"drop_mount_denied"` @@ -259,8 +255,6 @@ type registeredVM struct { verifyDriveRoot func(*os.Root, string, string) error resolvedFolders map[string]ResolvedSharedFolder verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error - keymapCarrierEnabled bool - keymapActive bool // Carrier confirmed by a status report since the last disconnect. lastStatus time.Time mountMode string dropMountDenied bool @@ -325,7 +319,6 @@ type Server struct { onDropAck func(vmKey, vmName string, ack DropEventAck) onHostDrop func(vmKey, vmName string, req HostDropRequest) (HostDropResult, error) onHostText func(vmKey, vmName, text string) - onStatusChange func(vmName string) hostDNSConfig HostDNSConfig hostDNS hostDNS } @@ -584,7 +577,6 @@ func (s *Server) RegisterVM(cfg VMConfig) { } else if cur.token != cfg.Token { cur.dropShares.revokeClipboard() s.clearVMClipFilesLocked(key) - cur.keymapActive = false cur.windowReportGen = 0 cur.windowReport = windowReport{} cur.clipboardDelivery = guestClipboardDelivery{} @@ -883,7 +875,6 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { HostDNSActive: dnsReported && vm.hostDNSActive, HostDNSReported: dnsReported, HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale, - KeymapActive: connected && vm.keymapActive, Connected: connected, MountMode: vm.mountMode, DropMountDenied: freshStatus && vm.dropMountDenied, @@ -897,35 +888,11 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { } } -func (s *Server) SetKeymapCarrier(vmName string, enabled bool) { - vmName = normalizeVMRegistryKey(vmName) - 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 (vm *registeredVM) markSeen(now time.Time) { - // After a disconnected session, require the agent to confirm the mapping again. - if now.Sub(vm.lastSeen) > KeymapStatusMaxAge { - vm.keymapActive = false - } - vm.lastSeen = now -} - func (s *Server) touchLastSeen(vmName string) { vmName = normalizeVMRegistryKey(vmName) s.mu.Lock() if vm := s.vms[vmName]; vm != nil { - vm.markSeen(time.Now()) + vm.lastSeen = time.Now() } s.mu.Unlock() } @@ -956,31 +923,30 @@ func (s *Server) authenticateToken(tok string) *registeredVM { defer s.mu.Unlock() for _, vm := range s.vms { if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 { - vm.markSeen(time.Now()) + vm.lastSeen = time.Now() // A snapshot of the plain fields only: copying *vm would copy // injectMu and alias the text queues. Handlers that need the // queues look the live VM up again by name under s.mu. cp := registeredVM{ - key: vm.key, - name: vm.name, - token: vm.token, - regGen: vm.regGen, - dropDAVHandler: vm.dropDAVHandler, - sharedDir: vm.sharedDir, - sharedRoot: vm.sharedRoot, - preventSleep: vm.preventSleep, - hostDNSEnabled: vm.hostDNSEnabled, - guestTimezone: vm.guestTimezone, - driveSharingEnabled: vm.driveSharingEnabled, - sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), - driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs), - resolvedFolders: maps.Clone(vm.resolvedFolders), - keymapCarrierEnabled: vm.keymapCarrierEnabled, - mountMode: vm.mountMode, - sleepActive: vm.sleepActive, - agentVersion: vm.agentVersion, - lastSeen: vm.lastSeen, - windowReportGen: vm.windowReportGen, + key: vm.key, + name: vm.name, + token: vm.token, + regGen: vm.regGen, + dropDAVHandler: vm.dropDAVHandler, + sharedDir: vm.sharedDir, + sharedRoot: vm.sharedRoot, + preventSleep: vm.preventSleep, + hostDNSEnabled: vm.hostDNSEnabled, + guestTimezone: vm.guestTimezone, + driveSharingEnabled: vm.driveSharingEnabled, + sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), + driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs), + resolvedFolders: maps.Clone(vm.resolvedFolders), + mountMode: vm.mountMode, + sleepActive: vm.sleepActive, + agentVersion: vm.agentVersion, + lastSeen: vm.lastSeen, + windowReportGen: vm.windowReportGen, } return &cp } @@ -1013,7 +979,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", "custom-folders", "keymap-carrier", "drop-events", "drop-webdav", "drop-paste"} + caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "drop-events", "drop-webdav", "drop-paste"} if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled { if policy.allowsHostToGuestFiles() { caps = append(caps, "clipboard-files") @@ -1046,7 +1012,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "vm": vm.name, - "keymap_carrier_enabled": vm.keymapCarrierEnabled, "window_report_generation": vm.windowReportGen, "prevent_sleep": vm.preventSleep, "webdav_drop_path": "/dav-drop/" + vm.name + "/", @@ -1076,7 +1041,6 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { return } var req struct { - KeymapActive bool `json:"keymap_active"` MountMode string `json:"mount_mode"` DropMountDenied bool `json:"drop_mount_denied"` SleepActive bool `json:"sleep_active"` @@ -1099,15 +1063,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { req.TimezoneApplied = "" } s.mu.Lock() - var notify func(string) if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token { now := time.Now() - cur.markSeen(now) - active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= KeymapAgentVersion - if cur.keymapActive != active || now.Sub(cur.lastStatus) > KeymapStatusMaxAge { - notify = s.onStatusChange - } - cur.keymapActive = active + cur.lastSeen = now cur.lastStatus = now if mode != "" { cur.mountMode = mode @@ -1126,9 +1084,6 @@ 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, wantFiles bool) (ClipPayload, uint32, error) { @@ -1574,7 +1529,7 @@ func (s *Server) handleTextInput(w http.ResponseWriter, r *http.Request) { item := cur.textQueue[0] cur.textQueue = cur.textQueue[1:] cur.textActive[item.id] = item - cur.markSeen(time.Now()) + cur.lastSeen = time.Now() cur.lastTextPoll = time.Now() s.mu.Unlock() diff --git a/internal/guesttools/timezone_test.go b/internal/guesttools/timezone_test.go index 41b34db..b838f2b 100644 --- a/internal/guesttools/timezone_test.go +++ b/internal/guesttools/timezone_test.go @@ -71,7 +71,6 @@ printf '#!/bin/sh\nexit 0\n' > "$TIMEZONE_HELPER" chmod +x "$TIMEZONE_HELPER" mount_mode=sync sleep_active=false -keymap_active=false current_timezone() { printf Asia/Shanghai; } curl() { while [ "$1" != "-d" ]; do shift; done diff --git a/internal/host/fullscreen_hotkey.go b/internal/host/fullscreen_hotkey.go index e15b92d..f817851 100644 --- a/internal/host/fullscreen_hotkey.go +++ b/internal/host/fullscreen_hotkey.go @@ -147,8 +147,14 @@ func (m *FullscreenHotkeyMatcher) setHotkey(hotkey FullscreenHotkey) { } const ( + vkLWin = 0x5B + vkRWin = 0x5C vkLShift = 0xA0 vkRShift = 0xA1 + vkLCtrl = 0xA2 + vkRCtrl = 0xA3 + vkLAlt = 0xA4 + vkRAlt = 0xA5 ) var fullscreenModifierVKs = [...]uint32{vkLCtrl, vkRCtrl, vkLShift, vkRShift, vkLAlt, vkRAlt, vkLWin, vkRWin} @@ -158,12 +164,12 @@ type fullscreenPhysicalModifiers struct { asyncReliable [len(fullscreenModifierVKs)]bool } -func (m *fullscreenPhysicalModifiers) handle(vk uint32, down, injected, remapped bool) { +func (m *fullscreenPhysicalModifiers) handle(vk uint32, down, injected bool) { for i, modifier := range fullscreenModifierVKs { if vk != modifier { continue } - m.asyncReliable[i] = !injected && !remapped + m.asyncReliable[i] = !injected if !injected { m.down[i] = down } diff --git a/internal/host/fullscreen_hotkey_other.go b/internal/host/fullscreen_hotkey_other.go index c980170..c5cea6f 100644 --- a/internal/host/fullscreen_hotkey_other.go +++ b/internal/host/fullscreen_hotkey_other.go @@ -10,6 +10,4 @@ func (h *fullscreenHotkeyHook) Close() {} func (h *fullscreenHotkeyHook) active() bool { return false } -func prioritizeFullscreenHotkeyHook() {} - func IsForegroundDisplayWindow(_ uintptr, _ uint32) bool { return false } diff --git a/internal/host/fullscreen_hotkey_test.go b/internal/host/fullscreen_hotkey_test.go index a5f3bc9..1dda57d 100644 --- a/internal/host/fullscreen_hotkey_test.go +++ b/internal/host/fullscreen_hotkey_test.go @@ -136,19 +136,19 @@ func TestFullscreenPhysicalModifiersIgnoreInjectedKeys(t *testing.T) { for i := 0; i < len(fullscreenModifierVKs); i += 2 { left, right := fullscreenModifierVKs[i], fullscreenModifierVKs[i+1] var m fullscreenPhysicalModifiers - m.handle(left, true, false, true) + m.handle(left, true, false) first := m.mods() if first == (FullscreenHotkeyMods{}) { t.Fatalf("physical modifier %#x was ignored", left) } - m.handle(left, false, true, true) - m.handle(right, true, false, true) - m.handle(left, false, false, true) + m.handle(left, false, true) + m.handle(right, true, false) + m.handle(left, false, false) if got := m.mods(); got != first { t.Fatalf("physical right modifier %#x: got %+v, want %+v", right, got, first) } - m.handle(right, false, false, true) - m.handle(left, true, true, true) + m.handle(right, false, false) + m.handle(left, true, true) if got := m.mods(); got != (FullscreenHotkeyMods{}) { t.Fatalf("injected modifier %#x changed physical state: %+v", left, got) } diff --git a/internal/host/fullscreen_hotkey_windows.go b/internal/host/fullscreen_hotkey_windows.go index ecf19ac..3659ede 100644 --- a/internal/host/fullscreen_hotkey_windows.go +++ b/internal/host/fullscreen_hotkey_windows.go @@ -14,11 +14,19 @@ import ( var ( fullscreenHotkeyCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(fullscreenKeyboardProc) }) activeFullscreenHotkey atomic.Pointer[fullscreenHotkeyHook] + procSetTimer = user32.NewProc("SetTimer") + procKillTimer = user32.NewProc("KillTimer") + procGetAsyncKeyState = user32.NewProc("GetAsyncKeyState") + procOpenInputDesktop = user32.NewProc("OpenInputDesktop") + procCloseDesktop = user32.NewProc("CloseDesktop") + procGetWindowTextW = user32.NewProc("GetWindowTextW") ) const ( - wmPrioritizeFullscreenHotkey = 0x8002 - fullscreenHotkeyTimerMS = 50 + wmTimer = 0x0113 + llkhfInjected = 0x10 + desktopReadObjects = 0x0001 + fullscreenHotkeyTimerMS = 50 // SDL3 may install its hook a moment after the VM window takes focus. fullscreenHotkeySettleTicks = 10 ) @@ -71,22 +79,17 @@ func (h *fullscreenHotkeyHook) run(ready chan<- bool) { return } defer activeFullscreenHotkey.CompareAndSwap(h, nil) - if keymapInputDesktopAccessible() { - keymapActive := activeKeymapHook.Load() != nil + if inputDesktopAccessible() { for _, vk := range fullscreenModifierVKs { - // Ctrl may already be held by key mapping when this hook starts. - if keymapActive && (vk == vkLCtrl || vk == vkRCtrl) { - continue - } - h.physical.handle(vk, keymapPhysicalDown(vk), false, keymapActive && hostModifiers[vk] != "") + h.physical.handle(vk, physicalKeyDown(vk), false) } } - timer, _, _ := procKeymapSetTimer.Call(0, 0, fullscreenHotkeyTimerMS, 0) + timer, _, _ := procSetTimer.Call(0, 0, fullscreenHotkeyTimerMS, 0) if timer == 0 { ready <- false return } - defer procKeymapKillTimer.Call(0, timer) + defer procKillTimer.Call(0, timer) module, _, _ := procGetModuleHandleW.Call(0) hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0) if hook == 0 { @@ -94,8 +97,7 @@ func (h *fullscreenHotkeyHook) run(ready chan<- bool) { return } defer func() { procUnhookWindowsHookEx.Call(hook) }() - // The newest hook runs first. Key mapping and SDL3 both swallow modifiers, - // so this hook must sit above them to see physical keys. + // The newest hook runs first. This hook must run before SDL3 swallows modifiers. promote := func() bool { next, _, err := procSetWindowsHookExW.Call(whKeyboardLL, fullscreenHotkeyCallback(), module, 0) if next == 0 { @@ -112,9 +114,8 @@ func (h *fullscreenHotkeyHook) run(ready chan<- bool) { if int32(result) <= 0 { return } - switch msg.message { - case wmTimer: - if !keymapInputDesktopAccessible() { + if msg.message == wmTimer { + if !inputDesktopAccessible() { h.resetKeys() continue } @@ -123,10 +124,6 @@ func (h *fullscreenHotkeyHook) run(ready chan<- bool) { if h.needsPromotion(window, title) && !promote() { return } - case wmPrioritizeFullscreenHotkey: - if !promote() { - return - } } } } @@ -145,12 +142,6 @@ func (h *fullscreenHotkeyHook) active() bool { } } -func prioritizeFullscreenHotkeyHook() { - if h := activeFullscreenHotkey.Load(); h != nil { - procPostThreadMessageW.Call(h.threadID, wmPrioritizeFullscreenHotkey, 0, 0) - } -} - func fullscreenKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr { if code == hcAction && kbd != nil { switch message { @@ -166,7 +157,7 @@ func fullscreenKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) u } func (h *fullscreenHotkeyHook) handleKey(vk uint32, down, injected bool) bool { - h.physical.handle(vk, down, injected, activeKeymapHook.Load() != nil && hostModifiers[vk] != "") + h.physical.handle(vk, down, injected) if injected { return false } @@ -178,7 +169,7 @@ func (h *fullscreenHotkeyHook) handleKey(vk uint32, down, injected bool) bool { if vk != settings.hotkey.VK && vk != h.matcher.suppressedVK { return false } - if !keymapInputDesktopAccessible() { + if !inputDesktopAccessible() { h.resetKeys() return false } @@ -218,7 +209,7 @@ func (h *fullscreenHotkeyHook) foregroundVMWindow() (uintptr, string) { return 0, "" } var title [256]uint16 - n, _, _ := procKeymapGetWindowTextW.Call(window, uintptr(unsafe.Pointer(&title[0])), uintptr(len(title))) + n, _, _ := procGetWindowTextW.Call(window, uintptr(unsafe.Pointer(&title[0])), uintptr(len(title))) return window, syscall.UTF16ToString(title[:n]) } @@ -246,7 +237,7 @@ func (h *fullscreenHotkeyHook) reconcilePhysical(vmForeground bool) { // A swallowed down does not update GetAsyncKeyState. return } - if h.matcher.down && !keymapPhysicalDown(h.matcher.Hotkey.VK) { + if h.matcher.down && !physicalKeyDown(h.matcher.Hotkey.VK) { h.matcher.Reset() } if vmForeground { @@ -255,12 +246,26 @@ func (h *fullscreenHotkeyHook) reconcilePhysical(vmForeground bool) { return } for i, vk := range fullscreenModifierVKs { - if h.physical.down[i] && h.physical.asyncReliable[i] && !keymapPhysicalDown(vk) { + if h.physical.down[i] && h.physical.asyncReliable[i] && !physicalKeyDown(vk) { h.physical.down[i] = false } } } +func physicalKeyDown(vk uint32) bool { + state, _, _ := procGetAsyncKeyState.Call(uintptr(vk)) + return state&0x8000 != 0 +} + +func inputDesktopAccessible() bool { + desk, _, _ := procOpenInputDesktop.Call(0, 0, desktopReadObjects) + if desk == 0 { + return false + } + procCloseDesktop.Call(desk) + return true +} + func (h *fullscreenHotkeyHook) dispatch() { for { select { diff --git a/internal/host/fullscreen_hotkey_windows_test.go b/internal/host/fullscreen_hotkey_windows_test.go index afe7960..34369ba 100644 --- a/internal/host/fullscreen_hotkey_windows_test.go +++ b/internal/host/fullscreen_hotkey_windows_test.go @@ -33,7 +33,7 @@ func TestFullscreenHotkeyDispatchAfterInputServiceCloses(t *testing.T) { func TestFullscreenHotkeyResetClearsPhysicalAndSuppressedKeys(t *testing.T) { hotkey, _, _ := ParseFullscreenHotkey("Ctrl+F8") h := fullscreenHotkeyHook{matcher: FullscreenHotkeyMatcher{Hotkey: hotkey}} - h.physical.handle(vkLCtrl, true, false, false) + h.physical.handle(vkLCtrl, true, false) if consume, trigger := h.matcher.Handle(hotkey.VK, true, true, h.physical.mods()); !consume || !trigger { t.Fatalf("initial chord = (%t, %t)", consume, trigger) } @@ -50,7 +50,7 @@ func TestFullscreenHotkeyKeepsSwallowedModifiersInVM(t *testing.T) { hotkey, _, _ := ParseFullscreenHotkey(DefaultFullscreenHotkey) h := fullscreenHotkeyHook{matcher: FullscreenHotkeyMatcher{Hotkey: hotkey}} // No key is physically held here, which matches a modifier swallowed by SDL3. - h.physical.handle(vkRCtrl, true, false, false) + h.physical.handle(vkRCtrl, true, false) h.reconcilePhysical(true) if !h.physical.mods().Ctrl { t.Fatal("held Ctrl was dropped while the VM window was focused") diff --git a/internal/host/input_service.go b/internal/host/input_service.go index 9020033..c2dc2fd 100644 --- a/internal/host/input_service.go +++ b/internal/host/input_service.go @@ -1,8 +1,6 @@ package host import ( - "maps" - "reflect" "strings" "sync" "sync/atomic" @@ -89,9 +87,6 @@ type InputService struct { targetByPID atomic.Pointer[map[uint32]IMETarget] rules atomic.Pointer[[]InputFilterRule] mouseHook *mouseWheelHook - keymapRules []KeymapRule - keymapState atomic.Pointer[keymapSnapshot] - keymapHook *keymapHook closed bool } @@ -142,11 +137,6 @@ 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)) @@ -162,88 +152,6 @@ func (s *InputService) setTargetsLocked(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) - if s.keymapHook != nil { - prioritizeFullscreenHotkeyHook() - } - } -} - // 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) { @@ -298,8 +206,6 @@ 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() @@ -310,7 +216,4 @@ func (s *InputService) Close() { if mh != nil { mh.Close() } - if kh != nil { - kh.Close() - } } diff --git a/internal/host/keymap.go b/internal/host/keymap.go deleted file mode 100644 index 0e2492d..0000000 --- a/internal/host/keymap.go +++ /dev/null @@ -1,262 +0,0 @@ -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 { - return e.ReleaseMatching(func(uint32) bool { return true }) -} - -func (e *KeymapEngine) ReleaseMatching(shouldRelease func(vk uint32) bool) []EmittedKey { - var emit []EmittedKey - hasActive := false - for vk, key := range e.activeMapped { - if !shouldRelease(vk) { - if key.VK != 0 { - hasActive = true - } - continue - } - // 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) - } - } - if !hasActive { - 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 deleted file mode 100644 index f499d1f..0000000 --- a/internal/host/keymap_other.go +++ /dev/null @@ -1,9 +0,0 @@ -//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 deleted file mode 100644 index 61b5523..0000000 --- a/internal/host/keymap_test.go +++ /dev/null @@ -1,234 +0,0 @@ -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 TestKeymapHostShortcutCapture(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{ - "lwin": "lcmd", "rwin": "rcmd", "lalt": "lopt", "ralt": "ropt", - }} - optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} - optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} - t.Run("focus loss", func(t *testing.T) { - e := NewKeymapEngine([]KeymapRule{rule}) - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{optionDown}) { - t.Fatalf("Alt down in VM: suppress=%v keys=%v", suppress, keys) - } - if keys := e.ReleaseIfFocusLost(""); !slices.Equal(keys, []EmittedKey{optionUp}) { - t.Fatalf("Alt carrier on focus loss: %v", keys) - } - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: true}, "", false); !suppress || len(keys) != 0 { - t.Fatalf("release of captured Alt: suppress=%v keys=%v", suppress, keys) - } - for _, up := range []bool{false, true} { - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: up}, "", false); suppress || len(keys) != 0 { - t.Fatalf("Alt outside VM (up=%v): suppress=%v keys=%v", up, suppress, keys) - } - } - }) - t.Run("release capture chord", func(t *testing.T) { - e := NewKeymapEngine([]KeymapRule{rule}) - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLCtrl}, "vm", true); suppress || len(keys) != 0 { - t.Fatalf("Ctrl down: suppress=%v keys=%v", suppress, keys) - } - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{optionDown}) { - t.Fatalf("Alt down: suppress=%v keys=%v", suppress, keys) - } - physicalAlt := EmittedKey{VK: vkLAlt, Scan: 0x38} - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); suppress || !slices.Equal(keys, []EmittedKey{optionUp, physicalAlt}) { - t.Fatalf("Ctrl+Alt+Win: suppress=%v keys=%v", suppress, keys) - } - physicalAlt.Up = true - if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLAlt, Up: true}, "vm", true); !suppress || !slices.Equal(keys, []EmittedKey{physicalAlt}) { - t.Fatalf("restored Alt up: suppress=%v keys=%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 deleted file mode 100644 index e7fcf7a..0000000 --- a/internal/host/keymap_windows.go +++ /dev/null @@ -1,582 +0,0 @@ -//go:build windows - -package host - -import ( - "runtime" - "sync" - "sync/atomic" - "syscall" - "unsafe" -) - -const ( - llkhfInjected = 0x10 - wmKeymapRefresh = 0x8001 - wmTimer = 0x0113 - desktopReadObjects = 0x0001 - eventSystemForeground = 0x0003 - eventObjectNameChange = 0x800C - wineventOutOfContext = 0x0000 - objidWindow = 0 - keymapActiveTimerMS = 50 - keymapFallbackTimerMS = 250 -) - -var ( - procKeymapSetTimer = user32.NewProc("SetTimer") - procKeymapKillTimer = user32.NewProc("KillTimer") - procKeymapAsyncKeyState = user32.NewProc("GetAsyncKeyState") - procOpenInputDesktop = user32.NewProc("OpenInputDesktop") - procCloseDesktop = user32.NewProc("CloseDesktop") - procSetWinEventHook = user32.NewProc("SetWinEventHook") - procUnhookWinEvent = user32.NewProc("UnhookWinEvent") - procTranslateMessage = user32.NewProc("TranslateMessage") - procDispatchMessageW = user32.NewProc("DispatchMessageW") - procKeymapGetWindowTextW = user32.NewProc("GetWindowTextW") - keymapCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapKeyboardProc) }) - keymapWinEventCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapWinEventProc) }) - 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 kbdEventSig struct { - message uintptr - vk uint32 - scan uint32 - flags uint32 - time uint32 -} - -type swapDedup struct { - valid bool - sig kbdEventSig - suppressed bool -} - -type keymapHook struct { - service *InputService - threadID uintptr - done chan struct{} - engine *KeymapEngine - snapshot *keymapSnapshot - hook uintptr - winEventHook uintptr - nameChangeHook uintptr - module uintptr - lastForegroundVM string - lastForegroundHWND uintptr - lastForegroundTitle string - activePressTime map[uint32]uint32 - promotePending bool - swappingHook bool - swapSeen swapDedup - timer uintptr - timerInterval uint32 - inputDesktopAvailable bool - closeOnce sync.Once - - vmForWindowFn func(hwnd uintptr) string - foregroundWindowFn func() uintptr - windowTitleFn func(hwnd uintptr) string - installWinEventFn func(event uint32) uintptr - promoteFn func() bool - emitFn func([]EmittedKey) - syncTimerFn func() -} - -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 - } - } - h.module, _, _ = procGetModuleHandleW.Call(0) - h.hook, _, _ = procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), h.module, 0) - if h.hook == 0 { - ready <- false - return - } - defer func() { - if h.hook != 0 { - procUnhookWindowsHookEx.Call(h.hook) - } - }() - defer func() { sendMappedKeys(h.engine.ReleaseAll()) }() - fg := h.lookupForegroundWindow() - h.lastForegroundHWND = fg - h.lastForegroundVM = h.lookupWindowVM(fg) - if h.lastForegroundVM != "" { - h.lastForegroundTitle = h.lookupWindowTitle(fg) - } - h.winEventHook = h.doInstallWinEvent(eventSystemForeground) - defer func() { - if h.winEventHook != 0 { - procUnhookWinEvent.Call(h.winEventHook) - } - }() - h.nameChangeHook = h.doInstallWinEvent(eventObjectNameChange) - defer func() { - if h.nameChangeHook != 0 { - procUnhookWinEvent.Call(h.nameChangeHook) - } - }() - 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 { - if h.inputDesktopAvailable && !keymapInputDesktopAccessible() { - h.resetTrackedKeys() - } else { - sendMappedKeys(h.engine.ReconcilePhysical(keymapPhysicalDown)) - } - h.handleForegroundChange() - continue - } - procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg))) - procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg))) - } -} - -func keymapWinEventProc(hook, event, hwnd, idObject, idChild, _, eventTime uintptr) uintptr { - h := activeKeymapHook.Load() - if h == nil { - return 0 - } - ev := uint32(event) - obj := int32(idObject) - child := int32(idChild) - ts := uint32(eventTime) - if hook == h.winEventHook && ev == eventSystemForeground { - h.handleForegroundEvent(hwnd, ts) - } else if hook == h.nameChangeHook && ev == eventObjectNameChange && obj == objidWindow && child == 0 && hwnd != 0 { - h.handleWindowNameChange(hwnd) - } - return 0 -} - -func (h *keymapHook) resetTrackedKeys() { - h.emitKeys(h.engine.Reset()) - clear(h.activePressTime) -} - -func (h *keymapHook) prunePressTimes() { - for vk := range h.activePressTime { - if key, ok := h.engine.activeMapped[vk]; !ok || key.VK == 0 { - delete(h.activePressTime, vk) - } - } -} - -func (h *keymapHook) syncForegroundTitle(fg uintptr) bool { - title := h.lookupWindowTitle(fg) - if fg == h.lastForegroundHWND { - if title != "" && h.lastForegroundTitle != "" && title != h.lastForegroundTitle { - h.lastForegroundTitle = title - return true - } - if h.lastForegroundTitle == "" && title != "" { - h.lastForegroundTitle = title - } - return false - } - h.lastForegroundHWND = fg - h.lastForegroundTitle = title - return false -} - -func (h *keymapHook) handleForegroundEvent(hwnd uintptr, eventTime uint32) { - h.syncSnapshot() - eventVM := h.lookupWindowVM(hwnd) - if h.engine.heldVM != "" && eventVM != h.engine.heldVM { - h.emitKeys(h.engine.ReleaseMatching(func(vk uint32) bool { - pressTime, ok := h.activePressTime[vk] - if eventTime == 0 || !ok { - return true - } - // Wrap-safe 32-bit GetTickCount comparison: release only keys pressed - // at or before the queued focus-loss notification occurred. - return int32(eventTime-pressTime) >= 0 - })) - h.prunePressTimes() - } - if eventVM != h.lastForegroundVM { - h.lastForegroundVM = "" - } - fg := h.lookupForegroundWindow() - liveVM := h.lookupWindowVM(fg) - h.applyForegroundFocus(fg, liveVM, true) - h.doSyncTimer() -} - -func (h *keymapHook) applyForegroundFocus(fg uintptr, vm string, alwaysPromote bool) { - h.emitKeys(h.engine.ReleaseIfFocusLost(vm)) - h.prunePressTimes() - if vm == "" { - h.lastForegroundHWND = fg - h.lastForegroundVM = "" - h.lastForegroundTitle = "" - h.promotePending = false - return - } - if h.syncForegroundTitle(fg) { - h.resetTrackedKeys() - h.promotePending = true - } - if alwaysPromote || vm != h.lastForegroundVM || h.promotePending { - if h.doPromoteHook() { - h.lastForegroundVM = vm - h.promotePending = false - } else { - h.lastForegroundVM = "" - h.promotePending = true - } - } -} - -func (h *keymapHook) handleWindowNameChange(hwnd uintptr) { - h.syncSnapshot() - fg := h.lookupForegroundWindow() - if hwnd == 0 || hwnd != fg { - return - } - liveVM := h.lookupWindowVM(fg) - if liveVM == "" { - return - } - title := h.lookupWindowTitle(fg) - if fg == h.lastForegroundHWND && title != "" && title == h.lastForegroundTitle { - return - } - // When SDL3 re-grabs the keyboard in an already-focused VM window, it - // updates the window title right after SDL_SetWindowKeyboardGrab. Reset - // tracked modifier state on real title transitions (clearing any physical - // key-up SDL3 may have swallowed before we re-promoted) and jump back above - // SDL3 in the WH_KEYBOARD_LL chain. - if h.syncForegroundTitle(fg) { - h.resetTrackedKeys() - } - if h.doPromoteHook() { - h.lastForegroundVM = liveVM - h.promotePending = false - } else { - h.lastForegroundVM = "" - h.promotePending = true - } - h.doSyncTimer() -} - -func (h *keymapHook) ensureWinEventHooks(liveVM string) { - if h.winEventHook == 0 { - if hk := h.doInstallWinEvent(eventSystemForeground); hk != 0 { - h.winEventHook = hk - if liveVM != "" { - h.promotePending = true - } - } - } - if h.nameChangeHook == 0 { - if hk := h.doInstallWinEvent(eventObjectNameChange); hk != 0 { - h.nameChangeHook = hk - if liveVM != "" { - h.promotePending = true - } - } - } -} - -func (h *keymapHook) handleForegroundChange() { - h.syncSnapshot() - fg := h.lookupForegroundWindow() - vm := h.lookupWindowVM(fg) - h.ensureWinEventHooks(vm) - h.applyForegroundFocus(fg, vm, false) - h.doSyncTimer() -} - -func (h *keymapHook) promoteHook() bool { - if h.hook == 0 || h.swappingHook { - return false - } - h.swappingHook = true - h.swapSeen = swapDedup{} - defer func() { - h.swappingHook = false - h.swapSeen = swapDedup{} - }() - newHook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), h.module, 0) - if newHook == 0 { - return false - } - old := h.hook - h.hook = newHook - procUnhookWindowsHookEx.Call(old) - prioritizeFullscreenHotkeyHook() - return true -} - -func (h *keymapHook) syncSnapshot() { - if h.service == nil { - return - } - if next := h.service.keymapState.Load(); next != h.snapshot { - h.snapshot = next - h.emitKeys(h.engine.SetRules(next.rules)) - h.prunePressTimes() - } -} - -func (h *keymapHook) vmForWindow(hwnd uintptr) string { - if hwnd == 0 || h.snapshot == nil { - return "" - } - var pid uint32 - procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid))) - return h.snapshot.targets[pid] -} - -func (h *keymapHook) lookupForegroundWindow() uintptr { - if h.foregroundWindowFn != nil { - return h.foregroundWindowFn() - } - window, _, _ := procGetForegroundWindow.Call() - return window -} - -func (h *keymapHook) lookupWindowVM(hwnd uintptr) string { - if h.vmForWindowFn != nil { - return h.vmForWindowFn(hwnd) - } - return h.vmForWindow(hwnd) -} - -func (h *keymapHook) lookupWindowTitle(hwnd uintptr) string { - if h.windowTitleFn != nil { - return h.windowTitleFn(hwnd) - } - if hwnd == 0 { - return "" - } - var buf [256]uint16 - n, _, _ := procKeymapGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) - if n == 0 { - return "" - } - return syscall.UTF16ToString(buf[:n]) -} - -func (h *keymapHook) doInstallWinEvent(event uint32) uintptr { - if h.installWinEventFn != nil { - return h.installWinEventFn(event) - } - hk, _, _ := procSetWinEventHook.Call( - uintptr(event), uintptr(event), 0, keymapWinEventCallback(), 0, 0, wineventOutOfContext, - ) - return hk -} - -func (h *keymapHook) doPromoteHook() bool { - if h.promoteFn != nil { - return h.promoteFn() - } - return h.promoteHook() -} - -func (h *keymapHook) emitKeys(keys []EmittedKey) { - if len(keys) == 0 { - return - } - if h.emitFn != nil { - h.emitFn(keys) - return - } - sendMappedKeys(keys) -} - -func (h *keymapHook) doSyncTimer() { - if h.syncTimerFn != nil { - h.syncTimerFn() - return - } - h.syncTimer() -} - -func (h *keymapHook) handleKeyEvent(message uintptr, kbd *kbdLLHookStruct) bool { - sig := kbdEventSig{ - message: message, - vk: kbd.vkCode, - scan: kbd.scanCode, - flags: kbd.flags, - time: kbd.time, - } - if h.swappingHook && h.swapSeen.valid && h.swapSeen.sig == sig { - return h.swapSeen.suppressed - } - h.syncSnapshot() - modifier := hostModifiers[kbd.vkCode] != "" - vm := "" - if modifier || h.engine.heldVM != "" { - vm = h.lookupWindowVM(h.lookupForegroundWindow()) - h.emitKeys(h.engine.ReleaseIfFocusLost(vm)) - h.prunePressTimes() - } - suppress := false - if modifier { - up := message == wmKeyUp || message == wmSysKeyUp - _, hadMapped := h.engine.activeMapped[kbd.vkCode] - var emit []EmittedKey - suppress, emit = h.engine.ProcessEvent(KeyEvent{ - VK: kbd.vkCode, ScanCode: kbd.scanCode, Up: up, - }, vm, vm != "") - if !up && !hadMapped { - if mapped, ok := h.engine.activeMapped[kbd.vkCode]; ok && mapped.VK != 0 { - if h.activePressTime == nil { - h.activePressTime = make(map[uint32]uint32) - } - h.activePressTime[kbd.vkCode] = kbd.time - } - } - h.prunePressTimes() - h.emitKeys(emit) - h.doSyncTimer() - } - if h.swappingHook { - h.swapSeen = swapDedup{valid: true, sig: sig, suppressed: suppress} - } - return suppress -} - -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.handleKeyEvent(message, kbd) { - 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) desiredTimerInterval() uint32 { - if h.engine.HasTrackedKeys() { - return keymapActiveTimerMS - } - if h.winEventHook == 0 || h.nameChangeHook == 0 || h.promotePending { - return keymapFallbackTimerMS - } - return 0 -} - -func (h *keymapHook) syncTimer() { - desired := h.desiredTimerInterval() - if desired == h.timerInterval && (desired == 0) == (h.timer == 0) { - return - } - if h.timer != 0 { - procKeymapKillTimer.Call(0, h.timer) - h.timer = 0 - h.timerInterval = 0 - } - if desired != 0 { - h.timer, _, _ = procKeymapSetTimer.Call(0, 0, uintptr(desired), 0) - if h.timer != 0 { - h.timerInterval = desired - } - } -} - -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/host/keymap_windows_test.go b/internal/host/keymap_windows_test.go deleted file mode 100644 index af41b82..0000000 --- a/internal/host/keymap_windows_test.go +++ /dev/null @@ -1,376 +0,0 @@ -//go:build windows - -package host - -import ( - "slices" - "testing" -) - -func newTestKeymapHook(rule KeymapRule) (*keymapHook, *[]EmittedKey, *int) { - var emitted []EmittedKey - promotions := 0 - h := &keymapHook{ - engine: NewKeymapEngine([]KeymapRule{rule}), - winEventHook: 1, - nameChangeHook: 2, - windowTitleFn: func(uintptr) string { return "macOS" }, - emitFn: func(keys []EmittedKey) { - emitted = append(emitted, keys...) - }, - promoteFn: func() bool { - promotions++ - return true - }, - syncTimerFn: func() {}, - } - return h, &emitted, &promotions -} - -func TestKeymapHookRapidFocusRoundTripUsesEventHWND(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} - const ( - hwndVM uintptr = 0x1001 - hwndWin uintptr = 0x2002 - ) - optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} - - t.Run("releases key pressed before focus left", func(t *testing.T) { - h, emitted, promotions := newTestKeymapHook(rule) - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { - t.Fatal("expected LAlt to be suppressed in VM") - } - *emitted = nil - - // Queued focus-loss event happened at t=120 (after press at t=100), while live focus is already back on VM. - h.handleForegroundEvent(hwndWin, 120) - if !slices.Equal(*emitted, []EmittedKey{optionUp}) { - t.Fatalf("queued focus loss did not release Option: %v", *emitted) - } - if *promotions != 1 || h.lastForegroundVM != "vm" { - t.Fatalf("expected re-promotion on live VM return: promotions=%d last=%q", *promotions, h.lastForegroundVM) - } - }) - - t.Run("stale focus-loss notification does not release newly pressed key", func(t *testing.T) { - h, emitted, promotions := newTestKeymapHook(rule) - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - - // User returned to VM and pressed a fresh LAlt at t=135 before delayed B event (t=120) arrived. - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 135}) { - t.Fatal("expected fresh LAlt to be suppressed in VM") - } - *emitted = nil - - h.handleForegroundEvent(hwndWin, 120) - if len(*emitted) != 0 { - t.Fatalf("stale focus-loss notification released newly pressed key: %v", *emitted) - } - if *promotions != 1 || h.lastForegroundVM != "vm" { - t.Fatalf("expected re-promotion on live VM: promotions=%d last=%q", *promotions, h.lastForegroundVM) - } - }) - - t.Run("releases stale key while preserving newly pressed key", func(t *testing.T) { - mixedRule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt", "lwin": "lcmd"}} - h, emitted, _ := newTestKeymapHook(mixedRule) - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - h.lastForegroundTitle = "macOS" - - // LAlt pressed before focus left (t=100), LWin pressed after returning (t=135). - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { - t.Fatal("expected LAlt to be suppressed") - } - if !h.handleKeyEvent(wmKeyDown, &kbdLLHookStruct{vkCode: vkLWin, scanCode: 0x5B, time: 135}) { - t.Fatal("expected LWin to be suppressed") - } - *emitted = nil - - // Delayed focus-loss event at t=120 releases LAlt (Option) only, keeping LWin (Command) held. - h.handleForegroundEvent(hwndWin, 120) - if !slices.Equal(*emitted, []EmittedKey{optionUp}) { - t.Fatalf("expected only stale Option up, got %v", *emitted) - } - if h.engine.heldVM != "vm" || h.engine.activeMapped[vkLWin].VK != 0x84 { - t.Fatalf("newly pressed Command should remain active: heldVM=%q active=%v", h.engine.heldVM, h.engine.activeMapped) - } - }) - - t.Run("foreground event resets when same HWND title changed before name-change callback", func(t *testing.T) { - h, emitted, _ := newTestKeymapHook(rule) - title := "macOS" - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.windowTitleFn = func(uintptr) string { return title } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - h.lastForegroundTitle = "macOS" - - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 100}) { - t.Fatal("expected LAlt to be suppressed") - } - *emitted = nil - - // SDL already changed the title and swallowed physical LAlt up before foreground event arrived. - title = "macOS — Ctrl+Alt+Win to release" - h.handleForegroundEvent(hwndVM, 150) - if !slices.Equal(*emitted, []EmittedKey{optionUp}) { - t.Fatalf("foreground event with changed title did not release Option: %v", *emitted) - } - *emitted = nil - optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 160}) || !slices.Equal(*emitted, []EmittedKey{optionDown}) { - t.Fatalf("next LAlt press after foreground title reset did not emit Option down: %v", *emitted) - } - }) -} - -func TestKeymapHookWindowNameChangeRepromotesAndReleases(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt", "lwin": "disabled"}} - h, emitted, promotions := newTestKeymapHook(rule) - const ( - hwndVM uintptr = 0x1001 - hwndVM2 uintptr = 0x1002 - hwndOther uintptr = 0x2002 - ) - titles := map[uintptr]string{ - hwndVM: "macOS", - hwndVM2: "macOS helper", - } - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM || hwnd == hwndVM2 { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.windowTitleFn = func(hwnd uintptr) string { return titles[hwnd] } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - h.lastForegroundTitle = "macOS" - - optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} - optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} - - // Hold LAlt in foreground VM window. - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 10}) { - t.Fatal("expected LAlt to be suppressed") - } - *emitted = nil - - // Non-VM window and second window of the SAME VM process must NOT release Option or promote. - h.handleWindowNameChange(hwndOther) - h.handleWindowNameChange(hwndVM2) - if len(*emitted) != 0 || *promotions != 0 { - t.Fatalf("non-foreground window title change interfered: emitted=%v promotions=%d", *emitted, *promotions) - } - - // Duplicate notification with unchanged title on foreground HWND is ignored. - h.handleWindowNameChange(hwndVM) - if len(*emitted) != 0 || *promotions != 0 { - t.Fatalf("unchanged title interfered: emitted=%v promotions=%d", *emitted, *promotions) - } - - // Simulate SDL3 re-capture: SDL3 grabs keyboard, swallows the physical LAlt key-up - // (so Reims never receives wmSysKeyUp), and updates the foreground window title. - titles[hwndVM] = "macOS — Ctrl+Alt+Win to release" - h.handleWindowNameChange(hwndVM) - if !slices.Equal(*emitted, []EmittedKey{optionUp}) { - t.Fatalf("SDL re-capture handoff did not release Option: %v", *emitted) - } - if *promotions != 1 { - t.Fatalf("SDL re-capture handoff did not re-promote hook: %d", *promotions) - } - - // Next physical LAlt press MUST immediately map to Option (not trapped by missed key-up). - *emitted = nil - if !h.handleKeyEvent(wmSysKeyDown, &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, time: 20}) { - t.Fatal("next LAlt press after missed key-up should be suppressed") - } - if !slices.Equal(*emitted, []EmittedKey{optionDown}) { - t.Fatalf("next LAlt press after missed key-up did not emit Option down: %v", *emitted) - } -} - -func TestKeymapWinEventProcTruncatesHighBits(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} - h, _, promotions := newTestKeymapHook(rule) - const hwndVM uintptr = 0x1001 - title := "macOS" - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.windowTitleFn = func(uintptr) string { return title } - h.lastForegroundVM = "vm" - h.lastForegroundHWND = hwndVM - h.lastForegroundTitle = "macOS" - - prev := activeKeymapHook.Swap(h) - t.Cleanup(func() { activeKeymapHook.Store(prev) }) - - // Set non-zero upper 32 bits simulating Win64 ABI stack garbage on DWORD/LONG params. - const dirtyHigh = uintptr(0xDEADBEEF) << 32 - title = "macOS — Ctrl+Alt+Win to release" - keymapWinEventProc( - h.nameChangeHook, - dirtyHigh|uintptr(eventObjectNameChange), - hwndVM, - dirtyHigh|uintptr(objidWindow), - dirtyHigh|0, - 0, - dirtyHigh|500, - ) - if *promotions != 1 { - t.Fatalf("keymapWinEventProc dropped EVENT_OBJECT_NAMECHANGE with dirty upper 32 bits: promotions=%d", *promotions) - } -} - -func TestKeymapHookPromotionRetryAndWinEventRecovery(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}} - h, _, promotions := newTestKeymapHook(rule) - const hwndVM uintptr = 0x1001 - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - - // Fail promotion once: lastForegroundVM stays empty and fallback timer stays armed. - allowPromote := false - h.promoteFn = func() bool { - *promotions++ - return allowPromote - } - h.handleForegroundEvent(hwndVM, 100) - if h.lastForegroundVM != "" || !h.promotePending { - t.Fatalf("failed promotion should stay pending: last=%q pending=%v", h.lastForegroundVM, h.promotePending) - } - if got := h.desiredTimerInterval(); got != keymapFallbackTimerMS { - t.Fatalf("desiredTimerInterval with promotePending = %d, want %d", got, keymapFallbackTimerMS) - } - - // Retry succeeds on timer tick and disarms idle timer when both WinEvent hooks are installed. - allowPromote = true - h.handleForegroundChange() - if h.lastForegroundVM != "vm" || h.promotePending || *promotions != 2 { - t.Fatalf("retry did not succeed: last=%q pending=%v promotions=%d", h.lastForegroundVM, h.promotePending, *promotions) - } - if got := h.desiredTimerInterval(); got != 0 { - t.Fatalf("idle desiredTimerInterval with WinEvent hooks = %d, want 0", got) - } - - // If nameChangeHook failed at startup, fallback timer stays armed, retries install, - // syncs title transitions that occurred while missing, resets trapped keys, and - // re-promotes both on recovery and on subsequent SDL3 re-capture (T2 -> T1). - title := "macOS — Ctrl+Alt+Win to release" - h.windowTitleFn = func(uintptr) string { return title } - h.lastForegroundHWND = hwndVM - h.lastForegroundTitle = title - h.nameChangeHook = 0 - if got := h.desiredTimerInterval(); got != keymapFallbackTimerMS { - t.Fatalf("desiredTimerInterval without nameChangeHook = %d, want %d", got, keymapFallbackTimerMS) - } - if !h.handleKeyEvent(wmKeyDown, &kbdLLHookStruct{vkCode: vkLWin, scanCode: 0x5B, time: 200}) { - t.Fatal("expected LWin to be suppressed before title transition") - } - title = "macOS" - installCalls := 0 - h.installWinEventFn = func(ev uint32) uintptr { - installCalls++ - if ev == eventObjectNameChange { - return 99 - } - return 0 - } - h.handleForegroundChange() - if installCalls != 1 || h.nameChangeHook != 99 || *promotions != 3 || h.lastForegroundTitle != "macOS" { - t.Fatalf("nameChangeHook recovery failed: calls=%d hook=%d promotions=%d title=%q", installCalls, h.nameChangeHook, *promotions, h.lastForegroundTitle) - } - if len(h.engine.activeMapped) != 0 { - t.Fatalf("recovery tick did not reset mapped keys after missed title change: %v", h.engine.activeMapped) - } - if got := h.desiredTimerInterval(); got != 0 { - t.Fatalf("idle desiredTimerInterval after recovery = %d, want 0", got) - } - - // Subsequent SDL3 re-capture switches title back to T1 and must re-promote. - title = "macOS — Ctrl+Alt+Win to release" - h.handleWindowNameChange(hwndVM) - if *promotions != 4 { - t.Fatalf("subsequent re-capture T2->T1 did not re-promote: promotions=%d", *promotions) - } -} - -func TestKeymapHookSwapDeduplicatesReentrantEvent(t *testing.T) { - rule := KeymapRule{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lalt": "lopt"}} - h, emitted, _ := newTestKeymapHook(rule) - const hwndVM uintptr = 0x1001 - h.foregroundWindowFn = func() uintptr { return hwndVM } - h.vmForWindowFn = func(hwnd uintptr) string { - if hwnd == hwndVM { - return "vm" - } - return "" - } - h.swappingHook = true - - ev := &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, flags: 0, time: 1234} - if !h.handleKeyEvent(wmSysKeyDown, ev) { - t.Fatal("first callback during swap should suppress LAlt") - } - if !h.handleKeyEvent(wmSysKeyDown, ev) { - t.Fatal("duplicate callback during swap should return same suppress decision") - } - optionDown := EmittedKey{VK: 0x83, Scan: 0x6B} - if !slices.Equal(*emitted, []EmittedKey{optionDown}) { - t.Fatalf("duplicate swap callback emitted twice: %v", *emitted) - } - - // Distinct key-up event during swap is still processed cleanly. - *emitted = nil - upEv := &kbdLLHookStruct{vkCode: vkLAlt, scanCode: 0x38, flags: 0x80, time: 1235} - if !h.handleKeyEvent(wmSysKeyUp, upEv) { - t.Fatal("key-up during swap should suppress physical LAlt up") - } - optionUp := EmittedKey{VK: 0x83, Scan: 0x6B, Up: true} - if !slices.Equal(*emitted, []EmittedKey{optionUp}) { - t.Fatalf("key-up during swap did not emit Option up: %v", *emitted) - } -} diff --git a/internal/vmstart/keymap.go b/internal/vmstart/keymap.go deleted file mode 100644 index af3952d..0000000 --- a/internal/vmstart/keymap.go +++ /dev/null @@ -1,164 +0,0 @@ -package vmstart - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/Nwflower/reims-go/internal/atomicfile" -) - -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"` - CaptureHostShortcuts bool `json:"capture_host_shortcuts,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 EffectiveKeymapBindings(cfg VMKeymapConfig) map[HostModifier]GuestModifier { - bindings := ResolveKeymapBindings(cfg) - if !cfg.CaptureHostShortcuts { - return bindings - } - for host, guest := range map[HostModifier]GuestModifier{ - "lwin": "lcmd", "rwin": "rcmd", "lalt": "lopt", "ralt": "ropt", - } { - if _, bound := bindings[host]; !bound { - bindings[host] = guest - } - } - 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 && !cfg.CaptureHostShortcuts { - 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 - } - if err := atomicfile.WriteJSON(dst, cfg, 0o600); err != nil { - return VMKeymapConfig{}, err - } - return cfg, nil -} diff --git a/internal/vmstart/keymap_test.go b/internal/vmstart/keymap_test.go deleted file mode 100644 index 29730d5..0000000 --- a/internal/vmstart/keymap_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package vmstart - -import ( - "bytes" - "encoding/json" - "maps" - "os" - "path/filepath" - "testing" -) - -func TestVMKeymapCapturePersistence(t *testing.T) { - dir := t.TempDir() - file := filepath.Join(dir, keymapConfigFile) - if err := os.WriteFile(file, []byte(`{"preset":"win_to_cmd"}`), 0600); err != nil { - t.Fatal(err) - } - if got := ReadVMKeymap(dir); got.Preset != KeymapWinToCmd || got.CaptureHostShortcuts { - t.Fatalf("legacy config = %+v", got) - } - cfg := VMKeymapConfig{Preset: KeymapOff, CaptureHostShortcuts: true} - got, err := SaveVMKeymap(dir, cfg) - if err != nil || got.Preset != KeymapOff || !got.CaptureHostShortcuts || got.Bindings != nil { - t.Fatalf("save capture only = %+v, %v", got, err) - } - data, err := os.ReadFile(file) - if err != nil { - t.Fatal(err) - } - var compact bytes.Buffer - if err := json.Compact(&compact, data); err != nil { - t.Fatal(err) - } - if want := `{"preset":"off","capture_host_shortcuts":true}`; compact.String() != want { - t.Fatalf("capture only JSON = %s, want %s", compact.String(), want) - } - if got := ReadVMKeymap(dir); got.Preset != KeymapOff || !got.CaptureHostShortcuts || got.Bindings != nil { - t.Fatalf("read capture only = %+v", got) - } - if _, err := SaveVMKeymap(dir, DefaultVMKeymapConfig()); err != nil { - t.Fatal(err) - } - if _, err := os.Stat(file); !os.IsNotExist(err) { - t.Fatalf("turning capture off did not remove config: %v", err) - } -} - -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) - } - } -} - -func TestEffectiveKeymapBindings(t *testing.T) { - defaults := map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd", "lalt": "lopt", "ralt": "ropt"} - for _, tc := range []struct { - preset KeymapPreset - explicit map[HostModifier]GuestModifier - want map[HostModifier]GuestModifier - }{ - {KeymapOff, nil, defaults}, - {KeymapWinToCmd, map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd"}, defaults}, - {KeymapSwapAltWin, map[HostModifier]GuestModifier{"lwin": "lopt", "rwin": "ropt", "lalt": "lcmd", "ralt": "rcmd"}, - map[HostModifier]GuestModifier{"lwin": "lopt", "rwin": "ropt", "lalt": "lcmd", "ralt": "rcmd"}}, - {KeymapCustom, map[HostModifier]GuestModifier{"lwin": "lctrl", "lalt": "disabled", "capslock": "esc"}, - map[HostModifier]GuestModifier{"lwin": "lctrl", "rwin": "rcmd", "lalt": "disabled", "ralt": "ropt", "capslock": "esc"}}, - } { - t.Run(string(tc.preset), func(t *testing.T) { - cfg := VMKeymapConfig{Preset: tc.preset, Bindings: tc.explicit, CaptureHostShortcuts: true} - if got := EffectiveKeymapBindings(cfg); !maps.Equal(got, tc.want) || !NeedsGuestCarrier(got) { - t.Fatalf("capture enabled = %v, want %v", got, tc.want) - } - if got := ResolveKeymapBindings(cfg); !maps.Equal(got, tc.explicit) { - t.Fatalf("explicit bindings = %v, want %v", got, tc.explicit) - } - cfg.CaptureHostShortcuts = false - if got := EffectiveKeymapBindings(cfg); !maps.Equal(got, tc.explicit) { - t.Fatalf("capture disabled = %v, want %v", got, tc.explicit) - } - }) - } -} diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 2fba528..58957e2 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -27,40 +27,6 @@ "bridgeApply": "Apply network", "bridgeRepair": "Check and repair", "bridgeApplyHint": "Network changes apply separately. Shut down this VM to change mode; bridged uplinks can change while running without reconfiguring other VMs. Host adapter IP, DNS, and bindings remain unchanged", - "keymapGroupTitle": "Modifier keys", - "keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture", - "keymapPresetTitle": "Preset", - "keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed", - "keymapCaptureHostShortcutsTitle": "Block host global hotkeys", - "keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS", - "keymapStatusTitle": "Status", - "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": "Images", "installersDownloaded": "Downloaded", "installersAvailable": "Releases from Apple", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 702b2e7..c74d6e9 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -27,40 +27,6 @@ "bridgeApply": "应用网络", "bridgeRepair": "检查并修复", "bridgeApplyHint": "网络设置单独应用。切换模式需关闭此虚拟机,更换桥接出口支持运行中应用,不影响其他虚拟机。宿主网卡的 IP、DNS 和绑定保持不变", - "keymapGroupTitle": "修饰键映射", - "keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获", - "keymapPresetTitle": "映射预设", - "keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可", - "keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键", - "keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option", - "keymapStatusTitle": "生效状态", - "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 提供的版本",