Skip to content

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

Separate local Window representation from authority

zohayrslileh159d08f54781
diff --git a/scripts/verify-client-surface.mjs b/scripts/verify-client-surface.mjs
index a97cc73..4c651ee 100644
--- a/scripts/verify-client-surface.mjs
+++ b/scripts/verify-client-surface.mjs
@@ -1,7 +1,8 @@
import assert from "node:assert/strict"
import ClientProcessBoundary from "../source/client/view/desktop/client-host/client-process-boundary.ts"
-import { clientSurfaceSettings, removeClientSurface, setClientSurface } from "../source/client/view/desktop/client-host/client-surface.ts"
+import { surfaceSettings, visualTransaction } from "../source/client/view/desktop/client-host/local-window.ts"
import host from "../source/client/view/desktop/client-host/host.ts"
+import LocalWindows from "../source/client/view/desktop/window-manager/local-windows.ts"
import ServerWindow from "../source/server/core/link-manager/auth-manager/process-manager/window.ts"
const authoritativeWindow = new ServerWindow(
@@ -15,26 +16,88 @@ const authoritativeWindow = new ServerWindow(
assert.equal("surface" in authoritativeWindow, false)
assert.equal("surface" in authoritativeWindow.toJSON(), false)
-const settings = clientSurfaceSettings({ opacity: 0.5, radius: "large", transaction: { duration: 240, easing: "ease-out" } })
-
-let firstDesktop = new Map()
-let secondDesktop = new Map()
-
-firstDesktop = setClientSurface(firstDesktop, "target", settings)
-
-assert.equal(firstDesktop.get("target")?.revision, 1)
-assert.equal(secondDesktop.has("target"), false)
-assert.equal(setClientSurface(firstDesktop, "target", settings), firstDesktop)
-
-firstDesktop = removeClientSurface(firstDesktop, "target")
-
-assert.equal(firstDesktop.has("target"), false)
-assert.equal(removeClientSurface(firstDesktop, "target"), firstDesktop)
-
-assert.throws(() => clientSurfaceSettings({ opacity: 2 }), /from 0 to 1/)
-assert.throws(() => clientSurfaceSettings({ radius: -1 }), /ScaleLevel/)
-assert.throws(() => clientSurfaceSettings({ transaction: { duration: 60_001 } }), /0 to 60000/)
-assert.throws(() => clientSurfaceSettings({ unknown: true }), /no "unknown" field/)
+const settings = surfaceSettings({ opacity: 0.5, radius: "large" })
+const transaction = visualTransaction({ duration: 240, easing: "ease-out", wait: true })
+
+assert.throws(() => surfaceSettings({ opacity: 2 }), /from 0 to 1/)
+assert.throws(() => surfaceSettings({ radius: -1 }), /ScaleLevel/)
+assert.throws(() => visualTransaction({}), /must provide duration or easing/)
+assert.throws(() => visualTransaction({ wait: true }), /must provide duration or easing/)
+assert.throws(() => visualTransaction({ duration: 60_001 }), /0 to 60000/)
+assert.throws(() => surfaceSettings({ unknown: true }), /no "unknown" field/)
+
+const ordinary = client("window")
+const bare = client("over")
+const clients = new Map([
+ ["ordinary", { identity: "ordinary:0", client: ordinary }],
+ ["bare", { identity: "bare:0", client: bare }]
+])
+const byProcess = new Map([["ordinary", ordinary], ["bare", bare]])
+const first = new LocalWindows(clients, identity => byProcess.get(identity) ?? null)
+const second = new LocalWindows(clients, identity => byProcess.get(identity) ?? 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 })
+
+first.represent("bare", () => ({ position: { x: 65, y: 75 }, size: { 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, wait: true })
+const matchingRevision = first.windows.get("ordinary:0").geometryAnimation.revision
+ordinary.window.position = { x: 30, y: 40 }
+first.reconcile(clients)
+assert.equal(first.windows.get("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 = first.windows.get("bare:0").geometryAnimation.revision
+first.complete("bare", "geometry", geometryRevision)
+await waiting
+assert.equal(first.windows.get("bare:0").geometryAnimation, null)
+
+const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, wait: true })
+await first.move("bare", { x: 120, y: 130 })
+await assert.rejects(interrupted, /interrupted/)
+
+const surfaceWaiting = first.setSurface("bare", settings, transaction)
+const surfaceRevision = first.windows.get("bare:0").surface.animation.revision
+first.complete("bare", "surface", surfaceRevision)
+await surfaceWaiting
+assert.equal(first.windows.get("bare:0").surface.animation, null)
+
+assert.throws(() => first.setSurface("ordinary", settings), /window-layer/)
+assert.equal(second.windows.get("bare:0").surface, null)
+
+first.release("bare")
+assert.deepEqual(first.state("bare").position, bare.window.position)
+assert.equal(first.windows.get("bare:0").surface, null)
+
+const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, wait: true })
+first.reconcile(new Map([["ordinary", clients.get("ordinary")]]))
+await assert.rejects(removed, /representation was removed/)
const requester = {
identity: "requester",
@@ -42,46 +105,33 @@ const requester = {
program: "program",
client: { window: { process: "requester", layer: "over" } }
}
-
-const target = {
- identity: "target",
- reference: "target-reference",
- program: "program",
- client: { window: { process: "target", layer: "under" } }
-}
-
-const processes = new Map([[requester.identity, requester], [target.identity, target]])
+const processes = new Map([[requester.identity, requester]])
const calls = []
-const surface = {
- set(identity, value) { calls.push(["set", identity, value]) },
- remove(identity) { calls.push(["remove", identity]) }
+const localWindow = {
+ setSurface(identity, value, motion) { calls.push(["set", identity, value, motion]) },
+ removeSurface(identity) { calls.push(["remove", identity]) }
}
-
const authManager = {
processManager: { processes },
programManager: { programs: new Map() }
}
+const request = host(authManager, requester.identity, () => ({ width: 1, height: 1 }), () => "owner", {}, localWindow)
-const request = host(authManager, requester.identity, () => ({ width: 1, height: 1 }), () => "owner", {}, surface)
-
-await request("surfaceSet", { identity: target.identity, reference: target.reference }, settings)
-await request("surfaceRemove", { identity: target.identity, reference: target.reference })
+await request("localWindowSurfaceSet", settings, transaction)
+await request("localWindowSurfaceRemove")
-assert.deepEqual(calls, [["set", "target", settings], ["remove", "target"]])
-
-target.client.window.layer = "window"
-
-await assert.rejects(request("surfaceSet", { identity: target.identity, reference: target.reference }, {}), /window-layer/)
+assert.deepEqual(calls, [["set", "requester", settings, transaction], ["remove", "requester"]])
+await assert.rejects(request("localWindowSurfaceSet", { identity: "target" }), /no "identity" field/)
const lifecycle = []
const boundary = new ClientProcessBoundary(
- "target",
+ "requester",
{ contentWindow: null },
authManager,
() => ({ width: 1, height: 1 }),
{},
{},
- { set() {}, remove(identity) { lifecycle.push(identity) } }
+ { release(identity) { lifecycle.push(identity) } }
)
boundary.receive(["boundary", "document", "first-document"])
@@ -89,4 +139,18 @@ boundary.receive(["boundary", "document", "first-document"])
boundary.receive(["boundary", "document", "second-document"])
await boundary.release()
-assert.deepEqual(lifecycle, ["target", "target"])
+assert.deepEqual(lifecycle, ["requester", "requester"])
+
+function client(layer) {
+ return {
+ window: {
+ title: "Window",
+ position: { x: 0, y: 0 },
+ size: { width: 300, height: 200 },
+ minimized: false,
+ layer,
+ location: "/",
+ depth: 1
+ }
+ }
+}
diff --git a/scripts/verify-window-geometry.mjs b/scripts/verify-window-geometry.mjs
index da12cae..29c8d02 100644
--- a/scripts/verify-window-geometry.mjs
+++ b/scripts/verify-window-geometry.mjs
@@ -63,14 +63,5 @@ const counterpart = new ClientWindow(
"process",
authority.toJSON()
)
-const draft = {
- position: { x: 5, y: 6 },
- size: { width: 700, height: 500 }
-}
-
-counterpart.localSetGeometry(draft)
-assert.deepEqual(counterpart.position, draft.position)
-assert.deepEqual(counterpart.size, draft.size)
-
await counterpart.setGeometry(next)
assert.deepEqual(publications, [["/geometry", "process", next]])
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 498deef..f61c82b 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 TransmittedWindow, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
-import { isRelativeValue, type WindowGeometry, type WindowLayer } from "@phreshos/core"
+import { type WindowGeometry, type WindowLayer } from "@phreshos/core"
import ProcessManager from "./process-manager"
/**
@@ -84,43 +84,6 @@ export default class Window {
}
- // A local geometry change is a draft held by this desktop. It redraws
- // through ProcessManager but says nothing through `$outbound`; the normal
- // move and resize methods remain the only roads to the authoritative host.
- public localMove(position: Position) {
-
- validate(position.x, "x")
-
- validate(position.y, "y")
-
- this.position = position
- }
-
- public localResize(size: Size) {
-
- validate(size.width, "width")
-
- validate(size.height, "height")
-
- this.size = size
- }
-
- /** Applies a complete desktop-local draft in one notification cycle. */
- public localSetGeometry(geometry: WindowGeometry) {
-
- validate(geometry.position.x, "x")
-
- validate(geometry.position.y, "y")
-
- validate(geometry.size.width, "width")
-
- validate(geometry.size.height, "height")
-
- this.position = geometry.position
-
- this.size = geometry.size
- }
-
public async move(position: Position) {
await this.processManager.$outbound.publish("/move", this.process, position)
@@ -155,11 +118,4 @@ export default class Window {
}
}
-function validate(value: number | string, name: string) {
-
- if (isRelativeValue(value)) return
-
- throw new Error(`${name} must be a finite pixel number or a relative expression such as "50% + 10"`)
-}
-
export type { Position, Size }
diff --git a/source/client/view/desktop/client-host/client-host.ts b/source/client/view/desktop/client-host/client-host.ts
index f3a84a8..b8aa8f4 100644
--- a/source/client/view/desktop/client-host/client-host.ts
+++ b/source/client/view/desktop/client-host/client-host.ts
@@ -5,17 +5,17 @@ import { type Space } from "./host"
import DesktopPointer from "./pointer"
import ClientProcessBoundary from "./client-process-boundary"
import ClientTraffic from "./client-traffic"
-import { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
+import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
import { AuthManagerContext } from "../../contexts"
import { isPermissionName } from "@phreshos/core"
-import { removeClientSurface, setClientSurface, type ClientSurfaceHost, type ClientSurfaceState } from "./client-surface"
+import { type LocalWindowHost } from "./local-window"
/**
* The browser boundary between a program pane and the desktop that hosts it.
* It owns frame messages and the measured surfaces those frames inhabit;
* neither fact participates in rendering.
*/
-export default function useClientHost(desktop: RefObject<HTMLDivElement | null>, sources: Map<string, HTMLIFrameElement | null>) {
+export default function useClientHost(desktop: RefObject<HTMLDivElement | null>, sources: Map<string, HTMLIFrameElement | null>, localWindow: LocalWindowHost) {
const authManager = AuthManagerContext.useValue()
@@ -33,22 +33,6 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
const [windowSurfaceSize, setWindowSurfaceSize] = useState<SurfaceSize>({ width: 0, height: 0 })
- const [clientSurfaces, setClientSurfaces] = useState<ReadonlyMap<string, ClientSurfaceState>>(() => new Map())
-
- const clientSurface = useMemo<ClientSurfaceHost>(() => ({
-
- set(identity, settings) {
-
- setClientSurfaces(current => setClientSurface(current, identity, settings))
- },
-
- remove(identity) {
-
- setClientSurfaces(current => removeClientSurface(current, identity))
- }
-
- }), [])
-
// Read by the gate at the moment a pane asks, so the answer is
// never a render behind.
const latest = useRef<Record<WindowLayer, Space>>({
@@ -240,7 +224,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
boundaries.current.get(identity)?.release().catch(() => undefined)
- boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, layer => latest.current[layer], pointer, traffic, clientSurface))
+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, layer => latest.current[layer], pointer, traffic, localWindow))
return
}
@@ -255,7 +239,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
boundary?.release().catch(() => undefined)
- }, [authManager, clientSurface, pointer, sources, traffic])
+ }, [authManager, localWindow, pointer, sources, traffic])
const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {
@@ -326,7 +310,7 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
}, [authManager, pointer, sources])
- return { windowSurfaceRef, windowSurfaceSize, clientSurfaces, frame, frameLoaded }
+ return { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded }
}
export interface SurfaceSize {
diff --git a/source/client/view/desktop/client-host/client-process-boundary.ts b/source/client/view/desktop/client-host/client-process-boundary.ts
index 0ae330d..2f0ae62 100644
--- a/source/client/view/desktop/client-host/client-process-boundary.ts
+++ b/source/client/view/desktop/client-host/client-process-boundary.ts
@@ -7,7 +7,7 @@ import ClientTraffic from "./client-traffic"
import { failed, succeeded } from "@server/core/outcome"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isPermissionName, type PermissionName } from "@phreshos/core"
-import { type ClientSurfaceHost } from "./client-surface"
+import { type LocalWindowHost } from "./local-window"
/** The desktop boundary around one iframe execution endpoint. */
export default class ClientProcessBoundary extends TheLink {
@@ -24,7 +24,7 @@ export default class ClientProcessBoundary extends TheLink {
private readonly traffic: ClientTraffic
- private readonly clientSurface: ClientSurfaceHost
+ private readonly localWindow: LocalWindowHost
private readonly subscriptions = new Map<string, EndpointSubscription>()
@@ -59,7 +59,7 @@ export default class ClientProcessBoundary extends TheLink {
private document: string | null = null
- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, space: (layer: WindowLayer) => Space, pointer: PointerHost, traffic: ClientTraffic, clientSurface: ClientSurfaceHost) {
+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, space: (layer: WindowLayer) => Space, pointer: PointerHost, traffic: ClientTraffic, localWindow: LocalWindowHost) {
super()
@@ -75,7 +75,7 @@ export default class ClientProcessBoundary extends TheLink {
this.traffic = traffic
- this.clientSurface = clientSurface
+ this.localWindow = localWindow
this.$outbound.forwardTo((route, ...values) => {
@@ -103,7 +103,7 @@ export default class ClientProcessBoundary extends TheLink {
public async release() {
- this.clientSurface.remove(this.pane)
+ this.localWindow.release(this.pane)
const owner = this.leased
@@ -210,7 +210,7 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.clientSurface)(values[0], ...values.slice(1)).catch((error: Error) => {
+ host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.localWindow)(values[0], ...values.slice(1)).catch((error: Error) => {
if (values[0] === "observe" && typeof values[1] === "string" && values[6] === true) {
@@ -292,7 +292,7 @@ export default class ClientProcessBoundary extends TheLink {
// The first document establishes this already-mounted iframe
// representation. A later document replaces it and therefore
// destroys the previous representation's local Surface.
- if (this.document !== null) this.clientSurface.remove(this.pane)
+ if (this.document !== null) this.localWindow.release(this.pane)
this.document = args[0]
@@ -449,7 +449,7 @@ export default class ClientProcessBoundary extends TheLink {
return
}
- this.answerRequest(question, host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.clientSurface)(args[0], ...args.slice(1)))
+ this.answerRequest(question, host(this.authManager, this.pane, this.space, () => this.owner, this.pointer, this.localWindow)(args[0], ...args.slice(1)))
}
private answerRequest(question: string, operation: Promise<unknown[] | TransferredAnswer>, cancel: () => void = () => undefined) {
diff --git a/source/client/view/desktop/client-host/client-surface.ts b/source/client/view/desktop/client-host/client-surface.ts
deleted file mode 100644
index 9f82a21..0000000
--- a/source/client/view/desktop/client-host/client-surface.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { isScaleLevel, type ClientSurfaceEasing, type ClientSurfaceSettings, type ClientSurfaceTransaction, type ScaleLevel } from "@phreshos/core"
-
-/** Desktop-local Surface commands applied to one exact iframe representation. */
-export interface ClientSurfaceHost {
-
- set(identity: string, settings: ClientSurfaceSettings): void
-
- remove(identity: string): void
-}
-
-/** Render target retained only while one iframe representation is alive. */
-export interface ClientSurfaceState {
-
- settings: ClientSurfaceSettings
-
- revision: number
-}
-
-export function setClientSurface(current: ReadonlyMap<string, ClientSurfaceState>, identity: string, settings: ClientSurfaceSettings) {
-
- const previous = current.get(identity)
-
- if (previous && JSON.stringify(previous.settings) === JSON.stringify(settings)) return current
-
- const next = new Map(current)
-
- next.set(identity, { settings, revision: (previous?.revision ?? 0) + 1 })
-
- return next
-}
-
-export function removeClientSurface(current: ReadonlyMap<string, ClientSurfaceState>, identity: string) {
-
- if (!current.has(identity)) return current
-
- const next = new Map(current)
-
- next.delete(identity)
-
- return next
-}
-
-/** Rejects malformed representation input before it can enter desktop state. */
-export function clientSurfaceSettings(value: unknown): ClientSurfaceSettings {
-
- const record = plain(value, "Surface settings")
-
- fields(record, ["opacity", "radius", "transaction"], "Surface settings")
-
- const settings: { opacity?: number, radius?: ScaleLevel | number | "full", transaction?: ClientSurfaceTransaction } = {}
-
- if ("opacity" in record) {
-
- if (!finite(record.opacity) || record.opacity < 0 || record.opacity > 1) throw new Error("Surface opacity must be a finite number from 0 to 1")
-
- settings.opacity = record.opacity
- }
-
- if ("radius" in record) {
-
- if (record.radius !== "full" && !isScaleLevel(record.radius) && (!finite(record.radius) || record.radius < 0)) throw new Error('Surface radius must be a ScaleLevel, a finite nonnegative pixel number, or "full"')
-
- settings.radius = record.radius
- }
-
- if ("transaction" in record) settings.transaction = transaction(record.transaction)
-
- return Object.freeze(settings)
-}
-
-function transaction(value: unknown): ClientSurfaceTransaction {
-
- const record = plain(value, "Surface transaction")
-
- fields(record, ["duration", "easing"], "Surface transaction")
-
- const result: { duration?: number, easing?: ClientSurfaceEasing } = {}
-
- if ("duration" in record) {
-
- if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Surface transaction duration must be finite milliseconds from 0 to 60000")
-
- result.duration = record.duration
- }
-
- if ("easing" in record) result.easing = easing(record.easing)
-
- return Object.freeze(result)
-}
-
-function easing(value: unknown): ClientSurfaceEasing {
-
- 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("Surface 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 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 fields(record: Record<string, unknown>, allowed: string[], name: string) {
-
- const unknown = Object.keys(record).find(field => !allowed.includes(field))
-
- if (unknown) throw new Error(`${name} has no "${unknown}" field`)
-}
-
-function finite(value: unknown): value is number {
-
- return typeof value === "number" && Number.isFinite(value)
-}
diff --git a/source/client/view/desktop/client-host/host.ts b/source/client/view/desktop/client-host/host.ts
index ddfc807..6a7eb12 100644
--- a/source/client/view/desktop/client-host/host.ts
+++ b/source/client/view/desktop/client-host/host.ts
@@ -7,7 +7,14 @@ import { type PointerHost } from "./pointer"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
import { isPermissionName, isServiceKey, type ProgramIconSize } from "@phreshos/core"
-import { clientSurfaceSettings, type ClientSurfaceHost } from "./client-surface"
+import {
+ localGeometry,
+ localPosition,
+ localSize,
+ surfaceSettings,
+ visualTransaction,
+ type LocalWindowHost
+} from "./local-window"
/** A host answer whose stream must be transferred rather than cloned. */
export class TransferredAnswer {
@@ -49,7 +56,7 @@ export interface Space {
* no prototypes and refuses functions — so every word answers with plain
* values built here, never with an instance the desktop holds.
*/
-export default function host(authManager: AuthManager, pane: string, space: (layer: WindowLayer) => Space, frameOwner: () => string | null, pointer: PointerHost, clientSurface: ClientSurfaceHost) {
+export default function host(authManager: AuthManager, pane: string, space: (layer: WindowLayer) => Space, frameOwner: () => string | null, pointer: PointerHost, localWindow: LocalWindowHost) {
const { processManager, programManager } = authManager
@@ -110,17 +117,6 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return found
}
- function surfaceWindow(named: unknown) {
-
- const found = window(named)
-
- if (found.layer === "window") throw new Error("A window-layer Window cannot own a Surface")
-
- if (found.layer === "wallpaper") throw new Error("A wallpaper-layer Window cannot own a Surface")
-
- return found
- }
-
function declared(found: ReturnType<typeof process>, half: "server" | "client") {
return (programManager.programs.get(found.program)?.[half] ?? null) !== null
@@ -623,15 +619,6 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return [pane]
}
- if (word === "localMove") {
-
- mutableWindow(args[0]).localMove(args[1] as never)
-
- await processManager.changed()
-
- return []
- }
-
if (word === "resize") {
await mutableWindow(args[0]).resize(args[1] as never)
@@ -646,31 +633,62 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return [pane]
}
- if (word === "localResize") {
+ if (word === "localWindow") return [localWindow.state(pane)]
- mutableWindow(args[0]).localResize(args[1] as never)
+ if (word === "localWindowMove") {
- await processManager.changed()
+ await localWindow.move(pane, localPosition(args[0]), visualTransaction(args[1]))
return []
}
- if (word === "surfaceSet") {
+ if (word === "localWindowResize") {
+
+ await localWindow.resize(pane, localSize(args[0]), visualTransaction(args[1]))
+
+ return []
+ }
- const target = surfaceWindow(args[0])
+ if (word === "localWindowGeometry") {
- clientSurface.set(target.process, clientSurfaceSettings(args[1] === undefined ? {} : args[1]))
+ await localWindow.geometry(pane, localGeometry(args[0]), visualTransaction(args[1]))
- return [pane]
+ return []
}
- if (word === "surfaceRemove") {
+ if (word === "localWindowMinimize") {
- const target = surfaceWindow(args[0])
+ localWindow.minimize(pane, args[0] !== false)
- clientSurface.remove(target.process)
+ return []
+ }
- return [pane]
+ if (word === "localWindowTitle") {
+
+ localWindow.title(pane, String(args[0] ?? ""))
+
+ return []
+ }
+
+ if (word === "localWindowRaise") {
+
+ localWindow.raise(pane)
+
+ return []
+ }
+
+ if (word === "localWindowSurfaceSet") {
+
+ await localWindow.setSurface(pane, surfaceSettings(args[0] === undefined ? {} : args[0]), visualTransaction(args[1]))
+
+ return []
+ }
+
+ if (word === "localWindowSurfaceRemove") {
+
+ localWindow.removeSurface(pane)
+
+ return []
}
if (word === "changeTitle") {
diff --git a/source/client/view/desktop/client-host/local-window.ts b/source/client/view/desktop/client-host/local-window.ts
new file mode 100644
index 0000000..08a261a
--- /dev/null
+++ b/source/client/view/desktop/client-host/local-window.ts
@@ -0,0 +1,148 @@
+import {
+ isRelativeValue,
+ isScaleLevel,
+ type Easing,
+ type Position,
+ type ScaleLevel,
+ type Size,
+ type SurfaceSettings,
+ type Transaction,
+ type WindowGeometry,
+ type WindowLayer,
+ type WindowState
+} from "@phreshos/core"
+
+export type LocalAnimation = Readonly<{
+ revision: number
+ transaction: Transaction
+}>
+
+export type LocalSurfaceState = Readonly<{
+ settings: SurfaceSettings
+ animation: LocalAnimation | null
+}>
+
+/** Everything physically represented by one exact live Client iframe. */
+export type LocalWindowState = WindowState & Readonly<{
+ depth: number
+ surface: LocalSurfaceState | null
+ geometryAnimation: 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?: Transaction): Promise<void>
+ resize(identity: string, size: Size, transaction?: Transaction): Promise<void>
+ geometry(identity: string, geometry: WindowGeometry, transaction?: Transaction): Promise<void>
+ minimize(identity: string, minimized: boolean): void
+ title(identity: string, title: string): void
+ raise(identity: string): void
+ setSurface(identity: string, settings: SurfaceSettings, transaction?: Transaction): Promise<void>
+ removeSurface(identity: string): void
+ complete(identity: string, kind: "geometry" | "surface", revision: number): void
+ release(identity: string): void
+}
+
+export function localPosition(value: unknown): Position {
+ const record = plain(value, "Local Window position")
+ fields(record, ["x", "y"], "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")
+ fields(record, ["width", "height"], "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")
+ fields(record, ["position", "size"], "Local Window geometry")
+ return Object.freeze({ position: localPosition(record.position), size: localSize(record.size) })
+}
+
+export function surfaceSettings(value: unknown): SurfaceSettings {
+ const record = plain(value, "Surface settings")
+ fields(record, ["opacity", "radius"], "Surface settings")
+ const result: { opacity?: number, radius?: ScaleLevel | number | "full" } = {}
+
+ if ("opacity" in record) {
+
+ if (!finite(record.opacity) || record.opacity < 0 || record.opacity > 1) throw new Error("Surface opacity must be a finite number from 0 to 1")
+ result.opacity = record.opacity
+ }
+
+ if ("radius" in record) {
+
+ if (record.radius !== "full" && !isScaleLevel(record.radius) && (!finite(record.radius) || record.radius < 0)) throw new Error('Surface radius must be a ScaleLevel, a finite nonnegative pixel number, or "full"')
+ result.radius = record.radius
+ }
+
+ return Object.freeze(result)
+}
+
+export function visualTransaction(value: unknown): Transaction | undefined {
+ if (value === undefined) return undefined
+
+ const record = plain(value, "Transaction")
+ fields(record, ["duration", "easing", "wait"], "Transaction")
+
+ if (!("duration" in record) && !("easing" in record)) throw new Error("A Transaction must provide duration or easing")
+
+ const result: { duration?: number, easing?: Easing, wait?: boolean } = {}
+
+ if ("duration" in record) {
+
+ if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Transaction duration must be finite milliseconds from 0 to 60000")
+ result.duration = record.duration
+ }
+
+ if ("easing" in record) result.easing = easing(record.easing)
+
+ if ("wait" in record) {
+
+ if (typeof record.wait !== "boolean") throw new Error("Transaction wait must be a boolean")
+ result.wait = record.wait
+ }
+
+ return Object.freeze(result) as Transaction
+}
+
+export function layerAllowsSurface(layer: WindowLayer) {
+
+ if (layer === "window") throw new Error("A window-layer representation cannot own a Surface")
+ if (layer === "wallpaper") throw new Error("A wallpaper-layer representation cannot own a 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("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 fields(record: Record<string, unknown>, allowed: string[], name: string) {
+
+ const unknown = Object.keys(record).find(field => !allowed.includes(field))
+ if (unknown) throw new Error(`${name} has no "${unknown}" field`)
+}
+
+function finite(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value)
+}
diff --git a/source/client/view/desktop/window-manager/local-windows.ts b/source/client/view/desktop/window-manager/local-windows.ts
new file mode 100644
index 0000000..2fed680
--- /dev/null
+++ b/source/client/view/desktop/window-manager/local-windows.ts
@@ -0,0 +1,313 @@
+import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
+import { type Transaction, type WindowGeometry, type WindowState } from "@phreshos/core"
+import { layerAllowsSurface, type LocalWindowHost, type LocalWindowState } from "../client-host/local-window"
+
+export interface LocalWindowEntry {
+ identity: string
+ client: ClientState
+}
+
+/** Owns the representations of one desktop without entering server transport. */
+export default class LocalWindows implements LocalWindowHost {
+
+ public windows: ReadonlyMap<string, LocalWindowState>
+
+ private readonly live = new Map<string, string>()
+ private readonly authoritative = new Map<string, string>()
+ private readonly waiting = new Map<string, WaitingAnimation>()
+ private readonly readers = new Map<string, LocalGeometryReader>()
+ private revision = 0
+ private changed: (windows: ReadonlyMap<string, LocalWindowState>) => void = () => undefined
+
+ public constructor(initial: ReadonlyMap<string, LocalWindowEntry>, private readonly client: (process: string) => ClientState | null) {
+
+ this.windows = new Map([...initial.values()].map(({ identity, client }) => [identity, localState(client)]))
+ this.reconcile(initial)
+ }
+
+ public listen(changed: (windows: ReadonlyMap<string, LocalWindowState>) => void) {
+
+ this.changed = changed
+ }
+
+ /** Projects new authority only where the ordinary Window layer delegates it. */
+ public reconcile(current: ReadonlyMap<string, LocalWindowEntry>) {
+
+ 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, "surface", "The local Window representation was removed")
+ }
+
+ this.live.clear()
+ const next = new Map(this.windows)
+
+ for (const [process, { identity, client }] of current) {
+
+ this.live.set(process, identity)
+ const previous = next.get(identity)
+ const signature = authoritativeSignature(client)
+
+ if (!previous) next.set(identity, localState(client))
+ else if (client.window.layer === "window" && this.authoritative.get(identity) !== signature) {
+
+ const geometryChanged = JSON.stringify([previous.position, previous.size]) !== JSON.stringify([client.window.position, client.window.size])
+ if (geometryChanged) this.cancel(identity, "geometry", "The local Window animation was replaced by authoritative state")
+ next.set(identity, projectAuthoritative(previous, client, geometryChanged))
+ }
+
+ this.authoritative.set(identity, signature)
+ }
+
+ this.publish(next)
+ }
+
+ public remove(identity: string) {
+
+ if (!this.windows.has(identity)) return
+ const next = new Map(this.windows)
+ next.delete(identity)
+ this.readers.delete(identity)
+ this.authoritative.delete(identity)
+ this.publish(next)
+ }
+
+ public state(process: string) {
+
+ const { identity, state } = this.existing(process)
+ const geometry = this.readers.get(identity)?.()
+ return windowState(state, frontmost(this.windows, state.layer) === identity, geometry)
+ }
+
+ public readonly represent = (process: string, reader: LocalGeometryReader | null) => {
+
+ const identity = this.live.get(process)
+
+ if (!identity) return
+
+ if (reader) this.readers.set(identity, reader)
+
+ else this.readers.delete(identity)
+ }
+
+ public move(process: string, position: WindowState["position"], transaction?: Transaction) {
+
+ const state = this.existing(process).state
+ return this.geometry(process, { position, size: state.size }, transaction)
+ }
+
+ public resize(process: string, size: WindowState["size"], transaction?: Transaction) {
+
+ const state = this.existing(process).state
+ return this.geometry(process, { position: state.position, size }, transaction)
+ }
+
+ public geometry(process: string, value: WindowGeometry, transaction?: Transaction) {
+
+ const { identity, state } = this.existing(process)
+ if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()
+
+ this.cancel(identity, "geometry")
+ const animation = transaction ? { revision: ++this.revision, transaction } : null
+ this.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })
+ return this.waitFor(identity, "geometry", animation)
+ }
+
+ public minimize(process: string, minimized: boolean) {
+
+ const { identity, state } = this.existing(process)
+ this.replace(identity, { ...state, minimized })
+ }
+
+ public title(process: string, title: string) {
+
+ const { identity, state } = this.existing(process)
+ this.replace(identity, { ...state, title })
+ }
+
+ public raise(process: string) {
+
+ const { identity, state } = this.existing(process)
+ 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 setSurface(process: string, settings: NonNullable<LocalWindowState["surface"]>["settings"], transaction?: Transaction) {
+
+ const { identity, state } = this.existing(process)
+ layerAllowsSurface(state.layer)
+ if (state.surface && JSON.stringify(state.surface.settings) === JSON.stringify(settings)) return Promise.resolve()
+
+ this.cancel(identity, "surface")
+ const animation = transaction ? { revision: ++this.revision, transaction } : null
+ this.replace(identity, { ...state, surface: { settings, animation } })
+ return this.waitFor(identity, "surface", animation)
+ }
+
+ public removeSurface(process: string) {
+
+ const { identity, state } = this.existing(process)
+ layerAllowsSurface(state.layer)
+ this.cancel(identity, "surface")
+ this.replace(identity, { ...state, surface: null })
+ }
+
+ public complete(process: string, kind: AnimationKind, revision: number) {
+
+ const identity = this.live.get(process)
+ if (!identity) return
+ const state = this.windows.get(identity)
+ const animation = kind === "geometry" ? state?.geometryAnimation : state?.surface?.animation
+ if (!state || animation?.revision !== revision) return
+
+ this.replace(identity, kind === "geometry"
+ ? { ...state, geometryAnimation: null }
+ : { ...state, surface: state.surface && { ...state.surface, animation: null } })
+
+ const key = animationKey(identity, kind)
+ const waiting = this.waiting.get(key)
+ if (!waiting || waiting.revision !== revision) return
+ this.waiting.delete(key)
+ waiting.resolve()
+ }
+
+ /** A new iframe representation always begins from authoritative truth. */
+ public release(process: string) {
+
+ const identity = this.live.get(process)
+ if (!identity) return
+ this.cancel(identity, "geometry", "The local Window representation was removed")
+ this.cancel(identity, "surface", "The local Window representation was removed")
+
+ const client = this.client(process)
+ if (!client || client.window.layer === "wallpaper") return
+ this.authoritative.set(identity, authoritativeSignature(client))
+ this.replace(identity, localState(client))
+ }
+
+ private existing(process: string) {
+
+ const identity = this.live.get(process)
+ if (!identity) throw new Error("This Client has no local Window representation")
+ const state = this.windows.get(identity)
+ if (!state) throw new Error("This Client has no local Window representation")
+ return { identity, state }
+ }
+
+ private replace(identity: string, state: LocalWindowState) {
+
+ const next = new Map(this.windows)
+ next.set(identity, state)
+ this.publish(next)
+ }
+
+ private publish(next: ReadonlyMap<string, LocalWindowState>) {
+
+ this.windows = next
+ this.changed(next)
+ }
+
+ private cancel(identity: string, kind: AnimationKind, reason = "The local Window animation was interrupted") {
+
+ const key = animationKey(identity, kind)
+ const waiting = this.waiting.get(key)
+ if (!waiting) return
+ this.waiting.delete(key)
+ waiting.reject(new Error(reason))
+ }
+
+ private waitFor(identity: string, kind: AnimationKind, animation: LocalWindowState["geometryAnimation"]) {
+
+ if (!animation?.transaction.wait) return Promise.resolve()
+ return new Promise<void>((resolve, reject) => {
+
+ this.waiting.set(animationKey(identity, kind), { revision: animation.revision, resolve, reject })
+ })
+ }
+}
+
+type AnimationKind = "geometry" | "surface"
+
+interface WaitingAnimation {
+ revision: number
+ resolve: () => void
+ reject: (error: Error) => void
+}
+
+function animationKey(identity: string, kind: AnimationKind) {
+
+ return `${identity}:${kind}`
+}
+
+function localState(client: ClientState): LocalWindowState {
+
+ const window = client.window
+ return {
+ title: window.title,
+ position: window.position,
+ size: window.size,
+ minimized: window.minimized,
+ front: false,
+ layer: window.layer,
+ location: window.location,
+ depth: window.depth,
+ surface: null,
+ geometryAnimation: null
+ }
+}
+
+function projectAuthoritative(local: LocalWindowState, client: ClientState, replaceGeometry: boolean): LocalWindowState {
+
+ const window = client.window
+ return {
+ ...local,
+ title: window.title,
+ position: window.position,
+ size: window.size,
+ minimized: window.minimized,
+ layer: window.layer,
+ location: window.location,
+ depth: window.depth,
+ geometryAnimation: replaceGeometry ? null : local.geometryAnimation
+ }
+}
+
+function windowState(local: LocalWindowState, front: boolean, geometry?: Readonly<{ position: WindowState["position"], size: WindowState["size"] }>): WindowState {
+
+ return {
+ title: local.title,
+ position: geometry?.position ?? local.position,
+ size: geometry?.size ?? local.size,
+ minimized: local.minimized,
+ front,
+ layer: local.layer,
+ location: local.location
+ }
+}
+
+export type LocalGeometryReader = () => Readonly<{
+ position: WindowState["position"]
+ size: WindowState["size"]
+}>
+
+function authoritativeSignature(client: ClientState) {
+
+ const window = client.window
+ return JSON.stringify([window.title, window.position, window.size, window.minimized, window.layer, window.location, window.depth])
+}
+
+function frontmost(windows: ReadonlyMap<string, LocalWindowState>, layer: LocalWindowState["layer"]) {
+
+ let best: [string, LocalWindowState] | null = null
+ for (const candidate of windows) {
+
+ const [, window] = candidate
+ if (window.layer !== layer || window.minimized) continue
+ if (!best || best[1].depth <= window.depth) best = candidate
+ }
+ return best?.[0] ?? null
+}
diff --git a/source/client/view/desktop/window-manager/process-window.tsx b/source/client/view/desktop/window-manager/process-window.tsx
index 6e908e8..6aeca47 100644
--- a/source/client/view/desktop/window-manager/process-window.tsx
+++ b/source/client/view/desktop/window-manager/process-window.tsx
@@ -1,7 +1,8 @@
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 "./window-geometry"
-import { type ClientSurfaceState } from "../client-host/client-surface"
+import { type LocalAnimation, type LocalSurfaceState } from "../client-host/local-window"
+import { type LocalGeometryReader } from "./local-windows"
import { type ProgramAccess } from "../program-access"
import { type Position, type Size } from "@phreshos/core"
import Loading from "../../components/loading"
@@ -18,7 +19,7 @@ const loadingExitDuration = 200
* 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, client, title, icon, position, size, clientSurface, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, onFrame, onFrameLoad, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, onFrame, onFrameLoad, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -38,6 +39,8 @@ export default memo(function ({ identity, record, client, title, icon, position,
const snap = useCallback((position: Position, size: Size) => onSnap(record, position, size), [onSnap, record])
+ const represent = useCallback((reader: LocalGeometryReader | null) => onLocalRepresentation(record.identity, reader), [onLocalRepresentation, record])
+
const frameSource = programFrameSource(record, client, door)
const [loading, setLoading] = useState<LoadingState>({ source: null, phase: "loading" })
@@ -96,7 +99,13 @@ export default memo(function ({ identity, record, client, title, icon, position,
size={size}
- clientSurface={clientSurface}
+ localSurface={localSurface}
+
+ geometryAnimation={geometryAnimation}
+
+ onLocalAnimationComplete={onLocalAnimationComplete}
+
+ onLocalRepresentation={represent}
paintSurfaceSize={paintSurfaceSize}
@@ -173,7 +182,13 @@ interface ProcessWindowProps {
size: Size
- clientSurface?: ClientSurfaceState
+ localSurface: LocalSurfaceState | null
+
+ geometryAnimation: LocalAnimation | null
+
+ onLocalAnimationComplete: (kind: "geometry" | "surface", revision: number) => void
+
+ onLocalRepresentation: (identity: string, reader: LocalGeometryReader | null) => void
paintSurfaceSize?: WindowSurfaceSize
diff --git a/source/client/view/desktop/window-manager/window-manager.ts b/source/client/view/desktop/window-manager/window-manager.ts
index a0ff9a3..07e38e7 100644
--- a/source/client/view/desktop/window-manager/window-manager.ts
+++ b/source/client/view/desktop/window-manager/window-manager.ts
@@ -6,15 +6,16 @@ import { type Position, type Size, type Value } from "@phreshos/core"
import { useCallback, useRef, useState } from "react"
import { AuthManagerContext } from "../../contexts"
import { wholeWindowGeometry } from "./window-geometry"
+import LocalWindows from "./local-windows"
/**
* The authorized view's windows: processes that have one. A window is a
* process whose program has a client half, so the process itself says
* whether it is shown — nothing else is consulted.
*
- * Requests are answered before the server is: the object mutates here,
- * the same tunnel event re-emits, and the echo lands on a peer already
- * agreeing — while every other session sees the change as news.
+ * The local representation and authoritative counterpart are distinct.
+ * Ordinary windows project authoritative changes automatically; under and
+ * over windows retain their local projection after its initial seed.
*
* 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
@@ -56,6 +57,16 @@ export default function useWindows() {
const initialClients = initialIncarnations.current
+ const localController = useRef<LocalWindows | null>(null)
+
+ if (!localController.current) localController.current = new LocalWindows(initialClients, process => peer.processes.get(process)?.client ?? null)
+
+ const localWindow = localController.current
+
+ const [localWindows, setLocalWindows] = useState(localWindow.windows)
+
+ localWindow.listen(setLocalWindows)
+
const previousClients = useRef(initialClients)
// Client states already present when this desktop mounts are restored,
@@ -96,6 +107,8 @@ export default function useWindows() {
const currentClients = new Map(list.flatMap(record => record.client && record.client.window.layer !== "wallpaper" ? [[record.identity, incarnation(record, record.client)] as const] : []))
+ localWindow.reconcile(currentClients)
+
let settled = false
for (const identity of stopping.current) {
@@ -157,23 +170,26 @@ export default function useWindows() {
for (const process of records) {
- const window = process.client!.window
+ const live = incarnation(process, process.client!)
- if (window.layer === "wallpaper" || window.minimized) continue
+ const window = localWindows.get(live.identity)
+
+ if (!window || window.layer === "wallpaper" || window.minimized) continue
const best = fronts[window.layer]
- if (!best || best.client!.window.depth <= window.depth) fronts[window.layer] = process
+ const bestWindow = best && localWindows.get(incarnation(best, best.client!).identity)
+
+ if (!bestWindow || bestWindow.depth <= window.depth) fronts[window.layer] = process
}
- // A request answered locally first: the object changes, the tunnel
- // re-emits, and the echo confirms what is already shown.
+ // Local representation and authoritative mutation are two explicit acts.
+ // The local 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>) {
- peer.$inbound.publish("/processes", [...peer.processes.values()]).catch(() => undefined)
-
request.catch(() => undefined)
- }, [peer])
+ }, [])
const close = useCallback(function (process: Process) {
@@ -198,19 +214,21 @@ export default function useWindows() {
setOrder(current => current.filter(entry => entry !== identity))
+ localWindow.remove(identity)
+
}, [])
const raise = useCallback(function (process: Process) {
const window = process.client?.window
- if (!window || window.layer === "wallpaper") return
+ if (!window || window.layer !== "window") return
const highest = summit(window.layer)
- if (window.depth === highest) return
+ localWindow.raise(process.identity)
- window.depth = highest + 1
+ if (window.depth === highest) return
commit(window.raise())
@@ -220,9 +238,9 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
- window.minimized = minimized
+ localWindow.minimize(process.identity, minimized)
commit(window.minimize(minimized))
@@ -232,9 +250,9 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
- if (window.minimized) minimize(process, false)
+ if (localWindow.state(process.identity).minimized) minimize(process, false)
raise(process)
@@ -244,9 +262,9 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
- window.localMove({ x, y })
+ void localWindow.move(process.identity, { x, y })
commit(window.move({ x, y }))
@@ -256,11 +274,11 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
if (!position) {
- window.localResize({ width, height })
+ void localWindow.resize(process.identity, { width, height })
commit(window.resize({ width, height }))
@@ -269,7 +287,7 @@ export default function useWindows() {
const geometry = { position, size: { width, height } }
- window.localSetGeometry(geometry)
+ void localWindow.geometry(process.identity, geometry)
commit(window.setGeometry(geometry))
@@ -279,11 +297,11 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
const geometry = { position, size }
- window.localSetGeometry(geometry)
+ void localWindow.geometry(process.identity, geometry)
commit(window.setGeometry(geometry))
@@ -293,11 +311,13 @@ export default function useWindows() {
const window = process.client?.window
- if (!window) return
+ if (!window || window.layer !== "window") return
+
+ const local = localWindow.state(process.identity)
const was = filled.current.get(process.identity)
- const whole = wholeWindowGeometry(window.position, window.size)
+ const whole = wholeWindowGeometry(local.position, local.size)
if (whole && was) {
@@ -308,7 +328,7 @@ export default function useWindows() {
return
}
- filled.current.set(process.identity, { position: window.position, size: window.size })
+ filled.current.set(process.identity, { position: local.position, size: local.size })
snap(process, { x: "0/1", y: "0/1" }, { width: "1/1", height: "1/1" })
@@ -328,10 +348,10 @@ export default function useWindows() {
const live = incarnation(record, record.client!)
- return { ...live, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
+ return { ...live, local: localWindows.get(live.identity)!, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
}),
- ...leaving.map(window => ({ ...window, closing: true, stopping: false, entering: !inheritedClients.current.has(window.client) }))
+ ...leaving.map(window => ({ ...window, local: localWindows.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))
@@ -340,7 +360,7 @@ export default function useWindows() {
for (const pane of panes) {
- const layer = pane.client.window.layer
+ const layer = pane.local.layer
if (layer !== "wallpaper") panesByLayer[layer].push(pane)
}
@@ -357,6 +377,8 @@ export default function useWindows() {
fronts,
+ localWindow,
+
close,
closed,
diff --git a/source/client/view/desktop/window-manager/window-surface.tsx b/source/client/view/desktop/window-manager/window-surface.tsx
index 96a63a9..7f5da30 100644
--- a/source/client/view/desktop/window-manager/window-surface.tsx
+++ b/source/client/view/desktop/window-manager/window-surface.tsx
@@ -1,18 +1,21 @@
import { useReducedMotion } from "@libs/react-motion"
-import { isScaleLevel, scale, type ClientSurfaceEasing, type ClientSurfaceSettings } from "@phreshos/core"
+import { isScaleLevel, scale, type Easing, type SurfaceSettings } from "@phreshos/core"
import { GlassSurface, useTheme } from "@phreshos/react-ui"
import { useLayoutEffect, useRef, useState } from "react"
+import { type LocalSurfaceState } from "../client-host/local-window"
const systemDuration = 240
const systemEasing = "ease-out"
/** Projects one representation-local target and animates explicit replacements. */
-export default function WindowSurface({ revision, settings }: WindowSurfaceProps) {
+export default function WindowSurface({ state, onComplete }: WindowSurfaceProps) {
+
+ const { settings, animation: requestedAnimation } = state
const element = useRef<HTMLDivElement>(null)
- const previousRevision = useRef<number | null>(null)
+ const firstRender = useRef(true)
const reducedMotion = useReducedMotion()
@@ -33,19 +36,17 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
const current = getComputedStyle(surface)
- const changed = previousRevision.current === null
-
- ? revision > 0
+ const revision = requestedAnimation?.revision ?? null
- : revision !== previousRevision.current
+ const changed = revision !== null
- const from = previousRevision.current === null && changed
+ const from = firstRender.current && changed
? { opacity: 0, borderRadius: "0px" }
: { opacity: Number(current.opacity), borderRadius: current.borderRadius }
- previousRevision.current = revision
+ firstRender.current = false
setRendered(settings)
@@ -53,11 +54,18 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
surface.style.borderRadius = target.borderRadius
- const transaction = settings.transaction
+ const transaction = requestedAnimation?.transaction
const duration = transaction?.duration ?? systemDuration
- if (!transaction || reducedMotion || duration === 0 || !changed) return
+ if (!transaction || !changed) return
+
+ if (reducedMotion || duration === 0) {
+
+ onComplete(revision!)
+
+ return
+ }
const animation = surface.animate([from, target], {
@@ -72,6 +80,8 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
animation.cancel()
+ onComplete(revision!)
+
}, () => undefined)
return function () {
@@ -85,7 +95,7 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
animation.cancel()
}
- }, [reducedMotion, revision, settings, themeRadius])
+ }, [reducedMotion, requestedAnimation?.revision, settings, themeRadius])
const target = values(rendered, themeRadius)
@@ -104,7 +114,7 @@ export default function WindowSurface({ revision, settings }: WindowSurfaceProps
/>
}
-function values(settings: ClientSurfaceSettings, themeRadius: number) {
+function values(settings: SurfaceSettings, themeRadius: number) {
const radius = settings.radius
@@ -116,7 +126,7 @@ function values(settings: ClientSurfaceSettings, themeRadius: number) {
}
}
-function easing(value: ClientSurfaceEasing | undefined) {
+function easing(value: Easing | undefined) {
if (typeof value === "string") return value
@@ -125,8 +135,7 @@ function easing(value: ClientSurfaceEasing | undefined) {
interface WindowSurfaceProps {
- settings: ClientSurfaceSettings
+ state: LocalSurfaceState
- /** Every positive revision came from an explicit live Client command. */
- revision: number
+ onComplete: (revision: number) => void
}
diff --git a/source/client/view/desktop/window-manager/window.tsx b/source/client/view/desktop/window-manager/window.tsx
index 8f5bc87..110e3cb 100644
--- a/source/client/view/desktop/window-manager/window.tsx
+++ b/source/client/view/desktop/window-manager/window.tsx
@@ -6,7 +6,8 @@ import { absoluteWindowGeometry, resolveWindowValue, wholeWindowGeometry, window
import { numericScale, type Position, type Size } from "@phreshos/core"
import WindowHeader from "./window-header"
import WindowSurface from "./window-surface"
-import { type ClientSurfaceState } from "../client-host/client-surface"
+import { type LocalAnimation, type LocalSurfaceState } from "../client-host/local-window"
+import { type LocalGeometryReader } from "./local-windows"
import gsap from "gsap"
/**
@@ -49,7 +50,7 @@ const settle = ["left", "top", "width", "height", "transform"].map(property => `
const morphing = ["left", "top", "width", "height"].map(property => `${property} 0.22s cubic-bezier(0.33, 1, 0.68, 1)`).join(", ")
-export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, clientSurface, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
+export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
const frame = useRef<HTMLDivElement>(null)
@@ -65,6 +66,46 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
const [gesture, setGesture] = useState<Gesture | null>(null)
+ useLayoutEffect(function () {
+
+ if (!onLocalRepresentation) return
+
+ const read: LocalGeometryReader = function () {
+
+ const element = frame.current
+
+ const parent = element?.offsetParent
+
+ if (!element || !parent) return { position, size }
+
+ const shown = element.getBoundingClientRect()
+
+ const surface = parent.getBoundingClientRect()
+
+ return {
+ position: { x: shown.left - surface.left, y: shown.top - surface.top },
+ size: { width: shown.width, height: shown.height }
+ }
+ }
+
+ onLocalRepresentation(read)
+
+ return () => onLocalRepresentation(null)
+
+ }, [onLocalRepresentation, position, size])
+
+ useLayoutEffect(function () {
+
+ if (!geometryAnimation) return
+
+ const duration = reducedMotion ? 0 : geometryAnimation.transaction.duration ?? 300
+
+ const completed = globalThis.setTimeout(() => onLocalAnimationComplete?.("geometry", geometryAnimation.revision), duration)
+
+ return () => globalThis.clearTimeout(completed)
+
+ }, [geometryAnimation?.revision, reducedMotion])
+
const closureCompleted = useRef(false)
function completeClosure() {
@@ -496,7 +537,11 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
// paints nothing on is one whose motion is not the
// system's either: asked to be somewhere, it is there,
// rather than gliding over half a second nobody asked for.
- transition: bare || landed || reducedMotion ? "none" : settle
+ transition: geometryAnimation && !reducedMotion
+
+ ? explicitGeometryTransition(geometryAnimation)
+
+ : bare || landed || reducedMotion ? "none" : settle
}
const surface = active
@@ -563,7 +608,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
{/* A bare Client cannot refract the desktop through its iframe.
Its host surface is therefore a sibling behind the frame,
with its own radius and no clipping parent. */}
- {bare && clientSurface && <WindowSurface settings={clientSurface.settings} revision={clientSurface.revision} />}
+ {bare && localSurface && <WindowSurface state={localSurface} onComplete={revision => onLocalAnimationComplete?.("surface", revision)} />}
{/* LAYER 1 — the shared Theme-driven glass material. */}
{!bare && <GlassSurface aria-hidden="true" radius="inherit" className="pointer-events-none absolute inset-0" />}
@@ -602,7 +647,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
</div>
- {edges.map(handle => <div
+ {!bare && edges.map(handle => <div
key={handle.edge}
@@ -661,10 +706,8 @@ interface WindowProps extends Omit<ComponentProps<"div">, "title"> {
// controls, and no gutter — so what a program asked to be is what it
// gets, edge to edge, rather than half a gutter smaller.
//
- // What stays is what is invisible and functional. The resize edges
- // are hit areas rather than paint, so they stay; the geometry, the
- // snapping and the layer are the system's and stay. What goes is
- // only what was there to be seen.
+ // 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
@@ -682,7 +725,13 @@ interface WindowProps extends Omit<ComponentProps<"div">, "title"> {
size?: Size
/** Surface target owned by this live iframe representation. */
- clientSurface?: ClientSurfaceState
+ localSurface?: LocalSurfaceState | null
+
+ geometryAnimation?: LocalAnimation | null
+
+ onLocalAnimationComplete?: (kind: "geometry" | "surface", revision: number) => void
+
+ onLocalRepresentation?: (reader: LocalGeometryReader | null) => void
/** Surface used only to decide which painted edges receive an inset. */
paintSurfaceSize?: WindowSurfaceSize
@@ -705,3 +754,14 @@ interface Gesture {
morph: boolean
}
+
+function explicitGeometryTransition(animation: LocalAnimation) {
+
+ const duration = animation.transaction.duration ?? 300
+
+ const easing = animation.transaction.easing
+
+ const curve = Array.isArray(easing) ? `cubic-bezier(${easing.join(", ")})` : easing ?? "ease-out"
+
+ return ["left", "top", "width", "height"].map(property => `${property} ${duration}ms ${curve}`).join(", ")
+}
diff --git a/source/client/view/desktop/workspace.tsx b/source/client/view/desktop/workspace.tsx
index 6d26801..247f887 100644
--- a/source/client/view/desktop/workspace.tsx
+++ b/source/client/view/desktop/workspace.tsx
@@ -47,7 +47,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, clientSurfaces, frame, frameLoaded } = useClientHost(desktop, sources.current)
+ const { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded } = useClientHost(desktop, sources.current, windows.localWindow)
const wallpaperLoaded = useCallback((event: SyntheticEvent<HTMLIFrameElement>) => {
@@ -80,7 +80,7 @@ export default function Workspace() {
function renderWindows(layer: Layer) {
- return windows.panesByLayer[layer].map(({ identity, record, client, closing, entering, stopping }) => <ProcessWindow
+ return windows.panesByLayer[layer].map(({ identity, record, client, local, closing, entering, stopping }) => <ProcessWindow
key={identity}
@@ -90,27 +90,33 @@ export default function Workspace() {
client={client}
- title={client.window.title}
+ title={local.title}
icon={icon(record)}
- position={client.window.position}
+ position={local.position}
- size={client.window.size}
+ size={local.size}
- clientSurface={clientSurfaces.get(record.identity)}
+ localSurface={local.surface}
+
+ geometryAnimation={local.geometryAnimation}
+
+ onLocalAnimationComplete={(kind, revision) => windows.localWindow.complete(record.identity, kind, revision)}
+
+ onLocalRepresentation={windows.localWindow.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={client.window.depth}
+ depth={local.depth}
active={fronts[layer]?.identity === record.identity}
bare={layer !== "window"}
- minimized={client.window.minimized}
+ minimized={local.minimized}
closing={closing}