Files
Reims-Go/frontend/src/wails.ts
T

220 lines
9.5 KiB
TypeScript

// Backend calls are the Wails-generated bindings (wailsjs/go/app/App). Only
// the calls whose results carry the unions or nil slices added in types.ts are
// re-typed here; everything else passes through unchanged.
//
// At module boot we privately capture `window.go.app.App` and `window.runtime`
// so `hideWailsGlobals()` can remove them from `window` before running any
// Tier-3 interactive theme script without breaking the app's own calls.
import * as Go from '../wailsjs/go/app/App'
import {
EventsEmit as RawEventsEmit,
EventsOn as RawEventsOn,
OnFileDrop as RawOnFileDrop,
OnFileDropOff as RawOnFileDropOff,
WindowMinimise as RawWindowMinimise,
WindowToggleMaximise as RawWindowToggleMaximise,
} from '../wailsjs/runtime/runtime'
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
interface WailsWindow {
go?: { app?: { App?: Record<string, AnyFn> } }
runtime?: Record<string, AnyFn>
}
const wailsWin = window as unknown as WailsWindow
const capturedGoApp: Record<string, AnyFn> = wailsWin.go?.app?.App ? { ...wailsWin.go.app.App } : {}
const capturedRuntime: Record<string, AnyFn> = wailsWin.runtime ? { ...wailsWin.runtime } : {}
let globalsHidden = false
const boundGo = {} as typeof Go
for (const key of Object.keys(Go) as Array<keyof typeof Go>) {
const fn = capturedGoApp[key as string]
;(boundGo as Record<string, unknown>)[key as string] = fn
? (...args: never[]) => fn(...args)
: Go[key]
}
/**
* Hides Wails binding globals (`window.go` and unsafe `window.runtime` methods)
* before mounting an interactive theme script. Only `ResolveFilePaths`
* (required internally by Wails's native drag-and-drop bridge) is retained on a
* frozen runtime stub.
*/
export function hideWailsGlobals(): void {
if (globalsHidden) return
globalsHidden = true
try {
delete wailsWin.go
Object.defineProperty(window, 'go', {
value: undefined,
writable: false,
configurable: false,
enumerable: false,
})
} catch (e) {
// non-configurable in some test environments
console.warn('[wails] hide window.go failed:', e)
}
try {
const minimalRuntime = typeof capturedRuntime.ResolveFilePaths === 'function'
? Object.freeze({ ResolveFilePaths: capturedRuntime.ResolveFilePaths })
: undefined
delete wailsWin.runtime
Object.defineProperty(window, 'runtime', {
value: minimalRuntime,
writable: false,
configurable: false,
enumerable: false,
})
} catch (e) {
// ignore if non-configurable
console.warn('[wails] hide window.runtime failed:', e)
}
}
export function OnFileDrop(
callback: (x: number, y: number, paths: string[]) => void,
useDropTarget: boolean,
): void {
if (typeof capturedRuntime.OnFileDrop === 'function') {
;(capturedRuntime.OnFileDrop as (cb: typeof callback, useTarget: boolean) => void)(callback, useDropTarget)
return
}
RawOnFileDrop(callback, useDropTarget)
}
export function OnFileDropOff(): void {
if (typeof capturedRuntime.OnFileDropOff === 'function') {
;(capturedRuntime.OnFileDropOff as () => void)()
return
}
RawOnFileDropOff()
}
export function WindowMinimise(): void {
if (typeof capturedRuntime.WindowMinimise === 'function') {
;(capturedRuntime.WindowMinimise as () => void)()
return
}
RawWindowMinimise()
}
export function WindowToggleMaximise(): void {
if (typeof capturedRuntime.WindowToggleMaximise === 'function') {
;(capturedRuntime.WindowToggleMaximise as () => void)()
return
}
RawWindowToggleMaximise()
}
function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
const off = typeof capturedRuntime.EventsOnMultiple === 'function'
? (capturedRuntime.EventsOnMultiple as (name: string, fn: (data: T) => void, max: number) => () => void)(
eventName,
cb,
-1,
)
: RawEventsOn(eventName, cb)
// Unsubscribing notifies the backend over IPC, which throws when the bridge
// is down (e.g. a browser preview); a failed unsubscribe must not take the
// unmounting component down with it.
return () => {
try {
off()
} catch (e) {
console.warn('[wails] unsubscribe event failed:', eventName, e)
}
}
}
function eventsEmit(eventName: string, ...args: unknown[]): void {
try {
if (typeof capturedRuntime.EventsEmit === 'function') {
;(capturedRuntime.EventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
return
}
;(RawEventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
} catch (e) {
// Wails runtime may be unavailable (e.g. standalone preview)
console.warn('[wails] emit event failed:', eventName, e)
}
}
export const api = {
...boundGo,
GetVMNetworkSettings: boundGo.GetVMNetworkSettings as (name: string) => Promise<VMNetworkSettings>,
GetVMNetworkPlan: boundGo.GetVMNetworkPlan as (name: string, mode: string, uplink: string) => Promise<VMNetworkPlan>,
ListNetworkAdapters: boundGo.ListNetworkAdapters as () => Promise<VMNetworkSettings['adapters']>,
ApplyVMNetwork: boundGo.ApplyVMNetwork as (name: string, mode: string, uplink: string) => Promise<VMNetworkSettings>,
InstallNpcap: boundGo.InstallNpcap as () => Promise<void>,
GetState: boundGo.GetState as () => Promise<AppState>,
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise<VMInfo>,
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
ListPlugins: boundGo.ListPlugins as () => Promise<PluginInfo[] | null>,
InspectPluginArchive: boundGo.InspectPluginArchive as (path: string) => Promise<ScanReport>,
ScanInstalledPlugin: boundGo.ScanInstalledPlugin as (id: string) => Promise<ScanReport>,
BrowsePluginMarket: boundGo.BrowsePluginMarket as (query: string, kind: string, includeAlpha: boolean, forceRefresh: boolean) => Promise<MarketBrowseResult>,
PeekPluginMarket: boundGo.PeekPluginMarket as (query: string, kind: string) => Promise<MarketBrowseResult>,
InstallMarketPlugin: boundGo.InstallMarketPlugin as (id: string, includeAlpha: boolean) => Promise<PluginInfo>,
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
}
export interface MarketInstallProgress {
id: string
phase: 'download' | 'install'
done: number
total: number
}
export interface ElevationPrompt {
id: string
plugin_id: string
plugin_name: string
publisher?: string
trust?: string
action: string
needs_reboot?: boolean
needs_logoff?: boolean
}
export const DROP_NETWORK_VOLUMES_DENIED = 'Network Volumes permission denied'
export const events = {
onHostDrop: (cb: (payload: { vm: string; drop_id: string; delivered: string[]; skipped?: string[]; mode: string }) => void) => eventsOn('reims:host-drop', cb),
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
onPluginInstall: (cb: (p: MarketInstallProgress) => void) => eventsOn('reims:plugin-install', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb),
// Closing the window while a download runs (internal/app/app.go beforeClose).
onConfirmCloseDownloads: (cb: () => void) => eventsOn('reims:confirm-close-downloads', cb),
// Controlled elevation request from a guest driver plugin (internal/app/elevate_flow.go).
onElevateRequest: (cb: (req: ElevationPrompt) => void) => eventsOn('reims:elevate-request', cb),
onElevateResolved: (cb: (id: string) => void) => eventsOn('reims:elevate-resolved', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
emitUIError: (detail: string) => eventsEmit('reims:ui-error', detail),
emitTheme: (theme: 'light' | 'dark') => eventsEmit('reims:theme', theme),
}