Merge pull request #118 from yxc0915/codex/macos-app-window
feat: 新增 macOS 应用窗口内置插件
This commit is contained in:
44 files changed
+3459
-92
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "启用「macOS 应用窗口」内置插件后,可在 Windows 无边框窗口中操作虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
|
||||
"en": "Enable the built-in macOS App Windows plugin to use a VM’s foreground app in a borderless Windows window with bidirectional copy and paste."
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
| 正在创建 | 无(展示分步进度) | 取消创建 |
|
||||
| 已停止 | 启动 | 设置、恢复点、派生副本、磁盘扩容与空间回收、打开目录、删除 |
|
||||
| 正在启动 | 启动中(忙碌禁用) | 设置、强制关机 |
|
||||
| 运行中 | 显示虚拟机窗口 | 挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
|
||||
| 运行中 | 显示虚拟机窗口 | 打开独立应用窗口(需启用 macOS 应用窗口插件并连接 Guest Tools)、挂起(需运行时支持)、关机、截屏、设置、重启、强制关机、发送文本、恢复模式切换、导出排障包 |
|
||||
| 正在停止 | 停止中(忙碌禁用) | 强制关机 |
|
||||
| 正在挂起 | 挂起中(忙碌禁用) | 强制关机 |
|
||||
| 已挂起 | 恢复(需运行时支持) | 放弃挂起状态(需破坏性操作确认)、打开目录 |
|
||||
|
||||
@@ -32,6 +32,8 @@ flowchart TB
|
||||
|
||||
内置虚拟机交互服务默认启用,通过宿主控制台代理串行处理每台虚拟机的 QMP 操作,每次操作后关闭连接,并与虚拟机生命周期操作共用锁。桌面文本输入期间暂停后台缩略图捕获。该服务不实现 MCP 协议。
|
||||
|
||||
内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。
|
||||
|
||||
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
|
||||
|
||||
+31
-26
@@ -11,7 +11,7 @@ import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
|
||||
import { DataRootReadOnly } from './components/DataRootReadOnly'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { VMAction, VMBusyAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
import { LogLine, appendLog } from './lib/logs'
|
||||
@@ -44,7 +44,7 @@ const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ def
|
||||
|
||||
const errText = (e: unknown) => parseAppError(e).summary
|
||||
|
||||
const failKey: Record<VMAction, I18nKey> = {
|
||||
const failKey: Record<VMBusyAction, I18nKey> = {
|
||||
start: 'failStart',
|
||||
suspend: 'failSuspend',
|
||||
resume: 'failResume',
|
||||
@@ -52,6 +52,7 @@ const failKey: Record<VMAction, I18nKey> = {
|
||||
focus: 'failFocus',
|
||||
fullscreen: 'failFullscreen',
|
||||
screenshot: 'failScreenshot',
|
||||
pluginCommand: 'failGeneric',
|
||||
stop: 'failStop',
|
||||
forceStop: 'failStop',
|
||||
restart: 'failRestart',
|
||||
@@ -97,8 +98,8 @@ export const App: React.FC = () => {
|
||||
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
|
||||
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState<Record<string, VMAction>>({})
|
||||
const busyOpsRef = useRef<Map<string, Map<number, VMAction>>>(new Map())
|
||||
const [busy, setBusy] = useState<Record<string, VMBusyAction>>({})
|
||||
const busyOpsRef = useRef<Map<string, Map<number, VMBusyAction>>>(new Map())
|
||||
const nextBusyTokenRef = useRef(0)
|
||||
const [dropping, setDropping] = useState(false)
|
||||
const [loadError, setLoadError] = useState('')
|
||||
@@ -217,17 +218,7 @@ export const App: React.FC = () => {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
api.GetPluginUIContributions().catch(() => null),
|
||||
refresh(),
|
||||
]).then(([pui]) => {
|
||||
if (pui) {
|
||||
setPluginLocales(pui.locales)
|
||||
setPluginUI(pui)
|
||||
} else {
|
||||
setPluginUI({} as PluginUIContributions)
|
||||
}
|
||||
})
|
||||
void refresh()
|
||||
events.emitUIPong()
|
||||
const offPing = events.onUIPing(() => { events.emitUIPong() })
|
||||
const offState = events.onStateChanged(() => {
|
||||
@@ -244,7 +235,6 @@ export const App: React.FC = () => {
|
||||
}
|
||||
setLogLines((prev) => appendLog(prev, entry))
|
||||
})
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
||||
// Tasks: seed from the backend, then follow events.
|
||||
api.GetTasks().then((list) => {
|
||||
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
|
||||
@@ -556,10 +546,19 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}, [taskMap])
|
||||
|
||||
// Apply active theme pack (zero extra CSS for builtin default theme).
|
||||
// Refresh contributions together with the active theme after registry changes.
|
||||
useEffect(() => {
|
||||
api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
||||
api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e))
|
||||
let live = true
|
||||
api.GetActiveTheme().then((theme) => {
|
||||
if (live) setActiveThemePayload(theme)
|
||||
}).catch((e) => console.warn('[app] GetActiveTheme failed:', e))
|
||||
api.GetPluginUIContributions().then((contributions) => {
|
||||
if (live) setPluginUI(contributions)
|
||||
}).catch((e) => {
|
||||
console.warn('[app] GetPluginUIContributions failed:', e)
|
||||
if (live) setPluginUI((previous) => previous ?? {} as PluginUIContributions)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [themeRevision, state?.safe_mode])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -620,25 +619,25 @@ export const App: React.FC = () => {
|
||||
if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '')
|
||||
}
|
||||
|
||||
const activeVMBusy = (name: string): VMAction | undefined => {
|
||||
const activeVMBusy = (name: string): VMBusyAction | undefined => {
|
||||
const ops = busyOpsRef.current.get(name)
|
||||
if (!ops || ops.size === 0) return undefined
|
||||
let latest: VMAction | undefined
|
||||
let latest: VMBusyAction | undefined
|
||||
for (const act of ops.values()) latest = act
|
||||
return latest
|
||||
}
|
||||
|
||||
const syncBusyState = () => {
|
||||
const next: Record<string, VMAction> = Object.create(null)
|
||||
const next: Record<string, VMBusyAction> = Object.create(null)
|
||||
for (const [vmName, ops] of busyOpsRef.current) {
|
||||
let latest: VMAction | undefined
|
||||
let latest: VMBusyAction | undefined
|
||||
for (const act of ops.values()) latest = act
|
||||
if (latest) next[vmName] = latest
|
||||
}
|
||||
setBusy(next)
|
||||
}
|
||||
|
||||
const beginVMBusy = (name: string, action: VMAction): number | null => {
|
||||
const beginVMBusy = (name: string, action: VMBusyAction): number | null => {
|
||||
const ops = busyOpsRef.current.get(name)
|
||||
if (ops && ops.size > 0) {
|
||||
if (action !== 'forceStop') return null
|
||||
@@ -647,7 +646,7 @@ export const App: React.FC = () => {
|
||||
}
|
||||
}
|
||||
const token = ++nextBusyTokenRef.current
|
||||
const vmOps = ops ?? new Map<number, VMAction>()
|
||||
const vmOps = ops ?? new Map<number, VMBusyAction>()
|
||||
vmOps.set(token, action)
|
||||
busyOpsRef.current.set(name, vmOps)
|
||||
syncBusyState()
|
||||
@@ -661,7 +660,7 @@ export const App: React.FC = () => {
|
||||
syncBusyState()
|
||||
}
|
||||
|
||||
const runVMAction = async (name: string, action: VMAction, fn: () => Promise<void>, okTitle?: string) => {
|
||||
const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise<void>, okTitle?: string) => {
|
||||
const token = beginVMBusy(name, action)
|
||||
if (token === null) return
|
||||
try {
|
||||
@@ -1236,6 +1235,12 @@ export const App: React.FC = () => {
|
||||
pending={pending}
|
||||
busyAction={Object.prototype.hasOwnProperty.call(busy, selectedVM.name) ? busy[selectedVM.name] : undefined}
|
||||
onAction={onVMAction}
|
||||
onPluginCommand={(pluginID, command, title) => {
|
||||
const name = selectedVM.name
|
||||
void runVMAction(name, 'pluginCommand', async () => {
|
||||
await api.InvokePluginCommand(pluginID, command, { vm: name })
|
||||
}, title)
|
||||
}}
|
||||
onSettings={() => setShowSettings(true)}
|
||||
onOpenAffinity={() => setAffinityTarget({ name: selectedVM.name, driverID: selectedVM.driver_id ?? '' })}
|
||||
onDelete={() => setDeleteTarget(selectedVM.name)}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { vmRefKey } from '../lib/vmRef'
|
||||
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
|
||||
import { VersionArt } from '../macos/VersionArt'
|
||||
import { BrandMark, HostIcon } from '../ui/themeVisuals'
|
||||
import { VMAction } from './VMPage'
|
||||
import type { VMAction, VMBusyAction } from './VMPage'
|
||||
|
||||
export const HOST_ID = '__host__'
|
||||
export const INSTALLERS_ID = '__installers__'
|
||||
@@ -24,7 +24,7 @@ interface Props {
|
||||
vms: VMListItem[]
|
||||
transitions: Record<string, string>
|
||||
/** VM name → currently running action (disables conflicting context menu actions). */
|
||||
busyActions?: Record<string, VMAction>
|
||||
busyActions?: Record<string, VMBusyAction>
|
||||
selected: string
|
||||
hostReady: boolean
|
||||
/** Whether the active runtime supports VM suspend/resume. */
|
||||
|
||||
@@ -83,6 +83,8 @@ export type VMAction =
|
||||
| 'delete'
|
||||
| 'openFolder'
|
||||
|
||||
export type VMBusyAction = VMAction | 'pluginCommand'
|
||||
|
||||
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
|
||||
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
|
||||
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
|
||||
@@ -113,8 +115,9 @@ interface Props {
|
||||
detail: VMDetail | null
|
||||
host: HostReport
|
||||
pending: PendingChange[]
|
||||
busyAction?: VMAction
|
||||
busyAction?: VMBusyAction
|
||||
onAction: (action: VMAction) => void
|
||||
onPluginCommand: (pluginID: string, command: string, title: string) => void
|
||||
onSettings: () => void
|
||||
onOpenAffinity: () => void
|
||||
onDelete: () => void
|
||||
@@ -180,7 +183,7 @@ interface Spec {
|
||||
}
|
||||
|
||||
export const VMPage: React.FC<Props> = ({
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, currentAgentVersion, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onPluginCommand, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const busy = busyAction !== undefined
|
||||
@@ -192,6 +195,17 @@ export const VMPage: React.FC<Props> = ({
|
||||
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
|
||||
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
|
||||
const isMacOSDriver = !driverID || driverID === BUILTIN_MACOS_DRIVER
|
||||
const toolbarMenus = (pluginUI?.menus ?? []).filter(({ slot, when }) => {
|
||||
if (slot !== 'vm.toolbar') return false
|
||||
switch (when) {
|
||||
case undefined:
|
||||
case '': return true
|
||||
case 'vm.running': return running
|
||||
case 'vm.stopped': return state === 'stopped'
|
||||
case 'vm.macos.running': return running && isMacOSDriver && detail?.name === name && !installing && !guideActive
|
||||
default: return false
|
||||
}
|
||||
})
|
||||
const canUseHostDNS = !!detail && !installing && !detail.guest_tools_disabled && isMacOSDriver && state !== 'broken'
|
||||
// Polled here rather than in App so each tick re-renders only this page.
|
||||
const stats = useVMStats(driverID, name, running)
|
||||
@@ -629,21 +643,19 @@ export const VMPage: React.FC<Props> = ({
|
||||
<Menu.Item className="menu-item rg-p-menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
|
||||
<Archive size={14} /> {tr('exportDiagnostics')}
|
||||
</Menu.Item>
|
||||
{(pluginUI?.menus ?? [])
|
||||
.filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : false)))
|
||||
.map((m) => (
|
||||
<Menu.Item
|
||||
key={`${m.pluginId}:${m.id}`}
|
||||
className="menu-item rg-p-menu-item"
|
||||
onSelect={() => {
|
||||
void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name })
|
||||
.then(() => onToast(locText(m.title, locale, m.id)))
|
||||
.catch((e) => onError(tr('failGeneric'), e))
|
||||
}}
|
||||
>
|
||||
{locText(m.title, locale, m.id)}
|
||||
</Menu.Item>
|
||||
))}
|
||||
{toolbarMenus.map((m) => {
|
||||
const title = locText(m.title, locale, m.id)
|
||||
return (
|
||||
<Menu.Item
|
||||
key={`${m.pluginId}:${m.id}`}
|
||||
className="menu-item rg-p-menu-item"
|
||||
disabled={busy}
|
||||
onSelect={() => onPluginCommand(m.pluginId ?? '', m.command, title)}
|
||||
>
|
||||
{title}
|
||||
</Menu.Item>
|
||||
)
|
||||
})}
|
||||
<Menu.Separator className="menu-sep" />
|
||||
{suspended && (
|
||||
<Menu.Item className="menu-item rg-p-menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
|
||||
|
||||
@@ -111,6 +111,7 @@ type App struct {
|
||||
stopPoll context.CancelFunc
|
||||
guestTools *guesttools.Server
|
||||
guestToolsConfigLocks sync.Map
|
||||
appWindowGate sync.Mutex
|
||||
vmDeleteEpochs map[string]uint64
|
||||
resolveFolderVolume func(string) (host.DirectoryVolume, error)
|
||||
imeBridge *host.IMEBridge
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/appwindow"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
)
|
||||
|
||||
func (a *App) openAppWindow(command context.Context, sessions *appwindow.Sessions, bridge *guesttools.Server, service builtin.ComputerUseService, name string) error {
|
||||
a.mu.Lock()
|
||||
locale := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
tmp := a.cfg.TempDir()
|
||||
a.mu.Unlock()
|
||||
coded := func(code, key string, cause error) error {
|
||||
return i18n.NewCodedError(locale, code, key, i18n.Vars{"name": name}, cause)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
return coded("E_APP_WINDOW_UNAVAILABLE", "err.app_window_unavailable", nil)
|
||||
}
|
||||
vm, ok := a.polledVMForDriver(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if !ok || vm.State != "running" || vm.Dir == "" {
|
||||
return coded("E_VM_NOT_RUNNING", "err.vm_not_running", nil)
|
||||
}
|
||||
err := sessions.Start(command, func(ctx context.Context) (func(), error) {
|
||||
// A previous activation may still be clearing its input when Windows
|
||||
// takes longer than the plugin's shutdown deadline.
|
||||
if !a.appWindowGate.TryLock() {
|
||||
return nil, appwindow.ErrWindowOpen
|
||||
}
|
||||
run, err := a.prepareAppWindow(ctx, bridge, service, vm, tmp, locale, coded)
|
||||
if err != nil {
|
||||
a.appWindowGate.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
return func() {
|
||||
defer a.appWindowGate.Unlock()
|
||||
run()
|
||||
}, nil
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, appwindow.ErrWindowOpen):
|
||||
return coded("E_APP_WINDOW_OPEN", "err.app_window_open", nil)
|
||||
case errors.Is(err, appwindow.ErrSessionsClosed), errors.Is(err, context.Canceled):
|
||||
return coded("E_APP_WINDOW_DISABLED", "err.app_window_disabled", nil)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, service builtin.ComputerUseService, vm driver.VMListItem, tmp string, locale i18n.Locale, coded func(string, string, error) error) (func(), error) {
|
||||
name := vm.Name
|
||||
status := bridge.Status(name, 15*time.Second)
|
||||
if !status.Connected {
|
||||
return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
|
||||
}
|
||||
if status.AgentVersion < guesttools.PasteReadyAgentVersion {
|
||||
return nil, coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
|
||||
}
|
||||
probe, stopProbe := context.WithTimeout(ctx, 2*time.Second)
|
||||
pointer, err := service.PointerAvailable(probe, vm.Dir)
|
||||
stopProbe()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if err != nil || !pointer {
|
||||
return nil, coded("E_APP_WINDOW_POINTER", "err.app_window_pointer", err)
|
||||
}
|
||||
if !bridge.SetWindowReporting(name, true) {
|
||||
return nil, coded("E_APP_WINDOW_GUEST_TOOLS", "err.app_window_guest_tools", nil)
|
||||
}
|
||||
clearReporting := sync.OnceFunc(func() { bridge.SetWindowReporting(name, false) })
|
||||
stopReporting := context.AfterFunc(ctx, clearReporting)
|
||||
finishReporting := func() {
|
||||
stopReporting()
|
||||
clearReporting()
|
||||
}
|
||||
show, err := appwindow.Prepare(ctx, appwindow.SessionOptions{
|
||||
VMDir: vm.Dir,
|
||||
TmpDir: tmp,
|
||||
Console: service,
|
||||
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) {
|
||||
return bridge.ActiveWindow(name, maxAge)
|
||||
},
|
||||
PrepareClipboard: func(wait context.Context) (func(), error) {
|
||||
return bridge.PrepareGuestClipboardPaste(wait, name)
|
||||
},
|
||||
OnClipboardError: func(err error) {
|
||||
a.emitVMLogForDriver(vm.DriverID, name, "App window paste: "+err.Error())
|
||||
a.mu.Lock()
|
||||
manager := a.trayMgr
|
||||
a.mu.Unlock()
|
||||
if manager != nil {
|
||||
manager.Notify(i18n.T(locale, "tray.notify.app_window_paste_retry"), name, true)
|
||||
}
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
finishReporting()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if errors.Is(err, appwindow.ErrNoWindow) {
|
||||
return nil, coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil)
|
||||
}
|
||||
return nil, coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err)
|
||||
}
|
||||
return func() {
|
||||
defer finishReporting()
|
||||
if err := show(); err != nil && ctx.Err() == nil {
|
||||
a.emitVMLogForDriver(vm.DriverID, name, "App window closed: "+err.Error())
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
@@ -172,6 +172,7 @@ func (a *App) initPlugins() {
|
||||
return a.guestToolsImagePath(vmName)
|
||||
},
|
||||
BuildGuestToolsImage: a.buildGuestToolsImage,
|
||||
OpenAppWindow: a.openAppWindow,
|
||||
PrepareVMNetwork: a.prepareManagedVMNetwork,
|
||||
RestorePacketBridges: func(ctx context.Context) func() {
|
||||
return a.startPacketBridgeRestore(ctx, func(ctx context.Context) {
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
// Package appwindow presents a guest application through the VM console.
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
)
|
||||
|
||||
var ErrNoWindow = errors.New("no foreground guest window reported")
|
||||
|
||||
const (
|
||||
windowMaxAge = time.Second
|
||||
frameTimeout = 800 * time.Millisecond
|
||||
pasteTimeout = 4 * time.Second
|
||||
maxFramePixels = 4096 * 2160
|
||||
)
|
||||
|
||||
// Console is the host's serialized VM console, shared with its lifecycle and
|
||||
// other screenshot and input callers.
|
||||
type Console interface {
|
||||
ScreendumpDisplay(context.Context, string, string, string, int) (string, error)
|
||||
MouseMove(context.Context, string, int, int, int, int) error
|
||||
MouseButtonAt(context.Context, string, int, int, int, int, string, bool) error
|
||||
MouseButton(context.Context, string, string, bool) error
|
||||
MouseScroll(context.Context, string, int, bool) error
|
||||
SendKey(context.Context, string, string, bool) error
|
||||
ReleaseInputs(context.Context, string, []string, []string) error
|
||||
}
|
||||
|
||||
type SessionOptions struct {
|
||||
VMDir string
|
||||
TmpDir string
|
||||
Window func(time.Duration) (guesttools.ActiveWindow, bool)
|
||||
Console Console
|
||||
PrepareClipboard func(context.Context) (func(), error)
|
||||
OnClipboardError func(error)
|
||||
}
|
||||
|
||||
type frameMapping struct {
|
||||
window guesttools.ActiveWindow
|
||||
screen image.Point
|
||||
crop image.Rectangle
|
||||
}
|
||||
|
||||
type session struct {
|
||||
SessionOptions
|
||||
path string
|
||||
id uint32
|
||||
|
||||
mu sync.Mutex
|
||||
mapping frameMapping
|
||||
tag uint64
|
||||
lastFrame time.Time
|
||||
}
|
||||
|
||||
type inputQueue struct {
|
||||
mu sync.Mutex
|
||||
events []queuedInput
|
||||
ready chan struct{}
|
||||
focus context.Context
|
||||
cancelFocus context.CancelFunc
|
||||
}
|
||||
|
||||
type queuedInput struct {
|
||||
ViewerEvent
|
||||
focus context.Context
|
||||
}
|
||||
|
||||
func (q *inputQueue) push(event ViewerEvent) bool {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if event.Kind == ViewerFocus || event.Kind == ViewerClose {
|
||||
if q.cancelFocus != nil {
|
||||
q.cancelFocus()
|
||||
q.focus, q.cancelFocus = nil, nil
|
||||
}
|
||||
if event.Kind == ViewerFocus && event.Down {
|
||||
q.focus, q.cancelFocus = context.WithCancel(context.Background())
|
||||
}
|
||||
}
|
||||
input := queuedInput{ViewerEvent: event, focus: q.focus}
|
||||
last := len(q.events) - 1
|
||||
if last >= 0 && q.events[last].Kind == ViewerMouseMove && event.Kind == ViewerMouseMove {
|
||||
q.events[last] = input
|
||||
return true
|
||||
}
|
||||
if len(q.events) == 64 {
|
||||
return event.Kind == ViewerMouseMove
|
||||
}
|
||||
q.events = append(q.events, input)
|
||||
if last < 0 {
|
||||
q.ready <- struct{}{}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (q *inputQueue) pop() queuedInput {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
event := q.events[0]
|
||||
copy(q.events, q.events[1:])
|
||||
q.events[len(q.events)-1] = queuedInput{}
|
||||
q.events = q.events[:len(q.events)-1]
|
||||
if len(q.events) > 0 {
|
||||
q.ready <- struct{}{}
|
||||
}
|
||||
return event
|
||||
}
|
||||
|
||||
// Prepare waits for the initial window report and confirms capture before the
|
||||
// viewer is shown. The caller must run the returned function to clean up.
|
||||
func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
|
||||
initial, err := waitForWindow(ctx, opts.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(opts.TmpDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dir, err := os.MkdirTemp(opts.TmpDir, "app-window-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &session{SessionOptions: opts, path: filepath.Join(dir, "frame.ppm"), id: initial.ID}
|
||||
cleanup := func() {
|
||||
_ = os.Remove(s.path)
|
||||
_ = os.Remove(dir)
|
||||
}
|
||||
first, err := s.capture(ctx)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, err
|
||||
}
|
||||
return func() error {
|
||||
defer cleanup()
|
||||
return s.run(ctx, initial.AppName, first)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, bool)) (guesttools.ActiveWindow, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
tick := time.NewTicker(150 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if report, ok := get(windowMaxAge); ok {
|
||||
return report, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return guesttools.ActiveWindow{}, ErrNoWindow
|
||||
}
|
||||
return guesttools.ActiveWindow{}, ctx.Err()
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
|
||||
before, ok := s.Window(windowMaxAge)
|
||||
if !ok || before.ID != s.id {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, frameTimeout)
|
||||
defer cancel()
|
||||
defer os.Remove(s.path)
|
||||
format, err := s.Console.ScreendumpDisplay(ctx, s.VMDir, s.path, "gfx", 0)
|
||||
if err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
size, err := thumb.Size(s.path, format)
|
||||
if err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
if size.X < 1 || size.Y < 1 || int64(size.X)*int64(size.Y) > maxFramePixels {
|
||||
return ViewerFrame{}, errors.New("guest display exceeds the app window capture size")
|
||||
}
|
||||
crop := guestCrop(before, size)
|
||||
if crop.Empty() {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
frame, err := thumb.Load(s.path, format)
|
||||
if err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
after, ok := s.Window(windowMaxAge)
|
||||
if !ok || before != after {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
img := image.NewRGBA(crop.Sub(crop.Min))
|
||||
draw.Draw(img, img.Bounds(), frame, crop.Min, draw.Src)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
mapping := frameMapping{window: before, screen: size, crop: crop}
|
||||
if s.tag == 0 || s.mapping != mapping {
|
||||
s.tag++
|
||||
s.mapping = mapping
|
||||
}
|
||||
s.lastFrame = time.Now()
|
||||
return ViewerFrame{Image: img, Tag: s.tag}, nil
|
||||
}
|
||||
|
||||
func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle {
|
||||
w, h := window.DisplayWidth, window.DisplayHeight
|
||||
if w <= 0 || h <= 0 || window.Width <= 0 || window.Height <= 0 {
|
||||
return image.Rectangle{}
|
||||
}
|
||||
visible := image.Rect(window.X, window.Y, window.X+window.Width, window.Y+window.Height).
|
||||
Intersect(image.Rect(0, 0, w, h))
|
||||
if visible.Empty() {
|
||||
return image.Rectangle{}
|
||||
}
|
||||
return image.Rect(
|
||||
visible.Min.X*size.X/w, visible.Min.Y*size.Y/h,
|
||||
(visible.Max.X*size.X+w-1)/w, (visible.Max.Y*size.Y+h-1)/h,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *session) eventMapping(event ViewerEvent) (frameMapping, bool) {
|
||||
window, ok := s.Window(windowMaxAge)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.mapping, ok && event.FrameTag == s.tag && window == s.mapping.window &&
|
||||
time.Since(s.lastFrame) <= windowMaxAge
|
||||
}
|
||||
|
||||
func (s *session) run(ctx context.Context, title string, first ViewerFrame) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
queue := &inputQueue{ready: make(chan struct{}, 1)}
|
||||
failure := make(chan error, 1)
|
||||
fail := func(err error) {
|
||||
select {
|
||||
case failure <- err:
|
||||
default:
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
done := make(chan struct{})
|
||||
var firstCaptureError time.Time
|
||||
go func() {
|
||||
defer close(done)
|
||||
if err := s.forwardInput(ctx, queue); err != nil && !errors.Is(err, context.Canceled) {
|
||||
fail(err)
|
||||
}
|
||||
}()
|
||||
err := RunViewer(ctx, ViewerOptions{
|
||||
Title: title,
|
||||
Initial: first,
|
||||
Frame: func(ctx context.Context) (ViewerFrame, error) {
|
||||
frame, err := s.capture(ctx)
|
||||
if err == nil {
|
||||
firstCaptureError = time.Time{}
|
||||
} else if firstCaptureError.IsZero() {
|
||||
firstCaptureError = time.Now()
|
||||
} else if time.Since(firstCaptureError) > 4*time.Second && ctx.Err() == nil {
|
||||
fail(err)
|
||||
}
|
||||
return frame, err
|
||||
},
|
||||
Input: func(event ViewerEvent) {
|
||||
if !queue.push(event) {
|
||||
fail(errors.New("app window input queue is full"))
|
||||
}
|
||||
},
|
||||
})
|
||||
cancel()
|
||||
<-done
|
||||
select {
|
||||
case err := <-failure:
|
||||
return err
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result error) {
|
||||
keys := make(map[string]bool)
|
||||
buttons := make(map[string]bool)
|
||||
release := func(timeout time.Duration) error {
|
||||
if len(keys)+len(buttons) == 0 {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
err := s.Console.ReleaseInputs(ctx, s.VMDir, slices.Sorted(maps.Keys(keys)), slices.Sorted(maps.Keys(buttons)))
|
||||
if err == nil {
|
||||
clear(keys)
|
||||
clear(buttons)
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
// Allow an in-flight QEMU readback to finish before releasing input.
|
||||
if err := release(4 * time.Second); err != nil {
|
||||
result = fmt.Errorf("release app window input: %w", err)
|
||||
}
|
||||
}()
|
||||
checkWindow := time.NewTicker(500 * time.Millisecond)
|
||||
defer checkWindow.Stop()
|
||||
var missingSince time.Time
|
||||
var wheel int
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-checkWindow.C:
|
||||
if window, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
|
||||
missingSince = time.Time{}
|
||||
} else if missingSince.IsZero() {
|
||||
missingSince = time.Now()
|
||||
if err := release(frameTimeout); err != nil {
|
||||
return fmt.Errorf("release app window input: %w", err)
|
||||
}
|
||||
wheel = 0
|
||||
} else if time.Since(missingSince) > 4*time.Second {
|
||||
return ErrNoWindow
|
||||
}
|
||||
case <-queue.ready:
|
||||
input := queue.pop()
|
||||
event := input.ViewerEvent
|
||||
if event.Kind == ViewerClose || (event.Kind == ViewerFocus && !event.Down) {
|
||||
if err := release(frameTimeout); err != nil {
|
||||
return fmt.Errorf("release app window input: %w", err)
|
||||
}
|
||||
wheel = 0
|
||||
continue
|
||||
}
|
||||
mapping, active := s.eventMapping(event)
|
||||
base := ctx
|
||||
finish := func() {}
|
||||
paste := active && s.PrepareClipboard != nil && isPaste(event, keys)
|
||||
if paste {
|
||||
if input.focus == nil || input.focus.Err() != nil {
|
||||
continue
|
||||
}
|
||||
focused, cancelFocus := context.WithCancel(ctx)
|
||||
stopFocus := context.AfterFunc(input.focus, cancelFocus)
|
||||
wait, cancelWait := context.WithTimeout(focused, pasteTimeout)
|
||||
releasePaste, err := s.PrepareClipboard(wait)
|
||||
cancelWait()
|
||||
finish = func() {
|
||||
if releasePaste != nil {
|
||||
releasePaste()
|
||||
}
|
||||
stopFocus()
|
||||
cancelFocus()
|
||||
}
|
||||
if err != nil || input.focus.Err() != nil || focused.Err() != nil {
|
||||
finish()
|
||||
if err != nil && input.focus.Err() == nil && ctx.Err() == nil && s.OnClipboardError != nil {
|
||||
s.OnClipboardError(err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
mapping, active = s.eventMapping(event)
|
||||
base = focused
|
||||
}
|
||||
request, cancel := context.WithTimeout(base, frameTimeout)
|
||||
err := s.forwardEvent(request, event, mapping, active, keys, buttons, &wheel)
|
||||
cancel()
|
||||
finish()
|
||||
if err != nil && paste && input.focus.Err() != nil {
|
||||
continue
|
||||
}
|
||||
// A newer movement supersedes a timed-out hover. Button and key
|
||||
// transitions still fail the session so held input gets released.
|
||||
if err != nil && event.Kind != ViewerMouseMove {
|
||||
return fmt.Errorf("app window input: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isPaste(event ViewerEvent, keys map[string]bool) bool {
|
||||
return event.Kind == ViewerKey && event.Down && qmp.QKeyCode(event.VirtualKey) == "v" &&
|
||||
!keys["v"] && (keys["meta_l"] || keys["meta_r"])
|
||||
}
|
||||
|
||||
func (s *session) forwardEvent(ctx context.Context, event ViewerEvent, m frameMapping, active bool, keys, buttons map[string]bool, wheel *int) error {
|
||||
if event.Kind == ViewerKey {
|
||||
key := qmp.QKeyCode(event.VirtualKey)
|
||||
if key == "" || event.Down == keys[key] || (!active && event.Down) {
|
||||
return nil
|
||||
}
|
||||
if event.Down {
|
||||
keys[key] = true
|
||||
}
|
||||
err := s.Console.SendKey(ctx, s.VMDir, key, event.Down)
|
||||
if err == nil && !event.Down {
|
||||
delete(keys, key)
|
||||
}
|
||||
return err
|
||||
}
|
||||
x, y := m.crop.Min.X+event.X, m.crop.Min.Y+event.Y
|
||||
positioned := active && event.Width == m.crop.Dx() && event.Height == m.crop.Dy() &&
|
||||
image.Pt(x, y).In(m.crop)
|
||||
switch event.Kind {
|
||||
case ViewerMouseMove:
|
||||
if positioned {
|
||||
return s.Console.MouseMove(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y)
|
||||
}
|
||||
case ViewerMouseButton:
|
||||
names := [...]string{"left", "right", "middle"}
|
||||
if event.Button < 0 || event.Button >= len(names) {
|
||||
return nil
|
||||
}
|
||||
button := names[event.Button]
|
||||
if event.Down == buttons[button] || (!positioned && event.Down) {
|
||||
return nil
|
||||
}
|
||||
if event.Down {
|
||||
buttons[button] = true
|
||||
}
|
||||
var err error
|
||||
if positioned {
|
||||
err = s.Console.MouseButtonAt(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y, button, event.Down)
|
||||
} else {
|
||||
err = s.Console.MouseButton(ctx, s.VMDir, button, false)
|
||||
}
|
||||
if err == nil && !event.Down {
|
||||
delete(buttons, button)
|
||||
}
|
||||
return err
|
||||
case ViewerMouseWheel:
|
||||
if positioned {
|
||||
*wheel += event.Delta
|
||||
steps := *wheel / 120
|
||||
*wheel %= 120
|
||||
if steps == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := s.Console.MouseMove(ctx, s.VMDir, x, y, m.screen.X, m.screen.Y); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Console.MouseScroll(ctx, s.VMDir, -steps, false)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"image"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
)
|
||||
|
||||
type captureConsole struct{ Console }
|
||||
|
||||
type pasteConsole struct {
|
||||
Console
|
||||
sent chan string
|
||||
}
|
||||
|
||||
func (c pasteConsole) SendKey(_ context.Context, _, key string, down bool) error {
|
||||
if down {
|
||||
c.sent <- key
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c pasteConsole) ReleaseInputs(context.Context, string, []string, []string) error {
|
||||
c.sent <- "released"
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPasteWaitsForClipboardAndCancelsOnBlur(t *testing.T) {
|
||||
for _, name := range []string{"applied", "blur"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
window := guesttools.ActiveWindow{ID: 1}
|
||||
ready, entered := make(chan struct{}), make(chan struct{})
|
||||
console := pasteConsole{sent: make(chan string, 8)}
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Console: console,
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return window, true },
|
||||
PrepareClipboard: func(ctx context.Context) (func(), error) {
|
||||
close(entered)
|
||||
select {
|
||||
case <-ready:
|
||||
return func() {}, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
},
|
||||
id: 1, tag: 1, mapping: frameMapping{window: window}, lastFrame: time.Now(),
|
||||
}
|
||||
queue := &inputQueue{ready: make(chan struct{}, 1)}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- s.forwardInput(ctx, queue) }()
|
||||
defer func() {
|
||||
cancel()
|
||||
<-done
|
||||
}()
|
||||
|
||||
queue.push(ViewerEvent{Kind: ViewerFocus, Down: true})
|
||||
queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 0x11, Down: true})
|
||||
queue.push(ViewerEvent{Kind: ViewerKey, FrameTag: 1, VirtualKey: 'V', Down: true})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("clipboard wait did not start")
|
||||
}
|
||||
if key := <-console.sent; key != "meta_l" {
|
||||
t.Fatalf("first key = %q", key)
|
||||
}
|
||||
select {
|
||||
case key := <-console.sent:
|
||||
t.Fatalf("forwarded %q before clipboard changed", key)
|
||||
default:
|
||||
}
|
||||
want := "v"
|
||||
if name == "blur" {
|
||||
queue.push(ViewerEvent{Kind: ViewerFocus})
|
||||
want = "released"
|
||||
} else {
|
||||
close(ready)
|
||||
}
|
||||
select {
|
||||
case key := <-console.sent:
|
||||
if key != want {
|
||||
t.Fatalf("event = %q, want %q", key, want)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("did not receive %q", want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInputQueueKeepsClickBetweenMoves(t *testing.T) {
|
||||
q := &inputQueue{ready: make(chan struct{}, 1)}
|
||||
for _, event := range []ViewerEvent{
|
||||
{Kind: ViewerMouseMove, X: 1},
|
||||
{Kind: ViewerMouseMove, X: 2},
|
||||
{Kind: ViewerMouseButton, X: 2, Down: true},
|
||||
{Kind: ViewerMouseMove, X: 3},
|
||||
{Kind: ViewerMouseMove, X: 4},
|
||||
} {
|
||||
if !q.push(event) {
|
||||
t.Fatal("queue unexpectedly full")
|
||||
}
|
||||
}
|
||||
for _, want := range []ViewerEvent{
|
||||
{Kind: ViewerMouseMove, X: 2},
|
||||
{Kind: ViewerMouseButton, X: 2, Down: true},
|
||||
{Kind: ViewerMouseMove, X: 4},
|
||||
} {
|
||||
select {
|
||||
case <-q.ready:
|
||||
default:
|
||||
t.Fatal("queue did not notify its reader")
|
||||
}
|
||||
if got := q.pop().ViewerEvent; got != want {
|
||||
t.Fatalf("event = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (captureConsole) ScreendumpDisplay(_ context.Context, _ string, path, device string, head int) (string, error) {
|
||||
if device != "gfx" || head != 0 {
|
||||
return "", ErrNoWindow
|
||||
}
|
||||
ppm := append([]byte("P6\n8 6\n255\n"), make([]byte, 8*6*3)...)
|
||||
return "ppm", os.WriteFile(path, ppm, 0o600)
|
||||
}
|
||||
|
||||
func TestCaptureTracksDisplayedGeometry(t *testing.T) {
|
||||
current := guesttools.ActiveWindow{
|
||||
ID: 1, AppName: "TextEdit", X: -1, Y: 1, Width: 4, Height: 2, DisplayWidth: 4, DisplayHeight: 3,
|
||||
}
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return current, true },
|
||||
Console: captureConsole{},
|
||||
},
|
||||
path: filepath.Join(t.TempDir(), "test.ppm"), id: 1,
|
||||
}
|
||||
frame, err := s.capture(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame.Image.Bounds() != image.Rect(0, 0, 6, 4) {
|
||||
t.Fatalf("crop bounds = %v", frame.Image.Bounds())
|
||||
}
|
||||
event := ViewerEvent{Kind: ViewerMouseButton, FrameTag: frame.Tag}
|
||||
if mapping, ok := s.eventMapping(event); !ok || mapping.crop.Min != image.Pt(0, 2) {
|
||||
t.Fatalf("event mapping = %#v, %v", mapping, ok)
|
||||
}
|
||||
current.X = 1
|
||||
if _, ok := s.eventMapping(event); ok {
|
||||
t.Fatal("accepted input against a stale window position")
|
||||
}
|
||||
next, err := s.capture(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next.Tag == frame.Tag {
|
||||
t.Fatal("changed window position retained the previous frame tag")
|
||||
}
|
||||
current.ID++
|
||||
if _, err := s.capture(context.Background()); err != ErrNoWindow {
|
||||
t.Fatalf("capture after guest changed windows = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrWindowOpen = errors.New("an app window is already open")
|
||||
ErrSessionsClosed = errors.New("app window service is closed")
|
||||
)
|
||||
|
||||
// Sessions owns the single app window opened during one plugin activation.
|
||||
type Sessions struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
active *activeSession
|
||||
}
|
||||
|
||||
type activeSession struct {
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// Start prepares the window under the command's cancellation and transfers
|
||||
// its runtime to Sessions after preparation succeeds.
|
||||
func (s *Sessions) Start(command context.Context, prepare func(context.Context) (func(), error)) error {
|
||||
if err := command.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return ErrSessionsClosed
|
||||
}
|
||||
if s.active != nil {
|
||||
s.mu.Unlock()
|
||||
return ErrWindowOpen
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
active := &activeSession{cancel: cancel, done: make(chan struct{})}
|
||||
s.active = active
|
||||
s.mu.Unlock()
|
||||
|
||||
finish := func() {
|
||||
cancel()
|
||||
s.mu.Lock()
|
||||
s.active = nil
|
||||
close(active.done)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
stopStartup := context.AfterFunc(command, cancel)
|
||||
run, err := prepare(ctx)
|
||||
if !stopStartup() {
|
||||
cancel()
|
||||
}
|
||||
if err != nil {
|
||||
finish()
|
||||
return err
|
||||
}
|
||||
// Run even when startup was canceled after preparation. The prepared
|
||||
// function owns the initial capture resources and releases them on exit.
|
||||
startupErr := ctx.Err()
|
||||
go func() {
|
||||
defer finish()
|
||||
run()
|
||||
}()
|
||||
return startupErr
|
||||
}
|
||||
|
||||
// Close prevents new sessions and cancels preparation or the active viewer.
|
||||
func (s *Sessions) Close() {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
active := s.active
|
||||
s.mu.Unlock()
|
||||
if active == nil {
|
||||
return
|
||||
}
|
||||
active.cancel()
|
||||
|
||||
// Keep plugin transitions bounded if the OS clipboard owner is stalled.
|
||||
timer := time.NewTimer(5 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-active.done:
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSessionsEnforcePluginLifetime(t *testing.T) {
|
||||
var sessions Sessions
|
||||
command, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var window context.Context
|
||||
finished := make(chan struct{})
|
||||
prepare := func(ctx context.Context) (func(), error) {
|
||||
window = ctx
|
||||
return func() {
|
||||
<-ctx.Done()
|
||||
close(finished)
|
||||
}, nil
|
||||
}
|
||||
if err := sessions.Start(command, prepare); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sessions.Close()
|
||||
cancel()
|
||||
if err := window.Err(); err != nil {
|
||||
t.Fatalf("command completion canceled the open window: %v", err)
|
||||
}
|
||||
if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrWindowOpen) {
|
||||
t.Fatalf("opening a second window: %v", err)
|
||||
}
|
||||
sessions.Close()
|
||||
select {
|
||||
case <-finished:
|
||||
default:
|
||||
t.Fatal("scope closed before the viewer finished")
|
||||
}
|
||||
if err := sessions.Start(context.Background(), prepare); !errors.Is(err, ErrSessionsClosed) {
|
||||
t.Fatalf("opening a window after deactivation: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionsCloseCancelsPendingStart(t *testing.T) {
|
||||
var sessions Sessions
|
||||
entered := make(chan struct{})
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
errs <- sessions.Start(context.Background(), func(ctx context.Context) (func(), error) {
|
||||
close(entered)
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
})
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("preparation did not start")
|
||||
}
|
||||
sessions.Close()
|
||||
select {
|
||||
case err := <-errs:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("startup after deactivation: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("preparation did not stop")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"image"
|
||||
)
|
||||
|
||||
type ViewerFrame struct {
|
||||
Image image.Image
|
||||
Tag uint64
|
||||
}
|
||||
|
||||
type ViewerEventKind uint8
|
||||
|
||||
const (
|
||||
ViewerFocus ViewerEventKind = iota + 1
|
||||
ViewerClose
|
||||
ViewerMouseMove
|
||||
ViewerMouseButton
|
||||
ViewerMouseWheel
|
||||
ViewerKey
|
||||
)
|
||||
|
||||
type ViewerEvent struct {
|
||||
Kind ViewerEventKind
|
||||
FrameTag uint64
|
||||
X, Y int
|
||||
Width, Height int
|
||||
Button int // 0 = left, 1 = right, 2 = middle
|
||||
Delta int // 120 units per wheel detent
|
||||
VirtualKey uint32
|
||||
Down bool
|
||||
}
|
||||
|
||||
type ViewerOptions struct {
|
||||
Title string
|
||||
Initial ViewerFrame
|
||||
Frame func(context.Context) (ViewerFrame, error)
|
||||
Input func(ViewerEvent) // Runs on the window thread and must return promptly.
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
func RunViewer(context.Context, ViewerOptions) error {
|
||||
return errors.New("the app-window viewer requires Windows")
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
//go:build windows
|
||||
|
||||
package appwindow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var (
|
||||
viewerUser32 = windows.NewLazySystemDLL("user32.dll")
|
||||
viewerGDI32 = windows.NewLazySystemDLL("gdi32.dll")
|
||||
viewerDWM = windows.NewLazySystemDLL("dwmapi.dll")
|
||||
viewerKernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||
|
||||
viewerRegisterClass = viewerUser32.NewProc("RegisterClassW")
|
||||
viewerCreateWindow = viewerUser32.NewProc("CreateWindowExW")
|
||||
viewerDefWindowProc = viewerUser32.NewProc("DefWindowProcW")
|
||||
viewerDestroyWindow = viewerUser32.NewProc("DestroyWindow")
|
||||
viewerShowWindow = viewerUser32.NewProc("ShowWindow")
|
||||
viewerUpdateWindow = viewerUser32.NewProc("UpdateWindow")
|
||||
viewerGetMessage = viewerUser32.NewProc("GetMessageW")
|
||||
viewerDispatchMessage = viewerUser32.NewProc("DispatchMessageW")
|
||||
viewerPostMessage = viewerUser32.NewProc("PostMessageW")
|
||||
viewerPostQuitMessage = viewerUser32.NewProc("PostQuitMessage")
|
||||
viewerLoadCursor = viewerUser32.NewProc("LoadCursorW")
|
||||
viewerInvalidateRect = viewerUser32.NewProc("InvalidateRect")
|
||||
viewerGetClientRect = viewerUser32.NewProc("GetClientRect")
|
||||
viewerGetWindowRect = viewerUser32.NewProc("GetWindowRect")
|
||||
viewerSetWindowPos = viewerUser32.NewProc("SetWindowPos")
|
||||
viewerBeginPaint = viewerUser32.NewProc("BeginPaint")
|
||||
viewerEndPaint = viewerUser32.NewProc("EndPaint")
|
||||
viewerFillRect = viewerUser32.NewProc("FillRect")
|
||||
viewerIsIconic = viewerUser32.NewProc("IsIconic")
|
||||
viewerIsZoomed = viewerUser32.NewProc("IsZoomed")
|
||||
viewerGetDpiForWindow = viewerUser32.NewProc("GetDpiForWindow")
|
||||
viewerGetKeyState = viewerUser32.NewProc("GetKeyState")
|
||||
viewerMonitorFromRect = viewerUser32.NewProc("MonitorFromRect")
|
||||
viewerGetMonitorInfo = viewerUser32.NewProc("GetMonitorInfoW")
|
||||
viewerSetCapture = viewerUser32.NewProc("SetCapture")
|
||||
viewerGetCapture = viewerUser32.NewProc("GetCapture")
|
||||
viewerReleaseCapture = viewerUser32.NewProc("ReleaseCapture")
|
||||
viewerScreenToClient = viewerUser32.NewProc("ScreenToClient")
|
||||
viewerClientToScreen = viewerUser32.NewProc("ClientToScreen")
|
||||
viewerGetStockObject = viewerGDI32.NewProc("GetStockObject")
|
||||
viewerSetStretchMode = viewerGDI32.NewProc("SetStretchBltMode")
|
||||
viewerStretchDIBits = viewerGDI32.NewProc("StretchDIBits")
|
||||
viewerSetDwmAttribute = viewerDWM.NewProc("DwmSetWindowAttribute")
|
||||
viewerMoveMemory = viewerKernel32.NewProc("RtlMoveMemory")
|
||||
|
||||
viewerClassOnce sync.Once
|
||||
viewerClassAtom uintptr
|
||||
viewerClassErr error
|
||||
viewerModule windows.Handle
|
||||
viewerWindows sync.Map // HWND -> *nativeViewer
|
||||
)
|
||||
|
||||
const (
|
||||
viewerWmDestroy = 0x0002
|
||||
viewerWmSize = 0x0005
|
||||
viewerWmSetFocus = 0x0007
|
||||
viewerWmKillFocus = 0x0008
|
||||
viewerWmPaint = 0x000f
|
||||
viewerWmClose = 0x0010
|
||||
viewerWmErase = 0x0014
|
||||
viewerWmNCCalcSize = 0x0083
|
||||
viewerWmNCHitTest = 0x0084
|
||||
viewerWmNCPaint = 0x0085
|
||||
viewerWmNCActivate = 0x0086
|
||||
viewerWmNCLeftDown = 0x00a1
|
||||
viewerWmKeyDown = 0x0100
|
||||
viewerWmKeyUp = 0x0101
|
||||
viewerWmSysKeyDown = 0x0104
|
||||
viewerWmSysKeyUp = 0x0105
|
||||
viewerWmSysCommand = 0x0112
|
||||
viewerWmMouseMove = 0x0200
|
||||
viewerWmLeftDown = 0x0201
|
||||
viewerWmLeftUp = 0x0202
|
||||
viewerWmRightDown = 0x0204
|
||||
viewerWmRightUp = 0x0205
|
||||
viewerWmMiddleDown = 0x0207
|
||||
viewerWmMiddleUp = 0x0208
|
||||
viewerWmMouseWheel = 0x020a
|
||||
viewerWmCaptureChanged = 0x0215
|
||||
viewerWmFrame = 0x8001
|
||||
viewerWmStop = 0x8002
|
||||
|
||||
viewerHTClient = 1
|
||||
viewerHTCaption = 2
|
||||
viewerHTLeft = 10
|
||||
viewerHTRight = 11
|
||||
viewerHTTop = 12
|
||||
viewerHTTopLeft = 13
|
||||
viewerHTTopRight = 14
|
||||
viewerHTBottom = 15
|
||||
viewerHTBottomLeft = 16
|
||||
viewerHTBottomRight = 17
|
||||
)
|
||||
|
||||
type viewerClass struct {
|
||||
style uint32
|
||||
windowProc uintptr
|
||||
classExtra int32
|
||||
windowExtra int32
|
||||
instance windows.Handle
|
||||
icon uintptr
|
||||
cursor uintptr
|
||||
background uintptr
|
||||
menuName *uint16
|
||||
className *uint16
|
||||
}
|
||||
|
||||
type viewerPoint struct{ x, y int32 }
|
||||
type viewerRect struct{ left, top, right, bottom int32 }
|
||||
|
||||
type viewerMonitorInfo struct {
|
||||
size uint32
|
||||
monitor, work viewerRect
|
||||
flags uint32
|
||||
}
|
||||
|
||||
type viewerMessage struct {
|
||||
hwnd uintptr
|
||||
message uint32
|
||||
wParam, lParam uintptr
|
||||
time uint32
|
||||
point viewerPoint
|
||||
private uint32
|
||||
}
|
||||
|
||||
type viewerPaint struct {
|
||||
dc uintptr
|
||||
erase int32
|
||||
rect viewerRect
|
||||
restore int32
|
||||
update int32
|
||||
padding [32]byte
|
||||
}
|
||||
|
||||
type viewerBitmapHeader struct {
|
||||
size uint32
|
||||
width, height int32
|
||||
planes, bits uint16
|
||||
compression uint32
|
||||
imageSize uint32
|
||||
xPPM, yPPM int32
|
||||
colorsUsed uint32
|
||||
colorsNeeded uint32
|
||||
}
|
||||
|
||||
type viewerBitmap struct {
|
||||
width, height int
|
||||
tag uint64
|
||||
pixels []byte
|
||||
}
|
||||
|
||||
type nativeViewer struct {
|
||||
hwnd uintptr
|
||||
options ViewerOptions
|
||||
|
||||
latest atomic.Pointer[viewerBitmap]
|
||||
pending atomic.Bool
|
||||
postMu sync.Mutex
|
||||
closed bool
|
||||
|
||||
// The message loop owns these fields. Inputs use the bitmap that was painted.
|
||||
displayed *viewerBitmap
|
||||
imageRect image.Rectangle
|
||||
keys map[uint32]bool
|
||||
buttons [3]bool
|
||||
lastMouse ViewerEvent
|
||||
}
|
||||
|
||||
func registerViewerClass() (uintptr, error) {
|
||||
viewerClassOnce.Do(func() {
|
||||
viewerClassErr = windows.GetModuleHandleEx(windows.GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, nil, &viewerModule)
|
||||
if viewerClassErr != nil {
|
||||
return
|
||||
}
|
||||
cursor, _, _ := viewerLoadCursor.Call(0, 32512) // IDC_ARROW
|
||||
className, _ := windows.UTF16PtrFromString("ReimsGoAppWindowClass")
|
||||
class := viewerClass{
|
||||
windowProc: windows.NewCallback(viewerWindowProc),
|
||||
instance: viewerModule,
|
||||
cursor: cursor,
|
||||
className: className,
|
||||
}
|
||||
atom, _, err := viewerRegisterClass.Call(uintptr(unsafe.Pointer(&class)))
|
||||
if atom == 0 {
|
||||
viewerClassErr = fmt.Errorf("register app-window viewer: %w", err)
|
||||
return
|
||||
}
|
||||
viewerClassAtom = atom
|
||||
})
|
||||
return viewerClassAtom, viewerClassErr
|
||||
}
|
||||
|
||||
// RunViewer owns a native window until the user closes it or the context is canceled.
|
||||
func RunViewer(ctx context.Context, opts ViewerOptions) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.Title == "" {
|
||||
opts.Title = "Reims-Go"
|
||||
}
|
||||
title, err := windows.UTF16PtrFromString(opts.Title)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid app-window title: %w", err)
|
||||
}
|
||||
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
class, err := registerViewerClass()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
first := makeViewerBitmap(opts.Initial)
|
||||
opts.Initial = ViewerFrame{}
|
||||
v := &nativeViewer{options: opts, keys: make(map[uint32]bool)}
|
||||
width, height := 900, 640
|
||||
if first != nil {
|
||||
v.latest.Store(first)
|
||||
size := fitViewerFrame(min(first.width, 920), min(first.height, 680), first.width, first.height)
|
||||
width, height = size.Dx(), size.Dy()
|
||||
}
|
||||
hwnd, _, callErr := viewerCreateWindow.Call(
|
||||
0x00040000, class, uintptr(unsafe.Pointer(title)), 0x00cf0000, // WS_EX_APPWINDOW, WS_OVERLAPPEDWINDOW
|
||||
0x80000000, 0x80000000, uintptr(width), uintptr(height), // CW_USEDEFAULT for x and y
|
||||
0, 0, uintptr(viewerModule), 0,
|
||||
)
|
||||
if hwnd == 0 {
|
||||
return fmt.Errorf("create app-window viewer: %w", callErr)
|
||||
}
|
||||
v.hwnd = hwnd
|
||||
viewerWindows.Store(hwnd, v)
|
||||
defer viewerWindows.Delete(hwnd)
|
||||
configureViewerFrame(hwnd)
|
||||
|
||||
work, cancel := context.WithCancel(ctx)
|
||||
var workers sync.WaitGroup
|
||||
defer func() {
|
||||
v.stopPosting()
|
||||
cancel()
|
||||
workers.Wait()
|
||||
}()
|
||||
workers.Go(func() {
|
||||
<-work.Done()
|
||||
v.post(viewerWmStop)
|
||||
})
|
||||
if opts.Frame != nil {
|
||||
workers.Go(func() { v.pollFrames(work) })
|
||||
}
|
||||
viewerShowWindow.Call(hwnd, 5) // SW_SHOW
|
||||
viewerInvalidateRect.Call(hwnd, 0, 0)
|
||||
viewerUpdateWindow.Call(hwnd)
|
||||
|
||||
var msg viewerMessage
|
||||
for {
|
||||
status, _, err := viewerGetMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
|
||||
switch int32(status) {
|
||||
case -1:
|
||||
v.releaseInputs()
|
||||
viewerWindows.Delete(hwnd)
|
||||
v.destroy()
|
||||
return fmt.Errorf("read app-window messages: %w", err)
|
||||
case 0:
|
||||
return nil
|
||||
}
|
||||
viewerDispatchMessage.Call(uintptr(unsafe.Pointer(&msg)))
|
||||
}
|
||||
}
|
||||
|
||||
func configureViewerFrame(hwnd uintptr) {
|
||||
// Retain overlapped-window behavior and calculate the entire window as client area.
|
||||
viewerSetWindowPos.Call(hwnd, 0, 0, 0, 0, 0, 0x37) // SWP_FRAMECHANGED | NOACTIVATE | NOZORDER | NOMOVE | NOSIZE
|
||||
color := uint32(0xfffffffe) // DWMWA_COLOR_NONE
|
||||
result, _, _ := viewerSetDwmAttribute.Call(hwnd, 34, uintptr(unsafe.Pointer(&color)), unsafe.Sizeof(color))
|
||||
if int32(result) < 0 {
|
||||
policy := uint32(1) // DWMNCRP_DISABLED on builds without DWMWA_BORDER_COLOR.
|
||||
viewerSetDwmAttribute.Call(hwnd, 2, uintptr(unsafe.Pointer(&policy)), unsafe.Sizeof(policy))
|
||||
}
|
||||
corner := uint32(1) // DWMWCP_DONOTROUND, so the host frame does not clip guest pixels.
|
||||
viewerSetDwmAttribute.Call(hwnd, 33, uintptr(unsafe.Pointer(&corner)), unsafe.Sizeof(corner))
|
||||
}
|
||||
|
||||
func fitViewerMaximizedClient(hwnd, rect uintptr) {
|
||||
if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed == 0 || rect == 0 {
|
||||
return
|
||||
}
|
||||
// The maximized outer frame extends past the work area. Keep the app's pixels inside it.
|
||||
monitor, _, _ := viewerMonitorFromRect.Call(rect, 2) // MONITOR_DEFAULTTONEAREST
|
||||
info := viewerMonitorInfo{size: uint32(unsafe.Sizeof(viewerMonitorInfo{}))}
|
||||
if ok, _, _ := viewerGetMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 {
|
||||
viewerMoveMemory.Call(rect, uintptr(unsafe.Pointer(&info.work)), unsafe.Sizeof(info.work))
|
||||
}
|
||||
}
|
||||
|
||||
func viewerFrameHitTest(hwnd uintptr, point viewerPoint) uintptr {
|
||||
if zoomed, _, _ := viewerIsZoomed.Call(hwnd); zoomed != 0 {
|
||||
return viewerHTClient
|
||||
}
|
||||
var bounds viewerRect
|
||||
if ok, _, _ := viewerGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))); ok == 0 {
|
||||
return viewerHTClient
|
||||
}
|
||||
return viewerResizeHit(bounds, point, viewerScale(hwnd, 5))
|
||||
}
|
||||
|
||||
func viewerScale(hwnd uintptr, logical int32) int32 {
|
||||
dpi, _, _ := viewerGetDpiForWindow.Call(hwnd)
|
||||
if dpi == 0 {
|
||||
return logical
|
||||
}
|
||||
return max(1, (logical*int32(dpi)+48)/96)
|
||||
}
|
||||
|
||||
func viewerResizeHit(bounds viewerRect, point viewerPoint, edge int32) uintptr {
|
||||
if point.x < bounds.left || point.x >= bounds.right || point.y < bounds.top || point.y >= bounds.bottom {
|
||||
return viewerHTClient
|
||||
}
|
||||
left, right := point.x < bounds.left+edge, point.x >= bounds.right-edge
|
||||
switch {
|
||||
case point.y < bounds.top+edge:
|
||||
if left {
|
||||
return viewerHTTopLeft
|
||||
}
|
||||
if right {
|
||||
return viewerHTTopRight
|
||||
}
|
||||
return viewerHTTop
|
||||
case point.y >= bounds.bottom-edge:
|
||||
if left {
|
||||
return viewerHTBottomLeft
|
||||
}
|
||||
if right {
|
||||
return viewerHTBottomRight
|
||||
}
|
||||
return viewerHTBottom
|
||||
case left:
|
||||
return viewerHTLeft
|
||||
case right:
|
||||
return viewerHTRight
|
||||
default:
|
||||
return viewerHTClient
|
||||
}
|
||||
}
|
||||
|
||||
func makeViewerBitmap(frame ViewerFrame) *viewerBitmap {
|
||||
if frame.Image == nil || frame.Image.Bounds().Empty() {
|
||||
return nil
|
||||
}
|
||||
bounds := frame.Image.Bounds()
|
||||
rgba := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
|
||||
draw.Draw(rgba, rgba.Bounds(), frame.Image, bounds.Min, draw.Src)
|
||||
for i := 0; i < len(rgba.Pix); i += 4 {
|
||||
rgba.Pix[i], rgba.Pix[i+2] = rgba.Pix[i+2], rgba.Pix[i]
|
||||
}
|
||||
return &viewerBitmap{width: bounds.Dx(), height: bounds.Dy(), tag: frame.Tag, pixels: rgba.Pix}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) post(message uintptr) bool {
|
||||
v.postMu.Lock()
|
||||
defer v.postMu.Unlock()
|
||||
if v.closed {
|
||||
return false
|
||||
}
|
||||
ok, _, _ := viewerPostMessage.Call(v.hwnd, message, 0, 0)
|
||||
return ok != 0
|
||||
}
|
||||
|
||||
func (v *nativeViewer) stopPosting() {
|
||||
v.postMu.Lock()
|
||||
v.closed = true
|
||||
v.postMu.Unlock()
|
||||
}
|
||||
|
||||
func (v *nativeViewer) destroy() {
|
||||
v.stopPosting()
|
||||
viewerDestroyWindow.Call(v.hwnd)
|
||||
}
|
||||
|
||||
func (v *nativeViewer) pollFrames(ctx context.Context) {
|
||||
timer := time.NewTimer(125 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if iconic, _, _ := viewerIsIconic.Call(v.hwnd); iconic == 0 {
|
||||
frame, err := v.options.Frame(ctx)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// A failed capture keeps the last painted frame until the next poll.
|
||||
if err == nil {
|
||||
if bitmap := makeViewerBitmap(frame); bitmap != nil {
|
||||
v.latest.Store(bitmap)
|
||||
if !v.pending.Swap(true) && !v.post(viewerWmFrame) {
|
||||
v.pending.Store(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
timer.Reset(125 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func fitViewerFrame(width, height, frameWidth, frameHeight int) image.Rectangle {
|
||||
if width <= 0 || height <= 0 || frameWidth <= 0 || frameHeight <= 0 {
|
||||
return image.Rectangle{}
|
||||
}
|
||||
w, h := width, height
|
||||
if width*frameHeight <= height*frameWidth {
|
||||
h = max(1, width*frameHeight/frameWidth)
|
||||
} else {
|
||||
w = max(1, height*frameWidth/frameHeight)
|
||||
}
|
||||
x, y := (width-w)/2, (height-h)/2
|
||||
return image.Rect(x, y, x+w, y+h)
|
||||
}
|
||||
|
||||
func (v *nativeViewer) paint() {
|
||||
var ps viewerPaint
|
||||
dc, _, _ := viewerBeginPaint.Call(v.hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||
defer viewerEndPaint.Call(v.hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||
if dc == 0 {
|
||||
return
|
||||
}
|
||||
var client viewerRect
|
||||
viewerGetClientRect.Call(v.hwnd, uintptr(unsafe.Pointer(&client)))
|
||||
brush, _, _ := viewerGetStockObject.Call(4) // BLACK_BRUSH
|
||||
bitmap := v.latest.Load()
|
||||
if bitmap == nil {
|
||||
viewerFillRect.Call(dc, uintptr(unsafe.Pointer(&client)), brush)
|
||||
return
|
||||
}
|
||||
area := fitViewerFrame(int(client.right), int(client.bottom), bitmap.width, bitmap.height)
|
||||
if area.Empty() {
|
||||
return
|
||||
}
|
||||
for _, bar := range [...]viewerRect{
|
||||
{0, 0, client.right, int32(area.Min.Y)},
|
||||
{0, int32(area.Max.Y), client.right, client.bottom},
|
||||
{0, int32(area.Min.Y), int32(area.Min.X), int32(area.Max.Y)},
|
||||
{int32(area.Max.X), int32(area.Min.Y), client.right, int32(area.Max.Y)},
|
||||
} {
|
||||
if bar.right > bar.left && bar.bottom > bar.top {
|
||||
viewerFillRect.Call(dc, uintptr(unsafe.Pointer(&bar)), brush)
|
||||
}
|
||||
}
|
||||
header := viewerBitmapHeader{
|
||||
size: uint32(unsafe.Sizeof(viewerBitmapHeader{})), width: int32(bitmap.width), height: -int32(bitmap.height),
|
||||
planes: 1, bits: 32,
|
||||
}
|
||||
viewerSetStretchMode.Call(dc, 3) // COLORONCOLOR
|
||||
rows, _, _ := viewerStretchDIBits.Call(
|
||||
dc, uintptr(area.Min.X), uintptr(area.Min.Y), uintptr(area.Dx()), uintptr(area.Dy()),
|
||||
0, 0, uintptr(bitmap.width), uintptr(bitmap.height),
|
||||
uintptr(unsafe.Pointer(&bitmap.pixels[0])), uintptr(unsafe.Pointer(&header)), 0, 0x00cc0020, // SRCCOPY
|
||||
)
|
||||
if int32(rows) != -1 && rows != 0 {
|
||||
v.displayed, v.imageRect = bitmap, area
|
||||
}
|
||||
}
|
||||
|
||||
func viewerWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintptr {
|
||||
if message == viewerWmNCCalcSize {
|
||||
fitViewerMaximizedClient(hwnd, lParam)
|
||||
return 0
|
||||
}
|
||||
entry, ok := viewerWindows.Load(hwnd)
|
||||
if !ok {
|
||||
result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam)
|
||||
return result
|
||||
}
|
||||
v := entry.(*nativeViewer)
|
||||
switch message {
|
||||
case viewerWmNCHitTest:
|
||||
return viewerFrameHitTest(hwnd, viewerMessagePoint(lParam))
|
||||
case viewerWmNCPaint:
|
||||
return 0
|
||||
case viewerWmNCActivate:
|
||||
// Let Windows update activation without repainting the nonclient frame.
|
||||
result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, ^uintptr(0))
|
||||
return result
|
||||
case viewerWmFrame:
|
||||
v.pending.Store(false)
|
||||
viewerInvalidateRect.Call(hwnd, 0, 0)
|
||||
case viewerWmSize:
|
||||
// Release a guest drag before changing its coordinate map. A system resize owns its own capture.
|
||||
if v.holdingButton() {
|
||||
v.releaseButtons()
|
||||
v.releaseCaptureIfIdle()
|
||||
}
|
||||
v.imageRect = image.Rectangle{}
|
||||
viewerInvalidateRect.Call(hwnd, 0, 0)
|
||||
case viewerWmPaint:
|
||||
v.paint()
|
||||
case viewerWmErase:
|
||||
return 1
|
||||
case viewerWmClose:
|
||||
v.releaseInputs()
|
||||
v.emit(ViewerEvent{Kind: ViewerClose})
|
||||
v.destroy()
|
||||
case viewerWmStop:
|
||||
v.destroy()
|
||||
case viewerWmDestroy:
|
||||
v.stopPosting()
|
||||
v.releaseInputs()
|
||||
viewerPostQuitMessage.Call(0)
|
||||
case viewerWmSetFocus:
|
||||
v.emit(ViewerEvent{Kind: ViewerFocus, FrameTag: v.frameTag(), Down: true})
|
||||
case viewerWmKillFocus:
|
||||
v.releaseInputs()
|
||||
v.emit(ViewerEvent{Kind: ViewerFocus, FrameTag: v.frameTag()})
|
||||
case viewerWmCaptureChanged:
|
||||
v.releaseButtons()
|
||||
case viewerWmMouseMove:
|
||||
v.pointer(ViewerMouseMove, viewerMessagePoint(lParam), 0, 0, false)
|
||||
case viewerWmLeftDown, viewerWmLeftUp:
|
||||
point := viewerMessagePoint(lParam)
|
||||
if message == viewerWmLeftDown {
|
||||
if state, _, _ := viewerGetKeyState.Call(0x12); int16(state) < 0 && v.moveWindow(point) { // VK_MENU
|
||||
return 0
|
||||
}
|
||||
}
|
||||
v.pointer(ViewerMouseButton, point, 0, 0, message == viewerWmLeftDown)
|
||||
case viewerWmRightDown, viewerWmRightUp:
|
||||
v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 1, 0, message == viewerWmRightDown)
|
||||
case viewerWmMiddleDown, viewerWmMiddleUp:
|
||||
v.pointer(ViewerMouseButton, viewerMessagePoint(lParam), 2, 0, message == viewerWmMiddleDown)
|
||||
case viewerWmMouseWheel:
|
||||
point := viewerMessagePoint(lParam)
|
||||
if ok, _, _ := viewerScreenToClient.Call(hwnd, uintptr(unsafe.Pointer(&point))); ok != 0 {
|
||||
v.pointer(ViewerMouseWheel, point, 0, int(int16(wParam>>16)), false)
|
||||
}
|
||||
case viewerWmSysKeyDown, viewerWmSysKeyUp, viewerWmKeyDown, viewerWmKeyUp:
|
||||
if message == viewerWmSysKeyDown && lParam&(1<<29) != 0 {
|
||||
switch wParam {
|
||||
case 0x73: // Alt+F4
|
||||
result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam)
|
||||
return result
|
||||
case ' ': // Alt+Space opens the native system menu, including Move.
|
||||
v.releaseInputs()
|
||||
result, _, _ := viewerDefWindowProc.Call(hwnd, viewerWmSysCommand, 0xf100, ' ') // SC_KEYMENU
|
||||
return result
|
||||
}
|
||||
}
|
||||
v.key(uint32(wParam), message == viewerWmKeyDown || message == viewerWmSysKeyDown)
|
||||
default:
|
||||
result, _, _ := viewerDefWindowProc.Call(hwnd, uintptr(message), wParam, lParam)
|
||||
return result
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (v *nativeViewer) moveWindow(point viewerPoint) bool {
|
||||
if !image.Pt(int(point.x), int(point.y)).In(v.imageRect) ||
|
||||
int(point.y)-v.imageRect.Min.Y >= int(viewerScale(v.hwnd, 36)) {
|
||||
return false
|
||||
}
|
||||
if ok, _, _ := viewerClientToScreen.Call(v.hwnd, uintptr(unsafe.Pointer(&point))); ok == 0 {
|
||||
return false
|
||||
}
|
||||
v.releaseInputs()
|
||||
packed := uintptr(uint16(point.x)) | uintptr(uint16(point.y))<<16
|
||||
viewerDefWindowProc.Call(v.hwnd, viewerWmNCLeftDown, viewerHTCaption, packed)
|
||||
return true
|
||||
}
|
||||
|
||||
func viewerMessagePoint(lParam uintptr) viewerPoint {
|
||||
return viewerPoint{int32(int16(lParam)), int32(int16(lParam >> 16))}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) emit(ev ViewerEvent) {
|
||||
if v.options.Input != nil {
|
||||
v.options.Input(ev)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) frameTag() uint64 {
|
||||
if v.displayed != nil {
|
||||
return v.displayed.tag
|
||||
}
|
||||
if first := v.latest.Load(); first != nil {
|
||||
return first.tag
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (v *nativeViewer) pointer(kind ViewerEventKind, pt viewerPoint, button, delta int, down bool) {
|
||||
frame, area := v.displayed, v.imageRect
|
||||
if frame == nil || area.Empty() {
|
||||
return
|
||||
}
|
||||
x, y := int(pt.x), int(pt.y)
|
||||
inside := image.Pt(x, y).In(area)
|
||||
anyButton := v.holdingButton()
|
||||
if !inside && !(kind == ViewerMouseMove && anyButton) &&
|
||||
!(kind == ViewerMouseButton && !down && v.buttons[button]) {
|
||||
return
|
||||
}
|
||||
ev := ViewerEvent{
|
||||
Kind: kind, FrameTag: frame.tag, Width: frame.width, Height: frame.height,
|
||||
X: max(0, min(x-area.Min.X, area.Dx()-1)) * frame.width / area.Dx(),
|
||||
Y: max(0, min(y-area.Min.Y, area.Dy()-1)) * frame.height / area.Dy(),
|
||||
Button: button, Delta: delta, Down: down,
|
||||
}
|
||||
if kind == ViewerMouseButton {
|
||||
if !down && !v.buttons[button] {
|
||||
return
|
||||
}
|
||||
v.buttons[button] = down
|
||||
if down && !anyButton {
|
||||
viewerSetCapture.Call(v.hwnd)
|
||||
}
|
||||
}
|
||||
v.lastMouse = ev
|
||||
v.emit(ev)
|
||||
if kind == ViewerMouseButton && !down {
|
||||
v.releaseCaptureIfIdle()
|
||||
}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) key(key uint32, down bool) {
|
||||
if down {
|
||||
v.keys[key] = true
|
||||
} else {
|
||||
if !v.keys[key] {
|
||||
return
|
||||
}
|
||||
delete(v.keys, key)
|
||||
}
|
||||
v.emit(ViewerEvent{Kind: ViewerKey, FrameTag: v.frameTag(), VirtualKey: key, Down: down})
|
||||
}
|
||||
|
||||
func (v *nativeViewer) releaseButtons() {
|
||||
for button, down := range v.buttons {
|
||||
if down {
|
||||
v.buttons[button] = false
|
||||
ev := v.lastMouse
|
||||
ev.Kind, ev.Button, ev.Down, ev.Delta = ViewerMouseButton, button, false, 0
|
||||
v.emit(ev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) releaseCaptureIfIdle() {
|
||||
if !v.holdingButton() {
|
||||
if hwnd, _, _ := viewerGetCapture.Call(); hwnd == v.hwnd {
|
||||
viewerReleaseCapture.Call()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (v *nativeViewer) holdingButton() bool {
|
||||
return v.buttons[0] || v.buttons[1] || v.buttons[2]
|
||||
}
|
||||
|
||||
func (v *nativeViewer) releaseInputs() {
|
||||
v.releaseButtons()
|
||||
v.releaseCaptureIfIdle()
|
||||
for key := range v.keys {
|
||||
v.key(key, false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build windows
|
||||
|
||||
package appwindow
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestViewerResizeHit(t *testing.T) {
|
||||
bounds := viewerRect{left: -900, top: -40, right: -500, bottom: 260}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
point viewerPoint
|
||||
want uintptr
|
||||
}{
|
||||
{"top left", viewerPoint{-900, -40}, viewerHTTopLeft},
|
||||
{"top", viewerPoint{-700, -38}, viewerHTTop},
|
||||
{"top right", viewerPoint{-501, -38}, viewerHTTopRight},
|
||||
{"right", viewerPoint{-501, 100}, viewerHTRight},
|
||||
{"bottom right", viewerPoint{-501, 259}, viewerHTBottomRight},
|
||||
{"bottom", viewerPoint{-700, 259}, viewerHTBottom},
|
||||
{"bottom left", viewerPoint{-899, 259}, viewerHTBottomLeft},
|
||||
{"left", viewerPoint{-899, 100}, viewerHTLeft},
|
||||
{"guest title controls", viewerPoint{-879, -20}, viewerHTClient},
|
||||
{"outside", viewerPoint{-901, 100}, viewerHTClient},
|
||||
} {
|
||||
if got := viewerResizeHit(bounds, tc.point, 8); got != tc.want {
|
||||
t.Errorf("%s: got hit %d, want %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,17 @@ func (m *Manager) Screendump(ctx context.Context, vmDir, path string) (string, e
|
||||
return format, err
|
||||
}
|
||||
|
||||
// ScreendumpDisplay selects a specific guest display under the same console lock.
|
||||
func (m *Manager) ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error) {
|
||||
var format string
|
||||
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
var err error
|
||||
format, err = qmp.ScreendumpDisplay(conn, path, device, head)
|
||||
return err
|
||||
})
|
||||
return format, err
|
||||
}
|
||||
|
||||
// TypeText sends US-layout key strokes as one serialized console job.
|
||||
func (m *Manager) TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
|
||||
strokes, err := qmp.Strokes(text)
|
||||
@@ -124,7 +135,7 @@ func (m *Manager) SendPasteShortcut(ctx context.Context, vmDir string) error {
|
||||
|
||||
func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, error) {
|
||||
var available bool
|
||||
err := m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
err := m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
mice, err := qmp.QueryMice(conn)
|
||||
if err == nil {
|
||||
available = qmp.HasCurrentAbsoluteMouse(mice)
|
||||
@@ -135,17 +146,35 @@ func (m *Manager) PointerAvailable(ctx context.Context, vmDir string) (bool, err
|
||||
}
|
||||
|
||||
func (m *Manager) MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error {
|
||||
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.MouseMove(conn, x, y, width, height)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Manager) MouseButton(ctx context.Context, vmDir, button string, down bool) error {
|
||||
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.MouseButton(conn, button, down)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Manager) MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.MouseButtonAt(conn, x, y, width, height, button, down)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Manager) SendKey(ctx context.Context, vmDir, key string, down bool) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.SendKey(conn, key, down)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Manager) ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.ReleaseInputs(conn, keys, buttons)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
|
||||
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
if err := qmp.MouseButton(conn, button, true); err != nil {
|
||||
@@ -173,7 +202,7 @@ func (m *Manager) MouseClick(ctx context.Context, vmDir, button string) error {
|
||||
}
|
||||
|
||||
func (m *Manager) MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error {
|
||||
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return m.withCancelableConn(ctx, vmDir, func(conn qmpSession) error {
|
||||
return qmp.MouseScroll(conn, delta, horizontal)
|
||||
})
|
||||
}
|
||||
@@ -242,6 +271,16 @@ func normalizeModifier(modifier string) (string, error) {
|
||||
}
|
||||
|
||||
func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
|
||||
return m.withConnMode(ctx, vmDir, false, operation)
|
||||
}
|
||||
|
||||
// Single-command operations can close their connection on cancellation.
|
||||
// Multi-command jobs need it to release any held guest keys or buttons.
|
||||
func (m *Manager) withCancelableConn(ctx context.Context, vmDir string, operation func(qmpSession) error) error {
|
||||
return m.withConnMode(ctx, vmDir, true, operation)
|
||||
}
|
||||
|
||||
func (m *Manager) withConnMode(ctx context.Context, vmDir string, cancelIO bool, operation func(qmpSession) error) error {
|
||||
if operation == nil {
|
||||
return errors.New("console operation is unavailable")
|
||||
}
|
||||
@@ -274,9 +313,12 @@ func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmp
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = conn.Close()
|
||||
}()
|
||||
closeConn := sync.OnceFunc(func() { _ = conn.Close() })
|
||||
defer closeConn()
|
||||
if cancelIO {
|
||||
stopCancel := context.AfterFunc(ctx, closeConn)
|
||||
defer stopCancel()
|
||||
}
|
||||
return operation(conn)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const (
|
||||
activeWindowPath = "/v1/active-window"
|
||||
maxWindowReportSize = 2048
|
||||
maxDisplayDimension = 16384
|
||||
)
|
||||
|
||||
// ActiveWindow describes the frontmost eligible window in the guest's main
|
||||
// display coordinate system. Bounds are in screen points with a top-left origin.
|
||||
type ActiveWindow struct {
|
||||
ID uint32 `json:"id"`
|
||||
AppName string `json:"app_name"`
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
DisplayWidth int `json:"display_width"`
|
||||
DisplayHeight int `json:"display_height"`
|
||||
}
|
||||
|
||||
type windowReport struct {
|
||||
window *ActiveWindow
|
||||
receivedAt time.Time
|
||||
}
|
||||
|
||||
// SetWindowReporting changes the transient reporting request for a registered VM.
|
||||
func (s *Server) SetWindowReporting(vmKey string, enabled bool) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
vm := s.vms[normalizeVMRegistryKey(vmKey)]
|
||||
if vm == nil {
|
||||
return false
|
||||
}
|
||||
if (vm.windowReportGen != 0) == enabled {
|
||||
return true
|
||||
}
|
||||
vm.windowReportGen = 0
|
||||
vm.windowReport = windowReport{}
|
||||
if enabled {
|
||||
s.nextWindowGen++
|
||||
vm.windowReportGen = s.nextWindowGen
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ActiveWindow returns the latest eligible window if it arrived within maxAge.
|
||||
func (s *Server) ActiveWindow(vmKey string, maxAge time.Duration) (ActiveWindow, bool) {
|
||||
if maxAge <= 0 {
|
||||
return ActiveWindow{}, false
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
vm := s.vms[normalizeVMRegistryKey(vmKey)]
|
||||
if vm == nil || vm.windowReportGen == 0 || vm.windowReport.window == nil ||
|
||||
time.Since(vm.windowReport.receivedAt) > maxAge {
|
||||
return ActiveWindow{}, false
|
||||
}
|
||||
return *vm.windowReport.window, true
|
||||
}
|
||||
|
||||
func (w ActiveWindow) valid() bool {
|
||||
return w.ID != 0 && strings.TrimSpace(w.AppName) != "" && len(w.AppName) <= 256 &&
|
||||
strings.IndexFunc(w.AppName, unicode.IsControl) < 0 &&
|
||||
w.DisplayWidth > 0 && w.DisplayWidth <= maxDisplayDimension &&
|
||||
w.DisplayHeight > 0 && w.DisplayHeight <= maxDisplayDimension &&
|
||||
w.Width > 0 && w.Width <= maxDisplayDimension && w.Height > 0 && w.Height <= maxDisplayDimension &&
|
||||
w.X > -w.Width && w.X < w.DisplayWidth && w.Y > -w.Height && w.Y < w.DisplayHeight
|
||||
}
|
||||
|
||||
func (s *Server) handleActiveWindow(w http.ResponseWriter, r *http.Request) {
|
||||
vm := s.authenticateToken(bearerToken(r))
|
||||
if vm == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if vm.windowReportGen == 0 {
|
||||
http.Error(w, "window reporting is disabled", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if controller.SetReadDeadline(time.Now().Add(3*time.Second)) == nil {
|
||||
defer controller.SetReadDeadline(time.Time{})
|
||||
}
|
||||
var req struct {
|
||||
Generation uint64 `json:"generation"`
|
||||
Window *ActiveWindow `json:"window"`
|
||||
}
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxWindowReportSize))
|
||||
dec.DisallowUnknownFields()
|
||||
err := dec.Decode(&req)
|
||||
if err == nil {
|
||||
err = dec.Decode(&struct{}{})
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
} else if err == nil {
|
||||
err = errors.New("multiple JSON values")
|
||||
}
|
||||
}
|
||||
if err != nil || (req.Window != nil && !req.Window.valid()) {
|
||||
var sizeErr *http.MaxBytesError
|
||||
if errors.As(err, &sizeErr) {
|
||||
http.Error(w, "window report too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
http.Error(w, "invalid window report", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
cur := s.vms[vm.key]
|
||||
current := cur != nil && cur.token == vm.token && vm.windowReportGen == req.Generation &&
|
||||
cur.windowReportGen == req.Generation
|
||||
if current {
|
||||
cur.windowReport = windowReport{window: req.Window, receivedAt: time.Now()}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !current {
|
||||
http.Error(w, "window report expired", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
ObjC.import('AppKit')
|
||||
ObjC.import('CoreFoundation')
|
||||
ObjC.import('CoreGraphics')
|
||||
ObjC.import('Foundation')
|
||||
|
||||
function overlaps(a, b) {
|
||||
return a.X < b.X + b.Width && b.X < a.X + a.Width && a.Y < b.Y + b.Height && b.Y < a.Y + a.Height
|
||||
}
|
||||
|
||||
function activeWindow() {
|
||||
// QMP captures the main display. The experimental mode requires a single display.
|
||||
if ($.NSScreen.screens.count !== 1) return null
|
||||
const display = $.CGDisplayBounds($.CGMainDisplayID())
|
||||
const displayWidth = Math.round(display.size.width)
|
||||
const displayHeight = Math.round(display.size.height)
|
||||
if (!(displayWidth > 0 && displayHeight > 0)) return null
|
||||
|
||||
const app = $.NSWorkspace.sharedWorkspace.frontmostApplication
|
||||
if (!app || app.isNil() || app.activationPolicy !== $.NSApplicationActivationPolicyRegular) return null
|
||||
const options = $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements
|
||||
const raw = $.CGWindowListCopyWindowInfo(options, 0)
|
||||
if (!raw) return null
|
||||
let windows
|
||||
try {
|
||||
windows = ObjC.deepUnwrap(ObjC.castRefToObject(raw))
|
||||
} finally {
|
||||
$.CFRelease(raw)
|
||||
}
|
||||
if (!Array.isArray(windows)) return null
|
||||
const appPID = app.processIdentifier
|
||||
const foreignAbove = []
|
||||
for (const window of windows) {
|
||||
const bounds = window && window.kCGWindowBounds
|
||||
if (!bounds || !(window.kCGWindowAlpha > 0.01)) continue
|
||||
if (window.kCGWindowOwnerPID !== appPID) {
|
||||
foreignAbove.push(bounds)
|
||||
continue
|
||||
}
|
||||
if (window.kCGWindowLayer !== 0 || !(bounds.Width >= 32 && bounds.Height >= 32)) continue
|
||||
const x = Math.floor(bounds.X - display.origin.x)
|
||||
const y = Math.floor(bounds.Y - display.origin.y)
|
||||
const width = Math.ceil(bounds.X + bounds.Width - display.origin.x) - x
|
||||
const height = Math.ceil(bounds.Y + bounds.Height - display.origin.y) - y
|
||||
if (x >= displayWidth || y >= displayHeight || x + width <= 0 || y + height <= 0) continue
|
||||
const id = window.kCGWindowNumber
|
||||
if (!Number.isInteger(id) || id <= 0 || id > 0xFFFFFFFF) continue
|
||||
if (foreignAbove.some(above => overlaps(above, bounds))) return null
|
||||
const label = app.localizedName
|
||||
const appName = ((label && !label.isNil() ? label.js : window.kCGWindowOwnerName) || '')
|
||||
.replace(/[\x00-\x1f\x7f-\x9f]/g, '').trim().slice(0, 64)
|
||||
return {id, app_name: appName || 'Mac App', x, y, width, height, display_width: displayWidth,
|
||||
display_height: displayHeight}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function postReport(url, token, generation, window) {
|
||||
const config = [
|
||||
'url = ' + JSON.stringify(url),
|
||||
'header = ' + JSON.stringify('Authorization: Bearer ' + token),
|
||||
'header = "Content-Type: application/json"',
|
||||
'data-raw = ' + JSON.stringify(JSON.stringify({generation, window})),
|
||||
]
|
||||
const task = $.NSTask.alloc.init
|
||||
const input = $.NSPipe.pipe
|
||||
const output = $.NSPipe.pipe
|
||||
task.launchPath = '/usr/bin/curl'
|
||||
task.arguments = $(['-q', '--noproxy', '*', '-sm', '1', '-o', '/dev/null', '-w', '%{http_code}', '-K', '-'])
|
||||
task.standardInput = input
|
||||
task.standardOutput = output
|
||||
task.standardError = $.NSFileHandle.fileHandleWithNullDevice
|
||||
task.launch
|
||||
try { input.fileHandleForWriting.writeData($(config.join('\n') + '\n').dataUsingEncoding($.NSUTF8StringEncoding)) }
|
||||
finally { input.fileHandleForWriting.closeFile }
|
||||
const data = output.fileHandleForReading.readDataToEndOfFile
|
||||
task.waitUntilExit
|
||||
return task.terminationStatus === 0 ? Number($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js) : 0
|
||||
}
|
||||
|
||||
function run(args) {
|
||||
const generation = Number(args[0])
|
||||
if (!Number.isSafeInteger(generation) || generation <= 0) return
|
||||
const env = $.NSProcessInfo.processInfo.environment
|
||||
const hostValue = env.objectForKey($('REIMS_HOST_URL'))
|
||||
const tokenValue = env.objectForKey($('REIMS_TOKEN'))
|
||||
const host = hostValue && !hostValue.isNil() ? hostValue.js.replace(/\/+$/, '') : ''
|
||||
const token = tokenValue && !tokenValue.isNil() ? tokenValue.js : ''
|
||||
if (!/^http:\/\/(?:[a-z0-9.-]+|\[[0-9a-f:]+\]):\d{1,5}$/i.test(host) || !token || /[\r\n\0]/.test(token)) return
|
||||
const url = host + '/v1/active-window'
|
||||
while (true) {
|
||||
let window
|
||||
try { window = activeWindow() } catch (_) { window = null }
|
||||
let status
|
||||
try { status = postReport(url, token, generation, window) } catch (_) { status = 0 }
|
||||
if (status === 401 || status === 403 || status === 409) return
|
||||
delay(status === 204 ? 0.25 : 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActiveWindowReporting(t *testing.T) {
|
||||
srv := NewTransportServer(&memClipboard{})
|
||||
srv.RegisterVM(VMConfig{VMName: "mac-one", Token: "token-one"})
|
||||
srv.RegisterVM(VMConfig{VMName: "mac-two", Token: "token-two"})
|
||||
port, err := srv.Start(-1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = srv.Close(context.Background()) })
|
||||
base := "http://" + net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
|
||||
httpClient := &http.Client{Timeout: 5 * time.Second}
|
||||
request := func(method, path, token, body string, wantStatus int) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(method, base+path, strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
if resp.StatusCode != wantStatus {
|
||||
t.Fatalf("%s %s returned %d, want %d", method, path, resp.StatusCode, wantStatus)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
generation := func(token string) uint64 {
|
||||
t.Helper()
|
||||
var cfg struct {
|
||||
Generation uint64 `json:"window_report_generation"`
|
||||
}
|
||||
resp := request(http.MethodGet, "/v1/config", token, "", http.StatusOK)
|
||||
defer resp.Body.Close()
|
||||
if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cfg.Generation
|
||||
}
|
||||
report := func(gen uint64, window *ActiveWindow) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(struct {
|
||||
Generation uint64 `json:"generation"`
|
||||
Window *ActiveWindow `json:"window"`
|
||||
}{gen, window})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
request(http.MethodPost, activeWindowPath, "", "", http.StatusUnauthorized)
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(0, nil), http.StatusForbidden)
|
||||
if got := generation("token-one"); got != 0 {
|
||||
t.Fatalf("generation = %d before opt-in", got)
|
||||
}
|
||||
if !srv.SetWindowReporting("mac-one", true) {
|
||||
t.Fatal("could not opt in")
|
||||
}
|
||||
gen := generation("token-one")
|
||||
if gen == 0 || generation("token-two") != 0 {
|
||||
t.Fatal("reporting opt-in did not stay within the specified VM")
|
||||
}
|
||||
request(http.MethodGet, activeWindowPath, "token-one", "", http.StatusMethodNotAllowed)
|
||||
request(http.MethodPost, activeWindowPath, "token-two", report(gen, nil), http.StatusForbidden)
|
||||
request(http.MethodPost, activeWindowPath, "token-one", strings.Repeat(" ", maxWindowReportSize+1), http.StatusRequestEntityTooLarge)
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(gen, nil)+"{}", http.StatusBadRequest)
|
||||
bad := ActiveWindow{ID: 9, AppName: "Safari", X: 16384, Width: 700, Height: 600, DisplayWidth: 1920, DisplayHeight: 1080}
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(gen, &bad), http.StatusBadRequest)
|
||||
|
||||
window := ActiveWindow{ID: 25, AppName: "Safari", X: -20, Y: 31, Width: 700, Height: 600, DisplayWidth: 1920, DisplayHeight: 1080}
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(gen, &window), http.StatusNoContent)
|
||||
if got, ok := srv.ActiveWindow("mac-one", time.Second); !ok || got != window {
|
||||
t.Fatalf("active window = %+v, %t", got, ok)
|
||||
}
|
||||
func() {
|
||||
srv.mu.Lock()
|
||||
defer srv.mu.Unlock()
|
||||
vm := srv.vms[normalizeVMRegistryKey("mac-one")]
|
||||
if vm == nil {
|
||||
t.Fatal("registered VM was not found")
|
||||
}
|
||||
vm.windowReport.receivedAt = time.Now().Add(-2 * time.Second)
|
||||
}()
|
||||
if _, ok := srv.ActiveWindow("mac-one", time.Second); ok {
|
||||
t.Fatal("report older than maxAge was accepted")
|
||||
}
|
||||
if _, ok := srv.ActiveWindow("mac-two", time.Second); ok {
|
||||
t.Fatal("another VM received the report")
|
||||
}
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(gen, nil), http.StatusNoContent)
|
||||
if _, ok := srv.ActiveWindow("mac-one", time.Second); ok {
|
||||
t.Fatal("null report failed to clear the window")
|
||||
}
|
||||
|
||||
srv.SetWindowReporting("mac-one", false)
|
||||
srv.SetWindowReporting("mac-one", true)
|
||||
nextGen := generation("token-one")
|
||||
if nextGen == 0 || nextGen == gen {
|
||||
t.Fatal("reporting reused the previous generation")
|
||||
}
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(gen, &window), http.StatusConflict)
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(nextGen, &window), http.StatusNoContent)
|
||||
srv.RegisterVM(VMConfig{VMName: "mac-one", Token: "rotated-token"})
|
||||
if _, ok := srv.ActiveWindow("mac-one", time.Second); ok || generation("rotated-token") != 0 {
|
||||
t.Fatal("token rotation retained the previous window reporting session")
|
||||
}
|
||||
request(http.MethodPost, activeWindowPath, "token-one", report(nextGen, &window), http.StatusUnauthorized)
|
||||
}
|
||||
@@ -76,6 +76,11 @@ func TestGuestAgentClipboardScript(t *testing.T) {
|
||||
cases []string
|
||||
}{
|
||||
{"download", []string{"failed_png", "failed_text", "missing_hash", "reencoded_png"}},
|
||||
{"paste_ready", []string{
|
||||
"paste_ack_text", "paste_ack_preapplied", "paste_ack_local_change", "paste_ack_unmarked",
|
||||
"paste_ack_png", "paste_ack_unstable_png", "paste_ack_without_request",
|
||||
"paste_recheck_guest_owned", "paste_recheck_local_change", "paste_recheck_inject", "paste_recheck_drop",
|
||||
}},
|
||||
{"download_during_copy", []string{
|
||||
"guest_changes_during_get", "cold_guest_changes_during_get", "cold_lock_during_get", "repeat_host_copy",
|
||||
}},
|
||||
@@ -231,6 +236,10 @@ post_code=200
|
||||
post_hash=C
|
||||
post_seq=9
|
||||
check_post_base=0
|
||||
offer_ack=0
|
||||
offer_recheck=0
|
||||
ack_hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
ack_nonce=ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
|
||||
# MSYS cannot apply RLIMIT_FSIZE. The fixture still verifies the archive and HTTP flow.
|
||||
case "$(uname -s)" in
|
||||
@@ -410,6 +419,11 @@ curl() {
|
||||
accept=""
|
||||
output=""
|
||||
base=""
|
||||
request_ack=""
|
||||
acknowledged_seq=""
|
||||
acknowledged_hash=""
|
||||
acknowledged_generation=""
|
||||
acknowledged_request=""
|
||||
body=""
|
||||
archive_upload=""
|
||||
url=""
|
||||
@@ -423,6 +437,11 @@ curl() {
|
||||
-H)
|
||||
case "$2" in
|
||||
'X-Clip-Base-Seq: '*) base="$2" ;;
|
||||
'X-Reims-Clipboard-Ack: '*) request_ack="${2#*: }" ;;
|
||||
'X-Clip-Seq: '*) acknowledged_seq="${2#*: }" ;;
|
||||
'X-Clip-Hash: '*) acknowledged_hash="${2#*: }" ;;
|
||||
'X-Reims-Clipboard-Generation: '*) acknowledged_generation="${2#*: }" ;;
|
||||
'X-Reims-Clipboard-Request: '*) acknowledged_request="${2#*: }" ;;
|
||||
'Accept: '*) accept="$2" ;;
|
||||
esac
|
||||
shift
|
||||
@@ -466,6 +485,13 @@ curl() {
|
||||
fi
|
||||
return
|
||||
;;
|
||||
*/v1/clipboard/applied)
|
||||
[ ! -d "$CLIP_LOCK" ] || exit 1
|
||||
expect "$method/$acknowledged_seq/$acknowledged_hash/$acknowledged_generation/$acknowledged_request" \
|
||||
"POST/$get_seq/$get_hash/14/$ack_nonce"
|
||||
printf 'ACK %s\n' "$url" >> calls
|
||||
return
|
||||
;;
|
||||
esac
|
||||
[ ! -d "$CLIP_LOCK" ] || exit 1
|
||||
if [ -n "$archive_upload" ]; then
|
||||
@@ -509,6 +535,13 @@ curl() {
|
||||
: > "$headers"
|
||||
else
|
||||
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers"
|
||||
if [ "$offer_ack/$get_code" = 1/200 ]; then
|
||||
expect "$request_ack" 1
|
||||
printf 'X-Reims-Clipboard-Ack: 1\r\nX-Reims-Clipboard-Generation: 14\r\nX-Reims-Clipboard-Request: %s\r\n' "$ack_nonce" >> "$headers"
|
||||
if [ "$offer_recheck" = 1 ]; then
|
||||
printf 'X-Reims-Clipboard-Recheck: 1\r\n' >> "$headers"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
printf '%s' "$get_value" > "$output"
|
||||
if [ "$fail_during_get" = 1 ]; then
|
||||
@@ -579,7 +612,10 @@ case "$1" in
|
||||
host_files_failed_write) : > test-fail-file-write ;;
|
||||
host_files_partial_write) : > test-partial-file-write ;;
|
||||
esac
|
||||
if [ "$1" != host_files_sync_no_echo ]; then
|
||||
if [ "$1" = host_files_sync_no_echo ]; then
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
else
|
||||
printf '%s\n' '{"changeCount":17,"items":[{"public.utf8-plain-text":"A"}]}' > test-pasteboard.json
|
||||
fi
|
||||
sync_clipboard
|
||||
@@ -589,7 +625,7 @@ case "$1" in
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
exit 0
|
||||
fi
|
||||
expect "$last_server_hash" B
|
||||
expect "$last_server_hash" "$get_hash"
|
||||
expect "$synced_local_cc/$synced_local_kind" 2/files
|
||||
expect "$(read_local_clipboard readback)" files
|
||||
expect "$(awk 'END {print NR}' readback)" 2
|
||||
@@ -598,12 +634,14 @@ a%23note.txt'
|
||||
expect "$last_local_hash" "files:$(cat readback)"
|
||||
get_code=304
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,GET
|
||||
expect_call -Fx 'GET http://stub/v1/clipboard?since=B&wait=2&accept=image,files&since_seq=8'
|
||||
expect "$(methods)" GET,ACK,GET
|
||||
expect_call -Fx "GET http://stub/v1/clipboard?since=$get_hash&wait=2&accept=image,files&since_seq=8"
|
||||
;;
|
||||
host_files_tar_fallback|host_files_tar_fallback_changed)
|
||||
flags=typed_files
|
||||
get_kind=files
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
get_value='{"drop_id":"clip-0123456789abcdef","items":["fallback.txt"]}'
|
||||
printf foreign > mount_owner
|
||||
printf '0 1048576\n' > clip_file_config
|
||||
@@ -612,13 +650,14 @@ a%23note.txt'
|
||||
tar -cf guest-fallback.tar fallback.txt
|
||||
if [ "$1" = host_files_tar_fallback_changed ]; then : > change_during_archive; fi
|
||||
sync_clipboard
|
||||
expect "$(methods)" GET,DOWNLOAD
|
||||
[ ! -d "$CLIP_LOCK" ]
|
||||
if [ "$1" = host_files_tar_fallback_changed ]; then
|
||||
expect "$(methods)" GET,DOWNLOAD
|
||||
expect "$last_server_hash/$file_retry_polls" /3
|
||||
expect "$(node -p 'require("./test-pasteboard.json").items[0]["public.utf8-plain-text"]')" 'new guest copy'
|
||||
else
|
||||
expect "$last_server_hash" B
|
||||
expect "$(methods)" GET,DOWNLOAD,ACK
|
||||
expect "$last_server_hash" "$get_hash"
|
||||
expect "$(cat "$CLIP_CACHE/clip-0123456789abcdef/fallback.txt")" fallback
|
||||
expect "$(read_local_clipboard readback)" files
|
||||
grep -q '/clip_cache/clip-0123456789abcdef/fallback.txt$' readback
|
||||
@@ -1033,6 +1072,53 @@ a%23note.txt'
|
||||
expect "$(methods)" GET,GET
|
||||
expect_call -F 'since=png:B&'
|
||||
;;
|
||||
paste_ack_*)
|
||||
offer_ack=1
|
||||
get_hash="$ack_hash"
|
||||
get_value="$get_hash"
|
||||
printf '10\n' > change_count
|
||||
case "$1" in
|
||||
paste_ack_preapplied) printf '%s' "$get_value" > local_value ;;
|
||||
paste_ack_local_change) flags=guest_change ;;
|
||||
paste_ack_unmarked) offer_ack=0 ;;
|
||||
paste_ack_png) get_kind=png ;;
|
||||
paste_ack_unstable_png) get_kind=png; flags=change_after_write ;;
|
||||
paste_ack_without_request) ack_nonce="" ;;
|
||||
esac
|
||||
sync_clipboard
|
||||
case "$1" in
|
||||
paste_ack_text|paste_ack_preapplied)
|
||||
expect "$(methods)/$(read_file local_value)" "GET,ACK/$get_value"
|
||||
if [ "$1" = paste_ack_preapplied ]; then [ ! -s copies ]; fi
|
||||
;;
|
||||
paste_ack_png) expect "$(methods)/$synced_local_kind" GET,ACK/png ;;
|
||||
paste_ack_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;;
|
||||
*) expect "$(methods)" GET ;;
|
||||
esac
|
||||
;;
|
||||
paste_recheck_*)
|
||||
offer_ack=1
|
||||
offer_recheck=1
|
||||
get_hash="$ack_hash"
|
||||
get_value="$get_hash"
|
||||
last_server_hash="$get_hash"
|
||||
last_server_seq="$get_seq"
|
||||
last_local_hash=guest-own
|
||||
printf '%s' "$last_local_hash" > local_value
|
||||
printf '10\n' > change_count
|
||||
case "$1" in
|
||||
paste_recheck_local_change) flags=guest_change ;;
|
||||
paste_recheck_inject) flags=inject_during_get ;;
|
||||
paste_recheck_drop) flags=drop_during_get ;;
|
||||
esac
|
||||
sync_clipboard
|
||||
[ ! -s copies ]
|
||||
case "$1" in
|
||||
paste_recheck_guest_owned) expect "$(methods)/$(read_file local_value)" GET,ACK/guest-own ;;
|
||||
paste_recheck_local_change) expect "$(methods)/$(read_file local_value)" GET/C ;;
|
||||
*) expect "$(methods)" GET ;;
|
||||
esac
|
||||
;;
|
||||
guest_changes_during_get|cold_guest_changes_during_get)
|
||||
if [ "$1" = guest_changes_during_get ]; then
|
||||
last_local_hash=A
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
clipboardAppliedPath = "/v1/clipboard/applied"
|
||||
clipboardAckHeader = "X-Reims-Clipboard-Ack"
|
||||
clipboardWindowHeader = "X-Reims-Clipboard-Generation"
|
||||
clipboardRequestHeader = "X-Reims-Clipboard-Request"
|
||||
clipboardRecheckHeader = "X-Reims-Clipboard-Recheck"
|
||||
)
|
||||
|
||||
type guestClipboardStamp struct {
|
||||
window uint64
|
||||
seq uint32
|
||||
hash string
|
||||
}
|
||||
|
||||
type guestClipboardDelivery struct {
|
||||
ticket string
|
||||
window uint64
|
||||
wanted guestClipboardStamp
|
||||
offered guestClipboardStamp
|
||||
applied guestClipboardStamp
|
||||
}
|
||||
|
||||
type guestClipboardOffer struct {
|
||||
ticket string
|
||||
window uint64
|
||||
}
|
||||
|
||||
// clipboardWindowVMLocked resolves an authenticated view of the active app
|
||||
// window. The caller holds s.mu for reading or writing.
|
||||
func (s *Server) clipboardWindowVMLocked(vm *registeredVM) *registeredVM {
|
||||
cur := s.vms[vm.key]
|
||||
if cur == nil || cur.token != vm.token || cur.windowReportGen == 0 {
|
||||
return nil
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
func (s *Server) windowClipboardActive(vm *registeredVM) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.clipboardWindowVMLocked(vm) != nil
|
||||
}
|
||||
|
||||
// offerGuestClipboard marks only snapshots currently requested by a paste.
|
||||
// For unchanged content, the caller asks the agent to recheck its own
|
||||
// pasteboard without overwriting a newer local selection.
|
||||
func (s *Server) offerGuestClipboard(vm *registeredVM, seq uint32, hash string, recheck, expired bool) guestClipboardOffer {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
cur := s.clipboardWindowVMLocked(vm)
|
||||
if cur == nil || !s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest() {
|
||||
return guestClipboardOffer{}
|
||||
}
|
||||
stamp := guestClipboardStamp{window: cur.windowReportGen, seq: seq, hash: hash}
|
||||
delivery := &cur.clipboardDelivery
|
||||
if delivery.ticket == "" || delivery.wanted != stamp || delivery.applied == stamp ||
|
||||
(recheck && delivery.offered == stamp && !expired) {
|
||||
return guestClipboardOffer{}
|
||||
}
|
||||
delivery.offered = stamp
|
||||
return guestClipboardOffer{ticket: delivery.ticket, window: delivery.window}
|
||||
}
|
||||
|
||||
func (s *Server) handleClipboardApplied(w http.ResponseWriter, r *http.Request) {
|
||||
vm := s.authenticate(r)
|
||||
if vm == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
seq, seqErr := strconv.ParseUint(r.Header.Get("X-Clip-Seq"), 10, 32)
|
||||
window, windowErr := strconv.ParseUint(r.Header.Get(clipboardWindowHeader), 10, 64)
|
||||
hash := r.Header.Get("X-Clip-Hash")
|
||||
ticket := r.Header.Get(clipboardRequestHeader)
|
||||
if seqErr != nil || windowErr != nil || window == 0 || len(hash) != 64 || ticket == "" || len(ticket) > 128 {
|
||||
http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, err := hex.DecodeString(hash); err != nil {
|
||||
http.Error(w, "invalid clipboard acknowledgment", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
stamp := guestClipboardStamp{window: window, seq: uint32(seq), hash: hash}
|
||||
hostSeq := s.clip.SequenceNumber()
|
||||
s.mu.Lock()
|
||||
cur := s.clipboardWindowVMLocked(vm)
|
||||
accepted := cur != nil && cur.windowReportGen == stamp.window && hostSeq == stamp.seq && cur.clipboardDelivery.ticket == ticket &&
|
||||
cur.clipboardDelivery.wanted == stamp && cur.clipboardDelivery.offered == stamp &&
|
||||
s.effectiveClipboardPolicyLocked(vm.key).allowsHostToGuest()
|
||||
changed := accepted && cur.clipboardDelivery.applied != stamp
|
||||
if changed {
|
||||
cur.clipboardDelivery.applied = stamp
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !accepted {
|
||||
http.Error(w, "clipboard acknowledgment expired", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
s.broadcastClipChange()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) beginGuestClipboardWait(vmKey string) (guestClipboardOffer, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
vm := s.vms[vmKey]
|
||||
if vm == nil || vm.windowReportGen == 0 || !s.effectiveClipboardPolicyLocked(vmKey).allowsHostToGuest() {
|
||||
return guestClipboardOffer{}, nil
|
||||
}
|
||||
if vm.clipboardDelivery.ticket != "" && vm.clipboardDelivery.window == vm.windowReportGen {
|
||||
return guestClipboardOffer{}, errors.New("guest clipboard paste is already pending")
|
||||
}
|
||||
request := guestClipboardOffer{ticket: rand.Text(), window: vm.windowReportGen}
|
||||
vm.clipboardDelivery = guestClipboardDelivery{ticket: request.ticket, window: request.window}
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (s *Server) endGuestClipboardWait(vmKey string, request guestClipboardOffer) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if vm := s.vms[vmKey]; vm != nil && vm.clipboardDelivery.ticket == request.ticket {
|
||||
vm.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForGuestClipboard waits until the active app window's guest agent has
|
||||
// applied the newest eligible host clipboard snapshot. Disabled or ineligible
|
||||
// clipboard data leaves the guest's ordinary Paste behavior available.
|
||||
func (s *Server) WaitForGuestClipboard(ctx context.Context, vmKey string) error {
|
||||
vmKey = normalizeVMRegistryKey(vmKey)
|
||||
request, err := s.beginGuestClipboardWait(vmKey)
|
||||
if err != nil || request.ticket == "" {
|
||||
return err
|
||||
}
|
||||
defer s.endGuestClipboardWait(vmKey, request)
|
||||
// The watcher also wakes the wait, but an independent sample covers a
|
||||
// concurrent change during server startup or registration teardown.
|
||||
tick := time.NewTicker(150 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
changed := s.clipNotifyChan()
|
||||
policy := s.EffectiveClipboardPolicy(vmKey)
|
||||
if !policy.allowsHostToGuest() {
|
||||
return nil
|
||||
}
|
||||
payload, seq, hash, err := s.readClipboardForSync(policy.SyncImages, policy.SyncFiles)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, hash = s.clipboardForGuest(vmKey, payload, seq, hash, policy.SyncFiles, policy.SyncImages, policy.MaxImageBytes)
|
||||
stamp := guestClipboardStamp{window: request.window, seq: seq, hash: hash}
|
||||
if seq != s.clip.SequenceNumber() {
|
||||
continue
|
||||
}
|
||||
s.mu.Lock()
|
||||
vm := s.vms[vmKey]
|
||||
active := vm != nil && vm.windowReportGen == request.window && vm.clipboardDelivery.ticket == request.ticket
|
||||
currentPolicy := s.effectiveClipboardPolicyLocked(vmKey)
|
||||
var pendingChanged, applied bool
|
||||
if active && currentPolicy == policy {
|
||||
delivery := &vm.clipboardDelivery
|
||||
if pendingChanged = delivery.wanted != stamp; pendingChanged {
|
||||
delivery.wanted = stamp
|
||||
delivery.offered = guestClipboardStamp{}
|
||||
delivery.applied = guestClipboardStamp{}
|
||||
}
|
||||
applied = delivery.applied == stamp
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !active {
|
||||
return errors.New("guest clipboard window is no longer active")
|
||||
}
|
||||
if currentPolicy != policy || seq != s.clip.SequenceNumber() {
|
||||
continue
|
||||
}
|
||||
if applied || hash == "" {
|
||||
return ctx.Err()
|
||||
}
|
||||
if pendingChanged {
|
||||
s.broadcastClipChange()
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-changed:
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareGuestClipboardPaste holds the per-VM text injection lock from
|
||||
// readiness check through actual Paste dispatch. Always call the returned
|
||||
// release function on success.
|
||||
func (s *Server) PrepareGuestClipboardPaste(ctx context.Context, vmKey string) (release func(), err error) {
|
||||
vmKey = normalizeVMRegistryKey(vmKey)
|
||||
s.mu.RLock()
|
||||
vm := s.vms[vmKey]
|
||||
var token string
|
||||
if vm != nil {
|
||||
token = vm.token
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if vm == nil {
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
tick := time.NewTicker(25 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for !vm.injectMu.TryLock() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
release = sync.OnceFunc(vm.injectMu.Unlock)
|
||||
s.mu.RLock()
|
||||
current := s.vms[vmKey] == vm && vm.token == token
|
||||
s.mu.RUnlock()
|
||||
if !current {
|
||||
release()
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
release()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.WaitForGuestClipboard(ctx, vmKey); err != nil {
|
||||
release()
|
||||
return nil, err
|
||||
}
|
||||
s.mu.RLock()
|
||||
current = s.vms[vmKey] == vm && vm.token == token
|
||||
s.mu.RUnlock()
|
||||
if !current {
|
||||
release()
|
||||
return nil, ErrGuestToolsNotConnected
|
||||
}
|
||||
return release, nil
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package guesttools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const clipboardReadyTestVM = "clipboard-test"
|
||||
|
||||
func clipboardOffer(t *testing.T, srv *Server, query string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/clipboard"+query, nil)
|
||||
req.Header.Set("Authorization", "Bearer clipboard-test-token")
|
||||
req.Header.Set(clipboardAckHeader, "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleClipboard(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func sendClipboardApplied(srv *Server, offer http.Header) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, clipboardAppliedPath, nil)
|
||||
req.Header.Set("Authorization", "Bearer clipboard-test-token")
|
||||
for _, key := range []string{"X-Clip-Seq", "X-Clip-Hash", clipboardWindowHeader, clipboardRequestHeader} {
|
||||
req.Header.Set(key, offer.Get(key))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleClipboardApplied(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func startGuestClipboardWait(t *testing.T, srv *Server) <-chan error {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
request := srv.clipNotifyChan()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM) }()
|
||||
select {
|
||||
case <-request:
|
||||
case err := <-done:
|
||||
t.Fatalf("paste did not request a clipboard snapshot: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("paste did not request a clipboard snapshot")
|
||||
}
|
||||
return done
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardWaitRequiresLatestAppliedOffer(t *testing.T) {
|
||||
clip := &memClipboard{kind: ClipText, data: []byte("first"), seq: 7}
|
||||
srv := newClipboardTestServer(clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
old := clipboardOffer(t, srv, "")
|
||||
if old.Code != http.StatusOK || old.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("guest clipboard offer: %d %v", old.Code, old.Header())
|
||||
}
|
||||
|
||||
request := srv.clipNotifyChan()
|
||||
if err := clip.WriteText("newest"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, old.Header()); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("stale acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
select {
|
||||
case <-request:
|
||||
case err := <-done:
|
||||
t.Fatalf("paste did not request the newest clipboard: %v", err)
|
||||
}
|
||||
latest := clipboardOffer(t, srv, "")
|
||||
if latest.Body.String() != "newest" || latest.Header().Get("X-Clip-Seq") != "8" || latest.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("latest clipboard offer: %q %v", latest.Body.String(), latest.Header())
|
||||
}
|
||||
forged := latest.Header().Clone()
|
||||
forged.Set("X-Clip-Hash", strings.Repeat("0", 64))
|
||||
if resp := sendClipboardApplied(srv, forged); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("unoffered acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("clipboard wait returned with no applied offer: %v", err)
|
||||
default:
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, latest.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("current acknowledgment got %d, want 204", resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardRechecksSynchronizedValueForEveryPaste(t *testing.T) {
|
||||
srv := newClipboardTestServer(&memClipboard{kind: ClipText, data: []byte("unchanged"), seq: 7})
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
first := clipboardOffer(t, srv, "")
|
||||
if first.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("ordinary synchronization should not ask for an acknowledgment: %v", first.Header())
|
||||
}
|
||||
query := "?since=" + url.QueryEscape(first.Header().Get("X-Clip-Hash")) + "&since_seq=7"
|
||||
if same := clipboardOffer(t, srv, query); same.Code != http.StatusNotModified || same.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("no pending paste should return 304: %d %v", same.Code, same.Header())
|
||||
}
|
||||
var previous http.Header
|
||||
for _, reopen := range []bool{false, false, true} {
|
||||
if reopen {
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, false)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
if untouched := clipboardOffer(t, srv, query); untouched.Code != http.StatusNotModified {
|
||||
t.Fatalf("reopening a window should not reoffer an unchanged clipboard: %d", untouched.Code)
|
||||
}
|
||||
}
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
current := clipboardOffer(t, srv, query)
|
||||
if current.Code != http.StatusOK || current.Header().Get(clipboardAckHeader) != "1" ||
|
||||
current.Header().Get(clipboardRecheckHeader) != "1" || current.Header().Get(clipboardRequestHeader) == "" {
|
||||
t.Fatalf("pending paste should request a non-writing recheck: %d %v", current.Code, current.Header())
|
||||
}
|
||||
if previous != nil {
|
||||
if current.Header().Get(clipboardRequestHeader) == previous.Get(clipboardRequestHeader) {
|
||||
t.Fatal("per-paste request ID was reused")
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, previous); resp.Code != http.StatusConflict {
|
||||
t.Fatalf("previous paste acknowledgment got %d, want 409", resp.Code)
|
||||
}
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, current.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("current paste acknowledgment got %d, want 204", resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous = current.Header()
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardWaitSkipsUnavailableHostPayload(t *testing.T) {
|
||||
clip := &memClipboard{seq: 7}
|
||||
srv := newClipboardTestServer(clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
||||
defer cancel()
|
||||
if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil {
|
||||
t.Fatalf("no host content should not delay Paste: %v", err)
|
||||
}
|
||||
if err := clip.WriteText("kept on host"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy := DefaultClipboardPolicy()
|
||||
policy.Direction = ClipboardGuestToHost
|
||||
srv.SetGlobalClipboardPolicy(policy)
|
||||
if err := srv.WaitForGuestClipboard(ctx, clipboardReadyTestVM); err != nil {
|
||||
t.Fatalf("guest-to-host policy should not delay Paste: %v", err)
|
||||
}
|
||||
if denied := clipboardOffer(t, srv, ""); denied.Code != http.StatusNoContent || denied.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("guest-to-host policy offered host data: %d %v", denied.Code, denied.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardAcknowledgesOrdinaryFormats(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "clip.txt")
|
||||
if err := os.WriteFile(path, []byte("file"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
clip Clipboard
|
||||
}{
|
||||
{"png", &memClipboard{kind: ClipPNG, data: makeSamplePNG(t, 1, 2, 3), seq: 23}},
|
||||
{"files", &fileClipboardSnapshot{
|
||||
memClipboard: &memClipboard{seq: 23},
|
||||
payload: ClipPayload{Kind: ClipFiles, Files: []string{path}},
|
||||
}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newClipboardTestServer(tt.clip)
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)]
|
||||
vm.clipOverride = &pendingClipOverride{text: "temporary", hash: strings.Repeat("a", 64), servedCh: make(chan struct{})}
|
||||
done := startGuestClipboardWait(t, srv)
|
||||
if temporary := clipboardOffer(t, srv, "?accept=image,files"); temporary.Body.String() != "temporary" ||
|
||||
temporary.Header().Get(clipboardAckHeader) != "" {
|
||||
t.Fatalf("temporary text should not register an acknowledgment: %d %v", temporary.Code, temporary.Header())
|
||||
}
|
||||
ordinary := clipboardOffer(t, srv, "?accept=image,files")
|
||||
if ordinary.Code != http.StatusOK || ordinary.Header().Get("X-Clip-Kind") != tt.name ||
|
||||
ordinary.Header().Get(clipboardAckHeader) != "1" {
|
||||
t.Fatalf("ordinary %s was not offered for acknowledgment: %d %v", tt.name, ordinary.Code, ordinary.Header())
|
||||
}
|
||||
if resp := sendClipboardApplied(srv, ordinary.Header()); resp.Code != http.StatusNoContent {
|
||||
t.Fatalf("%s acknowledgment got %d, want 204", tt.name, resp.Code)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("paste readiness after applying %s: %v", tt.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppWindowClipboardPrepareHoldsInjectionLockUntilRelease(t *testing.T) {
|
||||
srv := newClipboardTestServer(&memClipboard{seq: 7})
|
||||
srv.SetWindowReporting(clipboardReadyTestVM, true)
|
||||
vm := srv.vms[normalizeVMRegistryKey(clipboardReadyTestVM)]
|
||||
vm.injectMu.Lock()
|
||||
blocked, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
|
||||
_, err := srv.PrepareGuestClipboardPaste(blocked, clipboardReadyTestVM)
|
||||
cancel()
|
||||
vm.injectMu.Unlock()
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("paste should be cancellable while text injection owns the clipboard: %v", err)
|
||||
}
|
||||
release, err := srv.PrepareGuestClipboardPaste(t.Context(), clipboardReadyTestVM)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer release()
|
||||
if vm.injectMu.TryLock() {
|
||||
vm.injectMu.Unlock()
|
||||
t.Fatal("paste released the text injection lock before dispatch")
|
||||
}
|
||||
release()
|
||||
if !vm.injectMu.TryLock() {
|
||||
t.Fatal("paste release did not unlock the clipboard")
|
||||
}
|
||||
vm.injectMu.Unlock()
|
||||
}
|
||||
@@ -43,14 +43,12 @@ func TestGuestAgentFolderMounts(t *testing.T) {
|
||||
"/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command",
|
||||
)
|
||||
uninstall = dnsPaths.Replace(uninstall)
|
||||
if CurrentAgentVersion != BidirectionalClipboardFilesAgentVersion {
|
||||
t.Fatalf("CurrentAgentVersion = %d, want bidirectional clipboard files version %d", CurrentAgentVersion, BidirectionalClipboardFilesAgentVersion)
|
||||
}
|
||||
versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,`
|
||||
if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") {
|
||||
t.Fatal("Guest Tools scripts do not advertise the current agent version")
|
||||
}
|
||||
mounts := guestTimezoneAgent + guestTimezoneConfig +
|
||||
scriptSection(t, agent, "\nstop_window_reporter() {", "\ncleanup() {") +
|
||||
scriptSection(t, agent, "urlencode() {", "\nhash_file() {") +
|
||||
scriptSection(t, agent, "\ndrive_mount_failures=", "\nreport_status() {")
|
||||
t.Run("clipboard_setting_before_mounts", func(t *testing.T) {
|
||||
|
||||
@@ -21,8 +21,10 @@ const WindowDropAgentVersion = 13
|
||||
const ClipboardReliabilityAgentVersion = 14
|
||||
const ClipboardFilesAgentVersion = 15
|
||||
const BidirectionalClipboardFilesAgentVersion = 16
|
||||
const WindowReportAgentVersion = 17
|
||||
const PasteReadyAgentVersion = 18
|
||||
|
||||
const CurrentAgentVersion = BidirectionalClipboardFilesAgentVersion
|
||||
const CurrentAgentVersion = PasteReadyAgentVersion
|
||||
|
||||
type SharedFolderConfig struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -649,9 +649,10 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
|
||||
}
|
||||
}
|
||||
for name, script := range map[string][]byte{
|
||||
"dns-proxy.pl": guestDNSProxy,
|
||||
"Apply-Host-DNS.command": guestApplyHostDNS,
|
||||
"Disable-Host-DNS.command": guestDisableHostDNS,
|
||||
"dns-proxy.pl": guestDNSProxy,
|
||||
"Apply-Host-DNS.command": guestApplyHostDNS,
|
||||
"Disable-Host-DNS.command": guestDisableHostDNS,
|
||||
"active-window-reporter.js": guestWindowReporter,
|
||||
} {
|
||||
offset, size, err := installer.FindFileInHFSPlusImage(f, name)
|
||||
if err != nil {
|
||||
|
||||
@@ -31,6 +31,9 @@ var guestDropResolveJS string
|
||||
//go:embed drop_agent.sh
|
||||
var guestDropAgent string
|
||||
|
||||
//go:embed active_window_reporter.js
|
||||
var guestWindowReporter []byte
|
||||
|
||||
//go:embed dns-proxy.pl
|
||||
var guestDNSProxy []byte
|
||||
|
||||
@@ -112,6 +115,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
|
||||
{"dns-proxy.pl", guestDNSProxy},
|
||||
{"Apply-Host-DNS.command", guestApplyHostDNS},
|
||||
{"Disable-Host-DNS.command", guestDisableHostDNS},
|
||||
{"active-window-reporter.js", guestWindowReporter},
|
||||
} {
|
||||
// The Windows checkout may have CRLF line endings.
|
||||
data := bytes.ReplaceAll(script.data, []byte("\r\n"), []byte("\n"))
|
||||
@@ -164,10 +168,21 @@ CAFFEINATE_PID=""
|
||||
TEXT_INPUT_PID=""
|
||||
DROP_EVENTS_PID=""
|
||||
CLIPBOARD_PID=""
|
||||
WINDOW_REPORTER_PID=""
|
||||
window_report_generation=""
|
||||
keymap_active="false"
|
||||
keymap_applied="false"
|
||||
` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + `
|
||||
|
||||
stop_window_reporter() {
|
||||
if [ -n "${WINDOW_REPORTER_PID:-}" ]; then
|
||||
kill "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
wait "$WINDOW_REPORTER_PID" 2>/dev/null || true
|
||||
fi
|
||||
WINDOW_REPORTER_PID=""
|
||||
window_report_generation=""
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ "$keymap_applied" = "true" ]; then
|
||||
apply_hidutil_carrier disable
|
||||
@@ -185,6 +200,7 @@ cleanup() {
|
||||
if [ -n "$CLIPBOARD_PID" ]; then
|
||||
kill "$CLIPBOARD_PID" 2>/dev/null || true
|
||||
fi
|
||||
stop_window_reporter
|
||||
rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
@@ -489,9 +505,30 @@ EOF
|
||||
fi
|
||||
}
|
||||
|
||||
sync_window_reporter() {
|
||||
requested_generation=$(printf '%s\n' "$1" | sed -n 's/.*"window_report_generation"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p')
|
||||
case "$requested_generation" in
|
||||
''|0)
|
||||
stop_window_reporter
|
||||
return
|
||||
;;
|
||||
esac
|
||||
if [ "$requested_generation" = "${window_report_generation:-}" ] &&
|
||||
[ -n "${WINDOW_REPORTER_PID:-}" ] && kill -0 "$WINDOW_REPORTER_PID" 2>/dev/null; then
|
||||
return
|
||||
fi
|
||||
stop_window_reporter
|
||||
[ -f "$APP_DIR/active-window-reporter.js" ] || return 0
|
||||
REIMS_HOST_URL="$REIMS_HOST_URL" REIMS_TOKEN="$REIMS_TOKEN" /usr/bin/osascript -l JavaScript \
|
||||
"$APP_DIR/active-window-reporter.js" "$requested_generation" >/dev/null 2>&1 &
|
||||
WINDOW_REPORTER_PID=$!
|
||||
window_report_generation="$requested_generation"
|
||||
}
|
||||
|
||||
apply_host_config() {
|
||||
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
|
||||
cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true)
|
||||
sync_window_reporter "$cfg_json"
|
||||
[ -n "$cfg_json" ] || return 0
|
||||
if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then
|
||||
clip_enabled="0"
|
||||
@@ -832,7 +869,11 @@ clip_header() {
|
||||
case "$1:$hdr_key" in
|
||||
x-clip-hash:[Xx]-[Cc][Ll][Ii][Pp]-[Hh][Aa][Ss][Hh]|\
|
||||
x-clip-kind:[Xx]-[Cc][Ll][Ii][Pp]-[Kk][Ii][Nn][Dd]|\
|
||||
x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq])
|
||||
x-clip-seq:[Xx]-[Cc][Ll][Ii][Pp]-[Ss][Ee][Qq]|\
|
||||
x-reims-clipboard-ack:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Aa][Cc][Kk]|\
|
||||
x-reims-clipboard-generation:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Gg][Ee][Nn][Ee][Rr][Aa][Tt][Ii][Oo][Nn]|\
|
||||
x-reims-clipboard-request:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Qq][Uu][Ee][Ss][Tt]|\
|
||||
x-reims-clipboard-recheck:[Xx]-[Rr][Ee][Ii][Mm][Ss]-[Cc][Ll][Ii][Pp][Bb][Oo][Aa][Rr][Dd]-[Rr][Ee][Cc][Hh][Ee][Cc][Kk])
|
||||
hdr_val=${hdr_val#"${hdr_val%%[![:space:]]*}"}
|
||||
hdr_val=${hdr_val%"${hdr_val##*[![:space:]]}"}
|
||||
printf '%s\n' "$hdr_val"
|
||||
@@ -842,6 +883,30 @@ clip_header() {
|
||||
done < "$hdr_out"
|
||||
}
|
||||
|
||||
acknowledge_clipboard() {
|
||||
[ "$(clip_header x-reims-clipboard-ack)" = 1 ] &&
|
||||
[ "$read_ok" = 1 ] && [ -n "$read_cc" ] && ! clipboard_poll_interrupted || return 0
|
||||
if [ "$1" != 1 ]; then
|
||||
# macOS can re-encode PNGs, and a file offer's hash identifies the
|
||||
# Windows manifest, so only text has the same wire and read-back hash.
|
||||
[ "$read_kind" = "$new_kind" ] || return 0
|
||||
[ "$new_kind" != text ] || [ "$read_hash" = "$new_hash" ] || return 0
|
||||
fi
|
||||
case "$new_seq" in ''|*[!0-9]*) return 0 ;; esac
|
||||
case "$new_hash" in ''|*[!0-9a-f]*) return 0 ;; esac
|
||||
ack_generation=$(clip_header x-reims-clipboard-generation)
|
||||
case "$ack_generation" in ''|0*|*[!0-9]*) return 0 ;; esac
|
||||
ack_request=$(clip_header x-reims-clipboard-request)
|
||||
case "$ack_request" in ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]*) return 0 ;; esac
|
||||
[ "${#new_seq}" -le 10 ] && [ "${#new_hash}" -eq 64 ] &&
|
||||
[ "${#ack_generation}" -le 20 ] && [ "${#ack_request}" -eq 26 ] || return 0
|
||||
curl -fsS -m 1 -X POST -H "Authorization: Bearer $REIMS_TOKEN" \
|
||||
-H "X-Clip-Seq: $new_seq" -H "X-Clip-Hash: $new_hash" \
|
||||
-H "X-Reims-Clipboard-Generation: $ack_generation" \
|
||||
-H "X-Reims-Clipboard-Request: $ack_request" \
|
||||
"$REIMS_HOST_URL/v1/clipboard/applied" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
last_local_hash=""
|
||||
synced_local_cc=""
|
||||
synced_local_kind=""
|
||||
@@ -1082,7 +1147,7 @@ sync_clipboard() {
|
||||
clip_url="$clip_url&since_seq=$last_server_seq"
|
||||
fi
|
||||
code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" \
|
||||
-H "Authorization: Bearer $REIMS_TOKEN" -H "Accept: image/png" -H "X-Reims-Clipboard-Ack: 1" \
|
||||
"$clip_url" 2>/dev/null) || code=000
|
||||
case "$code" in
|
||||
200)
|
||||
@@ -1129,6 +1194,13 @@ sync_clipboard() {
|
||||
release_clip_lock
|
||||
return 0
|
||||
fi
|
||||
if [ "$(clip_header x-reims-clipboard-recheck)" = 1 ]; then
|
||||
# A paste of an unchanged host snapshot uses the current
|
||||
# ordinary macOS clipboard. A newer guest copy keeps ownership.
|
||||
release_clip_lock
|
||||
acknowledge_clipboard 1
|
||||
return 0
|
||||
fi
|
||||
if [ "$new_hash" != "$post_get_hash" ]; then
|
||||
if [ "$new_kind" = files ]; then
|
||||
delivery=0
|
||||
@@ -1189,6 +1261,7 @@ sync_clipboard() {
|
||||
fi
|
||||
last_server_hash="$new_hash"
|
||||
last_server_seq="$new_seq"
|
||||
acknowledge_clipboard 0
|
||||
;;
|
||||
204|304)
|
||||
if [ -z "$last_local_hash" ]; then
|
||||
@@ -1386,6 +1459,9 @@ if [ -f "$SRC/drop-resolve.js" ]; then
|
||||
cp "$SRC/drop-resolve.js" "$APP_DIR/drop-resolve.js"
|
||||
chmod 755 "$APP_DIR/drop-resolve.js"
|
||||
fi
|
||||
if [ -f "$SRC/active-window-reporter.js" ]; then
|
||||
cp "$SRC/active-window-reporter.js" "$APP_DIR/active-window-reporter.js"
|
||||
fi
|
||||
chmod 600 "$APP_DIR/config"
|
||||
chmod 755 "$APP_DIR/guest-tools.sh"
|
||||
[ -e "$HOME/Desktop/ReimsShare" ] || ln -s "$SHARE_SYNC" "$HOME/Desktop/ReimsShare" 2>/dev/null || true
|
||||
|
||||
@@ -274,6 +274,9 @@ type registeredVM struct {
|
||||
sleepActive bool
|
||||
agentVersion int
|
||||
lastSeen time.Time
|
||||
windowReportGen uint64
|
||||
windowReport windowReport
|
||||
clipboardDelivery guestClipboardDelivery
|
||||
|
||||
dropShares *dropShareStore
|
||||
dropDAVHandler *webdav.Handler
|
||||
@@ -308,6 +311,7 @@ type Server struct {
|
||||
folderAccessMu sync.RWMutex
|
||||
folderGeneration uint64
|
||||
registrationGen uint64
|
||||
nextWindowGen uint64
|
||||
dynamicRoutes map[string]http.HandlerFunc
|
||||
clipboardActive bool
|
||||
globalClipPolicy ClipboardPolicy
|
||||
@@ -392,10 +396,12 @@ func (s *Server) Start(preferredPort int) (int, error) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1/ping", s.handlePing)
|
||||
mux.HandleFunc("/v1/config", s.handleConfig)
|
||||
mux.HandleFunc(activeWindowPath, s.handleActiveWindow)
|
||||
mux.HandleFunc("/v1/folders", s.handleFolders)
|
||||
mux.HandleFunc("/v1/status", s.handleStatus)
|
||||
mux.HandleFunc("/v1/dns-query", s.handleDNSQuery)
|
||||
mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard"))
|
||||
mux.HandleFunc(clipboardAppliedPath, s.handleClipboardApplied)
|
||||
mux.HandleFunc("/v1/text-input", s.handleTextInput)
|
||||
mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck)
|
||||
mux.HandleFunc("/v1/drop-events", s.handleDropEvents)
|
||||
@@ -502,6 +508,11 @@ func (s *Server) Close(ctx context.Context) error {
|
||||
relays := s.management
|
||||
s.management = nil
|
||||
s.clearAllClipFilesLocked()
|
||||
for _, vm := range s.vms {
|
||||
vm.windowReportGen = 0
|
||||
vm.windowReport = windowReport{}
|
||||
vm.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.cleanupClipFiles()
|
||||
for _, relay := range relays {
|
||||
@@ -575,6 +586,9 @@ func (s *Server) RegisterVM(cfg VMConfig) {
|
||||
} else if cur.token != cfg.Token {
|
||||
cur.dropShares.revokeClipboard()
|
||||
s.clearVMClipFilesLocked(key)
|
||||
cur.windowReportGen = 0
|
||||
cur.windowReport = windowReport{}
|
||||
cur.clipboardDelivery = guestClipboardDelivery{}
|
||||
}
|
||||
folders := make(map[string]ResolvedSharedFolder, len(cfg.ResolvedFolders))
|
||||
for _, folder := range cfg.ResolvedFolders {
|
||||
@@ -957,6 +971,7 @@ func (s *Server) authenticateToken(tok string) *registeredVM {
|
||||
sleepActive: vm.sleepActive,
|
||||
agentVersion: vm.agentVersion,
|
||||
lastSeen: vm.lastSeen,
|
||||
windowReportGen: vm.windowReportGen,
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -1023,6 +1038,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
_ = 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 + "/",
|
||||
"host_dns_enabled": vm.hostDNSEnabled,
|
||||
@@ -1145,7 +1161,7 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
|
||||
s.serveClipboardArchive(w, r, vm)
|
||||
return
|
||||
}
|
||||
s.getClipboard(w, r, vm.key)
|
||||
s.getClipboard(w, r, vm)
|
||||
case http.MethodPost, http.MethodPut:
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if mediaType == "application/x-tar" {
|
||||
@@ -1253,12 +1269,15 @@ func (s *Server) clipboardForGuest(vmKey string, payload ClipPayload, seq uint32
|
||||
return ClipPayload{}, ""
|
||||
}
|
||||
|
||||
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) {
|
||||
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vm *registeredVM) {
|
||||
vmKey := vm.key
|
||||
waitSec, err := strconv.Atoi(r.URL.Query().Get("wait"))
|
||||
if err != nil {
|
||||
waitSec = 0
|
||||
}
|
||||
deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second)
|
||||
wait := time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second
|
||||
ackCapable := r.Header.Get(clipboardAckHeader) == "1"
|
||||
start := time.Now()
|
||||
wantsImage := acceptsClipFormat(r.URL.Query().Get("accept"), "image") ||
|
||||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
|
||||
wantsFiles := acceptsClipFormat(r.URL.Query().Get("accept"), "files")
|
||||
@@ -1268,6 +1287,10 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
|
||||
for {
|
||||
ch := s.clipNotifyChan()
|
||||
deadline := start.Add(wait)
|
||||
if ackCapable && s.windowClipboardActive(vm) {
|
||||
deadline = start.Add(min(wait, 250*time.Millisecond))
|
||||
}
|
||||
policy := s.EffectiveClipboardPolicy(vmKey)
|
||||
if !policy.Enabled {
|
||||
writeFeatureDisabled(w, "clipboard")
|
||||
@@ -1297,7 +1320,20 @@ func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey stri
|
||||
payload, h = s.clipboardForGuest(vmKey, payload, seq, h, wantFiles, wantImage, policy.MaxImageBytes)
|
||||
if h != "" {
|
||||
unchanged := since == h && (!hasSinceSeq || seq == uint32(sinceSeq))
|
||||
if !unchanged || time.Until(deadline) <= 0 {
|
||||
expired := !time.Now().Before(deadline)
|
||||
if ackCapable {
|
||||
recheck := unchanged && hasSinceSeq
|
||||
if offer := s.offerGuestClipboard(vm, seq, h, recheck, expired); offer.ticket != "" {
|
||||
w.Header().Set(clipboardAckHeader, "1")
|
||||
w.Header().Set(clipboardWindowHeader, strconv.FormatUint(offer.window, 10))
|
||||
w.Header().Set(clipboardRequestHeader, offer.ticket)
|
||||
if recheck {
|
||||
w.Header().Set(clipboardRecheckHeader, "1")
|
||||
}
|
||||
unchanged = false
|
||||
}
|
||||
}
|
||||
if !unchanged || expired {
|
||||
setClipboardSeq(w, seq)
|
||||
w.Header().Set("X-Clip-Hash", h)
|
||||
w.Header().Set("X-Clip-Kind", string(payload.Kind))
|
||||
|
||||
@@ -123,6 +123,14 @@ var catalog = map[Locale]map[string]string{
|
||||
"eject": "弹出安装盘",
|
||||
"emptyVMs": "还没有虚拟机",
|
||||
"err.affinity.empty_mask": "请至少选择 1 个可用的逻辑处理器",
|
||||
"err.app_window_capture": "无法获取 {name} 的应用画面",
|
||||
"err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试",
|
||||
"err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口",
|
||||
"err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口",
|
||||
"err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试",
|
||||
"err.app_window_open": "先关闭已打开的独立应用窗口",
|
||||
"err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口",
|
||||
"err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机",
|
||||
"err.clone.backing_in_use": "「{clone}」仍依赖此磁盘,删除该副本后才能继续",
|
||||
"err.clone.disk_busy": "等待此磁盘上的操作完成后再试",
|
||||
"err.clone.disk_missing": "找不到原虚拟机磁盘文件:{path}",
|
||||
@@ -584,6 +592,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"tray.menu.stop": "关机(&D)",
|
||||
"tray.menu.suspend": "挂起(&P)",
|
||||
"tray.menu.toggle_fullscreen": "切换全屏",
|
||||
"tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次",
|
||||
"tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态",
|
||||
"tray.notify.focus_fail": "找不到 {name} 的窗口",
|
||||
"tray.notify.force_stop_fail": "无法强制关机 {name}",
|
||||
@@ -793,6 +802,14 @@ var catalog = map[Locale]map[string]string{
|
||||
"eject": "Eject installer",
|
||||
"emptyVMs": "No virtual machines",
|
||||
"err.affinity.empty_mask": "Select at least 1 logical processor",
|
||||
"err.app_window_capture": "Could not capture the app window in {name}",
|
||||
"err.app_window_disabled": "Enable macOS App Windows under Plugins and try again",
|
||||
"err.app_window_guest_tools": "Connect Guest Tools in {name} and try again",
|
||||
"err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again",
|
||||
"err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again",
|
||||
"err.app_window_open": "Close the current separate app window first",
|
||||
"err.app_window_pointer": "Enable the USB tablet for {name} and try again",
|
||||
"err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows",
|
||||
"err.clone.backing_in_use": "Delete “{clone}” before continuing because it still depends on this disk",
|
||||
"err.clone.disk_busy": "Wait for the operation on this disk to finish and try again",
|
||||
"err.clone.disk_missing": "Source disk file not found: {path}",
|
||||
@@ -1254,6 +1271,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"tray.menu.stop": "Shut &Down",
|
||||
"tray.menu.suspend": "Sus&pend",
|
||||
"tray.menu.toggle_fullscreen": "Toggle full screen",
|
||||
"tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again",
|
||||
"tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}",
|
||||
"tray.notify.focus_fail": "Couldn't find the window of {name}",
|
||||
"tray.notify.force_stop_fail": "Couldn't force shut down {name}",
|
||||
@@ -1382,6 +1400,11 @@ var paramOrder = map[string][]string{
|
||||
"doctor.pcores.detail": {"count", "mask", "cpus"},
|
||||
"doctor.ram.detail": {"total", "avail"},
|
||||
"doctor.runtime.active": {"commit", "dir"},
|
||||
"err.app_window_capture": {"name"},
|
||||
"err.app_window_guest_tools": {"name"},
|
||||
"err.app_window_guest_tools_update": {"name"},
|
||||
"err.app_window_no_window": {"name"},
|
||||
"err.app_window_pointer": {"name"},
|
||||
"err.clone.backing_in_use": {"clone"},
|
||||
"err.clone.disk_missing": {"path"},
|
||||
"err.clone.disk_running": {"name"},
|
||||
@@ -1394,6 +1417,7 @@ var paramOrder = map[string][]string{
|
||||
"err.computer_use.not_owned": {"name"},
|
||||
"err.computer_use.phase_confirmation": {"name", "phase"},
|
||||
"err.computer_use.restore_confirmation": {"name"},
|
||||
"err.computer_use.vm_not_running": {"name"},
|
||||
"err.dataroot.damaged": {"dir"},
|
||||
"err.dataroot.locked": {"dir"},
|
||||
"err.dataroot.migration_failed": {"dir"},
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/appwindow"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
// IDAppWindow is the optional built-in extension for macOS application windows.
|
||||
const IDAppWindow = "builtin.macos.app-window"
|
||||
|
||||
func defAppWindow(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
const commandID = "open"
|
||||
title := plugin.LocalizedText{ZhCN: "打开独立应用窗口", EnUS: "Open app in separate window"}
|
||||
return plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
Schema: 1,
|
||||
ID: IDAppWindow,
|
||||
Version: ver,
|
||||
Name: plugin.LocalizedText{ZhCN: "macOS 应用窗口", EnUS: "macOS App Windows"},
|
||||
Description: plugin.LocalizedText{
|
||||
ZhCN: "在 Windows 桌面上显示和操作当前 macOS 应用窗口",
|
||||
EnUS: "View and control the active macOS app in a separate Windows window",
|
||||
},
|
||||
Publisher: "Reims-Go",
|
||||
License: "Apache-2.0",
|
||||
Platforms: []string{"windows-x64"},
|
||||
Requires: []plugin.ServiceRequirement{
|
||||
{Service: ServiceGuestToolsTransport, Version: "^1.0.0"},
|
||||
{Service: ServiceComputerUse, Version: "^1.0.0"},
|
||||
},
|
||||
Permissions: []string{"vm:screen", "qmp:write", "ui:slot"},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Trust: plugin.TrustOfficial,
|
||||
Desired: desiredFn(IDAppWindow, false),
|
||||
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
||||
// The CLI uses this definition to manage plugin state. Only the
|
||||
// supported desktop host can expose the native window command.
|
||||
if cb.OpenAppWindow == nil || runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
|
||||
return nil
|
||||
}
|
||||
rawTools, _ := sc.Lookup(ServiceGuestToolsTransport)
|
||||
tools, ok := rawTools.(*guesttools.Server)
|
||||
if !ok || tools == nil {
|
||||
return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport)
|
||||
}
|
||||
rawConsole, _ := sc.Lookup(ServiceComputerUse)
|
||||
console, ok := rawConsole.(ComputerUseService)
|
||||
if !ok || console == nil {
|
||||
return fmt.Errorf("invalid %q service instance", ServiceComputerUse)
|
||||
}
|
||||
|
||||
sessions := new(appwindow.Sessions)
|
||||
sc.OnDispose(sessions.Close)
|
||||
sc.Registry().RegisterCommand(sc, plugin.CommandContribution{ID: commandID, Title: title},
|
||||
func(ctx context.Context, args map[string]any) (any, error) {
|
||||
if sc.Disposed() {
|
||||
return nil, appwindow.ErrSessionsClosed
|
||||
}
|
||||
name, _ := args["vm"].(string)
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return nil, errors.New("a VM name is required")
|
||||
}
|
||||
return nil, cb.OpenAppWindow(ctx, sessions, tools, console, name)
|
||||
})
|
||||
sc.Registry().RegisterMenu(sc, plugin.MenuContribution{
|
||||
ID: commandID, Slot: "vm.toolbar", Command: commandID, Title: title, When: "vm.macos.running",
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"runtime"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/appwindow"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func TestAppWindowPluginDefaultOffAndCLIState(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
t.Cleanup(reg.DisposeAll)
|
||||
if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.Reconcile(t.Context())
|
||||
info, ok := reg.Info(IDAppWindow)
|
||||
if !ok || info.Enabled || info.State != plugin.StateOff {
|
||||
t.Fatalf("default app window plugin state: %+v", info)
|
||||
}
|
||||
assertAppWindowContributions(t, reg, false)
|
||||
if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reg.IsActive(IDAppWindow) {
|
||||
t.Fatalf("CLI cannot enable app window plugin state: %s", reg.StateOf(IDAppWindow))
|
||||
}
|
||||
assertAppWindowContributions(t, reg, false)
|
||||
}
|
||||
|
||||
func TestAppWindowPluginOwnsWindowAcrossDependencyChanges(t *testing.T) {
|
||||
if runtime.GOOS != "windows" || runtime.GOARCH != "amd64" {
|
||||
t.Skip("native app window command is available on Windows x64")
|
||||
}
|
||||
for _, dependency := range []string{IDGuestTools, IDComputerUse} {
|
||||
t.Run(dependency, func(t *testing.T) {
|
||||
reg := plugin.NewRegistry(nil)
|
||||
t.Cleanup(reg.DisposeAll)
|
||||
var owner *appwindow.Sessions
|
||||
var closed chan struct{}
|
||||
cb := HostCallbacks{
|
||||
OpenAppWindow: func(ctx context.Context, sessions *appwindow.Sessions, tools *guesttools.Server, console ComputerUseService, vm string) error {
|
||||
if tools == nil || console == nil || vm != "fixture" {
|
||||
t.Fatalf("invalid command arguments: tools=%v console=%v vm=%q", tools != nil, console != nil, vm)
|
||||
}
|
||||
owner = sessions
|
||||
done := make(chan struct{})
|
||||
closed = done
|
||||
return sessions.Start(ctx, func(sessionCtx context.Context) (func(), error) {
|
||||
return func() {
|
||||
<-sessionCtx.Done()
|
||||
close(done)
|
||||
}, nil
|
||||
})
|
||||
},
|
||||
}
|
||||
if err := RegisterAll(reg, cb, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reg.SetDesired(t.Context(), IDAppWindow, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAppWindowContributions(t, reg, true)
|
||||
if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": 17}); err == nil {
|
||||
t.Fatal("native window command accepted a non-string VM name")
|
||||
}
|
||||
open := func() {
|
||||
t.Helper()
|
||||
if _, err := reg.InvokeCommand(t.Context(), IDAppWindow, "open", map[string]any{"vm": "fixture"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
open()
|
||||
first := owner
|
||||
if err := reg.SetDesired(t.Context(), dependency, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reg.StateOf(IDAppWindow) != plugin.StatePending {
|
||||
t.Fatalf("app window plugin remained active without %s", dependency)
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
default:
|
||||
t.Fatalf("window was not closed when %s was disabled", dependency)
|
||||
}
|
||||
assertAppWindowContributions(t, reg, false)
|
||||
if err := first.Start(t.Context(), func(context.Context) (func(), error) {
|
||||
t.Fatal("disposed scope still accepted a window")
|
||||
return nil, nil
|
||||
}); !errors.Is(err, appwindow.ErrSessionsClosed) {
|
||||
t.Fatalf("disposed session owner returned %v", err)
|
||||
}
|
||||
|
||||
if err := reg.SetDesired(t.Context(), dependency, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAppWindowContributions(t, reg, true)
|
||||
open()
|
||||
if owner == first {
|
||||
t.Fatal("reactivation reused the disposed session owner")
|
||||
}
|
||||
if err := reg.SetDesired(t.Context(), IDAppWindow, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-closed:
|
||||
default:
|
||||
t.Fatal("disabling the app window plugin left a window open")
|
||||
}
|
||||
assertAppWindowContributions(t, reg, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertAppWindowContributions(t *testing.T, reg *plugin.Registry, want bool) {
|
||||
t.Helper()
|
||||
hasCommand := slices.ContainsFunc(reg.Commands(), func(cmd plugin.CommandContribution) bool {
|
||||
return cmd.PluginID == IDAppWindow && cmd.ID == "open"
|
||||
})
|
||||
hasMenu := slices.ContainsFunc(reg.Menus("vm.toolbar"), func(item plugin.MenuContribution) bool {
|
||||
return item.PluginID == IDAppWindow && item.Command == "open" && item.When == "vm.macos.running"
|
||||
})
|
||||
if hasCommand != want || hasMenu != want {
|
||||
t.Fatalf("app window command=%v menu=%v, want %v", hasCommand, hasMenu, want)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/appwindow"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
@@ -57,6 +58,7 @@ type HostCallbacks struct {
|
||||
CancelColdReboot func(vmName string)
|
||||
GuestToolsImg func(vmName string) string
|
||||
BuildGuestToolsImage func(vmName, vmDir string) error
|
||||
OpenAppWindow func(context.Context, *appwindow.Sessions, *guesttools.Server, ComputerUseService, string) error
|
||||
PrepareVMNetwork func(context.Context, string, bool) (func(), error)
|
||||
// 返回取消并等待本次恢复任务结束的清理函数,由插件 scope 先于通道释放执行。
|
||||
RestorePacketBridges func(context.Context) func()
|
||||
@@ -98,6 +100,7 @@ func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id strin
|
||||
defInput(ver, cb, desiredFn),
|
||||
defNpcapBridge(ver, cb, desiredFn),
|
||||
defComputerUse(ver, desiredFn),
|
||||
defAppWindow(ver, cb, desiredFn),
|
||||
defDownloaderParallel(ver, cb, desiredFn),
|
||||
}
|
||||
for _, d := range defs {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
type ComputerUseService interface {
|
||||
WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error
|
||||
Screendump(ctx context.Context, vmDir, path string) (string, error)
|
||||
ScreendumpDisplay(ctx context.Context, vmDir, path, device string, head int) (string, error)
|
||||
TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error)
|
||||
Forget(ctx context.Context, vmDir string) error
|
||||
Close()
|
||||
@@ -21,9 +22,12 @@ type ComputerUseService interface {
|
||||
PointerAvailable(ctx context.Context, vmDir string) (bool, error)
|
||||
MouseMove(ctx context.Context, vmDir string, x, y, width, height int) error
|
||||
MouseButton(ctx context.Context, vmDir, button string, down bool) error
|
||||
MouseButtonAt(ctx context.Context, vmDir string, x, y, width, height int, button string, down bool) error
|
||||
MouseClick(ctx context.Context, vmDir, button string) error
|
||||
MouseScroll(ctx context.Context, vmDir string, delta int, horizontal bool) error
|
||||
PressKey(ctx context.Context, vmDir, key string, modifiers ...string) error
|
||||
SendKey(ctx context.Context, vmDir, key string, down bool) error
|
||||
ReleaseInputs(ctx context.Context, vmDir string, keys, buttons []string) error
|
||||
}
|
||||
|
||||
func defComputerUse(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||||
|
||||
@@ -110,6 +110,9 @@ func TestRegistryDependencyReconcileAndCascade(t *testing.T) {
|
||||
if reg.StateOf("builtin.clipboard") != StatePending {
|
||||
t.Fatalf("clipboard state = %s, want pending", reg.StateOf("builtin.clipboard"))
|
||||
}
|
||||
if want := []string{"up:transport", "up:clipboard", "down:clipboard", "down:transport"}; !reflect.DeepEqual(log, want) {
|
||||
t.Fatalf("lifecycle order = %v, want %v", log, want)
|
||||
}
|
||||
|
||||
// Re-enabling provider automatically reactivates pending dependent.
|
||||
if err := reg.SetDesired(context.Background(), "builtin.transport", true); err != nil {
|
||||
@@ -120,6 +123,72 @@ func TestRegistryDependencyReconcileAndCascade(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryDisposesTransitiveRequiredConsumersBeforePublishedProvider(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
ctx := context.Background()
|
||||
const (
|
||||
shadowed = "builtin.legacy-transport"
|
||||
provider = "builtin.transport"
|
||||
bridge = "builtin.bridge"
|
||||
viewer = "builtin.viewer"
|
||||
optional = "builtin.optional"
|
||||
)
|
||||
var disposed []string
|
||||
register := func(id, service string, requirements ...ServiceRequirement) {
|
||||
t.Helper()
|
||||
def := PluginDef{
|
||||
Manifest: Manifest{ID: id, Version: "1.0.0", Requires: requirements},
|
||||
Source: SourceBuiltin,
|
||||
Trust: TrustOfficial,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, sc *Scope) error {
|
||||
if service != "" {
|
||||
sc.Provide(service, "1.0.0", id)
|
||||
}
|
||||
sc.OnDispose(func() {
|
||||
for _, req := range requirements {
|
||||
if _, ok := sc.Lookup(req.Service); !req.Optional && !ok {
|
||||
t.Errorf("%s lost %s before its disposer ran", id, req.Service)
|
||||
}
|
||||
}
|
||||
disposed = append(disposed, id)
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
if err := reg.Register(def); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
register(shadowed, "transport")
|
||||
register(provider, "transport")
|
||||
register(bridge, "bridge", ServiceRequirement{Service: "transport"})
|
||||
register(viewer, "", ServiceRequirement{Service: "bridge"})
|
||||
register(optional, "", ServiceRequirement{Service: "transport", Optional: true})
|
||||
reg.Reconcile(ctx)
|
||||
|
||||
if svc, ok := reg.LookupService("transport"); !ok || svc != provider || !reg.IsActive(viewer) {
|
||||
t.Fatalf("expected active consumer using published provider, service=%v consumer=%s", svc, reg.StateOf(viewer))
|
||||
}
|
||||
if err := reg.SetDesired(ctx, shadowed, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(disposed, []string{shadowed}) || !reg.IsActive(viewer) {
|
||||
t.Fatalf("disabling shadowed provider affected consumer, disposed=%v", disposed)
|
||||
}
|
||||
if err := reg.SetDesired(ctx, provider, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []string{shadowed, viewer, bridge, provider}; !reflect.DeepEqual(disposed, want) {
|
||||
t.Fatalf("disposal order = %v, want %v", disposed, want)
|
||||
}
|
||||
if reg.StateOf(viewer) != StatePending || reg.StateOf(bridge) != StatePending ||
|
||||
reg.StateOf(provider) != StateOff || !reg.IsActive(optional) {
|
||||
t.Fatalf("unexpected final states: viewer=%s bridge=%s provider=%s optional=%s",
|
||||
reg.StateOf(viewer), reg.StateOf(bridge), reg.StateOf(provider), reg.StateOf(optional))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryPanicRollbackAndInUseFailClosed(t *testing.T) {
|
||||
reg := NewRegistry(nil)
|
||||
rolledBack := false
|
||||
|
||||
+28
-14
@@ -369,27 +369,41 @@ func (r *Registry) Reconcile(ctx context.Context) {
|
||||
for {
|
||||
var toDispose []*pluginEntry
|
||||
r.mu.RLock()
|
||||
dependedOn := make(map[string]bool)
|
||||
for _, e := range r.entries {
|
||||
if e.scope == nil {
|
||||
continue
|
||||
}
|
||||
for _, req := range e.def.Manifest.Requires {
|
||||
if svc, ok := r.services[req.Service]; ok && svc.pluginID != e.def.Manifest.ID {
|
||||
dependedOn[svc.pluginID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
requiredBy := make(map[string][]*pluginEntry)
|
||||
scheduled := make(map[string]bool)
|
||||
var allDue []*pluginEntry
|
||||
for _, e := range r.entries {
|
||||
for id, e := range r.entries {
|
||||
if e.scope == nil {
|
||||
continue
|
||||
}
|
||||
if !e.def.Desired || !r.requirementsSatisfiedLocked(e.def.Manifest.Requires) {
|
||||
allDue = append(allDue, e)
|
||||
if !dependedOn[e.def.Manifest.ID] {
|
||||
toDispose = append(toDispose, e)
|
||||
scheduled[id] = true
|
||||
}
|
||||
for _, req := range e.def.Manifest.Requires {
|
||||
if req.Optional {
|
||||
continue
|
||||
}
|
||||
if svc, ok := r.services[req.Service]; ok && svc.pluginID != id {
|
||||
requiredBy[svc.pluginID] = append(requiredBy[svc.pluginID], e)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A provider scheduled to close still publishes its service. Include
|
||||
// its required consumers before selecting leaves, even when their
|
||||
// requirements are currently satisfied.
|
||||
for i := 0; i < len(allDue); i++ {
|
||||
for _, consumer := range requiredBy[allDue[i].def.Manifest.ID] {
|
||||
id := consumer.def.Manifest.ID
|
||||
if !scheduled[id] {
|
||||
scheduled[id] = true
|
||||
allDue = append(allDue, consumer)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, e := range allDue {
|
||||
if len(requiredBy[e.def.Manifest.ID]) == 0 {
|
||||
toDispose = append(toDispose, e)
|
||||
}
|
||||
}
|
||||
// Break cycles if every due plugin is mutually depended upon.
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package qmp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type commandRecorder struct {
|
||||
command string
|
||||
args any
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *commandRecorder) Execute(command string, args any) error {
|
||||
r.command = command
|
||||
r.args = args
|
||||
r.calls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestScreendumpDisplay(t *testing.T) {
|
||||
q := &commandRecorder{}
|
||||
format, err := ScreendumpDisplay(q, "frame.ppm", "gfx", 1)
|
||||
if err != nil || format != "ppm" || q.command != "screendump" {
|
||||
t.Fatalf("display dump returned %q, %v, command %q", format, err, q.command)
|
||||
}
|
||||
args := q.args.(map[string]any)
|
||||
if args["filename"] != "frame.ppm" || args["format"] != "ppm" || args["device"] != "gfx" || args["head"] != 1 {
|
||||
t.Fatalf("unexpected display dump arguments: %v", args)
|
||||
}
|
||||
if _, err := ScreendumpDisplay(q, "primary.ppm", "", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args = q.args.(map[string]any)
|
||||
if len(args) != 2 {
|
||||
t.Fatalf("primary display dump should omit device and head: %v", args)
|
||||
}
|
||||
if _, err := ScreendumpDisplay(q, "invalid.ppm", "", 1); err == nil || q.calls != 2 {
|
||||
t.Fatalf("invalid display head reached QEMU: calls=%d err=%v", q.calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMouseButtonAtReportsPositionAndPressTogether(t *testing.T) {
|
||||
q := &commandRecorder{}
|
||||
if err := MouseButtonAt(q, 99, 0, 100, 50, "left", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args, err := json.Marshal(q.args)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := `{"events":[{"data":{"axis":"x","value":32767},"type":"abs"},{"data":{"axis":"y","value":0},"type":"abs"},{"data":{"button":"left","down":true},"type":"btn"}]}`
|
||||
if q.calls != 1 || q.command != "input-send-event" || string(args) != want {
|
||||
t.Fatalf("unexpected mouse press: calls=%d command=%q args=%s", q.calls, q.command, args)
|
||||
}
|
||||
if err := MouseButtonAt(q, 100, 0, 100, 50, "left", true); err == nil || q.calls != 1 {
|
||||
t.Fatalf("invalid position reached QEMU: calls=%d err=%v", q.calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQKeyCode(t *testing.T) {
|
||||
for vk, want := range map[uint32]string{
|
||||
'A': "a", '9': "9", 0x11: "meta_l", 0xA3: "meta_r", 0x5B: "ctrl", 0xA5: "alt_r",
|
||||
0x21: "pgup", 0x22: "pgdn", 0x60: "kp_0", 0x87: "f24", 0xDB: "bracket_left", 0xE7: "",
|
||||
} {
|
||||
if got := QKeyCode(vk); got != want {
|
||||
t.Errorf("QKeyCode(%#02x) = %q, want %q", vk, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendKey(t *testing.T) {
|
||||
q := &recorder{}
|
||||
if err := SendKey(q, "meta_l", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(q.events) != 1 || q.events[0] != "meta_l up" {
|
||||
t.Fatalf("unexpected key release: %v", q.events)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ func Dial(ctx context.Context, network, addr string) (*Conn, error) {
|
||||
c := &Conn{nc: nc, scanner: bufio.NewScanner(nc)}
|
||||
c.scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
|
||||
stopCancel := context.AfterFunc(ctx, func() { _ = nc.Close() })
|
||||
defer stopCancel()
|
||||
_ = nc.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if !c.scanner.Scan() { // greeting
|
||||
nc.Close()
|
||||
@@ -38,6 +40,10 @@ func Dial(ctx context.Context, network, addr string) (*Conn, error) {
|
||||
nc.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
nc.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package qmp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
@@ -108,6 +109,32 @@ func sendKeys(q Executor, down bool, keys ...string) error {
|
||||
return q.Execute("input-send-event", map[string]any{"events": events})
|
||||
}
|
||||
|
||||
// SendKey sends one QKeyCode transition. Callers pair a press with a release.
|
||||
func SendKey(q Executor, key string, down bool) error {
|
||||
if q == nil {
|
||||
return errors.New("QMP session is unavailable")
|
||||
}
|
||||
return sendKeys(q, down, key)
|
||||
}
|
||||
|
||||
// ReleaseInputs clears held keys and pointer buttons in one QMP input report.
|
||||
func ReleaseInputs(q Executor, keys, buttons []string) error {
|
||||
if q == nil {
|
||||
return errors.New("QMP session is unavailable")
|
||||
}
|
||||
if len(keys)+len(buttons) == 0 {
|
||||
return nil
|
||||
}
|
||||
events := make([]map[string]any, 0, len(keys)+len(buttons))
|
||||
for _, key := range keys {
|
||||
events = append(events, keyEvent(key, false))
|
||||
}
|
||||
for _, button := range buttons {
|
||||
events = append(events, mouseButtonEvent(button, false))
|
||||
}
|
||||
return q.Execute("input-send-event", map[string]any{"events": events})
|
||||
}
|
||||
|
||||
// TypeStrokes presses and releases each key in turn, holding it for hold and
|
||||
// waiting gap before the next, so the guest's USB keyboard queue never fills.
|
||||
// On any error or cancel it releases Shift so no modifier is left held down.
|
||||
|
||||
+29
-4
@@ -52,18 +52,43 @@ func MouseMove(q Executor, x, y, width, height int) error {
|
||||
if q == nil {
|
||||
return errors.New("QMP session is unavailable")
|
||||
}
|
||||
events, err := mouseMoveEvents(x, y, width, height)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return q.Execute("input-send-event", map[string]any{"events": events})
|
||||
}
|
||||
|
||||
// MouseButtonAt sends the position and one button transition in the same
|
||||
// input report, so a press cannot land at the pointer's previous position.
|
||||
func MouseButtonAt(q Executor, x, y, width, height int, button string, down bool) error {
|
||||
if q == nil {
|
||||
return errors.New("QMP session is unavailable")
|
||||
}
|
||||
button = normalizeMouseButton(button)
|
||||
if !validMouseButton(button) {
|
||||
return fmt.Errorf("unsupported mouse button %q", button)
|
||||
}
|
||||
events, err := mouseMoveEvents(x, y, width, height)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return q.Execute("input-send-event", map[string]any{"events": append(events, mouseButtonEvent(button, down))})
|
||||
}
|
||||
|
||||
func mouseMoveEvents(x, y, width, height int) ([]any, error) {
|
||||
ax, err := absoluteAxis(x, width)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mouse x coordinate: %w", err)
|
||||
return nil, fmt.Errorf("mouse x coordinate: %w", err)
|
||||
}
|
||||
ay, err := absoluteAxis(y, height)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mouse y coordinate: %w", err)
|
||||
return nil, fmt.Errorf("mouse y coordinate: %w", err)
|
||||
}
|
||||
return q.Execute("input-send-event", map[string]any{"events": []any{
|
||||
return []any{
|
||||
map[string]any{"type": "abs", "data": map[string]any{"axis": "x", "value": ax}},
|
||||
map[string]any{"type": "abs", "data": map[string]any{"axis": "y", "value": ay}},
|
||||
}})
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MouseButton sends one supported QEMU mouse button transition.
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package qmp
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Screendump asks QEMU to write the current frame of console 0 to path as a
|
||||
// binary PPM and returns "ppm". PPM rather than PNG on purpose: QEMU encodes
|
||||
@@ -8,7 +11,24 @@ import "context"
|
||||
// ~820 ms there against ~35 ms for PPM (measured 2026-11-28, QEMU 11.1), so
|
||||
// PNG would stall the guest each time the page refreshes its thumbnail.
|
||||
func (c *Conn) Screendump(path string) (string, error) {
|
||||
if err := c.Execute("screendump", map[string]any{"filename": path, "format": "ppm"}); err != nil {
|
||||
return ScreendumpDisplay(c, path, "", 0)
|
||||
}
|
||||
|
||||
// ScreendumpDisplay writes a binary PPM from the requested display device and
|
||||
// head. An empty device selects QEMU's primary console.
|
||||
func ScreendumpDisplay(q Executor, path, device string, head int) (string, error) {
|
||||
if q == nil {
|
||||
return "", errors.New("QMP session is unavailable")
|
||||
}
|
||||
if head < 0 || (device == "" && head != 0) {
|
||||
return "", errors.New("invalid QMP display head")
|
||||
}
|
||||
args := map[string]any{"filename": path, "format": "ppm"}
|
||||
if device != "" {
|
||||
args["device"] = device
|
||||
args["head"] = head
|
||||
}
|
||||
if err := q.Execute("screendump", args); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "ppm", nil
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package qmp
|
||||
|
||||
import "strconv"
|
||||
|
||||
// QKeyCode maps a Windows virtual-key code from an app window to a macOS guest
|
||||
// key. Windows Ctrl acts as Command for familiar shortcuts, and the Windows
|
||||
// key acts as Control. OEM punctuation follows the US keyboard layout.
|
||||
// An empty result means the virtual key has no mapping.
|
||||
func QKeyCode(vk uint32) string {
|
||||
switch {
|
||||
case vk >= 'A' && vk <= 'Z':
|
||||
return string(rune(vk - 'A' + 'a'))
|
||||
case vk >= '0' && vk <= '9':
|
||||
return string(rune(vk))
|
||||
case vk >= 0x60 && vk <= 0x69: // VK_NUMPAD0 through VK_NUMPAD9
|
||||
return "kp_" + strconv.FormatUint(uint64(vk-0x60), 10)
|
||||
case vk >= 0x70 && vk <= 0x87: // VK_F1 through VK_F24
|
||||
return "f" + strconv.FormatUint(uint64(vk-0x70+1), 10)
|
||||
default:
|
||||
return windowsVirtualKeys[vk]
|
||||
}
|
||||
}
|
||||
|
||||
var windowsVirtualKeys = map[uint32]string{
|
||||
0x08: "backspace", // VK_BACK
|
||||
0x09: "tab", // VK_TAB
|
||||
0x0D: "ret", // VK_RETURN
|
||||
0x10: "shift", // VK_SHIFT
|
||||
0x11: "meta_l", // VK_CONTROL
|
||||
0x12: "alt", // VK_MENU
|
||||
0x13: "pause", // VK_PAUSE
|
||||
0x14: "caps_lock", // VK_CAPITAL
|
||||
0x1B: "esc", // VK_ESCAPE
|
||||
0x20: "spc", // VK_SPACE
|
||||
0x21: "pgup", // VK_PRIOR
|
||||
0x22: "pgdn", // VK_NEXT
|
||||
0x23: "end", // VK_END
|
||||
0x24: "home", // VK_HOME
|
||||
0x25: "left", // VK_LEFT
|
||||
0x26: "up", // VK_UP
|
||||
0x27: "right", // VK_RIGHT
|
||||
0x28: "down", // VK_DOWN
|
||||
0x2C: "print", // VK_SNAPSHOT
|
||||
0x2D: "insert", // VK_INSERT
|
||||
0x2E: "delete", // VK_DELETE
|
||||
0x5B: "ctrl", // VK_LWIN
|
||||
0x5C: "ctrl_r", // VK_RWIN
|
||||
0x5D: "menu", // VK_APPS
|
||||
0x6A: "kp_multiply", // VK_MULTIPLY
|
||||
0x6B: "kp_add", // VK_ADD
|
||||
0x6D: "kp_subtract", // VK_SUBTRACT
|
||||
0x6E: "kp_decimal", // VK_DECIMAL
|
||||
0x6F: "kp_divide", // VK_DIVIDE
|
||||
0x90: "num_lock", // VK_NUMLOCK
|
||||
0x91: "scroll_lock", // VK_SCROLL
|
||||
0xA0: "shift", // VK_LSHIFT
|
||||
0xA1: "shift_r", // VK_RSHIFT
|
||||
0xA2: "meta_l", // VK_LCONTROL
|
||||
0xA3: "meta_r", // VK_RCONTROL
|
||||
0xA4: "alt", // VK_LMENU
|
||||
0xA5: "alt_r", // VK_RMENU
|
||||
0xBA: "semicolon", // VK_OEM_1
|
||||
0xBB: "equal", // VK_OEM_PLUS
|
||||
0xBC: "comma", // VK_OEM_COMMA
|
||||
0xBD: "minus", // VK_OEM_MINUS
|
||||
0xBE: "dot", // VK_OEM_PERIOD
|
||||
0xBF: "slash", // VK_OEM_2
|
||||
0xC0: "grave_accent", // VK_OEM_3
|
||||
0xDB: "bracket_left", // VK_OEM_4
|
||||
0xDC: "backslash", // VK_OEM_5
|
||||
0xDD: "bracket_right", // VK_OEM_6
|
||||
0xDE: "apostrophe", // VK_OEM_7
|
||||
0xE2: "less", // VK_OEM_102
|
||||
}
|
||||
@@ -311,6 +311,15 @@
|
||||
"err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone",
|
||||
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
|
||||
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
|
||||
"err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows",
|
||||
"err.app_window_disabled": "Enable macOS App Windows under Plugins and try again",
|
||||
"err.app_window_guest_tools": "Connect Guest Tools in {name} and try again",
|
||||
"err.app_window_guest_tools_update": "Update Guest Tools in {name} and try again",
|
||||
"err.app_window_open": "Close the current separate app window first",
|
||||
"err.app_window_pointer": "Enable the USB tablet for {name} and try again",
|
||||
"err.app_window_no_window": "Open a foreground app on the single-display desktop of {name} and try again",
|
||||
"err.app_window_capture": "Could not capture the app window in {name}",
|
||||
"tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again",
|
||||
"err.vm_window_not_found": "Couldn’t find the display window for {name}",
|
||||
"err.fullscreen_failed": "Couldn’t toggle full screen for {name}",
|
||||
"err.guest_tools_disabled": "Guest Tools Transport is turned off on the Plugins page; turn it on to use clipboard, shared folders and keep-awake",
|
||||
|
||||
@@ -311,6 +311,15 @@
|
||||
"err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆",
|
||||
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
|
||||
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
|
||||
"err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机",
|
||||
"err.app_window_disabled": "在插件页启用 macOS 应用窗口后重试",
|
||||
"err.app_window_guest_tools": "连接 {name} 的 Guest Tools 后再打开独立窗口",
|
||||
"err.app_window_guest_tools_update": "更新 {name} 的 Guest Tools 后再打开独立窗口",
|
||||
"err.app_window_open": "先关闭已打开的独立应用窗口",
|
||||
"err.app_window_pointer": "在 {name} 中启用 USB 数位板后再打开独立窗口",
|
||||
"err.app_window_no_window": "在 {name} 的单屏桌面打开一个前台应用窗口后重试",
|
||||
"err.app_window_capture": "无法获取 {name} 的应用画面",
|
||||
"tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次",
|
||||
"err.vm_window_not_found": "找不到 {name} 的显示窗口",
|
||||
"err.fullscreen_failed": "无法切换 {name} 的全屏状态",
|
||||
"err.guest_tools_disabled": "Guest Tools 传输服务已在插件页停用,启用后才能使用剪贴板、共享文件夹与防休眠",
|
||||
|
||||
Reference in new issue
Block a user