Skip to content

An open-source, self-hosted system for apps built with web technologies.

Unify authoritative windows and Desktop presentations

zohayrslileha3581d0cc307
diff --git a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
index 313e0a8..a94586d 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -1,5 +1,4 @@
import { type ProcessSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process"
-import ProcessManager from "./process-manager"
import Window from "./window"
/** One desktop counterpart of the server-authoritative client state. */
@@ -11,9 +10,9 @@ export default class ClientState {
public readonly service: NonNullable<ProcessSnapshot["client"]>["service"]
- public constructor(processManager: ProcessManager, process: string, payload: NonNullable<ProcessSnapshot["client"]>) {
+ public constructor(window: Window, payload: NonNullable<ProcessSnapshot["client"]>) {
- this.window = new Window(processManager, process, payload.window)
+ this.window = window
this.sameOrigin = payload.sameOrigin
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
index 8ba5e84..595d210 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -51,7 +51,7 @@ export default class ProcessManager extends TheLink {
for (const [identity, process] of this.processes) {
- const window = process.client?.window
+ const window = process.client ? process.clientEndpoint?.window : null
if (!window || window.minimized || window.layer !== layer || window.depth <= depth) continue
@@ -204,7 +204,7 @@ export default class ProcessManager extends TheLink {
if (!payload) return
- this.processes.get(payload.identity)?.client?.window.follow(payload.window)
+ this.processes.get(payload.identity)?.clientEndpoint?.window.follow(payload.window)
return this.list()
}
@@ -346,6 +346,20 @@ export default class ProcessManager extends TheLink {
return this.followed(payload)
}
+ @Subscribe("/change-frame")
+ @Publish("/processes", "inbound")
+ protected async changeFrameHandle(payload: { identity: string, window: WindowSnapshot } | null) {
+
+ return this.followed(payload)
+ }
+
+ @Subscribe("/change-opening-transaction")
+ @Publish("/processes", "inbound")
+ protected async changeOpeningTransactionHandle(payload: { identity: string, window: WindowSnapshot } | null) {
+
+ return this.followed(payload)
+ }
+
@Subscribe("/maximize")
@Publish("/processes", "inbound")
protected async maximizeHandle(payload: { identity: string, window: WindowSnapshot } | null) {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
index b256489..0a8dc02 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -1,11 +1,13 @@
import { ProcessSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process"
import ProcessManager from "./process-manager"
import ClientState from "./client-state"
+import Window from "./window"
/**
* A running instance, as this side holds it: rebuilt from what the core
- * transmitted. Its client state owns the Window counterpart while that state
- * is live. Every act is a request; the truth answers with an echo.
+ * transmitted. Its Client Endpoint retains its Window counterpart independently
+ * of the current execution context. Every act is a request; the truth answers
+ * with an echo.
*/
export default class Process {
@@ -29,6 +31,9 @@ export default class Process {
public client: ClientState | null
+ /** Permanent Client Endpoint state retained between execution contexts. */
+ public readonly clientEndpoint: Readonly<{ window: Window }> | null
+
// Retained lineage from creation. It remains sufficient to reconstruct
// the same Process handle after the parent leaves the live registry.
public readonly parent: ProcessLineage | null
@@ -52,7 +57,11 @@ export default class Process {
this.server = payload.server
- this.client = payload.client ? new ClientState(processManager, payload.identity, payload.client) : null
+ this.clientEndpoint = payload.clientEndpoint
+ ? Object.freeze({ window: new Window(processManager, payload.identity, payload.clientEndpoint.window) })
+ : null
+
+ this.client = payload.client && this.clientEndpoint ? new ClientState(this.clientEndpoint.window, payload.client) : null
this.parent = payload.parent
@@ -84,7 +93,9 @@ export default class Process {
public clientStarted(payload: ProcessSnapshot) {
- if (!payload.client) return
+ if (!payload.client || !this.clientEndpoint) return
+
+ if (payload.clientEndpoint) this.clientEndpoint.window.follow(payload.clientEndpoint.window)
// A Process creation snapshot already contains every endpoint that is
// live at birth. Its following lifecycle announcement describes that
@@ -92,14 +103,12 @@ export default class Process {
// inventing a second local incarnation for the Window Manager.
if (this.client) {
- this.client.window.follow(payload.client.window)
-
this.client.sameOrigin = payload.client.sameOrigin
return
}
- this.client = new ClientState(this.processManager, this.identity, payload.client)
+ this.client = new ClientState(this.clientEndpoint.window, payload.client)
}
public clientStopped() {
diff --git a/source/client/core/link-manager/auth-manager/process-manager/window.ts b/source/client/core/link-manager/auth-manager/process-manager/window.ts
index 1cc8e8e..0b9398b 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,5 +1,5 @@
import { type WindowSnapshot, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
-import { type WindowGeometry, type WindowLayer, type WindowState } from "@phreshos/core"
+import { type WindowFrame, type WindowGeometry, type WindowLayer, type WindowState, type WindowTransaction } from "@phreshos/core"
import ProcessManager from "./process-manager"
/**
@@ -35,6 +35,10 @@ export default class Window implements Omit<WindowState, "front"> {
public header: boolean
+ public frame: WindowFrame
+
+ public transaction: WindowTransaction
+
// The authoritative Desktop layer.
public layer: WindowLayer
@@ -44,6 +48,10 @@ export default class Window implements Omit<WindowState, "front"> {
this.header = payload.header
+ this.frame = payload.frame
+
+ this.transaction = payload.transaction
+
this.layer = payload.layer
this.processManager = processManager
@@ -69,6 +77,10 @@ export default class Window implements Omit<WindowState, "front"> {
this.header = payload.header
+ this.frame = payload.frame
+
+ this.transaction = payload.transaction
+
this.layer = payload.layer
this.position = payload.position
@@ -108,6 +120,16 @@ export default class Window implements Omit<WindowState, "front"> {
await this.processManager.$outbound.publish("/change-header", this.process, header)
}
+ public async changeFrame(frame: WindowFrame) {
+
+ await this.processManager.$outbound.publish("/change-frame", this.process, frame)
+ }
+
+ public async changeOpeningTransaction(transaction: WindowTransaction) {
+
+ await this.processManager.$outbound.publish("/change-opening-transaction", this.process, transaction)
+ }
+
// To the front of its own layer, and nothing else. A hidden window
// raised stays hidden and appears at its new place in the order when
// it is shown.
diff --git a/source/client/view/appearance/motion.ts b/source/client/view/appearance/motion.ts
index d91e2e7..ce4188c 100644
--- a/source/client/view/appearance/motion.ts
+++ b/source/client/view/appearance/motion.ts
@@ -1,4 +1,4 @@
-import { type AppearanceTransaction, type Easing } from "@phreshos/core"
+import { type AppearanceTransaction, type Easing, type WindowTransaction } from "@phreshos/core"
import { type Transition } from "motion/react"
const easings: Record<Exclude<Easing, readonly number[]>, Transition["ease"]> = {
@@ -19,6 +19,18 @@ export function motionTransition(transaction: AppearanceTransaction, reduced = f
}
}
+/** Resolves a Window transaction against the current Appearance transaction. */
+export function resolveWindowTransaction(transaction: WindowTransaction, appearance: AppearanceTransaction): AppearanceTransaction | null {
+
+ if (transaction === false) return null
+
+ if (transaction === true) return appearance
+
+ if (typeof transaction === "number") return { duration: transaction, easing: appearance.easing }
+
+ return transaction
+}
+
/** Translates the public easing vocabulary into a CSS timing function. */
export function cssEasing(easing: Easing) {
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index 2ac8eb7..6b5e419 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -209,5 +209,5 @@ type HostedProcessRecord = {
name: string | null
options: Record<string, string>
server: { ready: boolean, service: boolean } | null
- client: { window: unknown, service: boolean } | null
+ client: { service: boolean } | null
}
diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.ts
index d5ddddb..2d797a1 100644
--- a/source/client/view/components/desktop-host/client-host.ts
+++ b/source/client/view/components/desktop-host/client-host.ts
@@ -5,7 +5,7 @@ import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
import { type RefObject, useCallback, useLayoutEffect, useRef, useState } from "react"
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
-import { type LocalWindowHost } from "./local-window"
+import { type WindowPresentationHost } from "./window-presentation"
import messagepack from "@the-link/messagepack"
/**
@@ -13,7 +13,7 @@ import messagepack from "@the-link/messagepack"
* It owns frame messages and the measured desktop containing those frames;
* neither fact participates in rendering.
*/
-export default function useClientHost(authManager: AuthManager, desktop: RefObject<HTMLDivElement | null>, sources: Map<string, HTMLIFrameElement | null>, localWindow: LocalWindowHost) {
+export default function useClientHost(authManager: AuthManager, desktop: RefObject<HTMLDivElement | null>, sources: Map<string, HTMLIFrameElement | null>, presentation: WindowPresentationHost) {
const windowSurfaceRef = useRef<HTMLDivElement>(null)
@@ -203,7 +203,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
boundaries.current.get(identity)?.release().catch(() => undefined)
- boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopViewport, traffic, localWindow))
+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopViewport, traffic, presentation))
return
}
@@ -218,7 +218,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
boundary?.release().catch(() => undefined)
- }, [authManager, desktopViewport, localWindow, sources, traffic])
+ }, [authManager, desktopViewport, presentation, sources, traffic])
const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index 674f7da..8947e29 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -5,7 +5,7 @@ import ClientTraffic from "./client-traffic"
import { failed, succeeded } from "@libs/request-outcome"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isServiceKey, parseProgramInstallOptions, type DesktopViewportSnapshot, type ServiceKey, type ShellOptions } from "@phreshos/core"
-import { type LocalWindowHost } from "./local-window"
+import { type WindowPresentationHost } from "./window-presentation"
import messagepack from "@the-link/messagepack"
import { sdkProcess, type SdkProcessSource } from "./sdk-records"
import SystemAccess from "./system-access"
@@ -23,7 +23,9 @@ export default class ClientProcessBoundary extends TheLink {
private readonly traffic: ClientTraffic
- private readonly localWindow: LocalWindowHost
+ private readonly presentation: WindowPresentationHost
+
+ private readonly presentationSubscriptions = new Map<string, () => void>()
private readonly systemAccess: SystemAccess
@@ -60,7 +62,7 @@ export default class ClientProcessBoundary extends TheLink {
private leased: string | null = null
- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: () => DesktopViewportSnapshot, traffic: ClientTraffic, localWindow: LocalWindowHost) {
+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: () => DesktopViewportSnapshot, traffic: ClientTraffic, presentation: WindowPresentationHost) {
super()
@@ -74,7 +76,7 @@ export default class ClientProcessBoundary extends TheLink {
this.traffic = traffic
- this.localWindow = localWindow
+ this.presentation = presentation
this.systemAccess = new SystemAccess(authManager, pane)
@@ -92,7 +94,7 @@ export default class ClientProcessBoundary extends TheLink {
// envelopes only after the new server-host lease exists.
const pending = this.pending.splice(0)
- if (this.leased) this.localWindow.release(this.pane)
+ if (this.leased) this.presentation.release(this.pane)
this.resetEndpoint()
@@ -126,7 +128,7 @@ export default class ClientProcessBoundary extends TheLink {
public async release() {
- this.localWindow.release(this.pane)
+ this.presentation.release(this.pane)
const owner = this.leased
@@ -235,7 +237,7 @@ export default class ClientProcessBoundary extends TheLink {
this.trackSystemSubscription(values)
- host(this.authManager, this.pane, this.viewport, () => this.owner, this.localWindow)(values[0], ...values.slice(1)).catch((error: Error) => {
+ host(this.authManager, this.pane, this.viewport, () => this.owner, this.presentation)(values[0], ...values.slice(1)).catch((error: Error) => {
if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {
@@ -456,7 +458,13 @@ export default class ClientProcessBoundary extends TheLink {
this.subscriptions.set(subscription, description)
- if (!localPropertySubscription(description)) this.addTraffic(kind, route, event)
+ if (presentationSubscription(description)) {
+ this.presentationSubscriptions.set(subscription, this.presentation.observe(this.pane, event, (word, value) => {
+ this.deliver("presentation", word, value).catch(() => undefined)
+ }))
+ }
+
+ if (!desktopOwnedSubscription(description)) this.addTraffic(kind, route, event)
if (this.owner && directSubscription(description)) this.authManager.processManager.subscribeFrame(this.pane, this.owner, subscription, kind, event).catch(() => undefined)
@@ -534,14 +542,14 @@ export default class ClientProcessBoundary extends TheLink {
this.answerRequest(
question,
- host(this.authManager, this.pane, this.viewport, () => this.owner, this.localWindow)(args[0], ...args.slice(1)),
+ host(this.authManager, this.pane, this.viewport, () => this.owner, this.presentation)(args[0], ...args.slice(1)),
() => { this.authManager.cancelPermission(this.pane, args[1] as string).catch(() => undefined) }
)
return
}
- this.answerRequest(question, host(this.authManager, this.pane, this.viewport, () => this.owner, this.localWindow)(args[0], ...args.slice(1)))
+ this.answerRequest(question, host(this.authManager, this.pane, this.viewport, () => this.owner, this.presentation)(args[0], ...args.slice(1)))
}
private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {
@@ -868,6 +876,10 @@ export default class ClientProcessBoundary extends TheLink {
this.subscriptions.delete(subscription)
+ this.presentationSubscriptions.get(subscription)?.()
+
+ this.presentationSubscriptions.delete(subscription)
+
if (this.desktopPreferencesSubscriptions.delete(subscription) && this.desktopPreferencesSubscriptions.size === 0) {
this.stopDesktopPreferences?.()
@@ -973,6 +985,10 @@ export default class ClientProcessBoundary extends TheLink {
this.appearanceSubscriptions.clear()
+ for (const stop of this.presentationSubscriptions.values()) stop()
+
+ this.presentationSubscriptions.clear()
+
this.stopDesktopPreferences?.()
this.stopDesktopPreferences = null
@@ -1118,9 +1134,14 @@ function appearanceSubscription(subscription: EndpointSubscription) {
return subscription.kind === "publish" && subscription.route === "host-appearance" && (subscription.event === null || subscription.event === "change")
}
-function localPropertySubscription(subscription: EndpointSubscription) {
+function presentationSubscription(subscription: EndpointSubscription) {
+
+ return subscription.kind === "publish" && subscription.route === "presentation"
+}
+
+function desktopOwnedSubscription(subscription: EndpointSubscription) {
- return desktopPreferencesSubscription(subscription) || appearanceSubscription(subscription)
+ return desktopPreferencesSubscription(subscription) || appearanceSubscription(subscription) || presentationSubscription(subscription)
}
function directSubscription(subscription: EndpointSubscription) {
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 065713b..2a303b2 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -20,13 +20,14 @@ import {
type ProgramIconSize
} from "@phreshos/core"
import {
- localGeometry,
- localPosition,
- localSize,
- requireLocalSurfaceLayer,
- parseLocalWindowTransaction,
- type LocalWindowHost
-} from "./local-window"
+ presentationFrame,
+ presentationGeometry,
+ presentationPosition,
+ presentationSize,
+ presentationTransaction,
+ type WindowPresentationHost
+} from "./window-presentation"
+import { isWindowPresentationProperty, requireWindowPresentationTransactions } from "@shared/window-layers"
import SystemAccess from "./system-access"
/** A host answer whose stream must be transferred rather than cloned. */
@@ -36,7 +37,7 @@ export class TransferredAnswer {
}
/** Adapts the complete System contract and contextual Desktop capabilities to one Client frame. */
-export default function host(authManager: AuthManager, pane: string, viewport: () => DesktopViewportSnapshot, frameOwner: () => string | null, localWindow: LocalWindowHost) {
+export default function host(authManager: AuthManager, pane: string, viewport: () => DesktopViewportSnapshot, frameOwner: () => string | null, presentation: WindowPresentationHost) {
const { processManager, programManager } = authManager
@@ -135,11 +136,18 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return found.client
}
- function localProcess(value: unknown) {
+ function windowOf(found: ClientProcess) {
+
+ if (!found.clientEndpoint) throw new Error("This Program declared no Client Endpoint")
+
+ return found.clientEndpoint.window
+ }
+
+ function presentationProcess(value: unknown) {
const found = holdProcess(value)
- if (found !== process()) throw new Error("Local Window operations belong to the current Client Context")
+ if (found !== process()) throw new Error("Window presentation operations belong to the current Client Context")
clientOf(found)
@@ -295,13 +303,25 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
return []
}
- if (word === "exists") {
+ if (word === "running") {
const target = await permittedProcess(args[1])
- if (args[0] === "server") return [target.server !== null]
+ if (args[0] === "server") {
+
+ const program = authManager.programManager.programs.get(target.program)
+
+ if (!program?.server) throw new Error("This Program declared no Server Endpoint")
+
+ return [target.server !== null]
+ }
+
+ if (args[0] === "client") {
- if (args[0] === "client") return [target.client !== null]
+ if (!target.clientEndpoint) throw new Error("This Program declared no Client Endpoint")
+
+ return [target.client !== null]
+ }
throw new Error("A Process endpoint is server or client")
}
@@ -344,6 +364,13 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
+ const program = authManager.programManager.programs.get(target.program)
+
+ if (endpoint === "server" ? !program?.server : !target.clientEndpoint) {
+
+ throw new Error(`This Program declared no ${endpoint === "server" ? "Server" : "Client"} Endpoint`)
+ }
+
return [await processManager.endpointIsService(pane, address(target), endpoint)]
}
@@ -737,7 +764,7 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "window") {
const target = await permittedProcess(args[0])
- const shown = clientOf(target).window
+ const shown = windowOf(target)
return [{
@@ -745,6 +772,10 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
header: shown.header,
+ frame: shown.frame,
+
+ transaction: shown.transaction,
+
position: shown.position,
size: shown.size,
@@ -761,129 +792,127 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (word === "move") {
- await clientOf(await permittedProcess(args[0])).window.move(args[1] as never)
+ await windowOf(await permittedProcess(args[0])).move(args[1] as never)
return [pane]
}
if (word === "resize") {
- await clientOf(await permittedProcess(args[0])).window.resize(args[1] as never)
+ await windowOf(await permittedProcess(args[0])).resize(args[1] as never)
return [pane]
}
if (word === "setGeometry") {
- await clientOf(await permittedProcess(args[0])).window.setGeometry(args[1] as never)
+ await windowOf(await permittedProcess(args[0])).setGeometry(args[1] as never)
return [pane]
}
- if (word === "windowLocalMove") {
-
- const target = localProcess(args[0])
- await localWindow.move(target.identity, localPosition(args[1]), parseLocalWindowTransaction(args[2]))
-
- return []
+ if (word === "windowPresentationRead") {
+ const target = presentationProcess(args[0])
+ if (!isWindowPresentationProperty(args[1])) throw new Error("The Window presentation property does not exist")
+ return [presentation.read(target.identity, args[1])]
}
- if (word === "windowLocalResize") {
-
- const target = localProcess(args[0])
- await localWindow.resize(target.identity, localSize(args[1]), parseLocalWindowTransaction(args[2]))
-
- return []
+ const selectedTransaction = (target: ClientProcess) => {
+ const selected = presentationTransaction(args[2], args[3])
+ if (selected) requireWindowPresentationTransactions(clientOf(target).window.layer)
+ return selected
}
- if (word === "windowLocalGeometry") {
+ if (word === "windowPresentationMove") {
- const target = localProcess(args[0])
- await localWindow.geometry(target.identity, localGeometry(args[1]), parseLocalWindowTransaction(args[2]))
+ const target = presentationProcess(args[0])
+ await presentation.move(target.identity, presentationPosition(args[1]), selectedTransaction(target))
return []
}
- if (word === "windowLocalSurfaceAdd") {
+ if (word === "windowPresentationResize") {
- const target = localProcess(args[0])
- requireLocalSurfaceLayer(target.client!.window.layer)
- await localWindow.addSurface(target.identity, parseLocalWindowTransaction(args[2]))
+ const target = presentationProcess(args[0])
+ await presentation.resize(target.identity, presentationSize(args[1]), selectedTransaction(target))
return []
}
- if (word === "windowLocalSurfaceRemove") {
+ if (word === "windowPresentationGeometry") {
- const target = localProcess(args[0])
- requireLocalSurfaceLayer(target.client!.window.layer)
- await localWindow.removeSurface(target.identity, parseLocalWindowTransaction(args[2]))
+ const target = presentationProcess(args[0])
+ await presentation.geometry(target.identity, presentationGeometry(args[1]), selectedTransaction(target))
return []
}
- if (word === "windowLocalTitle") {
- const target = localProcess(args[0])
+ if (word === "windowPresentationTitle") {
+ const target = presentationProcess(args[0])
const title = String(args[1] ?? "").trim()
if (!title) throw new Error("A Window title must not be empty")
- localWindow.title(target.identity, title)
+ presentation.title(target.identity, title)
return []
}
- if (word === "windowLocalHeader") {
- const target = localProcess(args[0])
- if (typeof args[1] !== "boolean") throw new Error("Local Window header state must be true or false")
- localWindow.header(target.identity, args[1])
+ if (word === "windowPresentationHeader") {
+ const target = presentationProcess(args[0])
+ if (typeof args[1] !== "boolean") throw new Error("Window presentation header state must be true or false")
+ presentation.header(target.identity, args[1])
return []
}
- if (word === "windowLocalMaximize") {
- const target = localProcess(args[0])
- if (typeof args[1] !== "boolean") throw new Error("Local Window maximize takes a boolean state")
- await localWindow.maximize(target.identity, args[1], parseLocalWindowTransaction(args[2]))
+ if (word === "windowPresentationFrame") {
+ const target = presentationProcess(args[0])
+ await presentation.frame(target.identity, presentationFrame(args[1]), selectedTransaction(target))
return []
}
- if (word === "windowLocalMinimize") {
+ if (word === "windowPresentationMaximize") {
+ const target = presentationProcess(args[0])
+ if (typeof args[1] !== "boolean") throw new Error("Window presentation maximize takes a boolean state")
+ await presentation.maximize(target.identity, args[1], selectedTransaction(target))
+ return []
+ }
- const target = localProcess(args[0])
+ if (word === "windowPresentationMinimize") {
- if (typeof args[1] !== "boolean") throw new Error("Local Window minimize takes a boolean state")
+ const target = presentationProcess(args[0])
- await localWindow.minimize(target.identity, args[1], parseLocalWindowTransaction(args[2]))
+ if (typeof args[1] !== "boolean") throw new Error("Window presentation minimize takes a boolean state")
+
+ await presentation.minimize(target.identity, args[1], selectedTransaction(target))
return []
}
- if (word === "windowLocalFollow") {
+ if (word === "windowPresentationFollow") {
- const target = localProcess(args[0])
- const followed = await permittedProcess(args[1])
- clientOf(followed)
- await localWindow.follow(target.identity, followed.identity, parseLocalWindowTransaction(args[2]))
+ const target = presentationProcess(args[0])
+ await presentation.follow(target.identity, selectedTransaction(target))
return []
}
- if (word === "windowLocalUnfollow") {
+ if (word === "windowPresentationUnfollow") {
- const target = localProcess(args[0])
- await localWindow.unfollow(target.identity, parseLocalWindowTransaction(args[1]))
+ const target = presentationProcess(args[0])
+ await presentation.unfollow(target.identity)
return []
}
- if (word === "windowLocalRaise") {
+ if (word === "windowPresentationRaise") {
- const target = localProcess(args[0])
- localWindow.raise(target.identity)
+ const target = presentationProcess(args[0])
+ presentation.raise(target.identity)
return []
}
if (word === "changeTitle") {
- await clientOf(await permittedProcess(args[0])).window.changeTitle(String(args[1] ?? ""))
+ await windowOf(await permittedProcess(args[0])).changeTitle(String(args[1] ?? ""))
return [pane]
}
@@ -892,26 +921,40 @@ export default function host(authManager: AuthManager, pane: string, viewport: (
if (typeof args[1] !== "boolean") throw new Error("Window header state must be true or false")
- await clientOf(await permittedProcess(args[0])).window.changeHeader(args[1])
+ await windowOf(await permittedProcess(args[0])).changeHeader(args[1])
+
+ return [pane]
+ }
+
+ if (word === "changeFrame") {
+
+ await windowOf(await permittedProcess(args[0])).changeFrame(args[1] as never)
+
+ return [pane]
+ }
+
+ if (word === "changeOpeningTransaction") {
+
+ await windowOf(await permittedProcess(args[0])).changeOpeningTransaction(args[1] as never)
return [pane]
}
if (word === "raise") {
- await clientOf(await permittedProcess(args[0])).window.raise()
+ await windowOf(await permittedProcess(args[0])).raise()
return [pane]
}
if (word === "maximize") {
- await clientOf(await permittedProcess(args[0])).window.maximize(args[1] !== false)
+ await windowOf(await permittedProcess(args[0])).maximize(args[1] !== false)
return [pane]
}
if (word === "minimize") {
- await clientOf(await permittedProcess(args[0])).window.minimize(args[1] !== false)
+ await windowOf(await permittedProcess(args[0])).minimize(args[1] !== false)
return [pane]
}
diff --git a/source/client/view/components/desktop-host/local-window.ts b/source/client/view/components/desktop-host/local-window.ts
deleted file mode 100644
index bd8b8c3..0000000
--- a/source/client/view/components/desktop-host/local-window.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import {
- appearanceLimits,
- isRelativeValue,
- type AppearanceTransaction,
- type Easing,
- type Position,
- type Size,
- type WaitedTransaction,
- type WindowGeometry,
- type WindowLayer,
- type WindowState
-} from "@phreshos/core"
-import { isDesktopReplacementLayer } from "@shared/desktop-replacement"
-
-export type LocalAnimation = Readonly<{
- revision: number
- transaction: AppearanceTransaction
-}>
-
-export type LocalSurfaceState = Readonly<{
- visible: boolean
- transition: LocalAnimation | null
-}>
-
-/** Everything physically represented by one exact live Client iframe. */
-export type LocalWindowState = WindowState & Readonly<{
- depth: number
- surface: LocalSurfaceState | null
- geometryAnimation: LocalAnimation | null
- minimizeAnimation: LocalAnimation | null
-}>
-
-/** The only interface through which an iframe changes its local representation. */
-export interface LocalWindowHost {
- state(identity: string): WindowState
- move(identity: string, position: Position, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- resize(identity: string, size: Size, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- geometry(identity: string, geometry: WindowGeometry, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- maximize(identity: string, maximized: boolean, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- minimize(identity: string, minimized: boolean, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- follow(identity: string, target: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- unfollow(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- title(identity: string, title: string): void
- header(identity: string, header: boolean): void
- raise(identity: string): void
- addSurface(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- removeSurface(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>
- complete(identity: string, kind: "geometry" | "minimize" | "surface", revision: number): void
- release(identity: string): void
-}
-
-export function localPosition(value: unknown): Position {
- const record = plain(value, "Local Window position")
- valueTerm(record.x, "x")
- valueTerm(record.y, "y")
- return Object.freeze({ x: record.x, y: record.y }) as Position
-}
-
-export function localSize(value: unknown): Size {
- const record = plain(value, "Local Window size")
- valueTerm(record.width, "width")
- valueTerm(record.height, "height")
- return Object.freeze({ width: record.width, height: record.height }) as Size
-}
-
-export function localGeometry(value: unknown): WindowGeometry {
- const record = plain(value, "Local Window geometry")
- return Object.freeze({ position: localPosition(record.position), size: localSize(record.size) })
-}
-
-export function parseLocalWindowTransaction(value: unknown): AppearanceTransaction | WaitedTransaction | undefined {
- if (value === undefined) return undefined
-
- const record = plain(value, "Appearance transaction")
-
- if (!("duration" in record) || !("easing" in record)) throw new Error("An Appearance transaction must provide duration and easing")
- const { minimum, maximum } = appearanceLimits.transaction.duration
- if (!finite(record.duration) || record.duration < minimum || record.duration > maximum) throw new Error(`Appearance transaction duration must be finite milliseconds from ${minimum} to ${maximum}`)
-
- const result: { duration: number, easing: Easing, wait?: true } = {
- duration: record.duration,
- easing: easing(record.easing)
- }
-
- if ("wait" in record) {
-
- if (record.wait !== true) throw new Error("Appearance transaction wait must be true when present")
- result.wait = true
- }
-
- return Object.freeze(result)
-}
-
-export function requireLocalSurfaceLayer(layer: WindowLayer) {
-
- if (layer === "window") throw new Error("A standard Window already owns its host Surface")
- if (isDesktopReplacementLayer(layer)) throw new Error(`The ${layer} layer does not allow a local Surface`)
-}
-
-function easing(value: unknown): Easing {
- if (value === "linear" || value === "ease" || value === "ease-in" || value === "ease-out" || value === "ease-in-out") return value
- if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Appearance transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")
- return Object.freeze([...value]) as [number, number, number, number]
-}
-
-function valueTerm(value: unknown, name: string) {
-
- if (!finite(value) && !isRelativeValue(value)) throw new Error(`Local Window ${name} must be a finite number or relative value`)
-}
-
-function plain(value: unknown, name: string): Record<string, unknown> {
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be an object`)
- const prototype = Object.getPrototypeOf(value)
- if (prototype !== Object.prototype && prototype !== null) throw new Error(`${name} must be an object`)
- return value as Record<string, unknown>
-}
-
-function finite(value: unknown): value is number {
- return typeof value === "number" && Number.isFinite(value)
-}
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 204c09a..a89d8bd 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -125,7 +125,7 @@ export default class SystemAccess {
return launch
}
- /** Authorize one fresh Client Endpoint incarnation in an existing Process. */
+ /** Authorize one fresh Client Endpoint execution context in an existing Process. */
public async clientLaunch(value: unknown = {}) {
const launch = parseLaunch({ client: value }).client
diff --git a/source/client/view/components/desktop-host/window-presentation.ts b/source/client/view/components/desktop-host/window-presentation.ts
new file mode 100644
index 0000000..6c457ff
--- /dev/null
+++ b/source/client/view/components/desktop-host/window-presentation.ts
@@ -0,0 +1,89 @@
+import {
+ isRelativeValue,
+ parseWindowFrame,
+ parseWindowTransaction,
+ type Position,
+ type Size,
+ type WindowFrame,
+ type WindowGeometry,
+ type WindowState,
+ type WindowTransaction
+} from "@phreshos/core"
+import type { WindowPresentationProperty } from "@shared/window-layers"
+
+export type PresentationAnimation = Readonly<{
+ revision: number
+ transaction: WindowTransaction
+}>
+
+/** Everything physically represented by one exact live Client iframe. */
+export type WindowPresentationState = WindowState & Readonly<{
+ depth: number
+ frameAnimation: PresentationAnimation | null
+ geometryAnimation: PresentationAnimation | null
+ minimizeAnimation: PresentationAnimation | null
+}>
+
+export type PresentationTransactionRequest = Readonly<{
+ transaction: WindowTransaction
+ wait: boolean
+}>
+
+/** The only interface through which an iframe changes or observes its Desktop presentation. */
+export interface WindowPresentationHost {
+ read(identity: string, property: WindowPresentationProperty): unknown
+ move(identity: string, position: Position, transaction?: PresentationTransactionRequest): Promise<void>
+ resize(identity: string, size: Size, transaction?: PresentationTransactionRequest): Promise<void>
+ geometry(identity: string, geometry: WindowGeometry, transaction?: PresentationTransactionRequest): Promise<void>
+ maximize(identity: string, maximized: boolean, transaction?: PresentationTransactionRequest): Promise<void>
+ minimize(identity: string, minimized: boolean, transaction?: PresentationTransactionRequest): Promise<void>
+ follow(identity: string, transaction?: PresentationTransactionRequest): Promise<void>
+ unfollow(identity: string): Promise<void>
+ title(identity: string, title: string): void
+ header(identity: string, header: boolean): void
+ frame(identity: string, frame: WindowFrame, transaction?: PresentationTransactionRequest): Promise<void>
+ raise(identity: string): void
+ observe(identity: string, event: string | null, listener: (event: string, value: unknown) => void): () => void
+ complete(identity: string, kind: "geometry" | "minimize" | "frame", revision: number): void
+ release(identity: string): void
+}
+
+export function presentationPosition(value: unknown): Position {
+ const record = plain(value, "Window presentation position")
+ valueTerm(record.x, "x")
+ valueTerm(record.y, "y")
+ return Object.freeze({ x: record.x, y: record.y }) as Position
+}
+
+export function presentationSize(value: unknown): Size {
+ const record = plain(value, "Window presentation size")
+ valueTerm(record.width, "width")
+ valueTerm(record.height, "height")
+ return Object.freeze({ width: record.width, height: record.height }) as Size
+}
+
+export function presentationGeometry(value: unknown): WindowGeometry {
+ const record = plain(value, "Window presentation geometry")
+ return Object.freeze({ position: presentationPosition(record.position), size: presentationSize(record.size) })
+}
+
+export function presentationFrame(value: unknown) {
+ return parseWindowFrame(value)
+}
+
+export function presentationTransaction(value: unknown, wait: unknown): PresentationTransactionRequest | undefined {
+ if (value === undefined) return undefined
+ if (wait !== undefined && typeof wait !== "boolean") throw new Error("A Window presentation wait value must be true or false")
+ return Object.freeze({ transaction: parseWindowTransaction(value), wait: wait === true })
+}
+
+function valueTerm(value: unknown, name: string) {
+ if (!isRelativeValue(value)) throw new Error(`Window presentation ${name} must be a finite number or relative value`)
+}
+
+function plain(value: unknown, name: string): Record<string, unknown> {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${name} must be an object`)
+ const prototype = Object.getPrototypeOf(value)
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${name} must be an object`)
+ return value as Record<string, unknown>
+}
diff --git a/source/client/view/components/window-manager/layer-policy.ts b/source/client/view/components/window-manager/layer-policy.ts
index 9f15930..eae05cb 100644
--- a/source/client/view/components/window-manager/layer-policy.ts
+++ b/source/client/view/components/window-manager/layer-policy.ts
@@ -1,31 +1,18 @@
-import type { WindowLayer } from "@phreshos/core"
-import type { LocalWindowState } from "../desktop-host/local-window"
+import type { WindowPresentationState } from "../desktop-host/window-presentation"
+import { requireWindowPresentationApplication, supportsWindowPresentationApplication, type WindowPresentationProperty } from "@shared/window-layers"
-type PresentationProperty = "title" | "header" | "position" | "size" | "minimized" | "maximized" | "depth" | "surface"
-
-/** Properties owned by Desktop for each local Window role. */
-const properties: Readonly<Record<WindowLayer, readonly PresentationProperty[]>> = {
- window: ["title", "header", "position", "size", "minimized", "maximized", "depth"],
- under: ["position", "size", "minimized", "maximized", "depth", "surface"],
- over: ["position", "size", "minimized", "maximized", "depth", "surface"],
- wallpaper: [],
- "start-menu": []
-}
-
-export function requireLocalProperty(layer: WindowLayer, property: PresentationProperty) {
- if (!properties[layer].includes(property)) {
- throw new Error(`The ${layer} layer does not allow local ${property} changes`)
- }
-}
+export const requirePresentationApplication = requireWindowPresentationApplication
/** A target contributes only properties allowed by the receiving role. */
-export function followedState(current: LocalWindowState, target: LocalWindowState, previous?: LocalWindowState) {
- const changes: Partial<LocalWindowState> = {}
- for (const property of properties[current.layer]) {
- if (property === "surface") continue
+export function followedState(current: WindowPresentationState, target: WindowPresentationState, previous?: WindowPresentationState) {
+ const changes: Partial<WindowPresentationState> = {}
+ for (const property of followedProperties) {
+ if (!supportsWindowPresentationApplication(current.layer, property)) continue
if (!previous || JSON.stringify(previous[property]) !== JSON.stringify(target[property])) {
Object.assign(changes, { [property]: target[property] })
}
}
return changes
}
+
+const followedProperties = ["title", "header", "frame", "position", "size", "minimized", "maximized"] as const satisfies readonly WindowPresentationProperty[]
diff --git a/source/client/view/components/window-manager/window-manager.ts b/source/client/view/components/window-manager/window-manager.ts
index aeb2fe7..23afe97 100644
--- a/source/client/view/components/window-manager/window-manager.ts
+++ b/source/client/view/components/window-manager/window-manager.ts
@@ -4,8 +4,8 @@ import { ReactTunnel } from "@the-link/react"
import { type Layer, type Position, type Size, type Value } from "@phreshos/core"
import { useCallback, useRef, useState } from "react"
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
-import LocalWindows from "./local-windows"
-import { isDesktopReplacementLayer } from "@shared/desktop-replacement"
+import WindowPresentations from "./window-presentations"
+import { isDesktopReplacementLayer } from "@shared/window-layers"
import { type SharedResizeWindow } from "./shared-resize"
import { type WindowRegion } from "./window-geometry"
@@ -14,14 +14,14 @@ import { type WindowRegion } from "./window-geometry"
* process whose program has a client half, so the process itself says
* whether it is shown — nothing else is consulted.
*
- * The local representation and authoritative counterpart are distinct.
+ * The Desktop presentation and authoritative counterpart are distinct.
* Following starts enabled for ordinary windows and disabled for the other layers.
* Each Client can subsequently follow an authoritative Window or detach.
*
- * Departure is representation. The truth drops a stopped client and its
- * Window at once; the exit still has to play, so the last desktop-owned
- * representation is kept until its animation reports done. Its iframe is
- * not part of that snapshot and leaves as soon as the stop is confirmed.
+ * Departure is representation. Stopping a Client removes only its execution
+ * context; its Client Endpoint-owned authoritative Window remains. The last
+ * desktop-owned representation is kept until its exit animation reports
+ * done, while the iframe leaves as soon as the stop is confirmed.
*/
export default function useWindows(authManager: AuthManager) {
@@ -56,15 +56,15 @@ export default function useWindows(authManager: AuthManager) {
const initialClients = initialIncarnations.current
- const localController = useRef<LocalWindows | null>(null)
+ const presentationController = useRef<WindowPresentations | null>(null)
- if (!localController.current) localController.current = new LocalWindows(initialClients, process => peer.processes.get(process)?.client ?? null)
+ if (!presentationController.current) presentationController.current = new WindowPresentations(initialClients, process => peer.processes.get(process)?.client ?? null)
- const localWindow = localController.current
+ const presentation = presentationController.current
- const [localWindows, setLocalWindows] = useState(localWindow.windows)
+ const [presentations, setPresentations] = useState(presentation.windows)
- localWindow.listen(setLocalWindows)
+ presentation.listen(setPresentations)
const previousClients = useRef(initialClients)
@@ -97,7 +97,7 @@ export default function useWindows(authManager: AuthManager) {
const currentClients = new Map(list.flatMap(record => record.client ? [[record.identity, incarnation(record, record.client)] as const] : []))
- localWindow.reconcile(currentClients)
+ presentation.reconcile(currentClients)
let settled = false
@@ -116,7 +116,7 @@ export default function useWindows(authManager: AuthManager) {
const departed = new Set(gone.filter(({ client }) => isDesktopReplacementLayer(client.window.layer)).map(({ identity }) => identity))
- for (const identity of departed) localWindow.remove(identity)
+ for (const identity of departed) presentation.remove(identity)
const animated = gone.filter(({ identity }) => !departed.has(identity))
@@ -165,19 +165,19 @@ export default function useWindows(authManager: AuthManager) {
const live = incarnation(process, process.client!)
- const window = localWindows.get(live.identity)
+ const window = presentations.get(live.identity)
if (!window || window.minimized) continue
const best = fronts[window.layer]
- const bestWindow = best && localWindows.get(incarnation(best, best.client!).identity)
+ const bestWindow = best && presentations.get(incarnation(best, best.client!).identity)
if (!bestWindow || bestWindow.depth <= window.depth) fronts[window.layer] = process
}
- // Local representation and authoritative mutation are two explicit acts.
- // The local act already rendered the result; only the server echo may
+ // Presentation and authoritative mutation are two explicit acts.
+ // The presentation act already rendered the result; only the server echo may
// project the authoritative act back onto an ordinary Window.
const commit = useCallback(function (request: Promise<void>) {
@@ -207,7 +207,7 @@ export default function useWindows(authManager: AuthManager) {
setOrder(current => current.filter(entry => entry !== identity))
- localWindow.remove(identity)
+ presentation.remove(identity)
}, [])
@@ -219,7 +219,7 @@ export default function useWindows(authManager: AuthManager) {
const highest = summit(window.layer)
- localWindow.raise(process.identity)
+ presentation.raise(process.identity)
if (window.depth === highest) return
@@ -233,7 +233,7 @@ export default function useWindows(authManager: AuthManager) {
if (!window || window.layer !== "window") return
- void localWindow.minimize(process.identity, minimized)
+ void presentation.minimize(process.identity, minimized)
commit(window.minimize(minimized))
@@ -245,7 +245,7 @@ export default function useWindows(authManager: AuthManager) {
if (!window || window.layer !== "window") return
- if (localWindow.state(process.identity).minimized) minimize(process, false)
+ if (presentation.state(process.identity).minimized) minimize(process, false)
raise(process)
@@ -257,7 +257,7 @@ export default function useWindows(authManager: AuthManager) {
if (!window || window.layer !== "window") return
- void localWindow.move(process.identity, { x, y })
+ void presentation.move(process.identity, { x, y })
commit(window.move({ x, y }))
@@ -271,7 +271,7 @@ export default function useWindows(authManager: AuthManager) {
if (!position) {
- void localWindow.resize(process.identity, { width, height })
+ void presentation.resize(process.identity, { width, height })
commit(window.resize({ width, height }))
@@ -280,7 +280,7 @@ export default function useWindows(authManager: AuthManager) {
const geometry = { position, size: { width, height } }
- void localWindow.geometry(process.identity, geometry)
+ void presentation.geometry(process.identity, geometry)
commit(window.setGeometry(geometry))
@@ -294,7 +294,7 @@ export default function useWindows(authManager: AuthManager) {
const geometry = { position, size }
- void localWindow.geometry(process.identity, geometry)
+ void presentation.geometry(process.identity, geometry)
commit(window.setGeometry(geometry))
@@ -303,16 +303,16 @@ export default function useWindows(authManager: AuthManager) {
const fill = useCallback(function (process: Process) {
const window = process.client?.window
if (!window || window.layer !== "window") return
- const maximized = !localWindow.projection(process.identity).maximized
- void localWindow.maximize(process.identity, maximized)
+ const maximized = !presentation.projection(process.identity).maximized
+ void presentation.maximize(process.identity, maximized)
commit(window.maximize(maximized))
}, [commit])
// Every window on the desktop, in one list and one order.
//
// A closing client incarnation keeps the place it had. A restarted
- // Client receives a new desktop-local representation identity even when
- // the surrounding Process and its public Client-owned Window capability
+ // Client receives a new Desktop presentation identity even when
+ // the surrounding Process and its Client Endpoint-owned Window
// remain the same.
const rank = new Map(order.map((identity, index) => [identity, index]))
@@ -322,10 +322,10 @@ export default function useWindows(authManager: AuthManager) {
const live = incarnation(record, record.client!)
- return { ...live, local: localWindows.get(live.identity)!, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
+ return { ...live, presentation: presentations.get(live.identity)!, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
}),
- ...leaving.map(window => ({ ...window, local: localWindows.get(window.identity)!, closing: true, stopping: false, entering: !inheritedClients.current.has(window.client) }))
+ ...leaving.map(window => ({ ...window, presentation: presentations.get(window.identity)!, closing: true, stopping: false, entering: !inheritedClients.current.has(window.client) }))
]
.sort((one, other) => (rank.get(one.identity) ?? Number.MAX_SAFE_INTEGER) - (rank.get(other.identity) ?? Number.MAX_SAFE_INTEGER))
@@ -334,25 +334,25 @@ export default function useWindows(authManager: AuthManager) {
for (const pane of panes) {
- panesByLayer[pane.local.layer].push(pane)
+ panesByLayer[pane.presentation.layer].push(pane)
}
const sharedResizeWindows: SharedResizeWindow[] = panesByLayer.window.flatMap(function (pane) {
- if (pane.closing || pane.stopping || pane.local.minimized || pane.local.maximized) return []
+ if (pane.closing || pane.stopping || pane.presentation.minimized || pane.presentation.maximized) return []
- const geometry = localWindow.representedGeometry(pane.record.identity)
+ const geometry = presentation.representedGeometry(pane.record.identity)
if (!geometry) return []
- return [{ identity: pane.record.identity, geometry, depth: pane.local.depth }]
+ return [{ identity: pane.record.identity, geometry, depth: pane.presentation.depth }]
})
const presentSharedResize = useCallback(function (geometries: ReadonlyMap<string, WindowRegion>) {
- for (const [identity, geometry] of geometries) localWindow.presentGeometry(identity, geometry)
+ for (const [identity, geometry] of geometries) presentation.presentGeometry(identity, geometry)
- }, [localWindow])
+ }, [presentation])
const beginSharedResize = useCallback(function (identities: readonly string[]) {
@@ -360,7 +360,7 @@ export default function useWindows(authManager: AuthManager) {
for (const identity of identities) {
- const geometry = localWindow.beginGeometry(identity)
+ const geometry = presentation.beginGeometry(identity)
if (geometry) {
@@ -369,26 +369,26 @@ export default function useWindows(authManager: AuthManager) {
continue
}
- for (const started of geometries.keys()) localWindow.cancelGeometry(started)
+ for (const started of geometries.keys()) presentation.cancelGeometry(started)
return null
}
return geometries
- }, [localWindow])
+ }, [presentation])
const finishSharedResize = useCallback(function (identities: readonly string[]) {
- for (const identity of identities) localWindow.finishGeometry(identity)
+ for (const identity of identities) presentation.finishGeometry(identity)
- }, [localWindow])
+ }, [presentation])
const cancelSharedResize = useCallback(function (identities: readonly string[]) {
- for (const identity of identities) localWindow.cancelGeometry(identity)
+ for (const identity of identities) presentation.cancelGeometry(identity)
- }, [localWindow])
+ }, [presentation])
const commitSharedResize = useCallback(function (geometries: ReadonlyMap<string, WindowRegion>) {
@@ -405,12 +405,12 @@ export default function useWindows(authManager: AuthManager) {
size: { width: region.width, height: region.height }
}
- void localWindow.geometry(identity, geometry)
+ void presentation.geometry(identity, geometry)
commit(window.setGeometry(geometry))
}
- }, [commit, localWindow, peer])
+ }, [commit, presentation, peer])
return {
@@ -422,7 +422,7 @@ export default function useWindows(authManager: AuthManager) {
fronts,
- localWindow,
+ presentation,
sharedResize: {
windows: sharedResizeWindows,
diff --git a/source/client/view/components/window-manager/local-windows.ts b/source/client/view/components/window-manager/window-presentations.ts
similarity index 57%
rename from source/client/view/components/window-manager/local-windows.ts
rename to source/client/view/components/window-manager/window-presentations.ts
index 60e2217..f7bba5e 100644
--- a/source/client/view/components/window-manager/local-windows.ts
+++ b/source/client/view/components/window-manager/window-presentations.ts
@@ -1,52 +1,54 @@
-import { followedState, requireLocalProperty } from "./layer-policy"
+import { followedState, requirePresentationApplication } from "./layer-policy"
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import {
- type AppearanceTransaction,
- type WaitedTransaction,
+ type WindowFrame,
type WindowGeometry,
type WindowState
} from "@phreshos/core"
-import { type LocalWindowHost, type LocalWindowState } from "../desktop-host/local-window"
-import { isDesktopReplacementLayer } from "@shared/desktop-replacement"
+import { type PresentationTransactionRequest, type WindowPresentationHost, type WindowPresentationState } from "../desktop-host/window-presentation"
import { type WindowRegion } from "./window-geometry"
+import { isFixedWindowPresentationLayer, requireWindowPresentationRead, supportsWindowPresentationApplication } from "@shared/window-layers"
-export interface LocalWindowEntry {
+export interface WindowPresentationEntry {
identity: string
client: ClientState
}
/** Owns the representations of one desktop without entering server transport. */
-export default class LocalWindows implements LocalWindowHost {
+export default class WindowPresentations implements WindowPresentationHost {
- public windows: ReadonlyMap<string, LocalWindowState>
+ public windows: ReadonlyMap<string, WindowPresentationState>
private readonly live = new Map<string, string>()
- private readonly authoritative = new Map<string, LocalWindowState>()
+ private readonly authoritative = new Map<string, WindowPresentationState>()
private readonly waiting = new Map<string, WaitingAnimation>()
- private readonly representations = new Map<string, LocalGeometryRepresentation>()
+ private readonly representations = new Map<string, PresentationGeometryRepresentation>()
private readonly representationListeners = new Map<string, () => void>()
private readonly following = new Map<string, FollowingWindow>()
+ private readonly observers = new Map<string, Set<(event: string, value: unknown) => void>>()
+ private readonly emitted = new Map<string, WindowState>()
private revision = 0
- private changed: (windows: ReadonlyMap<string, LocalWindowState>) => void = () => undefined
+ private changed: (windows: ReadonlyMap<string, WindowPresentationState>) => void = () => undefined
- public constructor(initial: ReadonlyMap<string, LocalWindowEntry>, private readonly client: (process: string) => ClientState | null) {
+ public constructor(initial: ReadonlyMap<string, WindowPresentationEntry>, private readonly client: (process: string) => ClientState | null) {
- this.windows = new Map([...initial.values()].map(({ identity, client }) => [identity, localState(client)]))
+ this.windows = new Map([...initial.values()].map(({ identity, client }) => [identity, initialPresentationState(client)]))
+ for (const [identity, state] of this.windows) this.emitted.set(identity, windowState(state, frontmost(this.windows, state.layer) === identity))
this.reconcile(initial)
}
- public listen(changed: (windows: ReadonlyMap<string, LocalWindowState>) => void) {
+ public listen(changed: (windows: ReadonlyMap<string, WindowPresentationState>) => void) {
this.changed = changed
}
/** Following projects the authoritative properties owned by the receiving layer. */
- public reconcile(current: ReadonlyMap<string, LocalWindowEntry>) {
+ public reconcile(current: ReadonlyMap<string, WindowPresentationEntry>) {
for (const [process, identity] of this.live) {
if (current.get(process)?.identity === identity) continue
- this.cancel(identity, "geometry", "The local Window representation was removed")
- this.cancel(identity, "minimize", "The local Window representation was removed")
- this.cancel(identity, "surface", "The local Window representation was removed")
+ this.cancel(identity, "geometry", "The Window presentation was removed")
+ this.cancel(identity, "minimize", "The Window presentation was removed")
+ this.cancel(identity, "frame", "The Window presentation was removed")
this.following.delete(identity)
this.authoritative.delete(identity)
}
@@ -57,20 +59,20 @@ export default class LocalWindows implements LocalWindowHost {
this.live.set(process, identity)
const snapshot = authoritativeState(client)
if (!this.authoritative.has(identity) && client.window.layer === "window") {
- this.following.set(identity, { target: identity, snapshot })
+ this.following.set(identity, { snapshot })
}
- if (!next.has(identity)) next.set(identity, localState(client))
+ if (!next.has(identity)) next.set(identity, initialPresentationState(client))
this.authoritative.set(identity, snapshot)
}
const alive = new Set(this.live.values())
for (const [identity, relation] of this.following) {
- if (!alive.has(identity) || !alive.has(relation.target)) {
+ if (!alive.has(identity)) {
this.following.delete(identity)
continue
}
const state = next.get(identity)!
- const target = this.authoritative.get(relation.target)!
+ const target = this.authoritative.get(identity)!
const previous = relation.snapshot
const changes = { ...followedState(state, target, previous) }
const maximized = changes.maximized ?? state.maximized
@@ -99,8 +101,8 @@ export default class LocalWindows implements LocalWindowHost {
this.removeRepresentation(identity)
this.authoritative.delete(identity)
this.following.delete(identity)
-
- for (const [follower, relation] of this.following) if (relation.target === identity) this.following.delete(follower)
+ this.observers.delete(identity)
+ this.emitted.delete(identity)
this.publish(next)
}
@@ -115,13 +117,19 @@ export default class LocalWindows implements LocalWindowHost {
})
}
+ public read(process: string, property: import("@shared/window-layers").WindowPresentationProperty) {
+ const { state } = this.existing(process)
+ requireWindowPresentationRead(state.layer, property)
+ return this.state(process)[property]
+ }
+
/** Returns the values currently driving this desktop's representation. */
public projection(process: string) {
return this.existing(process).state
}
- public readonly represent = (process: string, representation: LocalGeometryRepresentation | null) => {
+ public readonly represent = (process: string, representation: PresentationGeometryRepresentation | null) => {
const identity = this.live.get(process)
@@ -137,7 +145,7 @@ export default class LocalWindows implements LocalWindowHost {
if (this.representations.get(identity) !== representation) return
- this.publish(new Map(this.windows))
+ this.emitPresentationEvents()
}))
}
@@ -187,57 +195,56 @@ export default class LocalWindows implements LocalWindowHost {
if (identity) this.representations.get(identity)?.cancel()
}
- public move(process: string, position: WindowState["position"], transaction?: RequestedTransaction) {
+ public move(process: string, position: WindowState["position"], transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "position")
+ requirePresentationApplication(state.layer, "position")
return this.changeGeometry(identity, { position, size: state.size }, transaction)
}
- public resize(process: string, size: WindowState["size"], transaction?: RequestedTransaction) {
+ public resize(process: string, size: WindowState["size"], transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "size")
+ requirePresentationApplication(state.layer, "size")
return this.changeGeometry(identity, { position: state.position, size }, transaction)
}
- public geometry(process: string, value: WindowGeometry, transaction?: RequestedTransaction) {
+ public geometry(process: string, value: WindowGeometry, transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "position")
+ requirePresentationApplication(state.layer, "position")
return this.changeGeometry(identity, value, transaction)
}
- public minimize(process: string, minimized: boolean, transaction?: RequestedTransaction) {
+ public minimize(process: string, minimized: boolean, transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "minimized")
+ requirePresentationApplication(state.layer, "minimized")
return this.changeMinimized(identity, minimized, transaction)
}
- public maximize(process: string, maximized: boolean, transaction?: RequestedTransaction) {
+ public maximize(process: string, maximized: boolean, transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "maximized")
+ requirePresentationApplication(state.layer, "maximized")
if (state.maximized === maximized) return Promise.resolve()
this.cancel(identity, "geometry")
- const animation = transaction && !state.minimized ? localAnimation(++this.revision, transaction) : null
+ const animation = !state.minimized ? presentationAnimation(++this.revision, transaction) : null
this.replace(identity, { ...state, maximized, geometryAnimation: animation })
return this.waitFor(identity, "geometry", animation, transaction)
}
- public follow(process: string, targetProcess: string, transaction?: RequestedTransaction) {
+ public follow(process: string, transaction?: PresentationTransactionRequest) {
const { identity } = this.existing(process)
- const target = this.existing(targetProcess)
- const snapshot = this.authoritative.get(target.identity)!
- this.following.set(identity, { target: target.identity, snapshot })
+ const snapshot = this.authoritative.get(identity)!
+ this.following.set(identity, { snapshot })
const current = this.windows.get(identity)!
const projected = { ...current, ...followedState(current, snapshot) }
const geometryChanged = JSON.stringify([current.position, current.size, current.maximized]) !== JSON.stringify([projected.position, projected.size, projected.maximized])
const visibilityChanged = current.minimized !== projected.minimized
this.cancel(identity, "geometry")
this.cancel(identity, "minimize")
- const geometryAnimation = geometryChanged && !projected.minimized && transaction ? localAnimation(++this.revision, transaction) : null
- const minimizeAnimation = visibilityChanged && transaction ? localAnimation(++this.revision, transaction) : null
+ const geometryAnimation = geometryChanged && !projected.minimized ? presentationAnimation(++this.revision, transaction) : null
+ const minimizeAnimation = visibilityChanged ? presentationAnimation(++this.revision, transaction) : null
this.replace(identity, {
...projected,
geometryAnimation,
@@ -249,7 +256,7 @@ export default class LocalWindows implements LocalWindowHost {
]).then(() => undefined)
}
- public unfollow(process: string, _transaction?: RequestedTransaction) {
+ public unfollow(process: string) {
const { identity } = this.existing(process)
this.following.delete(identity)
return Promise.resolve()
@@ -258,14 +265,14 @@ export default class LocalWindows implements LocalWindowHost {
public title(process: string, title: string) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "title")
+ requirePresentationApplication(state.layer, "title")
this.replace(identity, { ...state, title })
}
public header(process: string, header: boolean) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "header")
+ requirePresentationApplication(state.layer, "header")
if (state.header === header) return
this.replace(identity, { ...state, header })
}
@@ -273,34 +280,38 @@ export default class LocalWindows implements LocalWindowHost {
public raise(process: string) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "depth")
+ requirePresentationApplication(state.layer, "front")
if (frontmost(this.windows, state.layer) === identity) return
const depth = [...this.windows.values()].reduce((highest, other) => other.layer === state.layer ? Math.max(highest, other.depth) : highest, 0)
this.replace(identity, { ...state, depth: depth + 1 })
}
- public addSurface(process: string, transaction?: RequestedTransaction) {
+ public observe(process: string, event: string | null, listener: (event: string, value: unknown) => void) {
- const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "surface")
- if (state.surface?.visible) return Promise.resolve()
+ const { identity } = this.existing(process)
+ const listeners = this.observers.get(identity) ?? new Set()
+ const selected = (emitted: string, value: unknown) => {
+ if (event === null || event === emitted) listener(emitted, value)
+ }
+ listeners.add(selected)
+ this.observers.set(identity, listeners)
- this.cancel(identity, "surface")
- const transition = transaction ? localAnimation(++this.revision, transaction) : null
- this.replace(identity, { ...state, surface: { visible: true, transition } })
- return this.waitFor(identity, "surface", transition, transaction)
+ return () => {
+ listeners.delete(selected)
+ if (!listeners.size) this.observers.delete(identity)
+ }
}
- public removeSurface(process: string, transaction?: RequestedTransaction) {
+ public frame(process: string, frame: WindowFrame, transaction?: PresentationTransactionRequest) {
const { identity, state } = this.existing(process)
- requireLocalProperty(state.layer, "surface")
- if (!state.surface || !state.surface.visible) return Promise.resolve()
+ requirePresentationApplication(state.layer, "frame")
+ if (JSON.stringify(state.frame) === JSON.stringify(frame)) return Promise.resolve()
- this.cancel(identity, "surface")
- const transition = transaction ? localAnimation(++this.revision, transaction) : null
- this.replace(identity, { ...state, surface: { visible: false, transition } })
- return this.waitFor(identity, "surface", transition, transaction)
+ this.cancel(identity, "frame")
+ const animation = presentationAnimation(++this.revision, transaction)
+ this.replace(identity, { ...state, frame, frameAnimation: animation })
+ return this.waitFor(identity, "frame", animation, transaction)
}
public complete(process: string, kind: AnimationKind, revision: number) {
@@ -312,14 +323,14 @@ export default class LocalWindows implements LocalWindowHost {
? state?.geometryAnimation
: kind === "minimize"
? state?.minimizeAnimation
- : state?.surface?.transition
+ : state?.frameAnimation
if (!state || animation?.revision !== revision) return
this.replace(identity, kind === "geometry"
? { ...state, geometryAnimation: null }
: kind === "minimize"
? { ...state, minimizeAnimation: null }
- : { ...state, surface: state.surface?.visible ? { ...state.surface, transition: null } : null })
+ : { ...state, frameAnimation: null })
const key = animationKey(identity, kind)
const waiting = this.waiting.get(key)
@@ -333,28 +344,28 @@ export default class LocalWindows implements LocalWindowHost {
const identity = this.live.get(process)
if (!identity) return
- this.cancel(identity, "geometry", "The local Window representation was removed")
- this.cancel(identity, "minimize", "The local Window representation was removed")
- this.cancel(identity, "surface", "The local Window representation was removed")
+ this.cancel(identity, "geometry", "The Window presentation was removed")
+ this.cancel(identity, "minimize", "The Window presentation was removed")
+ this.cancel(identity, "frame", "The Window presentation was removed")
const client = this.client(process)
if (!client) return
this.authoritative.set(identity, authoritativeState(client))
this.following.delete(identity)
- if (client.window.layer === "window") this.following.set(identity, { target: identity, snapshot: authoritativeState(client) })
- this.replace(identity, localState(client))
+ if (client.window.layer === "window") this.following.set(identity, { snapshot: authoritativeState(client) })
+ this.replace(identity, initialPresentationState(client))
}
private existing(process: string) {
const identity = this.live.get(process)
- if (!identity) throw new Error("This Client has no local Window representation")
+ if (!identity) throw new Error("This Client has no Window presentation")
const state = this.windows.get(identity)
- if (!state) throw new Error("This Client has no local Window representation")
+ if (!state) throw new Error("This Client has no Window presentation")
return { identity, state }
}
- private replace(identity: string, state: LocalWindowState) {
+ private replace(identity: string, state: WindowPresentationState) {
const next = new Map(this.windows)
next.set(identity, state)
@@ -370,10 +381,10 @@ export default class LocalWindows implements LocalWindowHost {
this.representations.delete(identity)
}
- private changeGeometry(identity: string, value: WindowGeometry, transaction?: RequestedTransaction) {
+ private changeGeometry(identity: string, value: WindowGeometry, transaction?: PresentationTransactionRequest) {
const state = this.windows.get(identity)
- if (!state) throw new Error("This Client has no local Window representation")
+ if (!state) throw new Error("This Client has no Window presentation")
if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()
if (state.minimized || state.maximized) {
@@ -381,31 +392,63 @@ export default class LocalWindows implements LocalWindowHost {
return Promise.resolve()
}
this.cancel(identity, "geometry")
- const animation = transaction ? localAnimation(++this.revision, transaction) : null
+ const animation = presentationAnimation(++this.revision, transaction)
this.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })
return this.waitFor(identity, "geometry", animation, transaction)
}
- private changeMinimized(identity: string, minimized: boolean, transaction?: RequestedTransaction) {
+ private changeMinimized(identity: string, minimized: boolean, transaction?: PresentationTransactionRequest) {
const state = this.windows.get(identity)
- if (!state) throw new Error("This Client has no local Window representation")
+ if (!state) throw new Error("This Client has no Window presentation")
if (state.minimized === minimized) return Promise.resolve()
this.cancel(identity, "minimize")
- if (minimized) this.cancel(identity, "geometry", "The local Window was minimized")
- const animation = transaction ? localAnimation(++this.revision, transaction) : null
+ if (minimized) this.cancel(identity, "geometry", "The Window presentation was minimized")
+ const animation = presentationAnimation(++this.revision, transaction)
this.replace(identity, { ...state, minimized, minimizeAnimation: animation, geometryAnimation: minimized ? null : state.geometryAnimation })
return this.waitFor(identity, "minimize", animation, transaction)
}
- private publish(next: ReadonlyMap<string, LocalWindowState>) {
+ private publish(next: ReadonlyMap<string, WindowPresentationState>) {
this.windows = next
+ this.emitPresentationEvents()
this.changed(next)
}
- private cancel(identity: string, kind: AnimationKind, reason = "The local Window animation was interrupted") {
+ private emitPresentationEvents() {
+
+ for (const [identity, presentation] of this.windows) {
+ const represented = this.representations.get(identity)?.read()
+ const current = windowState(presentation, frontmost(this.windows, presentation.layer) === identity, represented && {
+ position: { x: represented.x, y: represented.y },
+ size: { width: represented.width, height: represented.height }
+ })
+ const previous = this.emitted.get(identity)
+ this.emitted.set(identity, current)
+ if (!previous) continue
+
+ const emit = (property: import("@shared/window-layers").WindowPresentationProperty, event: string, value: unknown) => {
+ if (!supportsWindowPresentationApplication(presentation.layer, property)) return
+ for (const listener of this.observers.get(identity) ?? []) listener(event, value)
+ }
+
+ const moved = JSON.stringify(previous.position) !== JSON.stringify(current.position)
+ const resized = JSON.stringify(previous.size) !== JSON.stringify(current.size)
+ if (moved || resized) emit("position", "geometry", { position: current.position, size: current.size })
+ if (moved) emit("position", "move", current.position)
+ if (resized) emit("size", "resize", current.size)
+ if (previous.minimized !== current.minimized) emit("minimized", "minimize", current.minimized)
+ if (previous.maximized !== current.maximized) emit("maximized", "maximize", current.maximized)
+ if (previous.title !== current.title) emit("title", "changeTitle", current.title)
+ if (previous.header !== current.header) emit("header", "changeHeader", current.header)
+ if (JSON.stringify(previous.frame) !== JSON.stringify(current.frame)) emit("frame", "changeFrame", current.frame)
+ if (previous.front !== current.front) emit("front", "front", current.front)
+ }
+ }
+
+ private cancel(identity: string, kind: AnimationKind, reason = "The Window presentation transaction was interrupted") {
const key = animationKey(identity, kind)
const waiting = this.waiting.get(key)
@@ -414,9 +457,9 @@ export default class LocalWindows implements LocalWindowHost {
waiting.reject(new Error(reason))
}
- private waitFor(identity: string, kind: AnimationKind, animation: LocalWindowState["geometryAnimation"], transaction?: RequestedTransaction) {
+ private waitFor(identity: string, kind: AnimationKind, animation: WindowPresentationState["geometryAnimation"], transaction?: PresentationTransactionRequest) {
- if (!animation || !transaction || !("wait" in transaction)) return Promise.resolve()
+ if (!animation || !transaction?.wait) return Promise.resolve()
return new Promise<void>((resolve, reject) => {
this.waiting.set(animationKey(identity, kind), { revision: animation.revision, resolve, reject })
@@ -424,8 +467,7 @@ export default class LocalWindows implements LocalWindowHost {
}
}
-type AnimationKind = "geometry" | "minimize" | "surface"
-type RequestedTransaction = AppearanceTransaction | WaitedTransaction
+type AnimationKind = "geometry" | "minimize" | "frame"
interface WaitingAnimation {
revision: number
@@ -434,8 +476,7 @@ interface WaitingAnimation {
}
interface FollowingWindow {
- target: string
- snapshot: LocalWindowState
+ snapshot: WindowPresentationState
}
function animationKey(identity: string, kind: AnimationKind) {
@@ -443,36 +484,37 @@ function animationKey(identity: string, kind: AnimationKind) {
return `${identity}:${kind}`
}
-function baseTransaction(transaction: RequestedTransaction): AppearanceTransaction {
+function presentationAnimation(revision: number, request?: PresentationTransactionRequest) {
- return Object.freeze({ duration: transaction.duration, easing: transaction.easing })
+ const transaction = request?.transaction ?? true
+ return transaction === false ? null : Object.freeze({ revision, transaction })
}
-function localAnimation(revision: number, transaction: RequestedTransaction) {
-
- return Object.freeze({ revision, transaction: baseTransaction(transaction) })
-}
-
-function localState(client: ClientState): LocalWindowState {
+function initialPresentationState(client: ClientState): WindowPresentationState {
const window = client.window
+ const fixed = isFixedWindowPresentationLayer(window.layer)
return {
...authoritativeState(client),
- title: window.layer === "window" ? window.title : "",
- header: window.layer === "window" ? window.header : true,
- position: isDesktopReplacementLayer(window.layer) ? { x: 0, y: 0 } : window.position,
- size: isDesktopReplacementLayer(window.layer) ? { width: "100%", height: "100%" } : window.size,
- minimized: isDesktopReplacementLayer(window.layer) ? false : window.minimized,
- maximized: isDesktopReplacementLayer(window.layer) ? true : window.maximized,
- depth: isDesktopReplacementLayer(window.layer) ? 0 : window.depth,
+ title: window.title,
+ header: window.layer === "window" ? window.header : false,
+ frame: window.layer === "window" ? true : fixed ? false : window.frame,
+ position: fixed ? { x: 0, y: 0 } : window.position,
+ size: fixed ? { width: "100%", height: "100%" } : window.size,
+ minimized: fixed ? false : window.minimized,
+ maximized: fixed ? true : window.maximized,
+ depth: fixed ? 0 : window.depth,
+ frameAnimation: null,
}
}
-function authoritativeState(client: ClientState): LocalWindowState {
+function authoritativeState(client: ClientState): WindowPresentationState {
const window = client.window
return {
title: window.title,
header: window.header,
+ frame: window.frame,
+ transaction: window.transaction,
position: window.position,
size: window.size,
minimized: window.minimized,
@@ -480,17 +522,19 @@ function authoritativeState(client: ClientState): LocalWindowState {
front: false,
layer: window.layer,
depth: window.depth,
- surface: null,
+ frameAnimation: null,
geometryAnimation: null,
minimizeAnimation: null
}
}
-function windowState(local: LocalWindowState, front: boolean, geometry?: Readonly<{ position: WindowState["position"], size: WindowState["size"] }>): WindowState {
+function windowState(local: WindowPresentationState, front: boolean, geometry?: Readonly<{ position: WindowState["position"], size: WindowState["size"] }>): WindowState {
return {
title: local.title,
header: local.header,
+ frame: local.frame,
+ transaction: local.transaction,
position: geometry?.position ?? local.position,
size: geometry?.size ?? local.size,
minimized: local.minimized,
@@ -500,7 +544,7 @@ function windowState(local: LocalWindowState, front: boolean, geometry?: Readonl
}
}
-export interface LocalGeometryRepresentation {
+export interface PresentationGeometryRepresentation {
read: () => WindowRegion
@@ -515,9 +559,9 @@ export interface LocalGeometryRepresentation {
listen: (settled: () => void) => () => void
}
-function frontmost(windows: ReadonlyMap<string, LocalWindowState>, layer: LocalWindowState["layer"]) {
+function frontmost(windows: ReadonlyMap<string, WindowPresentationState>, layer: WindowPresentationState["layer"]) {
- let best: [string, LocalWindowState] | null = null
+ let best: [string, WindowPresentationState] | null = null
for (const candidate of windows) {
const [, window] = candidate
diff --git a/source/client/view/structure/authentication/credentials-form.tsx b/source/client/view/structure/authentication/credentials-form.tsx
index 0366ea2..3906c04 100644
--- a/source/client/view/structure/authentication/credentials-form.tsx
+++ b/source/client/view/structure/authentication/credentials-form.tsx
@@ -44,11 +44,11 @@ export default function CredentialsForm({ title, description, submitLabel, passw
>
- <Panel>
+ <Panel material="full">
<Panel.Header><SystemHeader name={application.displayName} version={application.version} /></Panel.Header>
- <Panel.Content className="grid gap-5 p-5">
+ <Panel.Content material="extended" className="grid gap-5 p-5">
<div className="grid gap-1">
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index 81deaea..51bd4ae 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -69,7 +69,7 @@ export default function Workspace() {
// lets the desktop announce the surface that actually contains it.
const sources = useRef(new Map<string, HTMLIFrameElement | null>())
- const { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded } = useClientHost(authManager, desktop, sources.current, windows.localWindow)
+ const { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded } = useClientHost(authManager, desktop, sources.current, windows.presentation)
const fileWallpaperLoaded = useCallback(() => {
@@ -111,7 +111,7 @@ export default function Workspace() {
function renderWindows(layer: Layer) {
- return windows.panesByLayer[layer].map(({ identity, record, client, local, closing, entering, stopping }) => <ProcessWindow
+ return windows.panesByLayer[layer].map(({ identity, record, client, presentation, closing, entering, stopping }) => <ProcessWindow
key={identity}
@@ -123,45 +123,49 @@ export default function Workspace() {
client={client}
- title={local.title}
+ title={presentation.title}
- header={local.header}
+ header={presentation.header}
+
+ frame={presentation.frame}
+
+ layer={presentation.layer}
+
+ openingTransaction={presentation.transaction}
icon={icon(record)}
- position={local.position}
+ position={presentation.position}
- size={local.size}
+ size={presentation.size}
- localSurface={local.surface}
+ frameAnimation={presentation.frameAnimation}
- geometryAnimation={local.geometryAnimation}
+ geometryAnimation={presentation.geometryAnimation}
- minimizeAnimation={local.minimizeAnimation}
+ minimizeAnimation={presentation.minimizeAnimation}
- onLocalAnimationComplete={(kind, revision) => windows.localWindow.complete(record.identity, kind, revision)}
+ onPresentationAnimationComplete={(kind, revision) => windows.presentation.complete(record.identity, kind, revision)}
- onLocalRepresentation={windows.localWindow.represent}
+ onPresentationRepresentation={windows.presentation.represent}
// Only system-painted windows need to know which paint edges
// touch their surface. Positioning is identical in every layer.
paintSurfaceSize={layer === "window" ? windowSurfaceSize : undefined}
- depth={local.depth}
+ depth={presentation.depth}
active={fronts[layer]?.identity === record.identity}
- bare={layer !== "window"}
-
- minimized={local.minimized}
+ minimized={presentation.minimized}
- maximized={local.maximized}
+ maximized={presentation.maximized}
closing={closing}
stopping={stopping}
- entering={layer === "window" && entering}
+ entering={entering}
door={application.doors.program}
@@ -215,7 +219,7 @@ export default function Workspace() {
{windows.listed.map(record => {
- const window = windows.localWindow.projection(record.identity)
+ const window = windows.presentation.projection(record.identity)
return <WindowTaskbarItem
diff --git a/source/client/view/structure/desktop/taskbar/launcher/start-menu-panel.tsx b/source/client/view/structure/desktop/taskbar/launcher/start-menu-panel.tsx
index 2b7cea0..553294b 100644
--- a/source/client/view/structure/desktop/taskbar/launcher/start-menu-panel.tsx
+++ b/source/client/view/structure/desktop/taskbar/launcher/start-menu-panel.tsx
@@ -15,7 +15,7 @@ export default function StartMenuPanel({ labelId, name, version, left, right, fo
const spacing = 8
- return <Surface style={{ display: "grid", gridTemplateRows: "auto minmax(0, 1fr)", minHeight: 0, height: "100%", maxHeight: "inherit", overflow: "hidden" }}>
+ return <Surface material="full" style={{ display: "grid", gridTemplateRows: "auto minmax(0, 1fr)", minHeight: 0, height: "100%", maxHeight: "inherit", overflow: "hidden" }}>
{replacement ? <>
@@ -31,9 +31,9 @@ export default function StartMenuPanel({ labelId, name, version, left, right, fo
<div className="grid min-h-0 min-w-0 grid-cols-2" style={{ gap: "inherit" }}>
- <Surface className="min-h-0 min-w-0 overflow-hidden">{left}</Surface>
+ <Surface material="extended" className="min-h-0 min-w-0 overflow-hidden">{left}</Surface>
- <Surface className="min-h-0 min-w-0 overflow-hidden">{right}</Surface>
+ <Surface material="extended" className="min-h-0 min-w-0 overflow-hidden">{right}</Surface>
</div>
diff --git a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
index 942b3ef..398eb80 100644
--- a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
+++ b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx
@@ -76,7 +76,7 @@ export default function SystemDialogs() {
>
- <TaskbarSurface label={dialog.kind === "permission" ? "Permission request" : "System error"} labelId={title}>
+ <TaskbarSurface material="full" label={dialog.kind === "permission" ? "Permission request" : "System error"} labelId={title}>
{dialog.kind === "permission"
diff --git a/source/client/view/structure/desktop/taskbar/taskbar.tsx b/source/client/view/structure/desktop/taskbar/taskbar.tsx
index f62f079..ef40469 100644
--- a/source/client/view/structure/desktop/taskbar/taskbar.tsx
+++ b/source/client/view/structure/desktop/taskbar/taskbar.tsx
@@ -14,6 +14,8 @@ export default function Taskbar({ leading, trailing, dialogs, className, childre
{...props}
+ material="full"
+
>
{leading}
diff --git a/source/client/view/structure/desktop/windows/process-window.tsx b/source/client/view/structure/desktop/windows/process-window.tsx
index a32c3c6..8e872d7 100644
--- a/source/client/view/structure/desktop/windows/process-window.tsx
+++ b/source/client/view/structure/desktop/windows/process-window.tsx
@@ -1,9 +1,9 @@
import Process from "@client/core/link-manager/auth-manager/process-manager/process"
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import { type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
-import { type LocalAnimation, type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"
-import { type LocalGeometryRepresentation } from "@client/view/components/window-manager/local-windows"
-import { type Position, type Size, type Theme } from "@phreshos/core"
+import { type PresentationAnimation } from "@client/view/components/desktop-host/window-presentation"
+import { type PresentationGeometryRepresentation } from "@client/view/components/window-manager/window-presentations"
+import { type Position, type Size, type Theme, type WindowFrame, type WindowLayer, type WindowTransaction } from "@phreshos/core"
import Spinner from "@client/view/components/spinner"
import Window from "./window"
import ProgramFrame, { programFrameSource } from "@client/view/components/program-frame"
@@ -17,7 +17,7 @@ const settleDelay = 80
* props so memoization can see which process actually changed even though
* the peer deliberately keeps each Process instance alive and mutates it.
*/
-export default memo(function ({ identity, record, assetId, client, title, header, icon, position, size, localSurface, geometryAnimation, minimizeAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, maximized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, assetId, client, title, header, frame, layer, openingTransaction, icon, position, size, frameAnimation, geometryAnimation, minimizeAnimation, onPresentationAnimationComplete, onPresentationRepresentation, paintSurfaceSize, depth, active, minimized, maximized, closing, stopping, entering, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -37,7 +37,7 @@ export default memo(function ({ identity, record, assetId, client, title, header
const snap = useCallback((position: Position, size: Size) => onSnap(record, position, size), [onSnap, record])
- const represent = useCallback((representation: LocalGeometryRepresentation | null) => onLocalRepresentation(record.identity, representation), [onLocalRepresentation, record])
+ const represent = useCallback((representation: PresentationGeometryRepresentation | null) => onPresentationRepresentation(record.identity, representation), [onPresentationRepresentation, record])
const frameSource = programFrameSource(assetId, door)
@@ -86,7 +86,9 @@ export default memo(function ({ identity, record, assetId, client, title, header
const frameLoading = programAccess === "available" && (loading.source !== frameSource || loading.phase !== "ready")
- const progress = !bare && (stopping || closing ? "Closing" : frameLoading ? "Loading" : null)
+ const framed = layer === "window" || (layer === "under" || layer === "over") && frame !== false
+
+ const progress = framed && (stopping || closing ? "Closing" : frameLoading ? "Loading" : null)
return <Window
@@ -94,28 +96,32 @@ export default memo(function ({ identity, record, assetId, client, title, header
header={header}
+ frame={frame}
+
+ layer={layer}
+
+ openingTransaction={openingTransaction}
+
icon={icon}
position={position}
size={size}
- localSurface={localSurface}
+ frameAnimation={frameAnimation}
geometryAnimation={geometryAnimation}
minimizeAnimation={minimizeAnimation}
- onLocalAnimationComplete={onLocalAnimationComplete}
+ onPresentationAnimationComplete={onPresentationAnimationComplete}
- onLocalRepresentation={represent}
+ onPresentationRepresentation={represent}
paintSurfaceSize={paintSurfaceSize}
active={active}
- bare={bare}
-
minimized={minimized}
maximized={maximized}
@@ -124,7 +130,7 @@ export default memo(function ({ identity, record, assetId, client, title, header
stopping={stopping}
- animateEntrance={entering}
+ entering={entering}
data-process-window={record.identity}
@@ -190,7 +196,7 @@ export default memo(function ({ identity, record, assetId, client, title, header
{/* First press focuses an inactive window before its program can
receive input. Bare layers have no system click-catcher. */}
- {!bare && !active && <div data-window-click-catcher className="absolute inset-0 bg-transparent" />}
+ {layer === "window" && !active && <div data-window-click-catcher className="absolute inset-0 bg-transparent" />}
</Window>
})
@@ -210,21 +216,27 @@ interface ProcessWindowProps {
header: boolean
+ frame: WindowFrame
+
+ layer: WindowLayer
+
+ openingTransaction: WindowTransaction
+
icon: string
position: Position
size: Size
- localSurface: LocalSurfaceState | null
+ frameAnimation: PresentationAnimation | null
- geometryAnimation: LocalAnimation | null
+ geometryAnimation: PresentationAnimation | null
- minimizeAnimation: LocalAnimation | null
+ minimizeAnimation: PresentationAnimation | null
- onLocalAnimationComplete: (kind: "geometry" | "minimize" | "surface", revision: number) => void
+ onPresentationAnimationComplete: (kind: "geometry" | "minimize" | "frame", revision: number) => void
- onLocalRepresentation: (identity: string, representation: LocalGeometryRepresentation | null) => void
+ onPresentationRepresentation: (identity: string, representation: PresentationGeometryRepresentation | null) => void
paintSurfaceSize?: WindowSurfaceSize
@@ -242,8 +254,6 @@ interface ProcessWindowProps {
entering: boolean
- bare: boolean
-
door: string
programAccess: ProgramAccess
diff --git a/source/client/view/structure/desktop/windows/window-frame.tsx b/source/client/view/structure/desktop/windows/window-frame.tsx
new file mode 100644
index 0000000..de413d0
--- /dev/null
+++ b/source/client/view/structure/desktop/windows/window-frame.tsx
@@ -0,0 +1,94 @@
+import { useReducedMotion } from "@libs/react-motion"
+import { Surface, type Color, type MaterialOptions } from "@phreshos/react-ui"
+import { useLayoutEffect, useRef, useState } from "react"
+import { motion } from "motion/react"
+import { type PresentationAnimation } from "@client/view/components/desktop-host/window-presentation"
+import { type AppearanceColor, type WindowFrame as WindowFrameDefinition } from "@phreshos/core"
+import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
+import { resolveWindowTransaction } from "@client/view/appearance/motion"
+import { useAppearance } from "@phreshos/react-ui"
+
+/** Paints the optional Desktop-owned frame around an under or over presentation. */
+export default function WindowFrame({ frame, animation, onComplete }: WindowFrameProps) {
+
+ const reducedMotion = useReducedMotion()
+ const appearanceTransaction = useAppearance().transaction
+ const revision = animation?.revision
+ const transaction = animation ? resolveWindowTransaction(animation.transaction, appearanceTransaction) : null
+ const visible = frame !== false
+ const animated = revision !== undefined && transaction !== null
+ const [hidden, setHidden] = useState(!visible)
+ const completed = useRef<number | null>(null)
+ const retained = useRef<Exclude<WindowFrameDefinition, false>>(true)
+
+ if (frame !== false) retained.current = frame
+
+ useLayoutEffect(function () {
+
+ if (visible) setHidden(false)
+
+ else if (!animated || reducedMotion) setHidden(true)
+
+ }, [visible, animated, reducedMotion])
+
+ function finish() {
+
+ if (revision === undefined || completed.current === revision) return
+
+ completed.current = revision
+
+ if (!visible) setHidden(true)
+
+ onComplete(revision)
+ }
+
+ if (frame === false && !animation) return null
+
+ return <motion.div
+ initial={animated && visible && !reducedMotion ? surfaceLifecyclePose.hidden : surfaceLifecyclePose.visible}
+ animate={visible ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
+ transition={animated
+ ? surfacePresenceTransition(reducedMotion, transaction)
+ : { duration: 0 }}
+ onAnimationComplete={finish}
+ className="pointer-events-none absolute inset-0"
+ style={{ visibility: !visible && hidden ? "hidden" : "visible" }}
+ >
+ <Surface
+ aria-hidden="true"
+ color={frameColor(retained.current)}
+ material={frameMaterial(retained.current)}
+ radius={typeof retained.current === "object" ? retained.current.radius : undefined}
+ style={{ position: "absolute", inset: 0 }}
+ />
+ </motion.div>
+}
+
+interface WindowFrameProps {
+
+ frame: WindowFrameDefinition
+
+ animation: PresentationAnimation | null
+
+ onComplete: (revision: number) => void
+}
+
+function frameColor(frame: Exclude<WindowFrameDefinition, false>): Color | undefined {
+
+ if (frame === true || frame.color === undefined) return undefined
+
+ return appearanceColors.includes(frame.color as AppearanceColor)
+ ? `${frame.color as AppearanceColor}:base`
+ : frame.color
+}
+
+function frameMaterial(frame: Exclude<WindowFrameDefinition, false>): "none" | "full" | MaterialOptions {
+
+ if (frame === true || frame.material === undefined || frame.material === true) return "full"
+
+ if (frame.material === false) return "none"
+
+ return frame.material
+}
+
+const appearanceColors = ["background", "foreground", "default", "primary", "secondary", "success", "warning", "danger", "info"] as const satisfies readonly AppearanceColor[]
diff --git a/source/client/view/structure/desktop/windows/window-geometry-motion.ts b/source/client/view/structure/desktop/windows/window-geometry-motion.ts
index 5f584db..c74ba7f 100644
--- a/source/client/view/structure/desktop/windows/window-geometry-motion.ts
+++ b/source/client/view/structure/desktop/windows/window-geometry-motion.ts
@@ -1,5 +1,6 @@
import { resolveWindowGeometry, type WindowRegion } from "@client/view/components/window-manager/window-geometry"
-import { type LocalAnimation } from "@client/view/components/desktop-host/local-window"
+import { type PresentationAnimation } from "@client/view/components/desktop-host/window-presentation"
+import { resolveWindowTransaction } from "@client/view/appearance/motion"
import { type AppearanceTransaction, type Position, type Size } from "@phreshos/core"
import { useMotionValue, useTransform, type MotionStyle } from "motion/react"
import { useLayoutEffect, useRef } from "react"
@@ -9,13 +10,13 @@ import { useAppearance } from "@phreshos/react-ui"
interface WindowGeometryMotionOptions {
position: Position
size: Size
- animation?: LocalAnimation | null
+ animation?: PresentationAnimation | null
immediate: boolean
onComplete?: (revision: number) => void
}
/**
- * One continuous local representation of Window geometry.
+ * One continuous presentation of Window geometry.
*
* Core values remain the destination. Motion values exclusively own the
* visible pixels, including during a pointer gesture, so releasing a drag
@@ -39,7 +40,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
const gesturing = useRef(false)
const restoringGesture = useRef(false)
const initialized = useRef(false)
- const settlementListeners = useRef(new Set<() => void>())
const values = useRef({ position, size, animation, immediate, onComplete })
values.current = { position, size, animation, immediate, onComplete }
@@ -54,16 +54,22 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
animator.current!.stop()
}
- function announceSettlement() {
-
- for (const listener of settlementListeners.current) listener()
- }
-
- function listen(settled: () => void) {
-
- settlementListeners.current.add(settled)
-
- return () => settlementListeners.current.delete(settled)
+ function listen(changed: () => void) {
+ let active = true
+ let queued = false
+ const notify = () => {
+ if (queued) return
+ queued = true
+ queueMicrotask(() => {
+ queued = false
+ if (active) changed()
+ })
+ }
+ const cleanup = [x, y, width, height].map(value => value.on("change", notify))
+ return () => {
+ active = false
+ for (const release of cleanup) release()
+ }
}
function completeGestureRestore() {
@@ -90,7 +96,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
if (immediate) {
set(region)
- announceSettlement()
complete?.()
return
@@ -99,7 +104,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
animator.current!.transition(region, transaction, () => {
completeGestureRestore()
- announceSettlement()
complete?.()
})
}
@@ -129,7 +133,15 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
return
}
- transition(region, animation?.transaction, revision === undefined ? undefined : () => onComplete?.(revision))
+ const selected = animation ? resolveWindowTransaction(animation.transaction, appearanceTransaction) : null
+
+ if (!selected) {
+ set(region)
+ if (revision !== undefined) onComplete?.(revision)
+ return
+ }
+
+ transition(region, selected, revision === undefined ? undefined : () => onComplete?.(revision))
}, [position.x, position.y, size.width, size.height, animation?.revision, immediate])
@@ -156,7 +168,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
if (region) {
set(region)
- announceSettlement()
}
})
@@ -206,7 +217,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
animator.current!.transitionSize(region, appearanceTransaction, () => {
completeGestureRestore()
- announceSettlement()
})
}
@@ -231,7 +241,6 @@ export default function useWindowGeometryMotion({ position, size, animation, imm
if (region) {
set(region)
- announceSettlement()
}
}
diff --git a/source/client/view/structure/desktop/windows/window-header.tsx b/source/client/view/structure/desktop/windows/window-header.tsx
index 6a74b3a..27d4b19 100644
--- a/source/client/view/structure/desktop/windows/window-header.tsx
+++ b/source/client/view/structure/desktop/windows/window-header.tsx
@@ -1,16 +1,16 @@
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react"
-import { WindowHeader as Header } from "@phreshos/react-ui"
+import { Window } from "@phreshos/react-ui"
/** Connects Desktop Window behavior to React UI's shared header. */
export default function WindowHeader({ title, icon, active, whole, stopping, onGrab, onMinimize, onMaximize, onClose }: WindowHeaderProps) {
- return <Header active={active} onPointerDown={onGrab} onDoubleClick={onMaximize}>
- <Header.Identity icon={icon} title={title} />
- <Header.Actions>
- {onMinimize && <Header.Minimize onPress={onMinimize} />}
- {onMaximize && <Header.Maximize maximized={whole} onPress={onMaximize} />}
- {onClose && <Header.Close onPress={onClose} disabled={stopping} />}
- </Header.Actions>
- </Header>
+ return <Window.Header active={active} onPointerDown={onGrab} onDoubleClick={onMaximize}>
+ <Window.Header.Identity icon={icon} title={title} />
+ <Window.Header.Actions>
+ {onMinimize && <Window.Header.Minimize onPress={onMinimize} />}
+ {onMaximize && <Window.Header.Maximize maximized={whole} onPress={onMaximize} />}
+ {onClose && <Window.Header.Close onPress={onClose} disabled={stopping} />}
+ </Window.Header.Actions>
+ </Window.Header>
}
interface WindowHeaderProps {
diff --git a/source/client/view/structure/desktop/windows/window-panel.tsx b/source/client/view/structure/desktop/windows/window-panel.tsx
index a5132a0..bdec840 100644
--- a/source/client/view/structure/desktop/windows/window-panel.tsx
+++ b/source/client/view/structure/desktop/windows/window-panel.tsx
@@ -9,6 +9,7 @@ const WindowPanel = forwardRef<HTMLDivElement, SurfaceProps & { header: ReactNod
return <Surface
{...properties}
ref={ref}
+ material="full"
style={{
display: "grid",
gridTemplateRows: header == null ? "minmax(0, 1fr)" : "auto minmax(0, 1fr)",
diff --git a/source/client/view/structure/desktop/windows/window-surface.tsx b/source/client/view/structure/desktop/windows/window-surface.tsx
deleted file mode 100644
index 6944a19..0000000
--- a/source/client/view/structure/desktop/windows/window-surface.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useReducedMotion } from "@libs/react-motion"
-import { Surface } from "@phreshos/react-ui"
-import { useLayoutEffect, useRef, useState } from "react"
-import { motion } from "motion/react"
-import { type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"
-import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
-
-/** Projects one representation-local Surface without animating its material host. */
-export default function WindowSurface({ state, onComplete }: WindowSurfaceProps) {
-
- const { transition, visible } = state
- const reducedMotion = useReducedMotion()
- const revision = transition?.revision
- const transaction = transition?.transaction
- const animated = revision !== undefined && transaction !== undefined
- const [hidden, setHidden] = useState(!visible)
- const completed = useRef<number | null>(null)
-
- useLayoutEffect(function () {
-
- if (visible) setHidden(false)
-
- else if (!animated || reducedMotion) setHidden(true)
-
- }, [visible, animated, reducedMotion])
-
- function finish() {
-
- if (revision === undefined || completed.current === revision) return
-
- completed.current = revision
-
- if (!visible) setHidden(true)
-
- onComplete(revision)
- }
-
- return <motion.div
- initial={animated && visible && !reducedMotion ? surfaceLifecyclePose.hidden : surfaceLifecyclePose.visible}
- animate={visible ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}
- transition={animated
- ? surfacePresenceTransition(reducedMotion, transaction)
- : { duration: 0 }}
- onAnimationComplete={finish}
- className="pointer-events-none absolute inset-0"
- style={{ visibility: !visible && hidden ? "hidden" : "visible" }}
- >
- <Surface aria-hidden="true" style={{ position: "absolute", inset: 0 }} />
- </motion.div>
-}
-
-interface WindowSurfaceProps {
-
- state: LocalSurfaceState
-
- onComplete: (revision: number) => void
-}
diff --git a/source/client/view/structure/desktop/windows/window.tsx b/source/client/view/structure/desktop/windows/window.tsx
index 7f2735b..6220f4f 100644
--- a/source/client/view/structure/desktop/windows/window.tsx
+++ b/source/client/view/structure/desktop/windows/window.tsx
@@ -3,13 +3,13 @@ import { useReducedMotion } from "@libs/react-motion"
import { surfaceLifecyclePose, surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"
import WindowPanel from "./window-panel"
import { absoluteWindowGeometry, minimumWindowSize, resolveWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
-import { type Position, type Size } from "@phreshos/core"
+import { type Position, type Size, type WindowFrame as WindowFrameDefinition, type WindowLayer, type WindowTransaction } from "@phreshos/core"
import WindowHeader from "./window-header"
-import WindowSurface from "./window-surface"
-import { type LocalAnimation, type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"
-import { type LocalGeometryRepresentation } from "@client/view/components/window-manager/local-windows"
+import WindowFrame from "./window-frame"
+import { type PresentationAnimation } from "@client/view/components/desktop-host/window-presentation"
+import { type PresentationGeometryRepresentation } from "@client/view/components/window-manager/window-presentations"
import { motion } from "motion/react"
-import { motionTransition } from "@client/view/appearance/motion"
+import { motionTransition, resolveWindowTransaction } from "@client/view/appearance/motion"
import { useAppearance } from "@phreshos/react-ui"
import SnapPreview, { type SnapTarget } from "./snap-preview"
import { windowPaintInset } from "../geometry"
@@ -19,8 +19,8 @@ import { physicalToDesktopPixels, useDesktopScale } from "../desktop-scale"
/**
* A window: a pure function of the record it is given. Every render
* declares the whole target geometry from props — a float as left/top
- * pixels, a tile as its relative form. Motion interpolates only the local
- * representation between targets; the record remains the truth and a
+ * pixels, a tile as its relative form. Motion interpolates only the Desktop
+ * presentation between targets; the record remains the truth and a
* refreshed page renders that truth directly.
*
* One set of Motion values owns the visible pixel geometry from rest,
@@ -50,11 +50,12 @@ const edges: { edge: WindowEdge, className: string }[] = [
const minimizedSurfacePose = { scale: 0.86, y: 28, opacity: 0 }
-export default function ({ title, header = true, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, maximized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = minimumWindowSize.width, minHeight = minimumWindowSize.height, className, style, ...props }: WindowProps) {
+export default function ({ title, header = true, frame: frameDefinition = false, layer, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onPresentationAnimationComplete, onPresentationRepresentation, onFocusCapture, active = false, closing = false, stopping = false, minimized = false, maximized = false, entering = false, openingTransaction = false, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, frameAnimation, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = minimumWindowSize.width, minHeight = minimumWindowSize.height, className, style, ...props }: WindowProps) {
const reducedMotion = useReducedMotion()
const appearanceTransaction = useAppearance().transaction
const desktopScale = useDesktopScale()
+ const standard = layer === "window"
// Hidden windows retain their last presentation while lower-priority state changes.
const presented = useRef({ position, size })
@@ -66,19 +67,19 @@ export default function ({ title, header = true, icon, children, onClose, onClos
position: presented.current.position,
size: presented.current.size,
animation: geometryAnimation,
- immediate: reducedMotion || (bare && !geometryAnimation),
- onComplete: revision => onLocalAnimationComplete?.("geometry", revision)
+ immediate: reducedMotion || !geometryAnimation,
+ onComplete: revision => onPresentationAnimationComplete?.("geometry", revision)
})
- const frame = geometryMotion.frame
+ const frameElement = geometryMotion.frame
const [gesture, setGesture] = useState<Gesture | null>(null)
useLayoutEffect(function () {
- if (!onLocalRepresentation) return
+ if (!onPresentationRepresentation) return
- const representation: LocalGeometryRepresentation = {
+ const representation: PresentationGeometryRepresentation = {
read: geometryMotion.read,
present: geometryMotion.present,
begin: () => geometryMotion.beginGesture()?.region ?? null,
@@ -87,11 +88,11 @@ export default function ({ title, header = true, icon, children, onClose, onClos
listen: geometryMotion.listen
}
- onLocalRepresentation(representation)
+ onPresentationRepresentation(representation)
- return () => onLocalRepresentation(null)
+ return () => onPresentationRepresentation(null)
- }, [onLocalRepresentation])
+ }, [onPresentationRepresentation])
const closureCompleted = useRef(false)
@@ -111,8 +112,6 @@ export default function ({ title, header = true, icon, children, onClose, onClos
const [presenceHidden, setPresenceHidden] = useState(minimized)
- const minimizeTransaction = minimizeAnimation?.transaction
-
useLayoutEffect(function () {
if (!minimized) setPresenceHidden(false)
@@ -133,9 +132,9 @@ export default function ({ title, header = true, icon, children, onClose, onClos
onUnavailable?.("close")
- if (bare || reducedMotion) completeClosure()
+ if (!standard || reducedMotion) completeClosure()
- }, [closing, bare, reducedMotion])
+ }, [closing, standard, reducedMotion])
useEffect(function () {
@@ -143,31 +142,41 @@ export default function ({ title, header = true, icon, children, onClose, onClos
if (revision === undefined || minimizeTransaction && !reducedMotion) return
- onLocalAnimationComplete?.("minimize", revision)
+ onPresentationAnimationComplete?.("minimize", revision)
- }, [bare, minimizeAnimation?.revision, reducedMotion])
+ }, [minimizeAnimation?.revision, reducedMotion])
- const initialPresence = bare || reducedMotion || !animateEntrance
- ? surfaceLifecyclePose.visible
- : surfaceLifecyclePose.hidden
+ const configuredOpeningTransaction = layer === "under" || layer === "over"
+ ? resolveWindowTransaction(openingTransaction, appearanceTransaction)
+ : standard ? appearanceTransaction : null
+ const opening = entering && !reducedMotion ? configuredOpeningTransaction : null
+ const [opened, setOpened] = useState(opening === null)
+ const minimizeTransaction = minimizeAnimation
+ ? resolveWindowTransaction(minimizeAnimation.transaction, appearanceTransaction)
+ : null
+ const initialPresence = opening ? surfaceLifecyclePose.hidden : surfaceLifecyclePose.visible
- const presencePose = closing && !bare
+ const presencePose = closing && standard
? surfaceLifecyclePose.hidden
: minimized
- ? bare ? surfacePresencePose.entering : minimizedSurfacePose
+ ? standard ? minimizedSurfacePose : surfacePresencePose.entering
: surfaceLifecyclePose.visible
const presenceTransition = reducedMotion
? { duration: 0 }
- : bare
- ? minimizeTransaction
+ : closing && standard
+ ? motionTransition(appearanceTransaction)
+ : minimizeTransaction
? surfacePresenceTransition(false, minimizeTransaction)
- : { duration: 0 }
- : motionTransition(closing ? appearanceTransaction : minimizeTransaction ?? appearanceTransaction)
+ : !opened && opening
+ ? surfacePresenceTransition(false, opening)
+ : { duration: 0 }
function completePresence() {
- if (closing && !bare) completeClosure()
+ if (!opened) setOpened(true)
+
+ if (closing && standard) completeClosure()
if (minimized) setPresenceHidden(true)
@@ -175,7 +184,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
if (revision !== undefined && minimizeTransaction && !reducedMotion) {
- onLocalAnimationComplete?.("minimize", revision)
+ onPresentationAnimationComplete?.("minimize", revision)
}
}
@@ -204,7 +213,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
let current: WindowRegion = { ...origin }
- if (geometryAnimation) onLocalAnimationComplete?.("geometry", geometryAnimation.revision)
+ if (geometryAnimation) onPresentationAnimationComplete?.("geometry", geometryAnimation.revision)
// Pulling a shared window out of its placement belongs to the
// header alone. An edge is not a hand asking to float — it is a
@@ -428,7 +437,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
{gesture?.shown && <SnapPreview
shown={gesture.shown}
visible={gesture.zone !== null}
- bare={bare}
+ bare={!standard}
paintSurfaceSize={paintSurfaceSize}
reducedMotion={reducedMotion}
zIndex={style?.zIndex}
@@ -436,7 +445,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
<motion.div
- ref={frame}
+ ref={frameElement}
onPointerDown={onActivate}
@@ -470,7 +479,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
Bare, there is no difference: the frame fills the box, so
the window is exactly as large as it asked to be and its
boundaries are the ones its own content draws. */}
- {bare ? <motion.div
+ {!standard ? <motion.div
data-window-container
initial={initialPresence}
animate={presencePose}
@@ -480,9 +489,11 @@ export default function ({ title, header = true, icon, children, onClose, onClos
style={{ visibility: minimized && presenceHidden ? "hidden" : "visible" }}
>
- {/* A bare Client controls its own host surface, separate from
- its content and without the header/content Panel shell. */}
- {localSurface && <WindowSurface state={localSurface} onComplete={revision => onLocalAnimationComplete?.("surface", revision)} />}
+ {(layer === "under" || layer === "over") && <WindowFrame
+ frame={frameDefinition}
+ animation={frameAnimation ?? null}
+ onComplete={revision => onPresentationAnimationComplete?.("frame", revision)}
+ />}
<div data-window-content className="relative min-h-0">{children}</div>
@@ -520,7 +531,7 @@ export default function ({ title, header = true, icon, children, onClose, onClos
>{children}</WindowPanel>
</motion.div>}
- {!bare && edges.map(handle => <div
+ {standard && edges.map(handle => <div
key={handle.edge}
@@ -546,6 +557,12 @@ interface WindowProps extends Omit<ComponentProps<"div">, "onAnimationStart" | "
/** Whether the Desktop-owned standard Window header is shown. */
header?: boolean
+ /** Frame definition applied by under and over presentations. */
+ frame?: WindowFrameDefinition
+
+ /** Presentation role currently occupied by the Window. */
+ layer: WindowLayer
+
// Drawn beside the title. A URL rather than a node: what a window
// shows of its program is a picture the browser fetches, and the
// path it fetches from is the view's to build.
@@ -572,15 +589,6 @@ interface WindowProps extends Omit<ComponentProps<"div">, "onAnimationStart" | "
active?: boolean
- // Nothing the system paints. The window's boundaries become the
- // frame's exactly: no surface, no shadow, no rounding, no header, no
- // controls, and no gutter — so what a program asked to be is what it
- // gets, edge to edge, rather than half a gutter smaller.
- //
- // The endpoint owns later local projection in a bare layer, so the
- // ordinary window manager contributes neither resize edges nor snapping.
- bare?: boolean
-
closing?: boolean
/** The Process termination request has not settled yet. */
@@ -590,23 +598,25 @@ interface WindowProps extends Omit<ComponentProps<"div">, "onAnimationStart" | "
maximized?: boolean
- // Whether mounting this element represents a newly opened window.
- animateEntrance?: boolean
+ /** Whether mounting this element represents a newly opened Window. */
+ entering?: boolean
+
+ /** Opening transaction used by under and over presentations. */
+ openingTransaction?: WindowTransaction
position?: Position
size?: Size
- /** Surface target owned by this live iframe representation. */
- localSurface?: LocalSurfaceState | null
+ frameAnimation?: PresentationAnimation | null
- geometryAnimation?: LocalAnimation | null
+ geometryAnimation?: PresentationAnimation | null
- minimizeAnimation?: LocalAnimation | null
+ minimizeAnimation?: PresentationAnimation | null
- onLocalAnimationComplete?: (kind: "geometry" | "minimize" | "surface", revision: number) => void
+ onPresentationAnimationComplete?: (kind: "geometry" | "minimize" | "frame", revision: number) => void
- onLocalRepresentation?: (representation: LocalGeometryRepresentation | null) => void
+ onPresentationRepresentation?: (representation: PresentationGeometryRepresentation | null) => void
/** Surface used only to decide which painted edges receive an inset. */
paintSurfaceSize?: WindowSurfaceSize
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
index ad5e201..467e426 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -1,21 +1,14 @@
-import Window from "./window"
-
/**
- * The one authoritative client state of a Process.
+ * The current execution context of a Process's Client Endpoint.
*
* Browser tabs may each represent this state with an iframe and a nearby
- * boundary, but none of those representations owns it. The Window is part of
- * this state and therefore begins and ends with the client, not with a tab.
+ * boundary. The Client Endpoint-owned Window survives when this context stops.
*/
export default class ClientState {
- public readonly window: Window
-
public readonly service: boolean
- public constructor(window: Window, service: boolean) {
-
- this.window = window
+ public constructor(service: boolean) {
this.service = service
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts
index b2ab06a..6cdda51 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts
@@ -6,7 +6,7 @@ import { type Half } from "./process-traffic"
*
* Unlike ProcessTraffic, these routes have no destination metadata: the
* Endpoint is the source being followed, and only explicit followers join its
- * route. Endpoint incarnation changes do not end a route; Process exit does.
+ * route. Endpoint execution-context changes do not end a route; Process exit does.
*/
export default class EndpointEvents extends TheLink {
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 481fe17..5ffb42c 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -34,7 +34,7 @@ import {
type WindowLayer,
type WindowState
} from "@phreshos/core"
-import { isDesktopReplacementLayer, type DesktopReplacementLayer } from "@shared/desktop-replacement"
+import { isDesktopReplacementLayer, type DesktopReplacementLayer } from "@shared/window-layers"
import type { ServerRuntime, ServerRuntimeFactory } from "@server/core/server-runtime"
import { permissionCatalog } from "@server/core/permissions"
import SystemAccess from "./system-access"
@@ -42,7 +42,7 @@ import { WebSocket } from "ws"
/**
* The core's processes: the wire and the collection. Each process owns
- * itself — its endpoint incarnations and serialisation — and this manager
+ * itself — its Endpoint execution contexts and serialisation — and this manager
* routes: it holds them by identity, carries operations in from connections,
* and broadcasts what changed.
*
@@ -66,7 +66,7 @@ export default class ProcessManager extends TheLink {
// Endpoint speaks once; only boundaries following that Endpoint join.
private readonly endpointEvents = new EndpointEvents()
- // Services route to live Endpoint incarnations. They own no registration state
+ // Services route to running Endpoint execution contexts. They own no registration state
// and never control the Process or Endpoint they address.
private readonly services: EndpointServices
@@ -139,18 +139,18 @@ export default class ProcessManager extends TheLink {
const process = this.system.holdProcess(value, fallback)
- const window = process.client?.window
+ const window = process.clientEndpoint?.window
- if (!window) throw new Error("This process has no live client endpoint")
+ if (!window) throw new Error("This Program declared no Client Endpoint")
return { process, window }
}
private windowOf(identity: string) {
- const window = this.find(identity).client?.window
+ const window = this.find(identity).clientEndpoint?.window
- if (!window) throw new Error("This process has no live client endpoint")
+ if (!window) throw new Error("This Program declared no Client Endpoint")
return window
}
@@ -173,6 +173,8 @@ export default class ProcessManager extends TheLink {
return Object.freeze({
title: window.title,
header: window.header,
+ frame: window.frame,
+ transaction: window.transaction,
position: window.position,
size: window.size,
minimized: window.minimized,
@@ -932,7 +934,7 @@ export default class ProcessManager extends TheLink {
private window(shape: Shape) {
- const shown = { title: shape.title, header: shape.header, layer: shape.layer }
+ const shown = { title: shape.title, header: shape.header, frame: shape.frame, transaction: shape.transaction, layer: shape.layer }
return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize, shape.maximize)
}
@@ -948,17 +950,19 @@ export default class ProcessManager extends TheLink {
}
private async replaceDesktopPresentation(layer: DesktopReplacementLayer) {
- const occupied = [...this.processes.values()].filter(process => process.client?.window.layer === layer)
+ const occupied = [...this.processes.values()].filter(process => process.client && process.clientEndpoint?.window.layer === layer)
for (const process of occupied) await this.exitProcess(process.identity, "complete")
}
/** Claims the role after serialized replacement has released its previous owner. */
- private activateClient(process: Process, window: Window, service: boolean) {
+ private activateClient(process: Process, service: boolean) {
+ const window = process.clientEndpoint?.window
+ if (!window) throw new Error("This Program declared no Client Endpoint")
if (isDesktopReplacementLayer(window.layer) && [...this.processes.values()].some(
- current => current.client?.window.layer === window.layer
+ current => current !== process && current.client && current.clientEndpoint?.window.layer === window.layer
)) throw new Error(`A Client Endpoint is already running in the ${window.layer} layer`)
- process.startClient(window, service)
+ process.startClient(service)
}
public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, runtime: ServerRuntimeFactory<Program> | null, client: boolean, shape: Shape | null, parent: Process | null, registration?: ProcessRegistration) {
@@ -987,7 +991,7 @@ export default class ProcessManager extends TheLink {
// do not hear about it.
const front = shape && this.front(shape.layer)
- const window = shape ? this.window(shape) : null
+ const window = registration?.window ? this.window(registration.window) : shape ? this.window(shape) : null
const process = new Process(
@@ -1005,7 +1009,9 @@ export default class ProcessManager extends TheLink {
this.hostTraffic,
- permissionCatalog.granted(this.authManager.programManager.permission(program, "all"))
+ permissionCatalog.granted(this.authManager.programManager.permission(program, "all")),
+
+ window
)
this.processes.set(identity, process)
@@ -1027,7 +1033,7 @@ export default class ProcessManager extends TheLink {
// order: Process creation, endpoint start, endpoint stop, Process exit.
await this.transition(process, async () => {
- if (client && window) this.activateClient(process, window, launch.client?.service ?? false)
+ if (client && window) this.activateClient(process, launch.client?.service ?? false)
if (runtime) this.activateServer(process, runtime, launch.server?.service ?? false)
@@ -1092,7 +1098,7 @@ export default class ProcessManager extends TheLink {
// Who had focus while this one was still here, in its own layer.
// A window closing hands it to whatever is left showing
// underneath *it* — a layer emptying hands nothing across.
- const layer = process.client?.window.layer ?? null
+ const layer = process.client ? process.clientEndpoint?.window.layer ?? null : null
const front = layer && this.front(layer)
@@ -1226,6 +1232,8 @@ export default class ProcessManager extends TheLink {
await this.transition(process, async () => {
+ if (!process.program.server) throw new Error("This Program declared no Server Endpoint")
+
if (!process.server) return
if (!process.client) throw new Error("The final live endpoint cannot be stopped; exit the Process instead")
@@ -1248,7 +1256,9 @@ export default class ProcessManager extends TheLink {
const shape = this.authManager.programManager.clientShape(process.program, launch)
- return await this.serializeClientLayer(shape.layer, () => this.startClientInLayer(identity, launch, shape))
+ const layer = launch.layer ?? process.clientEndpoint?.window.layer ?? shape.layer
+
+ return await this.serializeClientLayer(layer, () => this.startClientInLayer(identity, launch, shape))
}
private async startClientInLayer(identity: string, launch: ClientLaunch, shape: StandardShape) {
@@ -1265,13 +1275,17 @@ export default class ProcessManager extends TheLink {
await process.program.validate()
- const window = this.window(shape)
+ const window = process.clientEndpoint?.window
+
+ if (!window) throw new Error("This Program declared no Client Endpoint")
+
+ this.applyClientLaunch(process, window, shape, launch)
const before = this.front(window.layer)
if (isDesktopReplacementLayer(window.layer)) await this.replaceDesktopPresentation(window.layer)
- this.activateClient(process, window, launch.service ?? declaration.service)
+ this.activateClient(process, launch.service ?? declaration.service)
try {
@@ -1296,12 +1310,51 @@ export default class ProcessManager extends TheLink {
return identity
}
+ /** Explicit restart values replace their retained authoritative counterparts. */
+ private applyClientLaunch(process: Process, window: Window, shape: StandardShape, launch: ClientLaunch) {
+
+ if (launch.title !== undefined && window.changeTitle(shape.title)) this.said(process.identity, "changeTitle", window.title)
+
+ if (launch.header !== undefined && window.changeHeader(shape.header)) this.said(process.identity, "changeHeader", window.header)
+
+ if (launch.frame !== undefined && window.changeFrame(shape.frame)) this.said(process.identity, "changeFrame", window.frame)
+
+ if (launch.transaction !== undefined) window.changeOpeningTransaction(shape.transaction)
+
+ if (launch.position !== undefined && launch.size !== undefined) {
+ const changed = window.setGeometry({ position: shape.position, size: shape.size })
+ if (changed.moved || changed.resized) {
+ this.said(process.identity, "geometry", { position: window.position, size: window.size })
+ if (changed.moved) this.said(process.identity, "move", window.position)
+ if (changed.resized) this.said(process.identity, "resize", window.size)
+ }
+ }
+ else {
+ if (launch.position !== undefined && window.move(shape.position)) this.said(process.identity, "move", window.position)
+ if (launch.size !== undefined && window.resize(shape.size)) this.said(process.identity, "resize", window.size)
+ }
+
+ if (launch.minimize !== undefined && window.minimized !== shape.minimize) {
+ window.minimized = shape.minimize
+ this.said(process.identity, "minimize", window.minimized)
+ }
+
+ if (launch.maximize !== undefined && window.maximized !== shape.maximize) {
+ window.maximized = shape.maximize
+ this.said(process.identity, "maximize", window.maximized)
+ }
+
+ if (launch.layer !== undefined) window.layer = shape.layer
+ }
+
public async stopClient(identity: string) {
const process = this.find(identity)
await this.transition(process, async () => {
+ if (!process.program.client) throw new Error("This Program declared no Client Endpoint")
+
if (!process.client) return
if (!process.server) throw new Error("The final live endpoint cannot be stopped; exit the Process instead")
@@ -1314,7 +1367,7 @@ export default class ProcessManager extends TheLink {
private async deactivateClient(process: Process) {
- const layer = process.client?.window.layer ?? null
+ const layer = process.client ? process.clientEndpoint?.window.layer ?? null : null
const service = process.client?.service === true
@@ -1999,13 +2052,23 @@ export default class ProcessManager extends TheLink {
return [null]
}
- if (word === "exists") {
+ if (word === "running") {
const target = heldProcess(rest[1])
- if (rest[0] === "server") return [target.server !== null]
+ if (rest[0] === "server") {
- if (rest[0] === "client") return [target.client !== null]
+ if (!target.program.server) throw new Error("This Program declared no Server Endpoint")
+
+ return [target.server !== null]
+ }
+
+ if (rest[0] === "client") {
+
+ if (!target.program.client) throw new Error("This Program declared no Client Endpoint")
+
+ return [target.client !== null]
+ }
throw new Error("A Process endpoint is server or client")
}
@@ -2017,6 +2080,8 @@ export default class ProcessManager extends TheLink {
if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
+ if (!target.program[endpoint]) throw new Error(`This Program declared no ${endpoint === "server" ? "Server" : "Client"} Endpoint`)
+
return [endpoint === "server" ? target.server?.service === true : target.client?.service === true]
}
@@ -2182,6 +2247,24 @@ export default class ProcessManager extends TheLink {
return [target.identity]
}
+ if (word === "changeFrame") {
+
+ const target = heldWindow(rest[0]).process
+
+ await this.system.changeWindowFrame(target, rest[1] as never)
+
+ return [target.identity]
+ }
+
+ if (word === "changeOpeningTransaction") {
+
+ const target = heldWindow(rest[0]).process
+
+ await this.system.changeWindowOpeningTransaction(target, rest[1] as never)
+
+ return [target.identity]
+ }
+
if (word === "raise") {
const target = heldWindow(rest[0]).process
@@ -3080,6 +3163,28 @@ export default class ProcessManager extends TheLink {
return { identity, window }
}
+ @Connect("/change-frame")
+ public async changeFrame(identity: string, frame: import("@phreshos/core").WindowFrame) {
+
+ const window = this.mutableWindowOf(identity)
+
+ if (!window.changeFrame(frame)) return { identity, window }
+
+ this.said(identity, "changeFrame", window.frame)
+
+ return { identity, window }
+ }
+
+ @Connect("/change-opening-transaction")
+ public async changeOpeningTransaction(identity: string, transaction: import("@phreshos/core").WindowTransaction) {
+
+ const window = this.mutableWindowOf(identity)
+
+ window.changeOpeningTransaction(transaction)
+
+ return { identity, window }
+ }
+
// To the front of its own layer, and that is the whole of it.
//
// It was called `focus` and it did three things: it showed a hidden
@@ -3174,7 +3279,7 @@ export default class ProcessManager extends TheLink {
for (const [identity, process] of this.processes) {
- const window = process.client?.window
+ const window = process.clientEndpoint?.window
if (!process.client || !window || window.minimized || window.layer !== layer) continue
@@ -3216,6 +3321,9 @@ export default class ProcessManager extends TheLink {
interface ProcessRegistration {
+ /** Client Endpoint-owned Window created even when its execution context starts stopped. */
+ window?: Shape | null
+
/** Attach observers before either Endpoint can emit output or exit. */
prepare?: (process: Process) => void
@@ -3350,6 +3458,10 @@ interface ShapeBase {
header: boolean
+ frame: import("@phreshos/core").WindowFrame
+
+ transaction: import("@phreshos/core").WindowTransaction
+
position: Position
size: Size
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 2b7b2bd..e2f9b75 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -5,7 +5,7 @@ import ServerProcessBoundary, { type HostVisibility } from "./server-process-bou
import HostTraffic from "./host-traffic"
import ClientState from "./client-state"
import { randomUUID } from "node:crypto"
-import { type Layer } from "@phreshos/core"
+import { type Layer, type WindowFrame, type WindowTransaction } from "@phreshos/core"
import { Tunnel } from "@the-link/core"
import type { ServerRuntime } from "@server/core/server-runtime"
@@ -17,8 +17,8 @@ import type { ServerRuntime } from "@server/core/server-runtime"
* Program declaration that later launches inherit.
*
* Endpoint presence is mutable live state. Each start creates a fresh
- * boundary incarnation; each stop removes that boundary and everything it
- * owns. The Process remains the stable aggregate around those incarnations
+ * execution context; each stop removes that context's boundary and everything
+ * it owns. The Process remains the stable aggregate around those contexts
* and must always have at least one live endpoint.
*
* The Server runtime boundary lives here beside the transmitted values and is
@@ -56,15 +56,17 @@ export default class Process {
// must preserve that value without changing the domain shape.
public readonly startedAt = new Date()
- // The current server incarnation. Null is current live state, not a
+ // The current Server execution context. Null is current live state, not a
// declaration or a permanent launch-shape decision.
public server: ServerProcessBoundary | null = null
- // The current client incarnation and the Window it owns. Its nearby iframe
- // boundary belongs to the desktop session, but both existence and Window
- // lifetime originate here. Stopping the client destroys this value whole.
+ // The current Client execution context. Its nearby iframe boundary
+ // belongs to the Desktop session and ends when this context stops.
public client: ClientState | null = null
+ /** Permanent Client Endpoint state retained between execution contexts. */
+ public readonly clientEndpoint: Readonly<{ window: Window }> | null
+
// The process whose call to `program.createProcess()` created this
// one. Lineage only: keeping this handle neither owns nor prolongs
// either life.
@@ -93,7 +95,7 @@ export default class Process {
private exitProcess: (() => Promise<unknown>) | null = null
- public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic, clientSameOrigin: boolean) {
+ public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic, clientSameOrigin: boolean, window: Window | null = null) {
this.identity = identity
@@ -110,6 +112,8 @@ export default class Process {
this.hostTraffic = hostTraffic
this.clientSameOrigin = clientSameOrigin
+
+ this.clientEndpoint = window ? Object.freeze({ window }) : null
}
public setClientSameOrigin(sameOrigin: boolean) {
@@ -168,11 +172,13 @@ export default class Process {
return () => { this.readyWaiters[endpoint].delete(notify) }
}
- public startClient(window: Window, service: boolean) {
+ public startClient(service: boolean) {
if (this.client) return false
- this.client = new ClientState(window, service)
+ if (!this.clientEndpoint) throw new Error("This Program declared no Client Endpoint")
+
+ this.client = new ClientState(service)
this.becameReady("client")
@@ -302,6 +308,12 @@ export default class Process {
startedAt: this.startedAt,
+ /** Whether this Process's Program declared a Server Endpoint. */
+ serverEndpoint: this.program.server !== null,
+
+ /** Whether this Process's Program declared a Client Endpoint. */
+ clientEndpoint: this.clientEndpoint !== null,
+
// These are live endpoint snapshots. Program declarations answer
// which endpoint kinds can be started.
server: this.server ? { service: this.server.service } : null,
@@ -325,6 +337,10 @@ export default class Process {
// pane never receives this record whole.
parent: this.parent?.record() ?? null,
+ clientEndpoint: this.clientEndpoint
+ ? { window: this.clientEndpoint.window.toJSON() }
+ : null,
+
client: this.client ? { ...this.client, sameOrigin: this.clientSameOrigin } : null
}
}
@@ -347,18 +363,7 @@ export type HostedProcess = ReturnType<Process["hosted"]>
/** Public Process data from which an endpoint SDK reconstructs a handle. */
export type ProcessRecord = ReturnType<Process["record"]>
-export type ProcessSnapshot = Omit<HostedProcess, "client"> & {
-
- client: HostedProcess["client"] extends infer Client
-
- ? Client extends { window: Window }
-
- ? Omit<Client, "window"> & { window: ReturnType<Window["toJSON"]> }
-
- : Client
-
- : never
-}
+export type ProcessSnapshot = HostedProcess
export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
@@ -378,6 +383,12 @@ export interface ProcessLaunch {
title: string
+ header: boolean
+
+ frame: WindowFrame
+
+ transaction: WindowTransaction
+
position: Position | null
size: Size | null
diff --git a/source/server/core/link-manager/auth-manager/process-manager/window.ts b/source/server/core/link-manager/auth-manager/process-manager/window.ts
index 4f27b1c..90300ff 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,4 +1,16 @@
-import { isRelativeValue, type Position, type Size, type Value, type WindowGeometry, type WindowLayer, type WindowState } from "@phreshos/core"
+import {
+ isRelativeValue,
+ parseWindowFrame,
+ parseWindowTransaction,
+ type Position,
+ type Size,
+ type Value,
+ type WindowFrame,
+ type WindowGeometry,
+ type WindowLayer,
+ type WindowState,
+ type WindowTransaction
+} from "@phreshos/core"
/** Authoritative geometry, visibility, maximization, title, and layer ordering. */
// What a Window says about the Program behind it. Resolved when the Process
@@ -10,6 +22,10 @@ export interface Shown {
header: boolean
+ frame: WindowFrame
+
+ transaction: WindowTransaction
+
// Which structurally isolated Desktop layer this Window occupies.
layer: WindowLayer
@@ -37,7 +53,11 @@ export default class Window implements Omit<WindowState, "front"> {
public header: boolean
// The Window's authoritative Desktop layer.
- public readonly layer: WindowLayer
+ public layer: WindowLayer
+
+ public frame: WindowFrame
+
+ public transaction: WindowTransaction
public constructor(shown: Shown, position: Position, size: Size, depth: number, minimized: boolean, maximized = false) {
@@ -45,6 +65,10 @@ export default class Window implements Omit<WindowState, "front"> {
this.header = shown.header
+ this.frame = parseWindowFrame(shown.frame)
+
+ this.transaction = parseWindowTransaction(shown.transaction)
+
this.layer = shown.layer
this.position = position
@@ -140,6 +164,28 @@ export default class Window implements Omit<WindowState, "front"> {
return true
}
+ public changeFrame(frame: WindowFrame) {
+
+ const parsed = parseWindowFrame(frame)
+
+ if (JSON.stringify(this.frame) === JSON.stringify(parsed)) return false
+
+ this.frame = parsed
+
+ return true
+ }
+
+ public changeOpeningTransaction(transaction: WindowTransaction) {
+
+ const parsed = parseWindowTransaction(transaction)
+
+ if (JSON.stringify(this.transaction) === JSON.stringify(parsed)) return false
+
+ this.transaction = parsed
+
+ return true
+ }
+
public toJSON() {
return {
@@ -148,6 +194,10 @@ export default class Window implements Omit<WindowState, "front"> {
header: this.header,
+ frame: this.frame,
+
+ transaction: this.transaction,
+
layer: this.layer,
position: this.position,
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 5832a8c..ee47bd1 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -30,6 +30,7 @@ import {
type PermissionValue,
type Permissions
} from "@phreshos/core"
+import { windowLayerDefaults } from "@shared/window-layers"
const maximumProcessesPerProgram = 20
@@ -1385,7 +1386,9 @@ export default class ProgramManager extends TheLink {
// Resolving the Window here validates the same launch grammar even when
// the launch is being stored for a later boot. Only the original launch
// is persisted; system defaults are derived again when it actually runs.
- const shape = client ? this.clientShape(program, askedClient) : null
+ const windowShape = program.client ? this.clientShape(program, askedClient) : null
+
+ const shape = client ? windowShape : null
const intent: ProcessLaunch = {
@@ -1405,7 +1408,7 @@ export default class ProgramManager extends TheLink {
options
}
- return { options, server, client, shape, intent }
+ return { options, server, client, shape, windowShape, intent }
}
private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, prepared?: ReturnType<ProgramManager["resolveLaunch"]>) {
@@ -1463,6 +1466,7 @@ export default class ProgramManager extends TheLink {
// activated, so even a server command that exits immediately has a
// complete output and exit record.
await this.authManager.processManager.register(identity, launch.name ?? null, program, options, resolved.intent, runtime, client !== null, shape, parent, {
+ window: resolved.windowShape,
prepare: record => {
record.onServerStart(server => server.onOutput((stream, text) => logs.printed(identity, stream === "err" ? "stderr" : "stdout", text)))
record.onServerStop((code, signal) => logs.endpointExited(identity, "server", code, signal))
@@ -1525,11 +1529,17 @@ export default class ProgramManager extends TheLink {
const layer = asked.layer ?? client.layer ?? "window"
+ const defaults = windowLayerDefaults(layer)
+
return {
- title: asked.title ?? program.title,
+ title: asked.title ?? client.title ?? program.title,
+
+ header: asked.header ?? client.header ?? defaults.header,
+
+ frame: asked.frame ?? client.frame ?? defaults.frame,
- header: layer === "window" ? asked.header ?? client.header ?? true : true,
+ transaction: asked.transaction ?? client.transaction ?? defaults.transaction,
position: asked.position ?? client.position ?? { x: 120 + shift, y: 80 + shift },
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 7f6f90b..d051fbb 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:pat
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { validateIcon } from "./icon"
-import { parseLaunch, parseProgramDefinition, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"
+import { parseLaunch, parseProgramDefinition, parseWindowFrame, parseWindowTransaction, type ProgramCommandChunk, type ProgramSnapshot } from "@phreshos/core"
import { permissionCatalog, type DeclaredPermissions } from "@server/core/permissions"
/**
@@ -209,6 +209,10 @@ export default class Program {
header: client.header ?? null,
+ frame: client.frame ?? null,
+
+ transaction: client.transaction ?? null,
+
size: client.size ?? null,
position: client.position ?? null,
@@ -385,6 +389,10 @@ function coherent(config: ProgramConfig) {
if (config.client?.title !== undefined && typeof config.client.title !== "string") throw new Error("A client half's title must be text")
+ if (config.client?.frame !== undefined) parseWindowFrame(config.client.frame)
+
+ if (config.client?.transaction !== undefined) parseWindowTransaction(config.client.transaction)
+
if (config.client?.maximize !== undefined && typeof config.client.maximize !== "boolean") throw new Error("A client half's maximize default must be true or false")
if (config.client?.minimize !== undefined && typeof config.client.minimize !== "boolean") throw new Error("A client half's minimize default must be true or false")
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
index d59110f..0dce4f3 100644
--- a/source/server/core/system.ts
+++ b/source/server/core/system.ts
@@ -13,7 +13,9 @@ import type {
ServerLaunch,
ShellOptions,
Size,
- WindowGeometry
+ WindowFrame,
+ WindowGeometry,
+ WindowTransaction
} from "@phreshos/core"
import type { Half, TrafficKind } from "./link-manager/auth-manager/process-manager/process-traffic"
import { processReference, type ProcessReference } from "./link-manager/auth-manager/process-manager/endpoint-reference"
@@ -353,6 +355,16 @@ export default class System {
await this.processManager.changeHeader(process.identity, header)
}
+ public async changeWindowFrame(process: Process, frame: WindowFrame) {
+
+ await this.processManager.changeFrame(process.identity, frame)
+ }
+
+ public async changeWindowOpeningTransaction(process: Process, transaction: WindowTransaction) {
+
+ await this.processManager.changeOpeningTransaction(process.identity, transaction)
+ }
+
public async raiseWindow(process: Process) {
await this.processManager.raise(process.identity)
@@ -376,6 +388,9 @@ export default class System {
start: program.client.start,
service: program.client.service,
title: program.client.title ?? null,
+ header: program.client.header ?? null,
+ frame: program.client.frame ?? null,
+ transaction: program.client.transaction ?? null,
size: program.client.size ?? null,
position: program.client.position ?? null,
layer: program.client.layer ?? null,
diff --git a/source/shared/desktop-replacement.ts b/source/shared/desktop-replacement.ts
deleted file mode 100644
index 2090c9b..0000000
--- a/source/shared/desktop-replacement.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { WindowLayer } from "@phreshos/core"
-
-/** Window roles that replace one fixed Desktop-owned presentation. */
-export type DesktopReplacementLayer = Extract<WindowLayer, "wallpaper" | "start-menu">
-
-export function isDesktopReplacementLayer(layer: WindowLayer | undefined): layer is DesktopReplacementLayer {
-
- return layer === "wallpaper" || layer === "start-menu"
-}
diff --git a/source/shared/window-layers.ts b/source/shared/window-layers.ts
new file mode 100644
index 0000000..6df66a3
--- /dev/null
+++ b/source/shared/window-layers.ts
@@ -0,0 +1,129 @@
+import type { WindowLayer, WindowTransaction } from "@phreshos/core"
+
+/** Window facts a Desktop presentation may understand for one layer role. */
+export type WindowPresentationProperty =
+ | "title"
+ | "header"
+ | "frame"
+ | "position"
+ | "size"
+ | "minimized"
+ | "maximized"
+ | "front"
+ | "layer"
+
+/**
+ * The System's explicit model for how authoritative Windows are presented.
+ *
+ * A Window retains every authoritative value. These capabilities govern only
+ * what the current Desktop presentation can apply, read, or emit.
+ */
+type WindowLayerPresentation = Readonly<{
+ /** Facts this presentation role can report. */
+ readable: readonly WindowPresentationProperty[]
+
+ /** Facts this presentation role can apply, follow, mutate, and emit. */
+ applicable: readonly WindowPresentationProperty[]
+ defaults: Readonly<{
+ frame: boolean
+ header: boolean
+ transaction: WindowTransaction
+ }>
+ fixed: boolean
+ exclusive: boolean
+ transactions: boolean
+}>
+
+export const windowLayerModel: Readonly<Record<WindowLayer, WindowLayerPresentation>> = Object.freeze({
+ window: Object.freeze({
+ readable: Object.freeze(["title", "header", "frame", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ applicable: Object.freeze(["title", "header", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ defaults: Object.freeze({ frame: true, header: true, transaction: false }),
+ fixed: false,
+ exclusive: false,
+ transactions: false
+ }),
+ under: Object.freeze({
+ readable: Object.freeze(["title", "frame", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ applicable: Object.freeze(["title", "frame", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ defaults: Object.freeze({ frame: false, header: false, transaction: false }),
+ fixed: false,
+ exclusive: false,
+ transactions: true
+ }),
+ over: Object.freeze({
+ readable: Object.freeze(["title", "frame", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ applicable: Object.freeze(["title", "frame", "position", "size", "minimized", "maximized", "front", "layer"] satisfies WindowPresentationProperty[]),
+ defaults: Object.freeze({ frame: false, header: false, transaction: false }),
+ fixed: false,
+ exclusive: false,
+ transactions: true
+ }),
+ wallpaper: Object.freeze({
+ readable: Object.freeze(["title", "layer"] satisfies WindowPresentationProperty[]),
+ applicable: Object.freeze(["title", "layer"] satisfies WindowPresentationProperty[]),
+ defaults: Object.freeze({ frame: false, header: false, transaction: false }),
+ fixed: true,
+ exclusive: true,
+ transactions: false
+ }),
+ "start-menu": Object.freeze({
+ readable: Object.freeze(["title", "layer"] satisfies WindowPresentationProperty[]),
+ applicable: Object.freeze(["title", "layer"] satisfies WindowPresentationProperty[]),
+ defaults: Object.freeze({ frame: false, header: false, transaction: false }),
+ fixed: true,
+ exclusive: true,
+ transactions: false
+ })
+})
+
+export function windowLayerDefaults(layer: WindowLayer) {
+ return windowLayerModel[layer].defaults
+}
+
+export function supportsWindowPresentationRead(layer: WindowLayer, property: WindowPresentationProperty) {
+ return windowLayerModel[layer].readable.includes(property)
+}
+
+export function supportsWindowPresentationApplication(layer: WindowLayer, property: WindowPresentationProperty) {
+ return windowLayerModel[layer].applicable.includes(property)
+}
+
+export function isWindowPresentationProperty(value: unknown): value is WindowPresentationProperty {
+ return presentationProperties.includes(value as WindowPresentationProperty)
+}
+
+export function requireWindowPresentationRead(layer: WindowLayer, property: WindowPresentationProperty) {
+ if (!supportsWindowPresentationRead(layer, property)) {
+ throw new Error(`The ${layer} layer has no ${property} presentation value`)
+ }
+}
+
+export function requireWindowPresentationApplication(layer: WindowLayer, property: WindowPresentationProperty) {
+ if (!supportsWindowPresentationApplication(layer, property)) {
+ throw new Error(`The ${layer} layer cannot apply ${property} presentation changes`)
+ }
+}
+
+export function supportsWindowPresentationTransactions(layer: WindowLayer) {
+ return windowLayerModel[layer].transactions
+}
+
+/** Window roles that own one fixed Desktop presentation at a time. */
+export type DesktopReplacementLayer = Extract<WindowLayer, "wallpaper" | "start-menu">
+
+export function isDesktopReplacementLayer(layer: WindowLayer | undefined): layer is DesktopReplacementLayer {
+ return layer !== undefined && windowLayerModel[layer].exclusive
+}
+
+export function isFixedWindowPresentationLayer(layer: WindowLayer) {
+ return windowLayerModel[layer].fixed
+}
+
+export function requireWindowPresentationTransactions(layer: WindowLayer) {
+ if (!supportsWindowPresentationTransactions(layer)) {
+ throw new Error(`The ${layer} layer does not support explicit presentation transactions`)
+ }
+}
+
+const presentationProperties = ["title", "header", "frame", "position", "size", "minimized", "maximized", "front", "layer"] as const satisfies readonly WindowPresentationProperty[]
diff --git a/tests/client-launch.test.ts b/tests/client-launch.test.ts
index 2086820..349cde3 100644
--- a/tests/client-launch.test.ts
+++ b/tests/client-launch.test.ts
@@ -14,7 +14,7 @@ test("client launch contract", async () => {
}
const program = {
- client: { header: false },
+ client: { header: false, title: "Declared client title" },
title: "Declared title"
}
@@ -25,10 +25,10 @@ test("client launch contract", async () => {
)
assert.equal(shape({ title: "Fetched title" }).title, "Fetched title")
- assert.equal(shape({}).title, "Declared title")
+ assert.equal(shape({}).title, "Declared client title")
assert.throws(() => shape({ title: 42 } as unknown as ClientLaunch), /title must be text/)
assert.equal(shape({ header: false }).header, false)
assert.equal(shape({}).header, false)
- assert.equal(shape({ layer: "over", header: false }).header, true)
+ assert.equal(shape({ layer: "over", header: false }).header, false)
assert.throws(() => shape({ header: "hidden" } as unknown as ClientLaunch), /header state/)
}, 120_000)
diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.ts
index 32431e0..a7be639 100644
--- a/tests/client-layer-permissions.test.ts
+++ b/tests/client-layer-permissions.test.ts
@@ -11,7 +11,7 @@ function fixture() {
const program: ProgramSnapshot = {
identity: "owner", reference: "program-reference", assetId: "assets", name: "Owner",
version: null, description: null, hasAgent: false, server: null,
- client: { start: true, service: false, title: null, header: null, size: null, position: null, layer: "over", minimize: null, maximize: null }
+ client: { start: true, service: false, title: null, header: null, frame: null, transaction: null, size: null, position: null, layer: "over", minimize: null, maximize: null }
}
const process = { identity: "caller", reference: "process-reference", program: program.identity, name: null, startedAt: 0, options: {}, server: null, client: null }
const createProcess = vi.fn(async () => process.identity)
diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.ts
index c5272de..9cc5941 100644
--- a/tests/client-process-boundary-lifecycle.test.ts
+++ b/tests/client-process-boundary-lifecycle.test.ts
@@ -3,7 +3,7 @@ import messagepack from "@the-link/messagepack"
import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"
import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import type ClientTraffic from "@client/view/components/desktop-host/client-traffic"
-import type { LocalWindowHost } from "@client/view/components/desktop-host/local-window"
+import type { WindowPresentationHost } from "@client/view/components/desktop-host/window-presentation"
import { test } from "vitest"
test("a Client question expectation survives initial iframe ownership", async () => {
@@ -29,7 +29,7 @@ test("a Client question expectation survives initial iframe ownership", async ()
authManager,
() => ({ size: { width: 800, height: 600 } }),
{} as ClientTraffic,
- { release() {} } as unknown as LocalWindowHost
+ { release() {} } as unknown as WindowPresentationHost
)
const question = "client:process:question"
diff --git a/tests/client-sandbox.test.ts b/tests/client-sandbox.test.ts
index 249a335..27ec8ed 100644
--- a/tests/client-sandbox.test.ts
+++ b/tests/client-sandbox.test.ts
@@ -22,21 +22,23 @@ test("client sandbox contract", async () => {
{} as HostTraffic,
- false
- )
+ false,
+
+ new Window(
- process.startClient(new Window(
+ { title: "Client", header: true, frame: true, transaction: false, layer: "window" },
- { title: "Client", header: true, layer: "window" },
+ { x: 0, y: 0 },
- { x: 0, y: 0 },
+ { width: 640, height: 480 },
- { width: 640, height: 480 },
+ 1,
- 1,
+ false
+ )
+ )
- false
- ), false)
+ process.startClient(false)
assert.equal(process.hosted().client?.sameOrigin, false)
diff --git a/tests/client-surface.test.ts b/tests/client-surface.test.ts
deleted file mode 100644
index afc2d57..0000000
--- a/tests/client-surface.test.ts
+++ /dev/null
@@ -1,357 +0,0 @@
-import assert from "node:assert/strict"
-import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"
-import ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"
-import { parseLocalWindowTransaction } from "@client/view/components/desktop-host/local-window"
-import host from "@client/view/components/desktop-host/host"
-import LocalWindows from "@client/view/components/window-manager/local-windows"
-import type { LocalWindowEntry } from "@client/view/components/window-manager/local-windows"
-import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"
-import type { LocalWindowState } from "@client/view/components/desktop-host/local-window"
-import type { AppearanceTransaction, WaitedTransaction, WindowLayer } from "@phreshos/core"
-import { test } from "vitest"
-
-test("client surface contract", async () => {
- type RequestedTransaction = AppearanceTransaction | WaitedTransaction
-
- const authoritativeWindow = new ServerWindow(
- { title: "Target", header: true, layer: "over" },
- { x: 0, y: 0 },
- { width: 100, height: 100 },
- 1,
- false
- )
-
- assert.equal("surface" in authoritativeWindow, false)
- assert.equal("surface" in authoritativeWindow.toJSON(), false)
-
- const transaction = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })
- const visibility = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })!
-
- assert.throws(() => parseLocalWindowTransaction({}), /must provide duration and easing/)
- assert.throws(() => parseLocalWindowTransaction({ wait: true }), /must provide duration and easing/)
- assert.throws(() => parseLocalWindowTransaction({ duration: 60_001, easing: "linear" }), /0 to 60000/)
- assert.throws(() => parseLocalWindowTransaction({ duration: 120 }), /must provide duration and easing/)
- assert.throws(() => parseLocalWindowTransaction({ duration: 120, easing: "linear", wait: false }), /must be true/)
- assert.equal(parseLocalWindowTransaction({ duration: 120, easing: "linear", extension: true })?.duration, 120)
-
- const ordinary = client("window")
- const bare = client("over")
- const clients = new Map([
- ["ordinary", { identity: "ordinary:0", client: ordinary }],
- ["bare", { identity: "bare:0", client: bare }]
- ]) as unknown as ReadonlyMap<string, LocalWindowEntry>
- const byProcess = new Map([["ordinary", ordinary], ["bare", bare]])
- const first = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)
- const second = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)
-
- await first.move("ordinary", { x: 40, y: 50 })
- await first.move("bare", { x: 60, y: 70 })
-
- assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })
- assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })
- assert.deepEqual(second.state("ordinary").position, { x: 0, y: 0 })
- assert.deepEqual(ordinary.window.position, { x: 0, y: 0 })
-
- // A representation reports the rectangle currently painted by the browser. Policy
- // such as fill/restore still needs the underlying projection, because a
- // relative full-surface value and its measured pixels are not equivalent.
- first.represent("ordinary", representation({ x: 0, y: 0, width: 1200, height: 800 }))
- assert.deepEqual(first.state("ordinary").size, { width: 1200, height: 800 })
- assert.deepEqual(first.projection("ordinary").size, { width: 300, height: 200 })
- first.represent("ordinary", null)
-
- let settleRepresentation: () => void = () => undefined
- let representationPublications = 0
- first.listen(() => { representationPublications++ })
- first.represent("ordinary", {
- ...representation({ x: 0, y: 0, width: 1200, height: 800 }),
- listen(settled) {
- settleRepresentation = settled
- return () => { settleRepresentation = () => undefined }
- }
- })
- const registrationPublication = representationPublications
- settleRepresentation()
- assert.equal(representationPublications, registrationPublication + 1)
- first.represent("ordinary", null)
-
- first.represent("bare", representation({ x: 65, y: 75, width: 290, height: 190 }))
- assert.deepEqual(first.state("bare").position, { x: 65, y: 75 })
- assert.deepEqual(first.state("bare").size, { width: 290, height: 190 })
- first.represent("bare", null)
-
- // An unrelated full snapshot is not a Window change and must not erase a
- // local ordinary-window command.
- first.reconcile(clients)
- assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })
-
- ordinary.window.position = { x: 15, y: 25 }
- bare.window.position = { x: 20, y: 30 }
- first.reconcile(clients)
-
- assert.deepEqual(first.state("ordinary").position, { x: 15, y: 25 })
- assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })
-
- const matchingAuthority = first.move("ordinary", { x: 30, y: 40 }, { duration: 120, easing: "ease-out", wait: true })
- const matchingRevision = represented(first, "ordinary:0").geometryAnimation!.revision
- ordinary.window.position = { x: 30, y: 40 }
- first.reconcile(clients)
- assert.equal(represented(first, "ordinary:0").geometryAnimation!.revision, matchingRevision)
- first.complete("ordinary", "geometry", matchingRevision)
- await matchingAuthority
-
- const waiting = first.geometry("bare", {
- position: { x: 80, y: 90 },
- size: { width: 320, height: 240 }
- }, transaction)
- const geometryRevision = represented(first, "bare:0").geometryAnimation!.revision
- first.complete("bare", "geometry", geometryRevision)
- await waiting
- assert.equal(represented(first, "bare:0").geometryAnimation, null)
-
- const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, easing: "ease-out", wait: true })
- await first.move("bare", { x: 120, y: 130 })
- await assert.rejects(interrupted, /interrupted/)
-
- const following = first.follow("bare", "ordinary", transaction)
- const followRevision = represented(first, "bare:0").geometryAnimation!.revision
- first.reconcile(clients)
- assert.equal(represented(first, "bare:0").geometryAnimation!.revision, followRevision)
- first.complete("bare", "geometry", followRevision)
- await following
- assert.deepEqual(first.state("bare").position, first.state("ordinary").position)
-
- // Following reads authority, never another Desktop-local representation.
- await first.move("ordinary", { x: 150, y: 160 })
- assert.deepEqual(first.state("bare").position, ordinary.window.position)
- ordinary.window.position = { x: 170, y: 180 }
- first.reconcile(clients)
- assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
-
- await first.unfollow("bare", transaction)
- assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
- ordinary.window.position = { x: 190, y: 200 }
- first.reconcile(clients)
- assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })
-
- // Default following can be disabled on ordinary windows and enabled on bare ones.
- await first.unfollow("ordinary")
- ordinary.window.position = { x: 210, y: 220 }
- first.reconcile(clients)
- assert.deepEqual(first.state("ordinary").position, { x: 190, y: 200 })
- await first.follow("ordinary", "ordinary")
- assert.deepEqual(first.state("ordinary").position, { x: 210, y: 220 })
- await first.follow("bare", "ordinary")
- await first.move("bare", { x: 125, y: 135 })
- ordinary.window.title = "Renamed"
- first.reconcile(clients)
- assert.equal(first.state("bare").title, "")
- assert.throws(() => first.title("bare", "Local title"), /does not allow local title/)
- assert.deepEqual(first.state("bare").position, { x: 125, y: 135 })
- ordinary.window.position = { x: 230, y: 240 }
- first.reconcile(clients)
- assert.deepEqual(first.state("bare").position, ordinary.window.position)
-
- // Stored geometry cannot cancel an in-progress maximize presentation.
- const maximizing = first.maximize("bare", true, transaction)
- const maximizeRevision = represented(first, "bare:0").geometryAnimation!.revision
- await first.move("bare", { x: 9, y: 10 }, transaction)
- assert.equal(represented(first, "bare:0").geometryAnimation!.revision, maximizeRevision)
- first.complete("bare", "geometry", maximizeRevision)
- await maximizing
- await first.maximize("bare", false)
- const toInterrupt = first.maximize("bare", true, transaction)
- await first.minimize("bare", true)
- await assert.rejects(toInterrupt, /was minimized/)
- await first.minimize("bare", false)
- await first.maximize("bare", false)
-
- // Minimize and maximize never overwrite the retained geometry or each other.
- await first.maximize("bare", true)
- await first.minimize("bare", true)
- await first.geometry("bare", { position: { x: 11, y: 12 }, size: { width: 111, height: 112 } }, transaction)
- assert.equal(first.projection("bare").geometryAnimation, null)
- assert.equal(first.state("bare").maximized, true)
- assert.equal(first.state("bare").minimized, true)
- await first.minimize("bare", false)
- assert.equal(first.state("bare").maximized, true)
- await first.maximize("bare", false)
- assert.deepEqual(first.state("bare").position, { x: 11, y: 12 })
- assert.deepEqual(first.state("bare").size, { width: 111, height: 112 })
- await first.follow("bare", "ordinary")
- ordinary.window.maximized = true
- ordinary.window.minimized = true
- first.reconcile(clients)
- assert.equal(first.state("bare").maximized, true)
- assert.equal(first.state("bare").minimized, true)
- ordinary.window.maximized = false
- ordinary.window.minimized = false
- first.reconcile(clients)
-
- const surfaceWaiting = first.addSurface("bare", visibility)
- const surfaceRevision = surface(first, "bare:0").transition!.revision
- first.complete("bare", "surface", surfaceRevision)
- await surfaceWaiting
- assert.equal(surface(first, "bare:0").transition, null)
- assert.equal(surface(first, "bare:0").visible, true)
-
- const surfaceRemoval = first.removeSurface("bare", visibility)
- const removalRevision = surface(first, "bare:0").transition!.revision
- assert.equal(surface(first, "bare:0").visible, false)
- first.complete("bare", "surface", removalRevision)
- await surfaceRemoval
- assert.equal(represented(first, "bare:0").surface, null)
-
- assert.equal(represented(second, "bare:0").surface, null)
-
- first.release("bare")
- assert.deepEqual(first.state("bare").position, bare.window.position)
- assert.equal(represented(first, "bare:0").surface, null)
-
- const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, easing: "ease-out", wait: true })
- const remaining = clients.get("ordinary")
- assert(remaining)
- first.reconcile(new Map([["ordinary", remaining]]))
- await assert.rejects(removed, /representation was removed/)
-
- const parent = {
- identity: "parent",
- reference: "parent-reference",
- name: "manager",
- program: "program",
- options: {},
- startedAt: new Date(),
- server: null,
- client: null
- }
- const requester = {
- identity: "requester",
- reference: "requester-reference",
- program: "program",
- parent,
- client: { window: { process: "requester", layer: "over" } }
- }
- const target = {
- identity: "target",
- reference: "target-reference",
- program: "program",
- client: { window: { process: "target", layer: "over", position: { x: 10, y: 20 } } }
- }
- const processes = new Map<string, object>([[parent.identity, parent], [requester.identity, requester], [target.identity, target]])
- const calls: unknown[][] = []
- const localWindow = {
- state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },
- move(identity: string, value: unknown, motion: RequestedTransaction | undefined) { calls.push(["move", identity, value, motion]) },
- follow(identity: string, followed: string, motion: RequestedTransaction | undefined) { calls.push(["follow", identity, followed, motion]) },
- unfollow(identity: string, motion: RequestedTransaction | undefined) { calls.push(["unfollow", identity, motion]) },
- addSurface(identity: string, motion: RequestedTransaction) { calls.push(["add", identity, motion]) },
- removeSurface(identity: string, motion: RequestedTransaction) { calls.push(["remove", identity, motion]) }
- }
- const processManager = {
- processes,
- front: ClientProcessManager.prototype.front,
- async ownFrame() {},
- async releaseFrame() {},
- async unsubscribeFrame() {}
- }
- const authManager = {
- processManager,
- programManager: { programs: new Map([["program", {
- reference: "program-reference",
- identity: "program",
- assetId: "00000000-0000-4000-8000-000000000000",
- installed: true,
- name: "Program",
- version: null,
- description: null,
- hasAgent: false,
- server: null,
- client: null
- }]]) },
- }
- const request = host(authManager as never, requester.identity, () => ({ size: { width: 1, height: 1 } }), () => "owner", localWindow as never)
-
- assert.deepEqual(await request("desktopViewport"), [{ size: { width: 1, height: 1 } }])
- const targetAddress = { identity: target.identity, reference: target.reference }
- const requesterAddress = { identity: requester.identity, reference: requester.reference }
- processes.delete(parent.identity)
- const parentAnswer = await request("parent", requesterAddress)
- assert(Array.isArray(parentAnswer))
- const retainedParent = parentAnswer[0] as { identity: string }
- assert.equal(retainedParent.identity, parent.identity)
- await request("windowLocalMove", requesterAddress, { x: 70, y: 80 })
- await request("windowLocalFollow", requesterAddress, targetAddress, visibility)
- await request("windowLocalUnfollow", requesterAddress, visibility)
- await request("windowLocalSurfaceAdd", requesterAddress, undefined, visibility)
- await request("windowLocalSurfaceRemove", requesterAddress, undefined, visibility)
-
- assert.deepEqual(calls, [
- ["move", "requester", { x: 70, y: 80 }, undefined],
- ["follow", "requester", "target", visibility],
- ["unfollow", "requester", visibility],
- ["add", "requester", visibility],
- ["remove", "requester", visibility]
- ])
- assert.deepEqual(target.client.window.position, { x: 10, y: 20 })
- await request("windowLocalSurfaceAdd", requesterAddress, undefined, { ...visibility, extension: true })
- await assert.rejects(request("windowLocalSurfaceAdd", targetAddress), /current Client Context/)
- await assert.rejects(request("windowLocalSurfaceAdd", { ...requesterAddress, reference: "wrong" }), /represented by this handle does not exist/)
- requester.client.window.layer = "window"
- await request("windowLocalMove", requesterAddress, { x: 0, y: 0 })
- await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress), /already owns its host Surface/)
- await assert.rejects(request("windowLocalSurfaceRemove", requesterAddress), /already owns its host Surface/)
- requester.client.window.layer = "over"
-
- const lifecycle: string[] = []
- const boundary = new ClientProcessBoundary(
- "requester",
- { contentWindow: null } as unknown as HTMLIFrameElement,
- authManager as never,
- () => ({ size: { width: 1, height: 1 } }),
- {} as never,
- { release(identity: string) { lifecycle.push(identity) } } as never
- )
-
- await boundary.own("first-owner")
- await boundary.own("second-owner")
- await boundary.release()
-
- assert.deepEqual(lifecycle, ["requester", "requester"])
-
- function client(layer: WindowLayer) {
- return {
- window: {
- title: "Window",
- header: true,
- position: { x: 0, y: 0 },
- size: { width: 300, height: 200 },
- minimized: false, maximized: false,
- layer,
- depth: 1
- }
- }
- }
-
- function represented(windows: LocalWindows, identity: string): LocalWindowState {
- const value = windows.windows.get(identity)
- assert(value)
- return value
- }
-
- function representation(geometry: { x: number, y: number, width: number, height: number }) {
- return {
- read: () => geometry,
- present(next: typeof geometry) { geometry = next },
- begin: () => geometry,
- finish() {},
- cancel() {},
- listen() { return () => undefined }
- }
- }
-
- function surface(windows: LocalWindows, identity: string) {
- const value = represented(windows, identity).surface
- assert(value)
- return value
- }
-}, 120_000)
diff --git a/tests/desktop-replacement-lifecycle.test.ts b/tests/desktop-replacement-lifecycle.test.ts
index 423dbd7..b5ad9c7 100644
--- a/tests/desktop-replacement-lifecycle.test.ts
+++ b/tests/desktop-replacement-lifecycle.test.ts
@@ -5,7 +5,7 @@ import type AuthManager from "@server/core/link-manager/auth-manager/auth-manage
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
import type { ServerRuntimeFactory } from "@server/core/server-runtime"
-import type { DesktopReplacementLayer } from "@shared/desktop-replacement"
+import type { DesktopReplacementLayer } from "@shared/window-layers"
const replacementLayers = ["wallpaper", "start-menu"] as const satisfies readonly DesktopReplacementLayer[]
@@ -15,7 +15,8 @@ function fixture(replacementLayer: DesktopReplacementLayer) {
const program = new Program({ identity: "replacement-test", client: { location: "https://example.test/" } })
vi.spyOn(program, "validate").mockResolvedValue()
const shape = (layer: Layer = replacementLayer) => ({
- title: "Replacement", header: true, position: { x: 20, y: 30 }, size: { width: 320, height: 240 },
+ title: "Replacement", header: layer === "window", frame: false, transaction: false,
+ position: { x: 20, y: 30 }, size: { width: 320, height: 240 },
layer, minimize: false, maximize: false
})
Object.assign(auth, {
@@ -26,7 +27,7 @@ function fixture(replacementLayer: DesktopReplacementLayer) {
})
const register = (identity: string, layer: Layer | null = replacementLayer, runtime: ServerRuntimeFactory<Program> | null = null) => manager.register(
identity, null, program, {}, { server: null, client: null, options: {} },
- runtime, layer !== null, layer === null ? null : shape(layer), null
+ runtime, layer !== null, shape(layer ?? replacementLayer), null
)
return { manager, register }
}
@@ -39,14 +40,14 @@ test.each(replacementLayers)("concurrent %s launches replace the incumbent Proce
expect(manager.processes.has("second")).toBe(true)
expect(manager.processes.size).toBe(1)
const incumbent = [...manager.processes.values()][0]!
- expect(incumbent.client?.window.layer).toBe(replacementLayer)
- incumbent.client!.window.minimized = true
+ expect(incumbent.clientEndpoint?.window.layer).toBe(replacementLayer)
+ incumbent.clientEndpoint!.window.minimized = true
await register("third")
expect(manager.processes.has(incumbent.identity)).toBe(false)
expect(incumbent.client).toBeNull()
await register("ordinary", "window")
await register("overlay", "over")
- expect((await register("replacement")).client?.window.layer).toBe(replacementLayer)
+ expect((await register("replacement")).clientEndpoint?.window.layer).toBe(replacementLayer)
expect(manager.processes.has("third")).toBe(false)
expect(manager.processes.has("ordinary")).toBe(true)
expect(manager.processes.has("overlay")).toBe(true)
@@ -73,12 +74,12 @@ test.each(replacementLayers)("starting an existing Client and creating a Process
manager.startClient("existing", { layer: replacementLayer }), register("new")
])
expect(results.filter(result => result.status === "fulfilled")).toHaveLength(2)
- expect([...manager.processes.values()].filter(process => process.client?.window.layer === replacementLayer)).toHaveLength(1)
+ expect([...manager.processes.values()].filter(process => process.client && process.clientEndpoint?.window.layer === replacementLayer)).toHaveLength(1)
expect(manager.processes.has("existing")).toBe(false)
const waiting = await register("waiting", null)
await manager.startClient("waiting", { layer: replacementLayer })
expect(manager.processes.has("new")).toBe(false)
- expect(waiting.client?.window.layer).toBe(replacementLayer)
+ expect(waiting.clientEndpoint?.window.layer).toBe(replacementLayer)
})
test.each(replacementLayers)("failed activation releases the %s claim", async replacementLayer => {
@@ -94,5 +95,5 @@ test.each(replacementLayers)("failed activation releases the %s claim", async re
expect(manager.processes.get("existing")!.client).toBeNull()
fail = false
await manager.startClient("existing", { layer: replacementLayer })
- expect(manager.processes.get("existing")!.client?.window.layer).toBe(replacementLayer)
+ expect(manager.processes.get("existing")!.clientEndpoint?.window.layer).toBe(replacementLayer)
})
diff --git a/tests/desktop-replacements.test.tsx b/tests/desktop-replacements.test.tsx
index 798068f..730d5b4 100644
--- a/tests/desktop-replacements.test.tsx
+++ b/tests/desktop-replacements.test.tsx
@@ -61,6 +61,7 @@ test("Desktop replaces its default wallpaper with the running Client and restore
identity: "wallpaper-process", program: "wallpaper-program",
client: { window: {
layer: "wallpaper", title: "Internal", position: { x: 200, y: 300 },
+ header: false, frame: false, transaction: false,
size: { width: 100, height: 100 }, minimized: true, maximized: false, depth: 20
} }
} as unknown as Process
@@ -71,7 +72,7 @@ test("Desktop replaces its default wallpaper with the running Client and restore
expect(running).not.toContain("data-default-wallpaper")
expect(fixture.fallback).not.toHaveBeenCalled()
expect(fixture.pane.mock.lastCall?.[0]).toMatchObject({
- bare: true, minimized: false, maximized: true, entering: false, localSurface: null,
+ layer: "wallpaper", frame: false, minimized: false, maximized: true, entering: false,
position: { x: 0, y: 0 }, size: { width: "100%", height: "100%" }, depth: 0
})
@@ -93,6 +94,7 @@ test("Desktop replaces the built-in Start Menu in its existing host and restores
identity: "start-menu-process", program: "start-menu-program",
client: { window: {
layer: "start-menu", title: "Internal", position: { x: 200, y: 300 },
+ header: false, frame: false, transaction: false,
size: { width: 100, height: 100 }, minimized: true, maximized: false, depth: 20
} }
} as unknown as Process
@@ -102,7 +104,7 @@ test("Desktop replaces the built-in Start Menu in its existing host and restores
expect(running).toContain('title="start-menu Client"')
expect(running).not.toContain("data-default-start-menu")
expect(fixture.pane.mock.lastCall?.[0]).toMatchObject({
- bare: true, minimized: false, maximized: true, entering: false, localSurface: null,
+ layer: "start-menu", frame: false, minimized: false, maximized: true, entering: false,
position: { x: 0, y: 0 }, size: { width: "100%", height: "100%" }, depth: 0
})
diff --git a/tests/local-window-layers.test.ts b/tests/local-window-layers.test.ts
deleted file mode 100644
index 9566d5c..0000000
--- a/tests/local-window-layers.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { expect, test } from "vitest"
-import type { WindowLayer } from "@phreshos/core"
-import LocalWindows, { type LocalWindowEntry } from "@client/view/components/window-manager/local-windows"
-
-function fixture(layer: WindowLayer) {
- const client = (layer: WindowLayer) => ({ window: {
- layer, title: "Original", header: true, position: { x: 20, y: 30 }, size: { width: 320, height: 240 },
- minimized: true, maximized: false, depth: 5
- } })
- const own = client(layer)
- const target = client("window")
- const entries = new Map([
- ["own", { identity: "own:0", client: own }],
- ["target", { identity: "target:0", client: target }]
- ]) as unknown as ReadonlyMap<string, LocalWindowEntry>
- const windows = new LocalWindows(entries, process => entries.get(process)?.client ?? null)
- return { own, target, entries, windows }
-}
-
-test.each(["wallpaper", "start-menu"] as const)("%s local geometry and visibility belong to Desktop, not authoritative state", async layer => {
- const { own, target, entries, windows } = fixture(layer)
- const initial = windows.projection("own")
- expect(initial).toMatchObject({ title: "", header: true, position: { x: 0, y: 0 }, size: { width: "100%", height: "100%" }, minimized: false, maximized: true, depth: 0, surface: null })
- const operations = [
- () => windows.move("own", { x: 1, y: 2 }),
- () => windows.resize("own", { width: 1, height: 2 }),
- () => windows.geometry("own", { position: { x: 1, y: 2 }, size: { width: 1, height: 2 } }),
- () => windows.minimize("own", true), () => windows.maximize("own", false),
- () => windows.title("own", "Local"), () => windows.header("own", false), () => windows.raise("own"),
- () => windows.addSurface("own"), () => windows.removeSurface("own")
- ]
- for (const operation of operations) expect(operation).toThrow(new RegExp(`${layer} layer does not allow`))
- own.window.position = { x: 500, y: 600 }
- windows.reconcile(entries)
- expect(windows.projection("own")).toEqual(initial)
- await windows.follow("own", "target", { duration: 100, easing: "linear", wait: true })
- target.window.title = "Changed"
- target.window.position = { x: 100, y: 200 }
- target.window.size = { width: 400, height: 500 }
- target.window.minimized = false
- target.window.maximized = true
- target.window.depth = 100
- windows.reconcile(entries)
- expect(windows.projection("own")).toEqual(initial)
- await windows.unfollow("own")
- expect(own.window.title).toBe("Original")
- expect(own.window.position).toEqual({ x: 500, y: 600 })
-})
-
-test.each(["under", "over"] as const)("%s follows allowed properties without copying standard header state", async layer => {
- const { own, target, entries, windows } = fixture(layer)
- expect(() => windows.title("own", "Local")).toThrow(/local title/)
- expect(() => windows.header("own", false)).toThrow(/local header/)
- await windows.follow("own", "target")
- target.window.title = "Changed"
- target.window.header = false
- target.window.position = { x: 100, y: 200 }
- windows.reconcile(entries)
- expect(windows.projection("own").title).toBe("")
- expect(windows.projection("own").header).toBe(true)
- expect(windows.projection("own").position).toEqual({ x: 100, y: 200 })
- expect(own.window.title).toBe("Original")
- await windows.unfollow("own")
- target.window.position = { x: 900, y: 900 }
- windows.reconcile(entries)
- expect(windows.projection("own").position).toEqual({ x: 100, y: 200 })
- // The receiving layer defines projection, even when the target is bare.
- await windows.follow("target", "own")
- expect(windows.projection("target").title).toBe("Original")
- windows.title("target", "Local title")
- windows.header("target", false)
- expect(windows.projection("target").title).toBe("Local title")
- expect(windows.projection("target").header).toBe(false)
-})
diff --git a/tests/panel.test.tsx b/tests/panel.test.tsx
index dd5d7f0..f01165d 100644
--- a/tests/panel.test.tsx
+++ b/tests/panel.test.tsx
@@ -38,7 +38,7 @@ test("panel contract", async () => {
assert.match(taskbar, /<h2 id="title"/)
assert.match(taskbar, /<button>Action<\/button>/)
- const window = markup(<Window icon="/icon.svg" title="Window"><iframe title="Content" /></Window>)
+ const window = markup(<Window layer="window" icon="/icon.svg" title="Window"><iframe title="Content" /></Window>)
assert.equal(window.match(/data-material=""/g)?.length, 1)
assert.match(window, /grid-template-rows:auto minmax\(0, 1fr\)/)
assert.match(window, /data-window-content="true"/)
@@ -48,7 +48,7 @@ test("panel contract", async () => {
assert.match(window, /<iframe title="Content"/)
assert.doesNotMatch(window, /class="p-px"/)
- const bare = markup(<Window bare icon="/icon.svg" title="Bare"><iframe title="Content" /></Window>)
+ const bare = markup(<Window layer="over" icon="/icon.svg" title="Bare"><iframe title="Content" /></Window>)
assert.doesNotMatch(bare, /data-material/)
assert.doesNotMatch(bare, /grid-template-rows:auto minmax\(0, 1fr\)/)
diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.ts
index 55e7e7d..2ba332f 100644
--- a/tests/permission-requests.test.ts
+++ b/tests/permission-requests.test.ts
@@ -22,8 +22,9 @@ test("permission requests contract", async () => {
let whilePending: (() => void) | undefined
let accessUpdates = 0
- const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false)
- process.startClient(new Window({ title: "Client", header: true, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false), false)
+ const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false,
+ new Window({ title: "Client", header: true, frame: true, transaction: false, layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false))
+ process.startClient(false)
const authManager = {
dialogManager: {
diff --git a/tests/process-lifecycle.test.ts b/tests/process-lifecycle.test.ts
index ae61854..f6d0ad6 100644
--- a/tests/process-lifecycle.test.ts
+++ b/tests/process-lifecycle.test.ts
@@ -6,6 +6,7 @@ import ProcessManager from "@server/core/link-manager/auth-manager/process-manag
import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"
import type { ServerRuntime } from "@server/core/server-runtime"
+import type { ClientLaunch } from "@phreshos/core"
import { test } from "vitest"
test("process lifecycle contract", async () => {
@@ -21,18 +22,20 @@ test("process lifecycle contract", async () => {
permission() { return null },
grantsPermission() { return true },
grantsStorage() { return true },
- clientShape(_program: Program, launch: { service?: boolean, title?: string } = {}) {
+ clientShape(_program: Program, launch: ClientLaunch = {}) {
if (launch.service !== undefined && typeof launch.service !== "boolean") throw new Error("A launch client's service role must be true or false")
return {
title: launch.title ?? "Client",
- header: true,
- position: { x: 0, y: 0 },
- size: { width: 640, height: 480 },
- layer: "window" as const,
- minimize: false,
- maximize: false
+ header: launch.header ?? true,
+ frame: launch.frame ?? true,
+ transaction: launch.transaction ?? false,
+ position: launch.position ?? { x: 0, y: 0 },
+ size: launch.size ?? { width: 640, height: 480 },
+ layer: launch.layer ?? "window",
+ minimize: launch.minimize ?? false,
+ maximize: launch.maximize ?? false
}
}
},
@@ -59,6 +62,76 @@ test("process lifecycle contract", async () => {
return manager
}
+ // Window state belongs permanently to the Client Endpoint, not to one of
+ // its execution contexts. Stopping the Client preserves the Window; omitted
+ // restart values preserve it, while explicit launch values replace only
+ // themselves.
+ {
+ const manager = processManager()
+ const owner = new Program({
+ identity: "retained-window",
+ server: { location: ".", command: "true" },
+ client: { location: "https://example.test/" }
+ })
+ const initial = {
+ title: "Initial",
+ header: true,
+ frame: true,
+ transaction: false,
+ position: { x: 12, y: 24 },
+ size: { width: 640, height: 480 },
+ layer: "window" as const,
+ minimize: false,
+ maximize: false
+ }
+ const process = await manager.register(
+ "retained-window",
+ null,
+ owner,
+ {},
+ launch,
+ null,
+ true,
+ initial,
+ null,
+ { window: initial }
+ )
+
+ process.server = {} as ServerProcessBoundary
+ await manager.stopClient(process.identity)
+
+ assert.equal(process.client, null)
+ assert.ok(process.clientEndpoint)
+
+ await manager.move(process.identity, { x: 80, y: 90 })
+ await manager.changeHeader(process.identity, false)
+ await manager.changeFrame(process.identity, { radius: "full", color: "primary" })
+
+ await manager.startClient(process.identity)
+
+ assert.deepEqual(process.clientEndpoint.window.position, { x: 80, y: 90 })
+ assert.equal(process.clientEndpoint.window.header, false)
+ assert.deepEqual(process.clientEndpoint.window.frame, { radius: "full", color: "primary" })
+
+ await manager.stopClient(process.identity)
+ await manager.startClient(process.identity, { layer: "over", title: "Overlay" })
+
+ assert.equal(process.clientEndpoint.window.layer, "over")
+ assert.equal(process.clientEndpoint.window.title, "Overlay")
+ assert.deepEqual(process.clientEndpoint.window.position, { x: 80, y: 90 })
+ assert.equal(process.clientEndpoint.window.header, false)
+
+ await manager.stopClient(process.identity)
+ await manager.changeHeader(process.identity, true)
+ await manager.move(process.identity, { x: 140, y: 150 })
+ await manager.startClient(process.identity, { layer: "window" })
+
+ assert.equal(process.clientEndpoint.window.layer, "window")
+ assert.equal(process.clientEndpoint.window.header, true)
+ assert.deepEqual(process.clientEndpoint.window.position, { x: 140, y: 150 })
+ assert.deepEqual(process.clientEndpoint.window.frame, { radius: "full", color: "primary" })
+ }
+
function program(identity: string) {
return new Program({ identity, server: { location: ".", command: "true" } })
@@ -69,7 +142,7 @@ test("process lifecycle contract", async () => {
return await manager.register(identity, null, program(identity), {}, launch, null, false, null, null)
}
- // Endpoint start and stop establish incarnation state. Repeating the same
+ // Endpoint start and stop establish execution-context state. Repeating the same
// request on a valid permanent handle is a silent success; removing the
// owning Process still invalidates that handle.
{
@@ -92,6 +165,8 @@ test("process lifecycle contract", async () => {
{
title: "Client",
header: true,
+ frame: true,
+ transaction: false,
position: { x: 0, y: 0 },
size: { width: 640, height: 480 },
layer: "window",
@@ -185,10 +260,10 @@ test("process lifecycle contract", async () => {
null,
client,
{},
- { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", minimize: false, maximize: false, service: false } },
+ { ...launch, client: { title: "Partial", header: true, frame: true, transaction: false, position: null, size: null, layer: "window", minimize: false, maximize: false, service: false } },
null,
true,
- { title: "Partial", header: true, position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false, maximize: false },
+ { title: "Partial", header: true, frame: true, transaction: false, position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false, maximize: false },
null
), /creation publication failed/)
diff --git a/tests/window-geometry.test.ts b/tests/window-geometry.test.ts
index 635c7d6..1bb094c 100644
--- a/tests/window-geometry.test.ts
+++ b/tests/window-geometry.test.ts
@@ -12,7 +12,7 @@ test("window geometry contract", async () => {
}
const authority = new ServerWindow(
- { title: "Geometry", header: true, layer: "window" },
+ { title: "Geometry", header: true, frame: true, transaction: false, layer: "window" },
initial.position,
initial.size,
1,
diff --git a/tests/window-presentation-layers.test.ts b/tests/window-presentation-layers.test.ts
new file mode 100644
index 0000000..32319d9
--- /dev/null
+++ b/tests/window-presentation-layers.test.ts
@@ -0,0 +1,98 @@
+import { expect, test } from "vitest"
+import type { WindowLayer } from "@phreshos/core"
+import WindowPresentations, { type WindowPresentationEntry } from "@client/view/components/window-manager/window-presentations"
+
+function fixture(layer: WindowLayer) {
+ const client = (selected: WindowLayer) => ({ window: {
+ layer: selected,
+ title: "Original",
+ header: selected === "window",
+ frame: selected === "window",
+ transaction: false,
+ position: { x: 20, y: 30 },
+ size: { width: 320, height: 240 },
+ minimized: true,
+ maximized: false,
+ depth: 5
+ } })
+ const own = client(layer)
+ const entries = new Map([
+ ["own", { identity: "own:0", client: own }]
+ ]) as unknown as ReadonlyMap<string, WindowPresentationEntry>
+ const presentations = new WindowPresentations(entries, process => entries.get(process)?.client ?? null)
+ return { own, entries, presentations }
+}
+
+test.each(["wallpaper", "start-menu"] as const)("%s exposes only concepts understood by its presentation", async layer => {
+ const { own, entries, presentations } = fixture(layer)
+
+ expect(presentations.read("own", "title")).toBe("Original")
+ expect(presentations.read("own", "layer")).toBe(layer)
+ for (const property of ["position", "size", "minimized", "maximized", "header", "frame", "front"] as const) {
+ expect(() => presentations.read("own", property)).toThrow(new RegExp(`${layer} layer has no`))
+ }
+
+ const unsupported = [
+ () => presentations.move("own", { x: 1, y: 2 }),
+ () => presentations.resize("own", { width: 1, height: 2 }),
+ () => presentations.geometry("own", { position: { x: 1, y: 2 }, size: { width: 1, height: 2 } }),
+ () => presentations.minimize("own", true),
+ () => presentations.maximize("own", false),
+ () => presentations.header("own", false),
+ () => presentations.frame("own", true),
+ () => presentations.raise("own")
+ ]
+ for (const operation of unsupported) expect(operation).toThrow(new RegExp(`${layer} layer cannot apply`))
+
+ own.window.position = { x: 500, y: 600 }
+ own.window.title = "Changed"
+ presentations.reconcile(entries)
+ expect(presentations.projection("own").position).toEqual({ x: 0, y: 0 })
+ expect(presentations.projection("own").title).toBe("Original")
+
+ await presentations.follow("own")
+ expect(presentations.projection("own").title).toBe("Changed")
+ expect(presentations.projection("own").position).toEqual({ x: 0, y: 0 })
+})
+
+test.each(["under", "over"] as const)("%s presents geometry and frame without a header", async layer => {
+ const { own, entries, presentations } = fixture(layer)
+
+ expect(() => presentations.read("own", "header")).toThrow(new RegExp(`${layer} layer has no header`))
+ expect(() => presentations.header("own", false)).toThrow(new RegExp(`${layer} layer cannot apply header`))
+
+ await presentations.frame("own", { color: "primary", radius: "full" })
+ expect(presentations.read("own", "frame")).toEqual({ color: "primary", radius: "full" })
+
+ await presentations.follow("own")
+ own.window.position = { x: 100, y: 200 }
+ own.window.frame = true
+ presentations.reconcile(entries)
+ expect(presentations.projection("own").position).toEqual({ x: 100, y: 200 })
+ expect(presentations.projection("own").frame).toBe(true)
+
+ await presentations.unfollow("own")
+ own.window.position = { x: 900, y: 900 }
+ presentations.reconcile(entries)
+ expect(presentations.projection("own").position).toEqual({ x: 100, y: 200 })
+})
+
+test("a standard presentation reports its permanent frame without allowing frame changes", async () => {
+ const { presentations } = fixture("window")
+
+ expect(presentations.read("own", "frame")).toBe(true)
+ expect(() => presentations.frame("own", false)).toThrow(/window layer cannot apply frame/)
+})
+
+test("unsupported presentation events remain silent", () => {
+ const { own, entries, presentations } = fixture("wallpaper")
+ const received: string[] = []
+ presentations.observe("own", null, event => received.push(event))
+
+ own.window.position = { x: 500, y: 600 }
+ own.window.title = "Changed"
+ presentations.follow("own")
+ presentations.reconcile(entries)
+
+ expect(received).toEqual(["changeTitle"])
+})
diff --git a/tests/window-presentation.test.ts b/tests/window-presentation.test.ts
new file mode 100644
index 0000000..cd6c8f7
--- /dev/null
+++ b/tests/window-presentation.test.ts
@@ -0,0 +1,148 @@
+import assert from "node:assert/strict"
+import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"
+import { presentationTransaction } from "@client/view/components/desktop-host/window-presentation"
+import WindowPresentations, { type WindowPresentationEntry } from "@client/view/components/window-manager/window-presentations"
+import { requireWindowPresentationTransactions } from "@shared/window-layers"
+import type { WindowLayer } from "@phreshos/core"
+import { test } from "vitest"
+
+test("Window presentation transactions remain independent from Appearance limits", () => {
+ assert.deepEqual(presentationTransaction(true, false), { transaction: true, wait: false })
+ assert.deepEqual(presentationTransaction(false, true), { transaction: false, wait: true })
+ assert.deepEqual(presentationTransaction(120_000, true), { transaction: 120_000, wait: true })
+ assert.deepEqual(presentationTransaction({ duration: 120_000, easing: "ease-out" }, false), {
+ transaction: { duration: 120_000, easing: "ease-out" }, wait: false
+ })
+ assert.throws(() => presentationTransaction(-1, false), /non-negative/)
+ assert.throws(() => presentationTransaction(true, "yes"), /true or false/)
+ assert.doesNotThrow(() => requireWindowPresentationTransactions("under"))
+ assert.doesNotThrow(() => requireWindowPresentationTransactions("over"))
+ assert.throws(() => requireWindowPresentationTransactions("window"), /does not support/)
+ assert.throws(() => requireWindowPresentationTransactions("wallpaper"), /does not support/)
+})
+
+test("each Desktop owns an independent Window presentation", async () => {
+ const ordinary = client("window")
+ const overlay = client("over")
+ const entries = new Map([
+ ["ordinary", { identity: "ordinary:0", client: ordinary }],
+ ["overlay", { identity: "overlay:0", client: overlay }]
+ ]) as unknown as ReadonlyMap<string, WindowPresentationEntry>
+ const byProcess = new Map([["ordinary", ordinary], ["overlay", overlay]])
+ const first = new WindowPresentations(entries, identity => byProcess.get(identity) as never ?? null)
+ const second = new WindowPresentations(entries, identity => byProcess.get(identity) as never ?? null)
+
+ await first.move("ordinary", { x: 40, y: 50 })
+ await first.move("overlay", { x: 60, y: 70 })
+
+ assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })
+ assert.deepEqual(first.state("overlay").position, { x: 60, y: 70 })
+ assert.deepEqual(second.state("ordinary").position, { x: 0, y: 0 })
+ assert.deepEqual(ordinary.window.position, { x: 0, y: 0 })
+
+ ordinary.window.position = { x: 15, y: 25 }
+ overlay.window.position = { x: 20, y: 30 }
+ first.reconcile(entries)
+
+ assert.deepEqual(first.state("ordinary").position, { x: 15, y: 25 })
+ assert.deepEqual(first.state("overlay").position, { x: 60, y: 70 })
+
+ await first.follow("overlay")
+ assert.deepEqual(first.state("overlay").position, { x: 20, y: 30 })
+ overlay.window.position = { x: 80, y: 90 }
+ first.reconcile(entries)
+ assert.deepEqual(first.state("overlay").position, { x: 80, y: 90 })
+
+ await first.unfollow("overlay")
+ overlay.window.position = { x: 100, y: 110 }
+ first.reconcile(entries)
+ assert.deepEqual(first.state("overlay").position, { x: 80, y: 90 })
+})
+
+test("transactionAndWait semantics resolve on completion and reject on interruption", async () => {
+ const overlay = client("over")
+ const entries = new Map([
+ ["overlay", { identity: "overlay:0", client: overlay }]
+ ]) as unknown as ReadonlyMap<string, WindowPresentationEntry>
+ const presentations = new WindowPresentations(entries, () => overlay as never)
+ const request = { transaction: { duration: 200, easing: "ease-out" } as const, wait: true }
+
+ const moving = presentations.move("overlay", { x: 30, y: 40 }, request)
+ const revision = presentations.projection("overlay").geometryAnimation?.revision
+ assert.equal(typeof revision, "number")
+ presentations.complete("overlay", "geometry", revision!)
+ await moving
+
+ const interrupted = presentations.move("overlay", { x: 50, y: 60 }, request)
+ await presentations.move("overlay", { x: 70, y: 80 })
+ await assert.rejects(interrupted, /interrupted/)
+
+ const changingFrame = presentations.frame("overlay", { color: "primary", radius: "full" }, request)
+ const frameRevision = presentations.projection("overlay").frameAnimation?.revision
+ presentations.complete("overlay", "frame", frameRevision!)
+ await changingFrame
+ assert.deepEqual(presentations.state("overlay").frame, { color: "primary", radius: "full" })
+})
+
+test("presentation geometry events expose each applied representation change", () => {
+ const ordinary = client("window")
+ const entries = new Map([
+ ["ordinary", { identity: "ordinary:0", client: ordinary }]
+ ]) as unknown as ReadonlyMap<string, WindowPresentationEntry>
+ const presentations = new WindowPresentations(entries, () => ordinary as never)
+ const moves: unknown[] = []
+ let changed: () => void = () => undefined
+ let geometry = { x: 0, y: 0, width: 300, height: 200 }
+
+ presentations.observe("ordinary", "move", (_event, value) => moves.push(value))
+ presentations.represent("ordinary", {
+ read: () => geometry,
+ present: value => { geometry = value },
+ begin: () => geometry,
+ finish() {},
+ cancel() {},
+ listen: listener => { changed = listener; return () => undefined }
+ })
+
+ geometry = { ...geometry, x: 10 }
+ changed()
+ geometry = { ...geometry, x: 20 }
+ changed()
+
+ assert.deepEqual(moves, [{ x: 10, y: 0 }, { x: 20, y: 0 }])
+})
+
+test("a Client boundary releases its presentation lease exactly once per document", async () => {
+ const lifecycle: string[] = []
+ const boundary = new ClientProcessBoundary(
+ "requester",
+ { contentWindow: null } as unknown as HTMLIFrameElement,
+ { processManager: { async ownFrame() {}, async releaseFrame() {} } } as never,
+ () => ({ size: { width: 1, height: 1 } }),
+ {} as never,
+ { release(identity: string) { lifecycle.push(identity) } } as never
+ )
+
+ await boundary.own("first-owner")
+ await boundary.own("second-owner")
+ await boundary.release()
+
+ assert.deepEqual(lifecycle, ["requester", "requester"])
+})
+
+function client(layer: WindowLayer) {
+ return {
+ window: {
+ title: "Window",
+ header: layer === "window",
+ frame: layer === "window",
+ transaction: false,
+ position: { x: 0, y: 0 },
+ size: { width: 300, height: 200 },
+ minimized: false,
+ maximized: false,
+ layer,
+ depth: 1
+ }
+ }
+}