Merge pull request #53 from reiasu2/feat/modifier-key-remap

This commit is contained in:
Nwflower committed 2026-12-01 04:59:51 -07:00
commit bc59aca9e5
34 files changed
+2003 -98

No files matched your search

+74
View File
@@ -330,3 +330,77 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr
assert.equal(appleBlue['--accent-text'], '#ffffff')
assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`)
})
test('VM keymap preserves preset bindings and isolates pending writes by VM', async () => {
const source = fs.readFileSync(path.join(srcDir, 'components/SettingsModal.tsx'), 'utf8')
const normalized = source.replaceAll('\r\n', '\n')
const effects = normalized.slice(
normalized.indexOf(' useEffect(() => {\n setKeymap(null)'),
normalized.indexOf(' const updateDriveShares'),
)
const preset = normalized.match(/onChange=\{(\(preset\) => \{\n\s+if \(preset === keymap\.preset\)[\s\S]*?\n\s+\})\} \/>/)?.[1]
assert.ok(effects.includes('const updateKeymap') && preset)
const { render } = await loadBundledTS(`
export function render({ detail, api, useEffect, window, activeVMNameRef, keymapWrite,
keymapRevision, setKeymap, setKeymapErr, setKeymapBusy, parseAppError, keymap }) {
const cat = 'input'
const running = true
${effects}
return ${preset}
}
`)
let finishWrite
const writes = []
const reads = []
const state = {}
let failRead = true
const context = {
api: {
SetVMKeymap(name, req) {
writes.push([name, req])
return new Promise((resolve) => { finishWrite = resolve })
},
async GetVMKeymap(name) {
reads.push(name)
if (name === 'b' && failRead) throw Error('temporary')
return { preset: 'off', bindings: {} }
},
},
useEffect(effect) {
const cleanup = effect()
if (cleanup) this.cleanups.push(cleanup)
},
cleanups: [],
window: { setInterval(refresh) { this.refresh = refresh }, clearInterval() {} },
activeVMNameRef: { current: 'a' },
keymapWrite: { current: new Set() },
keymapRevision: { current: new Map() },
setKeymap(value) { state.keymap = value },
setKeymapErr(value) { state.error = value },
setKeymapBusy(value) { state.busy = value },
parseAppError: (error) => ({ summary: error.message }),
}
context.useEffect = context.useEffect.bind(context)
const bindings = { lwin: 'lcmd' }
const change = render({ ...context, detail: { name: 'a' }, keymap: { preset: 'win_to_cmd', bindings } })
change('win_to_cmd')
assert.deepEqual(writes, [])
change('custom')
assert.deepEqual(writes, [['a', { preset: 'custom', bindings }]])
context.cleanups.pop()()
context.activeVMNameRef.current = 'b'
const changeB = render({ ...context, detail: { name: 'b' }, keymap: { preset: 'custom', bindings } })
changeB('custom')
assert.equal(writes.length, 1)
assert.deepEqual(reads, ['a', 'b'])
assert.equal(state.busy, false)
await new Promise(setImmediate)
assert.equal(state.error, 'temporary')
failRead = false
await context.window.refresh()
assert.equal(state.error, '')
finishWrite({ preset: 'custom', bindings })
await new Promise(setImmediate)
assert.deepEqual(state.keymap, { preset: 'off', bindings: {} })
})
+99
View File
@@ -33,6 +33,7 @@ import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier, VMKeymapStatus, VMKeymapUpdate } from '../types'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
@@ -179,6 +180,11 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
const gtConnected = liveStats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtAgentVersion = liveStats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
const [keymap, setKeymap] = useState<VMKeymapStatus | null>(null)
const [keymapErr, setKeymapErr] = useState('')
const [keymapBusy, setKeymapBusy] = useState(false)
const keymapWrite = useRef(new Set<string>())
const keymapRevision = useRef(new Map<string, number>())
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
const vmSettingsKey = `${driverID}:${detail.name}`
@@ -386,6 +392,53 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
}
}
useEffect(() => {
setKeymap(null)
setKeymapBusy(keymapWrite.current.has(detail.name))
setKeymapErr('')
}, [detail.name])
useEffect(() => {
if (cat !== 'input') return
let active = true
let pending = false
const refresh = async () => {
if (pending || keymapWrite.current.has(detail.name)) return
const revision = keymapRevision.current.get(detail.name)
pending = true
try {
const next = await api.GetVMKeymap(detail.name)
if (active && revision === keymapRevision.current.get(detail.name)) {
setKeymap(next)
setKeymapErr('')
}
} catch (e) {
if (active && revision === keymapRevision.current.get(detail.name)) setKeymapErr(parseAppError(e).summary)
} finally {
pending = false
}
}
void refresh()
const timer = window.setInterval(refresh, 3000)
return () => { active = false; window.clearInterval(timer) }
}, [cat, detail.name, running])
const updateKeymap = (req: VMKeymapUpdate) => {
const name = detail.name
if (keymapWrite.current.has(name)) return
keymapRevision.current.set(name, (keymapRevision.current.get(name) ?? 0) + 1)
keymapWrite.current.add(name)
setKeymapBusy(true)
setKeymapErr('')
void api.SetVMKeymap(name, req)
.then((next) => { if (activeVMNameRef.current === name) setKeymap(next) })
.catch((e) => { if (activeVMNameRef.current === name) setKeymapErr(parseAppError(e).summary) })
.finally(() => {
keymapWrite.current.delete(name)
if (activeVMNameRef.current === name) setKeymapBusy(false)
})
}
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
if (driveBusyRef.current || !driveSettings) return
driveBusyRef.current = true
@@ -1280,6 +1333,52 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
/>
</SetGroup>
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
{keymap && <>
<SetRow title={tr('keymapPresetTitle')} disabled={keymapBusy}
desc={keymap.preset === 'off' ? undefined
: !keymap.input_service_available ? tr('keymapInputServiceRequired')
: !keymap.running ? tr('keymapStopped')
: keymap.needs_guest_tools && !keymap.guest_connected ? tr('keymapWaiting')
: keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version
? tr('keymapUpgrade', { version: keymap.required_agent_version })
: keymap.needs_guest_tools && !keymap.guest_keymap_active ? tr('keymapPending')
: tr(keymap.hook_active ? 'keymapRunning' : 'keymapInactive')}
control={<Segmented<VMKeymapPreset> label={tr('keymapPresetTitle')} value={keymap.preset}
options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]}
onChange={(preset) => {
if (preset === keymap.preset) return
updateKeymap({ preset, bindings: preset === 'custom' && keymap.preset !== 'off' ? keymap.bindings : {} })
}} />}
/>
{keymap.preset === 'custom' && ([
['lwin', 'keymapHostLwin'],
['rwin', 'keymapHostRwin'],
['lalt', 'keymapHostLalt'],
['ralt', 'keymapHostRalt'],
['lctrl', 'keymapHostLctrl'],
['rctrl', 'keymapHostRctrl'],
['capslock', 'keymapHostCapslock'],
] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => (
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
control={<PopupSelect<VMKeymapGuestModifier> label={tr(label)} value={keymap.bindings[modifier] ?? 'default'}
options={[
{ value: 'default', label: tr('keymapGuestDefault') },
{ value: 'lcmd', label: tr('keymapGuestLcmd') },
{ value: 'rcmd', label: tr('keymapGuestRcmd') },
{ value: 'lopt', label: tr('keymapGuestLopt') },
{ value: 'ropt', label: tr('keymapGuestRopt') },
{ value: 'lctrl', label: tr('keymapGuestLctrl') },
{ value: 'rctrl', label: tr('keymapGuestRctrl') },
{ value: 'esc', label: tr('keymapGuestEsc') },
{ value: 'disabled', label: tr('keymapGuestDisabled') },
]}
onChange={(target) => updateKeymap({ preset: 'custom', bindings: { ...keymap.bindings, [modifier]: target } })} />}
/>
))}
</>}
</SetGroup>
{renderVMPluginGroup('keyboard')}
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
<SetRow
+1 -1
View File
@@ -969,7 +969,7 @@ export const VMPage: React.FC<Props> = ({
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 9
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 10
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
+60
View File
@@ -264,6 +264,36 @@ export const settingsZh: Record<string, string> = {
"kernelIrqchipLabel": "中断加速",
"kernelIrqchipOff": "关闭",
"kernelIrqchipOn": "开启",
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。",
"keymapGroupTitle": "修饰键映射",
"keymapGuestDefault": "默认",
"keymapGuestDisabled": "禁用",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "左 ⌘ Command",
"keymapGuestLctrl": "左 ⌃ Control",
"keymapGuestLopt": "左 ⌥ Option",
"keymapGuestRcmd": "右 ⌘ Command",
"keymapGuestRctrl": "右 ⌃ Control",
"keymapGuestRopt": "右 ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "左 Alt",
"keymapHostLctrl": "左 Ctrl",
"keymapHostLwin": "左 Win",
"keymapHostRalt": "右 Alt",
"keymapHostRctrl": "右 Ctrl",
"keymapHostRwin": "右 Win",
"keymapInactive": "修饰键映射未启用",
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
"keymapPending": "等待 Guest Tools 启用修饰键映射",
"keymapPresetCustom": "自定义",
"keymapPresetOff": "关闭",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "映射预设",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "虚拟机获得焦点时生效",
"keymapStopped": "虚拟机启动后生效",
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
"keymapWaiting": "等待 Guest Tools 连接",
"language": "语言",
"languageSub": "内置简体中文与英语,可通过插件扩展更多语言",
"logLevel": "日志级别",
@@ -650,6 +680,36 @@ export const settingsEn: Record<string, string> = {
"kernelIrqchipLabel": "Interrupt acceleration",
"kernelIrqchipOff": "Off",
"kernelIrqchipOn": "On",
"keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.",
"keymapGroupTitle": "Modifier keys",
"keymapGuestDefault": "Default",
"keymapGuestDisabled": "Disabled",
"keymapGuestEsc": "Esc",
"keymapGuestLcmd": "Left ⌘ Command",
"keymapGuestLctrl": "Left ⌃ Control",
"keymapGuestLopt": "Left ⌥ Option",
"keymapGuestRcmd": "Right ⌘ Command",
"keymapGuestRctrl": "Right ⌃ Control",
"keymapGuestRopt": "Right ⌥ Option",
"keymapHostCapslock": "Caps Lock",
"keymapHostLalt": "Left Alt",
"keymapHostLctrl": "Left Ctrl",
"keymapHostLwin": "Left Win",
"keymapHostRalt": "Right Alt",
"keymapHostRctrl": "Right Ctrl",
"keymapHostRwin": "Right Win",
"keymapInactive": "Modifier mapping is inactive",
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
"keymapPresetCustom": "Custom",
"keymapPresetOff": "Off",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetTitle": "Preset",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapRunning": "Active while this VM is focused",
"keymapStopped": "Applies when this VM is running",
"keymapUpgrade": "Update Guest Tools to version {version}",
"keymapWaiting": "Waiting for Guest Tools to connect",
"language": "Language",
"languageSub": "Simplified Chinese and English built in; add more via plugins",
"logLevel": "Log level",
+30
View File
@@ -450,6 +450,36 @@ export type I18nKey =
| "kernelIrqchipLabel"
| "kernelIrqchipOff"
| "kernelIrqchipOn"
| "keymapGroupNote"
| "keymapGroupTitle"
| "keymapGuestDefault"
| "keymapGuestDisabled"
| "keymapGuestEsc"
| "keymapGuestLcmd"
| "keymapGuestLctrl"
| "keymapGuestLopt"
| "keymapGuestRcmd"
| "keymapGuestRctrl"
| "keymapGuestRopt"
| "keymapHostCapslock"
| "keymapHostLalt"
| "keymapHostLctrl"
| "keymapHostLwin"
| "keymapHostRalt"
| "keymapHostRctrl"
| "keymapHostRwin"
| "keymapInactive"
| "keymapInputServiceRequired"
| "keymapPending"
| "keymapPresetCustom"
| "keymapPresetOff"
| "keymapPresetSwapAltWin"
| "keymapPresetTitle"
| "keymapPresetWinToCmd"
| "keymapRunning"
| "keymapStopped"
| "keymapUpgrade"
| "keymapWaiting"
| "language"
| "languageSub"
| "localeAuto"
+19
View File
@@ -176,3 +176,22 @@ export interface LogEntry {
source: string
line: string
}
export type VMKeymapPreset = 'off' | 'win_to_cmd' | 'swap_alt_win' | 'custom'
export type VMKeymapHostModifier = 'lwin' | 'rwin' | 'lalt' | 'ralt' | 'lctrl' | 'rctrl' | 'capslock'
export type VMKeymapGuestModifier = 'default' | 'lcmd' | 'rcmd' | 'lopt' | 'ropt' | 'lctrl' | 'rctrl' | 'esc' | 'disabled'
export interface VMKeymapUpdate {
preset: VMKeymapPreset
bindings: Partial<Record<VMKeymapHostModifier, VMKeymapGuestModifier>>
}
export interface VMKeymapStatus extends VMKeymapUpdate {
needs_guest_tools: boolean
guest_connected: boolean
guest_agent_version?: number
required_agent_version: number
input_service_available: boolean
guest_keymap_active: boolean
hook_active: boolean
running: boolean
}
+3 -1
View File
@@ -17,7 +17,7 @@ import {
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMKeymapStatus, VMKeymapUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -151,6 +151,8 @@ export const api = {
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
+4
View File
@@ -137,6 +137,8 @@ export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
@@ -289,6 +291,8 @@ export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
+8
View File
@@ -254,6 +254,10 @@ export function GetVMAffinityWithDriver(arg1, arg2) {
return window['go']['app']['App']['GetVMAffinityWithDriver'](arg1, arg2);
}
export function GetVMKeymap(arg1) {
return window['go']['app']['App']['GetVMKeymap'](arg1);
}
export function GetVMDetail(arg1) {
return window['go']['app']['App']['GetVMDetail'](arg1);
}
@@ -558,6 +562,10 @@ export function SetVMAffinityWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMAffinityWithDriver'](arg1, arg2, arg3);
}
export function SetVMKeymap(arg1, arg2) {
return window['go']['app']['App']['SetVMKeymap'](arg1, arg2);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
+47
View File
@@ -1,4 +1,51 @@
export namespace app {
export class VMKeymapUpdate {
preset: string;
bindings: Record<string, string>;
static createFrom(source: object | string = {}) {
return new VMKeymapUpdate(source);
}
constructor(source: Partial<VMKeymapUpdate> | string = {}) {
if (typeof source === "string") source = JSON.parse(source) as Partial<VMKeymapUpdate>;
this.preset = source.preset ?? "off";
this.bindings = source.bindings ?? {};
}
}
export class VMKeymapStatus {
preset: string;
bindings: Record<string, string>;
needs_guest_tools: boolean;
guest_connected: boolean;
guest_agent_version?: number;
required_agent_version: number;
input_service_available: boolean;
guest_keymap_active: boolean;
hook_active: boolean;
running: boolean;
static createFrom(source: object | string = {}) {
return new VMKeymapStatus(source);
}
constructor(source: Partial<VMKeymapStatus> | string = {}) {
if (typeof source === "string") source = JSON.parse(source) as Partial<VMKeymapStatus>;
this.preset = source.preset ?? "off";
this.bindings = source.bindings ?? {};
this.needs_guest_tools = source.needs_guest_tools ?? false;
this.guest_connected = source.guest_connected ?? false;
this.guest_agent_version = source.guest_agent_version;
this.required_agent_version = source.required_agent_version ?? 0;
this.input_service_available = source.input_service_available ?? false;
this.guest_keymap_active = source.guest_keymap_active ?? false;
this.hook_active = source.hook_active ?? false;
this.running = source.running ?? false;
}
}
export class AppState {
quit_mode?: string;
+13 -1
View File
@@ -127,6 +127,11 @@ type App struct {
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
keymapMu sync.Mutex
keymapPIDs map[string]int
fallbackInputSvc *host.InputService
inputShuttingDown bool
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -241,6 +246,13 @@ func (a *App) shutdown(ctx context.Context) {
}
tasks.cancelAll()
stopAllVMMonitors()
a.mu.Lock()
a.inputShuttingDown = true
fallback := a.fallbackInputSvc
a.mu.Unlock()
if fallback != nil {
fallback.Close()
}
a.shutdownPlugins()
a.mu.Lock()
for name, entry := range a.rebootWatchers {
@@ -434,7 +446,7 @@ func (a *App) pollVMs(ctx context.Context) {
if ib != nil {
ib.SetTargets(imeTargets)
}
a.syncInputTargets(imeTargets)
a.syncKeymapRules()
if tm != nil {
effLoc := i18n.EffectiveLocale(loc)
if runningCount >= 1 {
+1 -1
View File
@@ -88,7 +88,7 @@ func TestSharedFolderChangesAndVolumeDrift(t *testing.T) {
}
settings := change("", "add", work)
info := settings.Folders[0]
if settings.RequiredAgentVersion != guesttools.CurrentAgentVersion || !info.Available || !info.Enabled ||
if settings.RequiredAgentVersion != guesttools.SharedFolderAgentVersion || !info.Available || !info.Enabled ||
info.Writable || !strings.EqualFold(info.HostPath, work) || !strings.HasPrefix(list(), info.ID+"|ro|") {
t.Fatalf("initial settings: %+v", settings)
}
+4
View File
@@ -116,6 +116,7 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created
a.injectRemoteTextRef(vmKey, vmName, "", text)
})
a.guestTools = srv
srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() })
created = true
}
a.mu.Unlock()
@@ -170,6 +171,8 @@ 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,
@@ -188,6 +191,7 @@ func (a *App) registerExistingGuestTools(ctx context.Context) {
// guest agent that is already running reconnects after reims-go restarts or
// the Guest Tools plugin is switched back on.
func (a *App) registerVMsWithBridge(ctx context.Context, srv *guesttools.Server, port int) {
defer a.syncKeymapRules()
c, err := a.client()
if err != nil {
return
+142
View File
@@ -0,0 +1,142 @@
package app
import (
"time"
"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
const keymapStatusMaxAge = 30 * time.Second
type VMKeymapUpdate struct {
Preset string `json:"preset"`
Bindings map[string]string `json:"bindings"`
}
type VMKeymapStatus struct {
Preset string `json:"preset"`
Bindings map[string]string `json:"bindings"`
NeedsGuestTools bool `json:"needs_guest_tools"`
GuestConnected bool `json:"guest_connected"`
GuestAgentVersion int `json:"guest_agent_version,omitempty"`
RequiredAgentVersion int `json:"required_agent_version"`
GuestKeymapActive bool `json:"guest_keymap_active"`
InputServiceAvailable bool `json:"input_service_available"`
HookActive bool `json:"hook_active"`
Running bool `json:"running"`
}
func (a *App) GetVMKeymap(name string) (VMKeymapStatus, error) {
if vm, ok := a.polledVM(name); ok && vm.Dir != "" {
return a.keymapStatus(name, vm.State == "running", vmstart.ReadVMKeymap(vm.Dir)), nil
}
detail, err := a.GetVMDetail(name)
if err != nil {
return VMKeymapStatus{}, err
}
return a.keymapStatus(name, detail.State == "running", vmstart.ReadVMKeymap(detail.Directory)), nil
}
func (a *App) SetVMKeymap(name string, req VMKeymapUpdate) (VMKeymapStatus, error) {
detail, err := a.GetVMDetail(name)
if err != nil {
return VMKeymapStatus{}, err
}
cfg := vmstart.VMKeymapConfig{
Preset: vmstart.KeymapPreset(req.Preset),
Bindings: make(map[vmstart.HostModifier]vmstart.GuestModifier, len(req.Bindings)),
}
for k, v := range req.Bindings {
cfg.Bindings[vmstart.HostModifier(k)] = vmstart.GuestModifier(v)
}
cfg, err = vmstart.SaveVMKeymap(detail.Directory, cfg)
if err != nil {
return VMKeymapStatus{}, err
}
a.syncKeymapRules()
return a.keymapStatus(name, detail.State == "running", cfg), nil
}
func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig) VMKeymapStatus {
bindings := vmstart.ResolveKeymapBindings(cfg)
status := VMKeymapStatus{
Preset: string(cfg.Preset),
Bindings: keymapBindingStrings(bindings),
NeedsGuestTools: vmstart.NeedsGuestCarrier(bindings),
RequiredAgentVersion: KeymapRequiredAgentVersion,
Running: running,
}
a.mu.Lock()
srv := a.guestTools
a.mu.Unlock()
if srv != nil && running {
guest := srv.Status(name, keymapStatusMaxAge)
status.GuestConnected = guest.Connected
status.GuestAgentVersion = guest.AgentVersion
status.GuestKeymapActive = guest.KeymapActive && guest.AgentVersion >= KeymapRequiredAgentVersion
}
svc := a.getInputService()
status.InputServiceAvailable = svc != nil
if svc != nil && running {
status.HookActive = svc.IsKeymapActiveForVM(name)
}
return status
}
func keymapBindingStrings(bindings map[vmstart.HostModifier]vmstart.GuestModifier) map[string]string {
out := make(map[string]string, len(bindings))
for k, v := range bindings {
out[string(k)] = string(v)
}
return out
}
func (a *App) syncKeymapRules() {
a.keymapMu.Lock()
defer a.keymapMu.Unlock()
a.mu.Lock()
vms := append([]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.State != "running" || vm.PID == nil || *vm.PID <= 0 {
if srv != nil {
srv.SetKeymapCarrier(vm.Name, false)
}
continue
}
dir := vm.Dir
if dir == "" {
if detail, err := a.GetVMDetail(vm.Name); err == nil {
dir = detail.Directory
}
}
targets = append(targets, host.IMETarget{VMName: vm.Name, VMDir: dir, PID: uint32(*vm.PID)})
pids[vm.Name] = *vm.PID
bindings := vmstart.ResolveKeymapBindings(vmstart.ReadVMKeymap(dir))
rule := host.KeymapRule{VMName: vm.Name, Bindings: keymapBindingStrings(bindings)}
if srv != nil {
if oldPID := a.keymapPIDs[vm.Name]; oldPID != 0 && oldPID != *vm.PID {
srv.SetKeymapCarrier(vm.Name, false)
}
srv.SetKeymapCarrier(vm.Name, svc != nil && vmstart.NeedsGuestCarrier(bindings))
status := srv.Status(vm.Name, keymapStatusMaxAge)
rule.CarrierReady = status.Connected && status.KeymapActive && status.AgentVersion >= KeymapRequiredAgentVersion
}
if len(bindings) != 0 {
rules = append(rules, rule)
}
}
a.keymapPIDs = pids
if svc != nil {
svc.SetTargetsAndKeymapRules(targets, rules)
}
}
+32
View File
@@ -0,0 +1,32 @@
package app
import (
"testing"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func TestKeymapStatusWithoutPluginManager(t *testing.T) {
a := &App{}
t.Cleanup(func() { a.getInputService().Close() })
a.syncKeymapRules()
cfg := vmstart.VMKeymapConfig{Preset: vmstart.KeymapWinToCmd}
got := a.keymapStatus("mac", true, cfg)
if got.Preset != "win_to_cmd" || got.Bindings["lwin"] != "lcmd" ||
!got.NeedsGuestTools || !got.InputServiceAvailable || !got.Running || got.RequiredAgentVersion != 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)
}
}
+21 -9
View File
@@ -190,6 +190,7 @@ func (a *App) initPlugins() {
mgr.Registry().OnChange(func() {
a.syncRuntimeKinds(kindReg, mgr.Registry())
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
if a.ctx != nil {
@@ -197,16 +198,24 @@ func (a *App) initPlugins() {
}
})
a.keymapMu.Lock()
a.mu.Lock()
fallback := a.fallbackInputSvc
a.fallbackInputSvc = nil
a.pluginMgr = mgr
a.driverRouter = drvRouter
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
a.runtimeKinds = kindReg
a.mu.Unlock()
if fallback != nil {
fallback.Close()
}
a.keymapMu.Unlock()
mgr.Registry().Reconcile(context.Background())
mgr.MarkBootComplete()
a.syncInputFilters()
a.syncKeymapRules()
a.syncClipboardPolicies()
a.syncLocales()
}
@@ -331,11 +340,20 @@ func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
func (a *App) getInputService() *host.InputService {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
if a.inputShuttingDown {
a.mu.Unlock()
return nil
}
mgr := a.pluginMgr
if mgr == nil {
if a.fallbackInputSvc == nil {
a.fallbackInputSvc = host.NewInputService(nil)
}
svc := a.fallbackInputSvc
a.mu.Unlock()
return svc
}
a.mu.Unlock()
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
if !ok {
return nil
@@ -344,12 +362,6 @@ func (a *App) getInputService() *host.InputService {
return svc
}
func (a *App) syncInputTargets(targets []host.IMETarget) {
if svc := a.getInputService(); svc != nil {
svc.SetTargets(targets)
}
}
func (a *App) syncInputFilters() {
a.mu.Lock()
mgr := a.pluginMgr
+3 -2
View File
@@ -4,6 +4,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)
@@ -22,8 +23,8 @@ func TestGuestAgentClipboardScript(t *testing.T) {
if start < 0 || end <= start {
t.Fatal("missing generated clipboard code")
}
if !strings.Contains(agent, `"agent_version\":9}`) {
t.Fatal("missing agent version 8")
if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)[,\}]`).MatchString(agent) {
t.Fatal("clipboard sync requires agent version 6 or newer")
}
if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) {
t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u")
+4 -4
View File
@@ -44,8 +44,8 @@ print $mounts "$url on $target (webdav, read-only)\n";
t.Fatal(err)
}
script := string(GuestAgentScript())
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":9}`) {
t.Fatal("Windows drive sharing requires version 7 and the generated agent reports version 8")
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":10,`) {
t.Fatal("Windows drive sharing requires version 8 and the generated agent reports version 10")
}
harness := `set -eu
PATH="$PWD:/usr/bin:/bin:$PATH"
@@ -127,8 +127,8 @@ test "$(wc -l <"$MOUNT_STATE")" -eq 1
}
func TestShellSingleQuoteAndAgentVersion(t *testing.T) {
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":9}`) {
t.Fatal("GuestAgentScript must report agent_version 9")
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":10,`) {
t.Fatal("GuestAgentScript must report agent_version 10")
}
if DriveShareAgentVersion != 8 {
t.Fatalf("DriveShareAgentVersion = %d, want 8", DriveShareAgentVersion)
+3 -2
View File
@@ -34,9 +34,9 @@ func TestGuestAgentFolderMounts(t *testing.T) {
}
}
agent, uninstall, install := string(GuestAgentScript()), string(GuestUninstallScript()), string(GuestInstallScript())
if CurrentAgentVersion != 9 || !strings.Contains(agent, `"agent_version\":9}`) ||
if CurrentAgentVersion != 10 || !strings.Contains(agent, `"agent_version\":10,`) ||
!strings.Contains(install, "Reims Guest Tools 8 installed and connected!") {
t.Fatal("missing Guest Tools 8 version")
t.Fatal("missing Guest Tools version 10")
}
for name, script := range map[string]string{"agent": agent, "uninstaller": uninstall, "installer": install} {
t.Run(name+"_syntax", func(t *testing.T) { run(t, script, "-n") })
@@ -98,6 +98,7 @@ 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=""
+2 -1
View File
@@ -14,7 +14,8 @@ import (
)
const SharedFolderAgentVersion = 9
const CurrentAgentVersion = SharedFolderAgentVersion
const KeymapAgentVersion = 10
const CurrentAgentVersion = KeymapAgentVersion
type SharedFolderConfig struct {
ID string `json:"id"`
+97 -3
View File
@@ -109,8 +109,15 @@ rm -f "$INJECT_LOCK" 2>/dev/null || true
CAFFEINATE_PID=""
TEXT_INPUT_PID=""
keymap_active="false"
keymap_applied="false"
` + guestKeymapCarrier + `
cleanup() {
if [ "$keymap_applied" = "true" ]; then
apply_hidutil_carrier disable
report_status 1
fi
if [ -n "$CAFFEINATE_PID" ]; then
kill "$CAFFEINATE_PID" 2>/dev/null || true
fi
@@ -119,7 +126,8 @@ cleanup() {
fi
rm -f "$INJECT_LOCK" 2>/dev/null || true
}
trap cleanup EXIT INT TERM
trap cleanup EXIT
trap 'exit 0' INT TERM
` + guestIdentityHelpers + `
@@ -403,6 +411,7 @@ apply_host_config() {
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}"
sync_keymap_carrier "$cfg_json"
if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then
clip_enabled="0"
else
@@ -431,10 +440,10 @@ apply_host_config() {
report_status() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
curl -fsS -m 3 -X POST \
curl -fsS -m "${1:-3}" -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":9}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":10,\"keymap_active\":$keymap_active}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
@@ -786,6 +795,8 @@ FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders"
` + 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
@@ -865,6 +876,89 @@ 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
+179
View File
@@ -0,0 +1,179 @@
package guesttools
import (
"encoding/json"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
func TestGuestAgentKeymapScript(t *testing.T) {
sh, err := exec.LookPath("sh")
if err != nil {
sh = "C:/Program Files/Git/bin/sh.exe"
if _, err := os.Stat(sh); err != nil {
t.Skip("POSIX sh is unavailable")
}
}
agent := string(GuestAgentScript())
start := strings.Index(agent, "apply_hidutil_carrier() {")
end := strings.Index(agent, "load_conf() {")
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":10,\"keymap_active\":$keymap_active`) {
t.Fatal("missing guest keymap script or version 10 status")
}
for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} {
t.Run(input, func(t *testing.T) {
dir := t.TempDir()
fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil")
fixture += "\nprintf '%s\\n' \"$1\" > state\nsync_keymap_carrier '{}'\n"
fixture += "[ \"$keymap_carrier_clean\" = 1 ]\nrm state\nsync_keymap_carrier '{}'\n[ ! -f state ]\n"
cmd := exec.Command(sh, "-c", fixture, "fixture", input)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("shell fixture: %v\n%s", err, out)
}
gets, err := os.ReadFile(filepath.Join(dir, "get.log"))
if err != nil || strings.TrimSpace(string(gets)) != "get" {
t.Fatalf("expected exactly one hidutil read: %q, %v", gets, err)
}
got, err := os.ReadFile(filepath.Join(dir, "set.log"))
if strings.Contains(input, "30064771184") {
if err != nil || strings.TrimSpace(string(got)) != `{"UserKeyMapping":[]}` {
t.Fatalf("disable output = %q, %v", got, err)
}
} else if !os.IsNotExist(err) {
t.Fatalf("empty input should require no write: %q, %v", got, err)
}
})
}
for _, teardown := range []string{"disable", "exit", "uninstall"} {
t.Run(teardown, func(t *testing.T) {
dir := t.TempDir()
fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + keymapShellExercise
if teardown == "uninstall" {
uninstall := string(GuestUninstallScript())
start := strings.Index(uninstall, "apply_hidutil_carrier() {")
end := strings.Index(uninstall, "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=
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)
}
}
+77 -41
View File
@@ -91,6 +91,7 @@ type VMConfig struct {
// GuestStatus summarizes live Guest Tools connection and capability state.
type GuestStatus struct {
KeymapActive bool `json:"keymap_active"`
Connected bool `json:"connected"`
MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync"
PreventSleep bool `json:"prevent_sleep"`
@@ -208,22 +209,25 @@ type pendingClipOverride struct {
}
type registeredVM struct {
key string
name string
token string
sharedDir string
sharedRoot sharedRoot
preventSleep bool
driveSharingEnabled bool
sharedDriveRoots map[string]string
driveVolumeGUIDs map[string]string
verifyDriveRoot func(*os.Root, string, string) error
resolvedFolders map[string]ResolvedSharedFolder
verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error
mountMode string
sleepActive bool
agentVersion int
lastSeen time.Time
key string
name string
token string
sharedDir string
sharedRoot sharedRoot
preventSleep bool
driveSharingEnabled bool
sharedDriveRoots map[string]string
driveVolumeGUIDs map[string]string
verifyDriveRoot func(*os.Root, string, string) error
resolvedFolders map[string]ResolvedSharedFolder
verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error
keymapCarrierEnabled bool
keymapActive bool
lastStatus time.Time
mountMode string
sleepActive bool
agentVersion int
lastSeen time.Time
injectMu sync.Mutex
textSeq uint64
@@ -260,6 +264,7 @@ type Server struct {
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmKey, vmName, text string)
onStatusChange func(vmName string)
}
// NewServer constructs a Guest Tools HTTP bridge with clipboard active by default.
@@ -700,6 +705,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus {
}
connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge
return GuestStatus{
KeymapActive: connected && vm.keymapCarrierEnabled && vm.keymapActive && time.Since(vm.lastStatus) <= maxAge,
Connected: connected,
MountMode: vm.mountMode,
PreventSleep: vm.preventSleep,
@@ -709,6 +715,22 @@ 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 (s *Server) touchLastSeen(vmName string) {
vmName = normalizeVMRegistryKey(vmName)
s.mu.Lock()
@@ -739,20 +761,21 @@ func (s *Server) authenticate(r *http.Request) *registeredVM {
// injectMu and alias the text queues. Handlers that need the
// queues look the live VM up again by name under s.mu.
cp := registeredVM{
key: vm.key,
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
sharedRoot: vm.sharedRoot,
preventSleep: vm.preventSleep,
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,
key: vm.key,
name: vm.name,
token: vm.token,
sharedDir: vm.sharedDir,
sharedRoot: vm.sharedRoot,
preventSleep: vm.preventSleep,
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,
}
return &cp
}
@@ -785,7 +808,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"}
caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly", "custom-folders", "keymap-carrier"}
if policy := s.EffectiveClipboardPolicy(vm.key); policy.Enabled {
caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...)
if policy.SyncImages {
@@ -814,15 +837,16 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
policy := s.EffectiveClipboardPolicy(vm.key)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
"shared_folders_count": len(vm.resolvedFolders),
"clipboard_enabled": policy.Enabled,
"clipboard_direction": policy.Direction,
"clipboard_sync_images": policy.SyncImages,
"clipboard_max_bytes": policy.MaxImageBytes,
"vm": vm.name,
"keymap_carrier_enabled": vm.keymapCarrierEnabled,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
"shared_folders_count": len(vm.resolvedFolders),
"clipboard_enabled": policy.Enabled,
"clipboard_direction": policy.Direction,
"clipboard_sync_images": policy.SyncImages,
"clipboard_max_bytes": policy.MaxImageBytes,
})
}
@@ -837,6 +861,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
KeymapActive bool `json:"keymap_active"`
MountMode string `json:"mount_mode"`
SleepActive bool `json:"sleep_active"`
AgentVersion int `json:"agent_version"`
@@ -850,7 +875,15 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
mode = ""
}
s.mu.Lock()
if cur := s.vms[vm.key]; cur != nil {
var notify func(string)
if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token {
now := time.Now()
active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= KeymapAgentVersion
if cur.keymapActive != active || now.Sub(cur.lastStatus) > 30*time.Second {
notify = s.onStatusChange
}
cur.keymapActive = active
cur.lastStatus = now
if mode != "" {
cur.mountMode = mode
}
@@ -862,6 +895,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
}
s.mu.Unlock()
w.WriteHeader(http.StatusOK)
if notify != nil {
notify(vm.name)
}
}
func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) {
+12 -11
View File
@@ -12,17 +12,17 @@ import (
)
var (
procSetWindowsHookExW = user32.NewProc("SetWindowsHookExW")
procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
procCallNextHookEx = user32.NewProc("CallNextHookEx")
procGetMessageW = user32.NewProc("GetMessageW")
procPeekMessageW = user32.NewProc("PeekMessageW")
procPostThreadMessageW = user32.NewProc("PostThreadMessageW")
procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId")
imeKernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandleW = imeKernel32.NewProc("GetModuleHandleW")
procGetCurrentThreadId = imeKernel32.NewProc("GetCurrentThreadId")
procSetWindowsHookExW = user32.NewProc("SetWindowsHookExW")
procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
procCallNextHookEx = user32.NewProc("CallNextHookEx")
procGetMessageW = user32.NewProc("GetMessageW")
procPeekMessageW = user32.NewProc("PeekMessageW")
procPostThreadMessageW = user32.NewProc("PostThreadMessageW")
procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId")
imeKernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandleW = imeKernel32.NewProc("GetModuleHandleW")
procGetCurrentThreadId = imeKernel32.NewProc("GetCurrentThreadId")
)
const (
@@ -53,6 +53,7 @@ type winMsg struct {
time uint32
ptX int32
ptY int32
private uint32
}
var (
+108 -14
View File
@@ -1,6 +1,8 @@
package host
import (
"maps"
"reflect"
"strings"
"sync"
"sync/atomic"
@@ -11,11 +13,11 @@ import (
type InputFilterRule struct {
ID string `json:"id"`
PluginID string `json:"plugin_id"`
Event string `json:"event"` // "mouse_wheel"
Axis string `json:"axis"` // "vertical" | "horizontal" | "both"
Transform string `json:"transform"` // "invert"
Scope string `json:"scope"` // "vm_foreground"
VMNames map[string]bool `json:"vm_names,omitempty"` // empty = all VMs; non-empty = targeted VMs
Event string `json:"event"` // "mouse_wheel"
Axis string `json:"axis"` // "vertical" | "horizontal" | "both"
Transform string `json:"transform"` // "invert"
Scope string `json:"scope"` // "vm_foreground"
VMNames map[string]bool `json:"vm_names,omitempty"` // empty = all VMs; non-empty = targeted VMs
Vertical bool `json:"vertical"`
Horizontal bool `json:"horizontal"`
}
@@ -79,15 +81,18 @@ func hasMatchingWheelTarget(rules []InputFilterRule, targets []IMETarget) bool {
// InputService unifies low-level keyboard (IME bridge) and on-demand low-level
// mouse (declarative inputFilters) hooks behind one reversible host service (§5.4).
type InputService struct {
mu sync.Mutex
onIMEText func(target IMETarget, text string)
imeEnabled bool
imeBridge *IMEBridge
targets []IMETarget
targetByPID atomic.Pointer[map[uint32]IMETarget]
rules atomic.Pointer[[]InputFilterRule]
mouseHook *mouseWheelHook
closed bool
mu sync.Mutex
onIMEText func(target IMETarget, text string)
imeEnabled bool
imeBridge *IMEBridge
targets []IMETarget
targetByPID atomic.Pointer[map[uint32]IMETarget]
rules atomic.Pointer[[]InputFilterRule]
mouseHook *mouseWheelHook
keymapRules []KeymapRule
keymapState atomic.Pointer[keymapSnapshot]
keymapHook *keymapHook
closed bool
}
// NewInputService constructs an inactive InputService. No OS hooks are installed
@@ -137,6 +142,11 @@ func (s *InputService) SetTargets(targets []IMETarget) {
if s.closed {
return
}
s.setTargetsLocked(targets)
s.reconcileKeymapLocked()
}
func (s *InputService) setTargetsLocked(targets []IMETarget) {
cp := append([]IMETarget(nil), targets...)
s.targets = cp
m := make(map[uint32]IMETarget, len(cp))
@@ -152,6 +162,85 @@ func (s *InputService) SetTargets(targets []IMETarget) {
s.reconcileMouseHookLocked()
}
type keymapSnapshot struct {
rules []KeymapRule
targets map[uint32]string
}
func (s *InputService) SetKeymapRules(rules []KeymapRule) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
s.setKeymapRulesLocked(rules)
s.reconcileKeymapLocked()
}
func (s *InputService) SetTargetsAndKeymapRules(targets []IMETarget, rules []KeymapRule) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
s.setTargetsLocked(targets)
s.setKeymapRulesLocked(rules)
s.reconcileKeymapLocked()
}
func (s *InputService) setKeymapRulesLocked(rules []KeymapRule) {
s.keymapRules = make([]KeymapRule, len(rules))
for i, rule := range rules {
rule.Bindings = maps.Clone(rule.Bindings)
s.keymapRules[i] = rule
}
}
func (s *InputService) IsKeymapHookInstalled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.keymapHook != nil
}
func (s *InputService) IsKeymapActiveForVM(vmName string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.keymapHook == nil {
return false
}
for _, name := range s.keymapState.Load().targets {
if name == vmName {
return true
}
}
return false
}
func (s *InputService) reconcileKeymapLocked() {
active := make(map[string]bool)
for _, rule := range s.keymapRules {
active[rule.VMName] = rule.active()
}
next := &keymapSnapshot{rules: s.keymapRules, targets: make(map[uint32]string)}
for _, target := range s.targets {
if target.PID != 0 && active[target.VMName] {
next.targets[target.PID] = target.VMName
}
}
if !reflect.DeepEqual(next, s.keymapState.Load()) {
s.keymapState.Store(next)
if s.keymapHook != nil {
s.keymapHook.refresh()
}
}
if len(next.targets) == 0 && s.keymapHook != nil {
s.keymapHook.Close()
s.keymapHook = nil
} else if len(next.targets) != 0 && s.keymapHook == nil {
s.keymapHook = startKeymapHook(s)
}
}
// SetFilterRules replaces the active declarative input filters and installs or
// uninstalls the low-level mouse hook on demand (§5.4).
func (s *InputService) SetFilterRules(rules []InputFilterRule) {
@@ -206,6 +295,8 @@ func (s *InputService) Close() {
s.closed = true
ib := s.imeBridge
mh := s.mouseHook
kh := s.keymapHook
s.keymapHook = nil
s.imeBridge = nil
s.mouseHook = nil
s.mu.Unlock()
@@ -216,4 +307,7 @@ func (s *InputService) Close() {
if mh != nil {
mh.Close()
}
if kh != nil {
kh.Close()
}
}
+6 -7
View File
@@ -16,11 +16,11 @@ const (
wmMouseWheel = 0x020A
wmMouseHWheel = 0x020E
inputMouse = 0
mouseEventfWheel = 0x0800
mouseEventfHWheel = 0x01000
llmhfInjected = 0x00000001
gaRoot = 2
inputMouse = 0
mouseEventfWheel = 0x0800
mouseEventfHWheel = 0x01000
llmhfInjected = 0x00000001
gaRoot = 2
// reimsInjectedInputMagic tags re-emitted wheel events so the hook ignores
// its own inverted events and never loops (§5.4).
reimsInjectedInputMagic uintptr = 0x5245494D // "REIM"
@@ -52,13 +52,12 @@ type msLLHookStruct struct {
// winMouseInput mirrors Win32 INPUT for INPUT_MOUSE on amd64 (40 bytes total).
type winMouseInput struct {
inputType uint32
_pad uint32
_ [0]uintptr // Align the INPUT union on both 32-bit and 64-bit.
dx int32
dy int32
mouseData uint32
dwFlags uint32
time uint32
_pad2 uint32
dwExtraInfo uintptr
}
+249
View File
@@ -0,0 +1,249 @@
package host
import "maps"
const (
vkLWin = 0x5B
vkRWin = 0x5C
vkLCtrl = 0xA2
vkRCtrl = 0xA3
vkLAlt = 0xA4
vkRAlt = 0xA5
)
type KeymapRule struct {
VMName string
Bindings map[string]string
CarrierReady bool
}
type KeyEvent struct {
VK uint32
ScanCode uint32
Up bool
}
type EmittedKey struct {
VK uint16
Scan uint16
Extended bool
Up bool
}
var hostModifiers = map[uint32]string{
vkLWin: "lwin", vkRWin: "rwin", vkLCtrl: "lctrl", vkRCtrl: "rctrl",
vkLAlt: "lalt", vkRAlt: "ralt", 0x14: "capslock",
}
var keymapTargets = map[string]EmittedKey{
"lcmd": {VK: 0x84, Scan: 0x6C}, "rcmd": {VK: 0x85, Scan: 0x6D},
"lopt": {VK: 0x83, Scan: 0x6B}, "ropt": {VK: 0x87, Scan: 0x76},
"lctrl": {VK: vkLCtrl, Scan: 0x1D}, "rctrl": {VK: vkRCtrl, Scan: 0x1D, Extended: true},
"esc": {VK: 0x1B, Scan: 0x01}, "disabled": {},
}
func (r KeymapRule) target(vk uint32) (EmittedKey, bool) {
key, ok := keymapTargets[r.Bindings[hostModifiers[vk]]]
return key, ok && (r.CarrierReady || key.VK < 0x83 || key.VK > 0x87)
}
func (r KeymapRule) active() bool {
for vk := range hostModifiers {
if _, ok := r.target(vk); ok {
return true
}
}
return false
}
type KeymapEngine struct {
rules map[string]KeymapRule
physical map[uint32]bool
stalePhysical map[uint32]bool
activeMapped map[uint32]EmittedKey
heldVM string
altGrCtrlDown bool
altGrCtrlSuppressed bool
}
func NewKeymapEngine(rules []KeymapRule) *KeymapEngine {
e := &KeymapEngine{
physical: make(map[uint32]bool),
stalePhysical: make(map[uint32]bool),
activeMapped: make(map[uint32]EmittedKey),
}
e.SetRules(rules)
return e
}
func (e *KeymapEngine) SetRules(rules []KeymapRule) []EmittedKey {
previous := e.rules[e.heldVM]
e.rules = make(map[string]KeymapRule, len(rules))
for _, rule := range rules {
rule.Bindings = maps.Clone(rule.Bindings)
e.rules[rule.VMName] = rule
}
current := e.rules[e.heldVM]
if e.heldVM != "" && (previous.CarrierReady != current.CarrierReady || !maps.Equal(previous.Bindings, current.Bindings)) {
return e.ReleaseAll()
}
return nil
}
func (e *KeymapEngine) ProcessEvent(ev KeyEvent, vmName string, foregroundMatch bool) (bool, []EmittedKey) {
vk := ev.VK
if vk == vkLCtrl && ev.ScanCode&0x200 != 0 {
// Decide suppression once on the initial press so cross-focus auto-repeat
// never orphans Windows' synthetic AltGr Ctrl key-up.
if ev.Up {
suppress := e.altGrCtrlSuppressed
e.altGrCtrlDown = false
e.altGrCtrlSuppressed = false
return suppress, nil
}
if e.altGrCtrlDown {
return e.altGrCtrlSuppressed, nil
}
e.altGrCtrlDown = true
_, mapped := e.rules[vmName].target(vkRAlt)
e.altGrCtrlSuppressed = foregroundMatch && mapped
return e.altGrCtrlSuppressed, nil
}
if hostModifiers[vk] == "" {
return false, nil
}
wasDown := e.physical[vk]
delete(e.stalePhysical, vk)
if ev.Up {
delete(e.physical, vk)
if key, suppressed := e.activeMapped[vk]; suppressed {
delete(e.activeMapped, vk)
if key.VK != 0 && !e.targetHeld(key) {
key.Up = true
return true, []EmittedKey{key}
}
return true, nil
}
return false, nil
}
e.physical[vk] = true
if _, suppressed := e.activeMapped[vk]; suppressed {
return true, nil
}
if wasDown || !foregroundMatch {
return false, nil
}
if (vk == vkLWin || vk == vkRWin) &&
(e.physical[vkLCtrl] || e.physical[vkRCtrl]) &&
(e.physical[vkLAlt] || e.physical[vkRAlt]) {
return false, e.restoreCaptureModifiers(vmName)
}
key, ok := e.rules[vmName].target(vk)
if !ok {
return false, nil
}
alreadyHeld := e.targetHeld(key)
e.activeMapped[vk] = key
e.heldVM = vmName
if key.VK == 0 || alreadyHeld {
return true, nil
}
return true, []EmittedKey{key}
}
func (e *KeymapEngine) restoreCaptureModifiers(vmName string) []EmittedKey {
var emit []EmittedKey
for _, original := range [...]EmittedKey{
{VK: vkLCtrl, Scan: 0x1D}, {VK: vkRCtrl, Scan: 0x1D, Extended: true},
{VK: vkLAlt, Scan: 0x38}, {VK: vkRAlt, Scan: 0x38, Extended: true},
} {
vk := uint32(original.VK)
mapped, suppressed := e.activeMapped[vk]
if !suppressed || mapped == original {
continue
}
e.activeMapped[vk] = original
e.heldVM = vmName
_, targetMapped := e.activeMapped[uint32(mapped.VK)]
if mapped.VK != 0 && !e.targetHeld(mapped) && (targetMapped || !e.physical[uint32(mapped.VK)]) {
mapped.Up = true
emit = append(emit, mapped)
}
emit = append(emit, original)
}
return emit
}
// ReconcilePhysical clears unsuppressed physical modifiers whose KEYUP was
// missed (e.g., after Ctrl+Alt+Del or UAC), using a two-tick grace so a key
// pressed right before Windows updates GetAsyncKeyState is never cleared early.
// Keys in activeMapped were swallowed by WH_KEYBOARD_LL and never set
// GetAsyncKeyState, so they are intentionally skipped here and cleared via
// Reset() on secure-desktop transitions.
func (e *KeymapEngine) ReconcilePhysical(isDown func(vk uint32) bool) []EmittedKey {
for vk := range e.physical {
if _, suppressed := e.activeMapped[vk]; suppressed {
delete(e.stalePhysical, vk)
continue
}
if isDown(vk) {
delete(e.stalePhysical, vk)
continue
}
if !e.stalePhysical[vk] {
e.stalePhysical[vk] = true
continue
}
delete(e.physical, vk)
delete(e.stalePhysical, vk)
}
return nil
}
// Reset releases every active mapped target key and clears all tracked physical
// and suppressed key state (used when switching to a Windows Secure Desktop
// where user-mode WH_KEYBOARD_LL cannot observe key-up events).
func (e *KeymapEngine) Reset() []EmittedKey {
emit := e.ReleaseAll()
clear(e.physical)
clear(e.stalePhysical)
clear(e.activeMapped)
e.heldVM = ""
e.altGrCtrlDown = false
e.altGrCtrlSuppressed = false
return emit
}
func (e *KeymapEngine) HasTrackedKeys() bool {
return len(e.physical) != 0 || len(e.activeMapped) != 0 || e.altGrCtrlDown || e.altGrCtrlSuppressed
}
func (e *KeymapEngine) targetHeld(key EmittedKey) bool {
for _, mapped := range e.activeMapped {
if mapped == key {
return true
}
}
return false
}
func (e *KeymapEngine) ReleaseAll() []EmittedKey {
var emit []EmittedKey
for vk, key := range e.activeMapped {
// Keep swallowing the physical key until its matching key-up.
e.activeMapped[vk] = EmittedKey{}
if key.VK != 0 && !e.targetHeld(key) {
key.Up = true
emit = append(emit, key)
}
}
e.heldVM = ""
return emit
}
func (e *KeymapEngine) ReleaseIfFocusLost(currentVM string) []EmittedKey {
if e.heldVM != "" && currentVM != e.heldVM {
return e.ReleaseAll()
}
return nil
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package host
type keymapHook struct{}
func startKeymapHook(*InputService) *keymapHook { return nil }
func (*keymapHook) refresh() {}
func (*keymapHook) Close() {}
+192
View File
@@ -0,0 +1,192 @@
package host
import (
"slices"
"testing"
)
func TestKeymapEngine(t *testing.T) {
rule := KeymapRule{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd", "rwin": "rctrl", "lalt": "disabled"}}
e := NewKeymapEngine([]KeymapRule{rule})
event := func(vk uint32, up bool, vm string, suppress bool, expected ...EmittedKey) {
t.Helper()
got, emit := e.ProcessEvent(KeyEvent{VK: vk, Up: up}, vm, vm != "")
if got != suppress || !slices.Equal(emit, expected) {
t.Fatalf("event %#x up=%v vm=%q = %v %v, want %v %v", vk, up, vm, got, emit, suppress, expected)
}
}
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
rightCtrl := EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true}
event(vkRWin, false, "mac", true, rightCtrl)
event(vkRWin, false, "mac", true)
rightCtrl.Up = true
event(vkRWin, true, "", true, rightCtrl)
event(vkLAlt, false, "mac", true)
event(vkLCtrl, false, "mac", false)
event(vkLWin, false, "mac", false, EmittedKey{VK: vkLAlt, Scan: 0x38})
event(vkLAlt, true, "mac", true, EmittedKey{VK: vkLAlt, Scan: 0x38, Up: true})
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
event(vkLCtrl, true, "mac", false)
rule.CarrierReady = true
e.SetRules([]KeymapRule{rule})
event(vkLWin, false, "other", false)
event(vkLWin, false, "mac", false)
event(vkLWin, true, "mac", false)
cmd := EmittedKey{VK: 0x84, Scan: 0x6C}
event(vkLWin, false, "mac", true, cmd)
cmd.Up = true
if got := e.ReleaseIfFocusLost("other"); !slices.Equal(got, []EmittedKey{cmd}) {
t.Fatalf("focus loss = %v", got)
}
event(vkLWin, true, "", true)
event(vkRWin, false, "mac", true, EmittedKey{VK: vkRCtrl, Scan: 0x1D, Extended: true})
if got := e.SetRules(nil); !slices.Equal(got, []EmittedKey{rightCtrl}) {
t.Fatalf("rule replacement = %v", got)
}
event(vkRWin, true, "mac", true)
}
func TestKeymapHookStaysOffWithoutReadyTarget(t *testing.T) {
svc := NewInputService(nil)
defer svc.Close()
svc.SetKeymapRules([]KeymapRule{{VMName: "mac", Bindings: map[string]string{"lwin": "lcmd"}}})
svc.SetTargets([]IMETarget{{VMName: "mac", PID: 42}})
if svc.IsKeymapHookInstalled() || svc.IsKeymapActiveForVM("mac") {
t.Fatal("hook should stay inactive while the carrier is unavailable")
}
svc.SetKeymapRules([]KeymapRule{{VMName: "other", Bindings: map[string]string{"lwin": "esc"}}})
if svc.IsKeymapHookInstalled() {
t.Fatal("hook should stay inactive for a nonmatching VM")
}
}
func TestKeymapReconcilesLostKeyUps(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}})
for _, vk := range []uint32{vkLCtrl, vkLAlt} {
e.ProcessEvent(KeyEvent{VK: vk}, "vm", true)
}
isDown := func(uint32) bool { return false }
// First tick arms the two-tick grace so a freshly pressed key is never cleared early.
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || !e.physical[vkLCtrl] || !e.physical[vkLAlt] {
t.Fatalf("first reconcile tick should retain grace state: keys=%v physical=%v", keys, e.physical)
}
// Second tick clears lost unsuppressed modifiers.
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 || e.physical[vkLCtrl] || e.physical[vkLAlt] {
t.Fatalf("second reconcile tick should clear lost unmapped keys: keys=%v physical=%v", keys, e.physical)
}
// A suppressed mapped key never sets GetAsyncKeyState on Windows, so repeated
// ReconcilePhysical ticks with isDown==false must NEVER release it early.
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] {
t.Fatalf("Win down after reconciliation: %v %v", suppress, keys)
}
for i := 0; i < 5; i++ {
if keys := e.ReconcilePhysical(isDown); len(keys) != 0 {
t.Fatalf("reconcile tick %d prematurely released suppressed key: %v", i, keys)
}
}
if !e.physical[vkLWin] || e.activeMapped[vkLWin] != keymapTargets["lcmd"] {
t.Fatalf("suppressed Win key state lost during reconcile: physical=%v mapped=%v", e.physical, e.activeMapped)
}
// Secure Desktop transition clears both physical and suppressed state via Reset().
if keys := e.Reset(); len(keys) != 1 || keys[0].VK != keymapTargets["lcmd"].VK || !keys[0].Up {
t.Fatalf("Reset after secure desktop: %v", keys)
}
if e.HasTrackedKeys() {
t.Fatalf("Reset left tracked keys: physical=%v mapped=%v", e.physical, e.activeMapped)
}
// After returning from Secure Desktop, Win works normally again.
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets["lcmd"] {
t.Fatalf("Win down after Reset: %v %v", suppress, keys)
}
}
func TestKeymapAltGrCrossFocusAutoRepeat(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"ralt": "rcmd"}}})
fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D}
// Pressed outside the VM -> must not suppress.
if suppress, keys := e.ProcessEvent(fake, "", false); suppress || len(keys) != 0 || !e.HasTrackedKeys() {
t.Fatalf("AltGr down outside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys())
}
// Auto-repeat after focus enters the VM -> must keep initial non-suppressed decision.
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 {
t.Fatalf("AltGr repeat inside VM: suppress=%v keys=%v", suppress, keys)
}
// Release inside VM -> must pass through so Windows receives fake LCtrl UP.
fake.Up = true
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress || len(keys) != 0 || e.HasTrackedKeys() {
t.Fatalf("AltGr up inside VM: suppress=%v keys=%v tracked=%v", suppress, keys, e.HasTrackedKeys())
}
}
func TestKeymapAltGr(t *testing.T) {
for _, mapped := range []bool{false, true} {
bindings := map[string]string{"lctrl": "esc", "lwin": "lcmd"}
if mapped {
bindings["ralt"] = "rcmd"
bindings["lwin"] = "lopt"
}
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: bindings, CarrierReady: true}})
fake := KeyEvent{VK: vkLCtrl, ScanCode: 0x21D}
if suppress, keys := e.ProcessEvent(fake, "vm", true); suppress != mapped || len(keys) != 0 || e.physical[vkLCtrl] {
t.Fatalf("AltGr fake Ctrl down: %v %v", suppress, keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkRAlt}, "vm", true); suppress != mapped || (mapped && (len(keys) != 1 || keys[0] != keymapTargets["rcmd"])) {
t.Fatalf("AltGr right Alt: %v %v", suppress, keys)
}
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 || keys[0] != keymapTargets[bindings["lwin"]] {
t.Fatalf("Win with AltGr: %v %v", suppress, keys)
}
e.ReleaseIfFocusLost("")
fake.Up = true
if suppress, keys := e.ProcessEvent(fake, "", false); suppress != mapped || len(keys) != 0 || e.altGrCtrlSuppressed {
t.Fatalf("AltGr fake Ctrl up after focus loss: %v %v", suppress, keys)
}
}
}
func TestKeymapUnrelatedRuleChangeKeepsHeldKey(t *testing.T) {
rule := KeymapRule{VMName: "a", Bindings: map[string]string{"lwin": "lcmd"}, CarrierReady: true}
e := NewKeymapEngine([]KeymapRule{rule})
e.ProcessEvent(KeyEvent{VK: vkLWin}, "a", true)
if keys := e.SetRules([]KeymapRule{rule, {VMName: "b", Bindings: map[string]string{"lwin": "esc"}}}); len(keys) != 0 {
t.Fatalf("unrelated update released key: %v", keys)
}
if keys := e.SetRules(nil); len(keys) != 1 || !keys[0].Up {
t.Fatalf("removing held rule should release key: %v", keys)
}
}
func TestKeymapCapturePreservesPhysicalCtrl(t *testing.T) {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", Bindings: map[string]string{"lalt": "lctrl"}}})
e.ProcessEvent(KeyEvent{VK: vkLCtrl}, "vm", true)
e.ProcessEvent(KeyEvent{VK: vkLAlt}, "vm", true)
suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true)
if suppress || len(keys) != 1 || keys[0] != (EmittedKey{VK: vkLAlt, Scan: 0x38}) {
t.Fatalf("capture release with physical Ctrl: %v %v", suppress, keys)
}
}
func TestKeymapWinLPassesOrdinaryKey(t *testing.T) {
for _, modifier := range []uint32{0, 0xA0, vkLAlt, vkLCtrl} {
e := NewKeymapEngine([]KeymapRule{{VMName: "vm", CarrierReady: true, Bindings: map[string]string{"lwin": "lcmd"}}})
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vkLWin}, "vm", true); !suppress || len(keys) != 1 {
t.Fatalf("Win in VM: %v %v", suppress, keys)
}
if modifier != 0 {
e.ProcessEvent(KeyEvent{VK: modifier}, "vm", true)
}
for _, up := range []bool{false, true} {
if suppress, keys := e.ProcessEvent(KeyEvent{VK: 'L', Up: up}, "vm", true); suppress || len(keys) != 0 {
t.Fatalf("L with modifier %#x: %v %v", modifier, suppress, keys)
}
}
}
e := NewKeymapEngine(nil)
for _, vk := range []uint32{vkLWin, 'L'} {
if suppress, keys := e.ProcessEvent(KeyEvent{VK: vk}, "", false); suppress || len(keys) != 0 {
t.Fatalf("Win+L outside VM: %v %v", suppress, keys)
}
}
}
+225
View File
@@ -0,0 +1,225 @@
//go:build windows
package host
import (
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
const (
llkhfInjected = 0x10
wmKeymapRefresh = 0x8001
wmTimer = 0x0113
desktopReadObjects = 0x0001
)
var (
procKeymapSetTimer = user32.NewProc("SetTimer")
procKeymapKillTimer = user32.NewProc("KillTimer")
procKeymapAsyncKeyState = user32.NewProc("GetAsyncKeyState")
procOpenInputDesktop = user32.NewProc("OpenInputDesktop")
procCloseDesktop = user32.NewProc("CloseDesktop")
keymapCallback = sync.OnceValue(func() uintptr { return syscall.NewCallback(keymapKeyboardProc) })
activeKeymapHook atomic.Pointer[keymapHook]
)
type winKeyboardInput struct {
inputType uint32
keyboard struct {
vk uint16
scan uint16
flags uint32
time uint32
extra uintptr
padding [2]uint32
}
}
var _ [unsafe.Sizeof(winMouseInput{}) - unsafe.Sizeof(winKeyboardInput{})]byte
var _ [unsafe.Sizeof(winKeyboardInput{}) - unsafe.Sizeof(winMouseInput{})]byte
type keymapHook struct {
service *InputService
threadID uintptr
done chan struct{}
engine *KeymapEngine
snapshot *keymapSnapshot
timer uintptr
inputDesktopAvailable bool
closeOnce sync.Once
}
func startKeymapHook(service *InputService) *keymapHook {
h := &keymapHook{service: service, done: make(chan struct{})}
if !activeKeymapHook.CompareAndSwap(nil, h) {
return nil
}
ready := make(chan bool)
go h.run(ready)
if !<-ready {
<-h.done
return nil
}
return h
}
func (h *keymapHook) run(ready chan<- bool) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(h.done)
defer activeKeymapHook.CompareAndSwap(h, nil)
h.threadID, _, _ = procGetCurrentThreadId.Call()
var msg winMsg
procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove)
h.snapshot = h.service.keymapState.Load()
h.engine = NewKeymapEngine(h.snapshot.rules)
h.inputDesktopAvailable = keymapInputDesktopAccessible()
for vk := range hostModifiers {
if keymapPhysicalDown(vk) {
h.engine.physical[vk] = true
}
}
module, _, _ := procGetModuleHandleW.Call(0)
hook, _, _ := procSetWindowsHookExW.Call(whKeyboardLL, keymapCallback(), module, 0)
if hook == 0 {
ready <- false
return
}
defer procUnhookWindowsHookEx.Call(hook)
defer func() { sendMappedKeys(h.engine.ReleaseAll()) }()
h.syncTimer()
defer func() {
if h.timer != 0 {
procKeymapKillTimer.Call(0, h.timer)
}
}()
ready <- true
for {
result, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(result) <= 0 {
return
}
if msg.message == wmKeymapRefresh || msg.message == wmTimer {
h.syncSnapshot()
if h.inputDesktopAvailable && !keymapInputDesktopAccessible() {
sendMappedKeys(h.engine.Reset())
} else {
sendMappedKeys(h.engine.ReconcilePhysical(keymapPhysicalDown))
if h.engine.heldVM != "" {
sendMappedKeys(h.engine.ReleaseIfFocusLost(h.foregroundVM()))
}
}
h.syncTimer()
}
}
}
func (h *keymapHook) syncSnapshot() {
if next := h.service.keymapState.Load(); next != h.snapshot {
h.snapshot = next
sendMappedKeys(h.engine.SetRules(next.rules))
}
}
func (h *keymapHook) foregroundVM() string {
window, _, _ := procGetForegroundWindow.Call()
if window == 0 {
return ""
}
var pid uint32
procGetWindowThreadProcessId.Call(window, uintptr(unsafe.Pointer(&pid)))
return h.snapshot.targets[pid]
}
func keymapKeyboardProc(code int32, message uintptr, kbd *kbdLLHookStruct) uintptr {
if code == hcAction && kbd != nil &&
!(kbd.flags&llkhfInjected != 0 && kbd.dwExtraInfo == reimsInjectedInputMagic) {
switch message {
case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp:
if h := activeKeymapHook.Load(); h != nil {
h.syncSnapshot()
modifier := hostModifiers[kbd.vkCode] != ""
vm := ""
if modifier || h.engine.heldVM != "" {
vm = h.foregroundVM()
sendMappedKeys(h.engine.ReleaseIfFocusLost(vm))
}
if !modifier {
break
}
suppress, emit := h.engine.ProcessEvent(KeyEvent{
VK: kbd.vkCode, ScanCode: kbd.scanCode, Up: message == wmKeyUp || message == wmSysKeyUp,
}, vm, vm != "")
sendMappedKeys(emit)
h.syncTimer()
if suppress {
return 1
}
}
}
}
result, _, _ := procCallNextHookEx.Call(0, uintptr(code), message, uintptr(unsafe.Pointer(kbd)))
return result
}
func keymapPhysicalDown(vk uint32) bool {
state, _, _ := procKeymapAsyncKeyState.Call(uintptr(vk))
return state&0x8000 != 0
}
func keymapInputDesktopAccessible() bool {
desk, _, _ := procOpenInputDesktop.Call(0, 0, desktopReadObjects)
if desk == 0 {
return false
}
procCloseDesktop.Call(desk)
return true
}
func (h *keymapHook) syncTimer() {
if h.engine.HasTrackedKeys() {
if h.timer == 0 {
h.timer, _, _ = procKeymapSetTimer.Call(0, 0, 50, 0)
}
} else if h.timer != 0 {
procKeymapKillTimer.Call(0, h.timer)
h.timer = 0
}
}
func sendMappedKeys(keys []EmittedKey) {
if len(keys) == 0 {
return
}
inputs := make([]winKeyboardInput, len(keys))
for i, key := range keys {
input := &inputs[i]
input.inputType = 1 // INPUT_KEYBOARD
input.keyboard.vk = key.VK
input.keyboard.scan = key.Scan
input.keyboard.extra = reimsInjectedInputMagic
if key.Extended {
input.keyboard.flags |= 1 // KEYEVENTF_EXTENDEDKEY
}
if key.Up {
input.keyboard.flags |= 2 // KEYEVENTF_KEYUP
}
}
procSendInput.Call(uintptr(len(inputs)), uintptr(unsafe.Pointer(&inputs[0])), unsafe.Sizeof(inputs[0]))
}
func (h *keymapHook) refresh() {
procPostThreadMessageW.Call(h.threadID, wmKeymapRefresh, 0, 0)
}
func (h *keymapHook) Close() {
h.closeOnce.Do(func() {
procPostThreadMessageW.Call(h.threadID, wmQuit, 0, 0)
<-h.done
})
}
+159
View File
@@ -0,0 +1,159 @@
package vmstart
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
type KeymapPreset string
type HostModifier string
type GuestModifier string
const (
KeymapOff KeymapPreset = "off"
KeymapWinToCmd KeymapPreset = "win_to_cmd"
KeymapSwapAltWin KeymapPreset = "swap_alt_win"
KeymapCustom KeymapPreset = "custom"
keymapConfigFile = ".reims-go-keymap.json"
)
type VMKeymapConfig struct {
Preset KeymapPreset `json:"preset"`
Bindings map[HostModifier]GuestModifier `json:"bindings,omitempty"`
}
func DefaultVMKeymapConfig() VMKeymapConfig { return VMKeymapConfig{Preset: KeymapOff} }
func NormalizeKeymapPreset(p KeymapPreset) KeymapPreset {
switch p = KeymapPreset(normalizeKeymapValue(string(p))); p {
case KeymapWinToCmd, KeymapSwapAltWin, KeymapCustom:
return p
default:
return KeymapOff
}
}
func normalizeKeymapValue(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
func PresetBindings(p KeymapPreset) map[HostModifier]GuestModifier {
switch NormalizeKeymapPreset(p) {
case KeymapWinToCmd:
return map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd"}
case KeymapSwapAltWin:
return map[HostModifier]GuestModifier{"lalt": "lcmd", "ralt": "rcmd", "lwin": "lopt", "rwin": "ropt"}
default:
return map[HostModifier]GuestModifier{}
}
}
func validHostModifier(k HostModifier) bool {
switch k {
case "lwin", "rwin", "lalt", "ralt", "lctrl", "rctrl", "capslock":
return true
}
return false
}
func validGuestModifier(k GuestModifier) bool {
switch k {
case "", "default", "lcmd", "rcmd", "lopt", "ropt", "lctrl", "rctrl", "esc", "disabled":
return true
}
return false
}
func ResolveKeymapBindings(cfg VMKeymapConfig) map[HostModifier]GuestModifier {
bindings := PresetBindings(cfg.Preset)
if NormalizeKeymapPreset(cfg.Preset) != KeymapCustom {
return bindings
}
for rawHost, rawGuest := range cfg.Bindings {
k := HostModifier(normalizeKeymapValue(string(rawHost)))
v := GuestModifier(normalizeKeymapValue(string(rawGuest)))
if validHostModifier(k) && validGuestModifier(v) && v != "" && v != "default" && string(k) != string(v) {
bindings[k] = v
}
}
return bindings
}
func NeedsGuestCarrier(bindings map[HostModifier]GuestModifier) bool {
for _, v := range bindings {
switch v {
case "lcmd", "rcmd", "lopt", "ropt":
return true
}
}
return false
}
func ReadVMKeymap(vmDir string) VMKeymapConfig {
if strings.TrimSpace(vmDir) == "" {
return DefaultVMKeymapConfig()
}
data, err := os.ReadFile(filepath.Join(vmDir, keymapConfigFile))
var cfg VMKeymapConfig
if err != nil || json.Unmarshal(data, &cfg) != nil {
return DefaultVMKeymapConfig()
}
cfg.Preset = NormalizeKeymapPreset(cfg.Preset)
if cfg.Preset == KeymapCustom {
cfg.Bindings = ResolveKeymapBindings(cfg)
} else {
cfg.Bindings = nil
}
return cfg
}
func SaveVMKeymap(vmDir string, cfg VMKeymapConfig) (VMKeymapConfig, error) {
if strings.TrimSpace(vmDir) == "" {
return VMKeymapConfig{}, errors.New("VM directory is empty")
}
cfg.Preset = KeymapPreset(normalizeKeymapValue(string(cfg.Preset)))
if cfg.Preset != KeymapOff && NormalizeKeymapPreset(cfg.Preset) == KeymapOff {
return VMKeymapConfig{}, fmt.Errorf("invalid keymap preset %q", cfg.Preset)
}
seen := make(map[HostModifier]bool, len(cfg.Bindings))
for rawHost, rawGuest := range cfg.Bindings {
k := HostModifier(normalizeKeymapValue(string(rawHost)))
v := GuestModifier(normalizeKeymapValue(string(rawGuest)))
if !validHostModifier(k) || !validGuestModifier(v) || seen[k] {
return VMKeymapConfig{}, fmt.Errorf("invalid keymap binding %q → %q", rawHost, rawGuest)
}
seen[k] = true
}
dst := filepath.Join(vmDir, keymapConfigFile)
if cfg.Preset == KeymapOff {
err := os.Remove(dst)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return VMKeymapConfig{}, err
}
return DefaultVMKeymapConfig(), nil
}
if cfg.Preset == KeymapCustom {
cfg.Bindings = ResolveKeymapBindings(cfg)
} else {
cfg.Bindings = nil
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return VMKeymapConfig{}, err
}
tmp, err := os.CreateTemp(vmDir, keymapConfigFile+".*")
if err != nil {
return VMKeymapConfig{}, err
}
defer os.Remove(tmp.Name())
_, writeErr := tmp.Write(data)
if err := errors.Join(writeErr, tmp.Close()); err != nil {
return VMKeymapConfig{}, err
}
if err := os.Rename(tmp.Name(), dst); err != nil {
return VMKeymapConfig{}, err
}
return cfg, nil
}
+60
View File
@@ -0,0 +1,60 @@
package vmstart
import (
"maps"
"os"
"path/filepath"
"testing"
)
func TestVMKeymapPersistence(t *testing.T) {
dir := t.TempDir()
if got := ReadVMKeymap(dir); got.Preset != KeymapOff {
t.Fatalf("default = %+v", got)
}
cfg := VMKeymapConfig{Preset: " CUSTOM ", Bindings: map[HostModifier]GuestModifier{
" LWIN ": " LCMD ", "capslock": "esc", "lctrl": "lctrl", "rwin": "default",
}}
want := map[HostModifier]GuestModifier{"lwin": "lcmd", "capslock": "esc"}
for i := 0; i < 2; i++ {
got, err := SaveVMKeymap(dir, cfg)
if err != nil || got.Preset != KeymapCustom || !maps.Equal(got.Bindings, want) {
t.Fatalf("save = %+v, %v", got, err)
}
}
for _, bad := range []VMKeymapConfig{
{Preset: "bad"},
{Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"win": "esc"}},
{Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"lwin": "bad"}},
{Preset: KeymapCustom, Bindings: map[HostModifier]GuestModifier{"lwin": "lcmd", " LWIN": "esc"}},
} {
if _, err := SaveVMKeymap(dir, bad); err == nil {
t.Fatalf("accepted %+v", bad)
}
}
if got := ReadVMKeymap(dir); got.Preset != KeymapCustom || !maps.Equal(got.Bindings, want) {
t.Fatalf("read after invalid updates = %+v", got)
}
if _, err := SaveVMKeymap(dir, DefaultVMKeymapConfig()); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, keymapConfigFile)); !os.IsNotExist(err) {
t.Fatalf("disabled config was not removed: %v", err)
}
}
func TestKeymapPresets(t *testing.T) {
for _, tc := range []struct {
preset KeymapPreset
want map[HostModifier]GuestModifier
}{
{KeymapOff, nil},
{KeymapWinToCmd, map[HostModifier]GuestModifier{"lwin": "lcmd", "rwin": "rcmd"}},
{KeymapSwapAltWin, map[HostModifier]GuestModifier{"lwin": "lopt", "rwin": "ropt", "lalt": "lcmd", "ralt": "rcmd"}},
} {
bindings := ResolveKeymapBindings(VMKeymapConfig{Preset: tc.preset})
if !maps.Equal(bindings, tc.want) || NeedsGuestCarrier(bindings) != (len(tc.want) > 0) {
t.Fatalf("%s = %v", tc.preset, bindings)
}
}
}
+30
View File
@@ -1,4 +1,34 @@
{
"keymapGroupTitle": "Modifier keys",
"keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.",
"keymapPresetTitle": "Preset",
"keymapRunning": "Active while this VM is focused",
"keymapStopped": "Applies when this VM is running",
"keymapWaiting": "Waiting for Guest Tools to connect",
"keymapUpgrade": "Update Guest Tools to version {version}",
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
"keymapInactive": "Modifier mapping is inactive",
"keymapPresetOff": "Off",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetCustom": "Custom",
"keymapHostLwin": "Left Win",
"keymapHostRwin": "Right Win",
"keymapHostLalt": "Left Alt",
"keymapHostRalt": "Right Alt",
"keymapHostLctrl": "Left Ctrl",
"keymapHostRctrl": "Right Ctrl",
"keymapHostCapslock": "Caps Lock",
"keymapGuestDefault": "Default",
"keymapGuestLcmd": "Left ⌘ Command",
"keymapGuestRcmd": "Right ⌘ Command",
"keymapGuestLopt": "Left ⌥ Option",
"keymapGuestRopt": "Right ⌥ Option",
"keymapGuestLctrl": "Left ⌃ Control",
"keymapGuestRctrl": "Right ⌃ Control",
"keymapGuestEsc": "Esc",
"keymapGuestDisabled": "Disabled",
"installersTitle": "Installers",
"installersDownloaded": "Downloaded",
"installersAvailable": "Releases from Apple",
+30
View File
@@ -1,4 +1,34 @@
{
"keymapGroupTitle": "修饰键映射",
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。",
"keymapPresetTitle": "映射预设",
"keymapRunning": "虚拟机获得焦点时生效",
"keymapStopped": "虚拟机启动后生效",
"keymapWaiting": "等待 Guest Tools 连接",
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
"keymapPending": "等待 Guest Tools 启用修饰键映射",
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
"keymapInactive": "修饰键映射未启用",
"keymapPresetOff": "关闭",
"keymapPresetWinToCmd": "Win → ⌘",
"keymapPresetSwapAltWin": "Alt ↔ Win",
"keymapPresetCustom": "自定义",
"keymapHostLwin": "左 Win",
"keymapHostRwin": "右 Win",
"keymapHostLalt": "左 Alt",
"keymapHostRalt": "右 Alt",
"keymapHostLctrl": "左 Ctrl",
"keymapHostRctrl": "右 Ctrl",
"keymapHostCapslock": "Caps Lock",
"keymapGuestDefault": "默认",
"keymapGuestLcmd": "左 ⌘ Command",
"keymapGuestRcmd": "右 ⌘ Command",
"keymapGuestLopt": "左 ⌥ Option",
"keymapGuestRopt": "右 ⌥ Option",
"keymapGuestLctrl": "左 ⌃ Control",
"keymapGuestRctrl": "右 ⌃ Control",
"keymapGuestEsc": "Esc",
"keymapGuestDisabled": "禁用",
"installersTitle": "安装包",
"installersDownloaded": "已下载",
"installersAvailable": "Apple 提供的版本",