An open-source, self-hosted system for apps built with web technologies.
Add centered desktop plane and per-Desktop viewport navigation
zohayrslileh06a8faae4900
diff --git a/bun.lock b/bun.lockindex 346775d..e6b4a75 100644--- a/bun.lock+++ b/bun.lock@@ -8,7 +8,7 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",- "@phreshos/core": "^0.1.63",+ "@phreshos/core": "^0.1.64","@phreshos/react-ui": "^0.1.46","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1",@@ -200,7 +200,7 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="],- "@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-wzIRrjok93QJQb/cpm5A/PVRm50x6FTP4Agj2l8kUsg1rkrTLZAU/iX63DlQ02hrkYypM0aEfhbpuZJn9jpV3Q=="],+ "@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-c3wBWBHpDtTRCqrpsk1Iac1cQfUBeWm9xLlSBv1i4tJ0d1xQ5hIbOEq+a2qoO3kV3eOHYtBpYWUAeob+cMRsIA=="],"@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@base-ui/react": "^1.7.0", "@internationalized/date": "^3.12.3", "@phreshos/core": "^0.1.63", "colorjs.io": "^0.7.1", "lucide-react": "^1.48.0", "react-aria": "^3.51.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-AF36/07KX4IyES3ong/IhscPccILOLC9m5vxC4O4VbTHZud14UXKRUsoxNPM6F9twYVFjLE+iEzo4ZJTzfig7A=="],@@ -534,6 +534,8 @@"zod": ["[email protected]", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="],+ "@phreshos/react-ui/@phreshos/core": ["@phreshos/[email protected]", "", { "dependencies": { "zod": "^4.6.5" } }, "sha512-wzIRrjok93QJQb/cpm5A/PVRm50x6FTP4Agj2l8kUsg1rkrTLZAU/iX63DlQ02hrkYypM0aEfhbpuZJn9jpV3Q=="],+"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],diff --git a/package.json b/package.jsonindex fa1c56d..81ce92d 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.100",+ "version": "0.1.101","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -37,7 +37,7 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0",- "@phreshos/core": "^0.1.63",+ "@phreshos/core": "^0.1.64","@phreshos/react-ui": "^0.1.46","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1",diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.tsindex 2d797a1..dd9757b 100644--- a/source/client/view/components/desktop-host/client-host.ts+++ b/source/client/view/components/desktop-host/client-host.ts@@ -1,9 +1,11 @@import { ReactTunnel } from "@the-link/react"-import { type DesktopSize, type DesktopViewportSnapshot } from "@phreshos/core"+import { type DesktopSize } from "@phreshos/core"import useAnnouncements from "./announcements"import ClientProcessBoundary from "./client-process-boundary"import ClientTraffic from "./client-traffic"-import { type RefObject, useCallback, useLayoutEffect, useRef, useState } from "react"+import { type DesktopViewportHost } from "./host"+import { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"+import useViewportOffset from "@client/view/structure/desktop/viewport-offset"import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"import { type WindowPresentationHost } from "./window-presentation"import messagepack from "@the-link/messagepack"@@ -27,17 +29,48 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObjeconst [windowSurfaceSize, setWindowSurfaceSize] = useState<SurfaceSize>({ width: 0, height: 0 })- const latestDesktopViewport = useRef<DesktopViewportSnapshot>({ size: { width: 0, height: 0 } })+ const latestDesktopSize = useRef<DesktopSize>({ width: 0, height: 0 })- const desktopViewport = useCallback(function (): DesktopViewportSnapshot {+ // Where this Desktop looks on the plane of standard Windows. It is this connection's alone.+ const viewport = useViewportOffset(windowSurfaceSize)- const element = desktop.current+ const offset = useRef(viewport.offset)- return element- ? { size: measureElement(element) }- : latestDesktopViewport.current+ offset.current = viewport.offset- }, [desktop])+ const place = useRef(viewport.place)++ place.current = viewport.place++ // What a Client reaches of this viewport: both values, and moving the view once it is permitted.+ const desktopViewport = useMemo<DesktopViewportHost>(() => ({++ state() {++ const element = desktop.current++ return { size: element ? measureElement(element) : latestDesktopSize.current, offset: offset.current }+ },++ move: offset => place.current(offset)++ }), [desktop])++ // Every Client following this Desktop hears that its view moved.+ const announcedOffset = useRef(viewport.offset)++ useEffect(function () {++ if (announcedOffset.current === viewport.offset) return++ announcedOffset.current = viewport.offset++ for (const identity of sources.keys()) {++ traffic.emit(identity, "host-desktop-viewport", "move", viewport.offset).catch(() => undefined)+ }++ }, [viewport.offset, sources, traffic])useLayoutEffect(function () {@@ -50,13 +83,11 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObjefunction announceDesktop(size: DesktopSize) {- const previous = latestDesktopViewport.current.size+ const previous = latestDesktopSize.currentif (previous.width === size.width && previous.height === size.height) return- const snapshot = { size }-- latestDesktopViewport.current = snapshot+ latestDesktopSize.current = size// Announcements leave directly from the full desktop measurement.// Traffic carries them only to boundaries with a live interest.@@ -64,7 +95,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObjefor (const identity of sources.keys()) {- traffic.emit(identity, "host-desktop-viewport", "resize", snapshot).catch(() => undefined)+ traffic.emit(identity, "host-desktop-viewport", "resize", size).catch(() => undefined)}}@@ -75,7 +106,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObjeconst initialDesktop = measureElement(desktop.current)- latestDesktopViewport.current = { size: initialDesktop }+ latestDesktopSize.current = initialDesktopconst initialWindowSurface = measureElement(windowSurfaceRef.current)@@ -301,7 +332,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje}, [authManager, sources])- return { windowSurfaceRef, windowSurfaceSize, frame, frameLoaded }+ return { windowSurfaceRef, windowSurfaceSize, viewport, frame, frameLoaded }}export type ClientHost = ReturnType<typeof useClientHost>diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex 9b5b996..829acf5 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -1,10 +1,10 @@import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"import { TheLink } from "@the-link/core"-import host, { TransferredAnswer } from "./host"+import host, { TransferredAnswer, type DesktopViewportHost } from "./host"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 { isServiceAddress, parseProgramInstallOptions, type DesktopViewportSnapshot, type ServiceAddress, type ShellOptions, type WindowMovePoint } from "@phreshos/core"+import { isServiceAddress, parseProgramInstallOptions, type ServiceAddress, type ShellOptions, type WindowMovePoint } from "@phreshos/core"import { type PresentationMoveCoordinates, type PresentationMovePoint, type WindowPresentationHost } from "./window-presentation"import messagepack from "@the-link/messagepack"import { sdkProcess, type SdkProcessSource } from "./sdk-records"@@ -19,7 +19,7 @@ export default class ClientProcessBoundary extends TheLink {private readonly authManager: AuthManager- private readonly viewport: () => DesktopViewportSnapshot+ private readonly viewport: DesktopViewportHostprivate readonly traffic: ClientTraffic@@ -67,7 +67,7 @@ export default class ClientProcessBoundary extends TheLink {private leased: string | null = null- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: () => DesktopViewportSnapshot, traffic: ClientTraffic, presentation: WindowPresentationHost) {+ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: DesktopViewportHost, traffic: ClientTraffic, presentation: WindowPresentationHost) {super()diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 4fc3235..1795521 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -1,5 +1,6 @@import {- type DesktopViewportSnapshot,+ type DesktopOffset,+ type DesktopViewportState,type Launch,type WindowState} from "@phreshos/core"@@ -42,7 +43,15 @@ 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, moveCoordinates: PresentationMoveCoordinates, presentation: WindowPresentationHost) {+/** This Desktop's viewport as a Client reaches it: read both values, or move the view. */+export interface DesktopViewportHost {++ state(): DesktopViewportState++ move(offset: DesktopOffset): void+}++export default function host(authManager: AuthManager, pane: string, viewport: DesktopViewportHost, frameOwner: () => string | null, moveCoordinates: PresentationMoveCoordinates, presentation: WindowPresentationHost) {const { processManager, programManager } = authManager@@ -1227,7 +1236,16 @@ export default function host(authManager: AuthManager, pane: string, viewport: (// One desktop can frame many Client layers, but its complete area is// one host fact. It is this desktop's answer rather than a machine// fact, and the gutter remains private desktop layout state.- if (word === "desktopViewport") return [viewport()]+ if (word === "desktopViewport") return [viewport.state()]++ if (word === "moveDesktopViewport") {++ await access.require("desktopViewport", [])++ viewport.move(parseDesktopOffset(args[0]))++ return []+ }// Completed uploads are public values. Creating one has its own// permission; exposing the native directory requires complete access.@@ -1495,3 +1513,13 @@ function controlled(body: ReadableStream<Uint8Array>, controller: AbortControlle}})}++/** A Desktop offset from a Client: finite pixels on each axis. */+function parseDesktopOffset(value: unknown): DesktopOffset {++ const offset = value as { x?: unknown, y?: unknown } | null++ if (typeof offset !== "object" || offset === null || !Number.isFinite(offset.x) || !Number.isFinite(offset.y)) throw new Error("A Desktop offset needs finite x and y")++ return { x: offset.x as number, y: offset.y as number }+}diff --git a/source/client/view/components/window-manager/window-geometry.ts b/source/client/view/components/window-manager/window-geometry.tsindex c444078..07fee66 100644--- a/source/client/view/components/window-manager/window-geometry.ts+++ b/source/client/view/components/window-manager/window-geometry.ts@@ -20,6 +20,41 @@ export interface WindowSurfaceSize {export const minimumWindowSize = Object.freeze({ width: 260, height: 160 })+/** The size the Desktop shows a standard Window at, in each dimension the System records as zero. */+export const presentedWindowSize = Object.freeze({ width: 520, height: 340 })++const shownSizes = new WeakMap<Size, Size>()++/**+ * A zero dimension is no size at all: the System records zero when nobody chose one. The Desktop shows its+ * own size there instead, and records nothing until the Window is resized.+ */+export function shownSize(size: Size): Size {++ const width = isZero(size.width) ? presentedWindowSize.width : size.width++ const height = isZero(size.height) ? presentedWindowSize.height : size.height++ if (width === size.width && height === size.height) return size++ const cached = shownSizes.get(size)++ if (cached) return cached++ const shown = { width, height }++ shownSizes.set(size, shown)++ return shown+}++function isZero(value: Value) {++ const { relative: share, pixels } = relative(value)++ return share === 0 && pixels === 0+}+/*** Every window type uses this same calculation inside the CSS containing* block supplied by its layer. Every expression is one relative coefficient@@ -45,17 +80,107 @@ export function absoluteWindowGeometry(position: Position, size: Size) {return [position.x, position.y, size.width, size.height].every(value => relative(value).relative === 0)}-/** Resolves one declarative Window geometry inside a measured surface. */+/**+ * Resolves one declarative Window geometry inside a measured surface. A+ * position is the Window's top-left corner on a plane whose zero is the center+ * of the surface its layer provides; the region it returns is measured from+ * the surface's top-left corner, where the Desktop paints it.+ */export function resolveWindowGeometry(position: Position, size: Size, surface: WindowSurfaceSize): WindowRegion {return {- x: pixels(position.x, surface.width),- y: pixels(position.y, surface.height),+ x: surface.width / 2 + pixels(position.x, surface.width),+ y: surface.height / 2 + pixels(position.y, surface.height),width: pixels(size.width, surface.width),height: pixels(size.height, surface.height)}}+/** How many whole views the plane of standard Windows reaches from its center, in each direction. */+export const planeReach = 2++/** The largest a standard Window is shown, in views, in each dimension. */+export const largestWindowViews = 2++const boundedGeometries = new WeakMap<Position, { size: Size, surface: WindowSurfaceSize, bounded: { position: Position, size: Size } }>()++/**+ * The Desktop shows standard Windows only on its plane, which reaches two views from the center in each+ * direction, and no larger than two views in each dimension. A Window recorded beyond the plane is shown+ * at its edge, and one recorded larger is shown at that size; what the System records stays as it is,+ * until the Window is moved or resized here.+ */+export function boundedGeometry(position: Position, size: Size, surface: WindowSurfaceSize): { position: Position, size: Size } {++ if (!surface.width || !surface.height) return { position, size }++ const cached = boundedGeometries.get(position)++ if (cached && cached.size === size && cached.surface.width === surface.width && cached.surface.height === surface.height) return cached.bounded++ const width = pixels(size.width, surface.width)++ const height = pixels(size.height, surface.height)++ const shownWidth = Math.min(width, surface.width * largestWindowViews)++ const shownHeight = Math.min(height, surface.height * largestWindowViews)++ const x = pixels(position.x, surface.width)++ const y = pixels(position.y, surface.height)++ const edge = { x: surface.width * (planeReach + 0.5), y: surface.height * (planeReach + 0.5) }++ const shownX = Math.min(Math.max(x, -edge.x), edge.x - shownWidth)++ const shownY = Math.min(Math.max(y, -edge.y), edge.y - shownHeight)++ const bounded = {+ position: shownX === x && shownY === y ? position : { x: Math.round(shownX), y: Math.round(shownY) },+ size: shownWidth === width && shownHeight === height ? size : { width: Math.round(shownWidth), height: Math.round(shownHeight) }+ }++ boundedGeometries.set(position, { size, surface: { ...surface }, bounded })++ return bounded+}++/** How far this Desktop's view is moved across the plane. Positions it shows are the plane's minus it. */+export interface ViewportOffset {++ x: number++ y: number+}++/** Moves a position by pixels, keeping any share of the surface it names: `"-1/2"` moved by 100 is `"-50% + 100"`. */+export function shiftPosition(position: Position, by: ViewportOffset): Position {++ if (by.x === 0 && by.y === 0) return position++ return { x: shiftValue(position.x, by.x), y: shiftValue(position.y, by.y) }+}++function shiftValue(value: Value, by: number): Value {++ if (by === 0) return value++ const { relative: share, pixels } = relative(value)++ const moved = pixels + by++ if (share === 0) return moved++ return `${share * 100}% ${moved < 0 ? "-" : "+"} ${Math.abs(moved)}`+}++/** The inverse at the other end: a painted region's position on the plane, whose zero is the surface's center. */+export function planeGeometry(region: WindowRegion, surface: WindowSurfaceSize): WindowRegion {++ return { ...region, x: region.x - surface.width / 2, y: region.y - surface.height / 2 }+}+/*** Applies a presentation-owned minimum without rewriting authoritative values.* A smaller workspace is the only case where the Desktop cannot provide it.@@ -76,9 +201,9 @@ export function constrainWindowGeometry(region: WindowRegion, surface: WindowSur*/export function windowPaintInsets(position: Position, size: Size, surface: WindowSurfaceSize, inset: number, current?: WindowRegion) {- const x = current?.x ?? pixels(position.x, surface.width)+ const x = current?.x ?? surface.width / 2 + pixels(position.x, surface.width)- const y = current?.y ?? pixels(position.y, surface.height)+ const y = current?.y ?? surface.height / 2 + pixels(position.y, surface.height)const width = current?.width ?? pixels(size.width, surface.width)@@ -107,7 +232,8 @@ function startsAtBoundary(value: Value, resolved: number, span: number) {if (span) return closeTo(resolved, 0)- return equal(value, 0, 0)+ // Without a measured span, the surface's first edge is half of it before the center.+ return equal(value, -0.5, 0)}function endsAtBoundary(position: Value, size: Value, resolvedPosition: number, resolvedSize: number, span: number) {@@ -118,7 +244,7 @@ function endsAtBoundary(position: Value, size: Value, resolvedPosition: number,const second = relative(size)- return same(first.relative + second.relative, 1) && closeTo(first.pixels + second.pixels, 0)+ return same(first.relative + second.relative, 0.5) && closeTo(first.pixels + second.pixels, 0)}function closeTo(value: number, boundary: number) {diff --git a/source/client/view/components/window-manager/window-presentations.ts b/source/client/view/components/window-manager/window-presentations.tsindex 43d369a..0900a0b 100644--- a/source/client/view/components/window-manager/window-presentations.ts+++ b/source/client/view/components/window-manager/window-presentations.ts@@ -373,8 +373,8 @@ function initialPresentationState(client: ClientState): PresentedWindow {title: window.title,header: false,surface: false,- position: { x: 0, y: 0 },- size: { width: "100%", height: "100%" },+ position: { x: "-1/2", y: "-1/2" },+ size: { width: "1/1", height: "1/1" },minimized: false,maximized: true,interactive: true,diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsxindex 51cfea5..3eff738 100644--- a/source/client/view/structure/desktop/desktop.tsx+++ b/source/client/view/structure/desktop/desktop.tsx@@ -1,5 +1,4 @@-import { type Layer } from "@phreshos/core"-import { useCallback, useEffect, useRef, useState } from "react"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { ApplicationContext, AuthManagerContext, LinkManagerContext } from "../../contexts"import useClientHost from "../../components/desktop-host/client-host"import DesktopLayers from "./layers/desktop-layers"@@ -18,6 +17,11 @@ import { usePreferences, useThemedValue } from "@phreshos/react-ui"import { useProperty } from "@the-link/react"import SharedResizeBoundaries from "./windows/shared-resize-boundaries"import { programsRequirement } from "../readiness-requirements"+import { LaunchPlacementContext, type LaunchPlacement } from "./launch-placement"+import { boundedGeometry, planeGeometry, resolveWindowGeometry, shiftPosition, shownSize, type WindowRegion } from "@client/view/components/window-manager/window-geometry"+import { type MappedWindow } from "./layers/shell/taskbar/viewport/viewport-control"+import type Process from "@client/core/link-manager/auth-manager/process-manager/process"+import { type Layer, type Position, type Size } from "@phreshos/core"export default function Workspace() {@@ -67,7 +71,37 @@ 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.presentation)+ const { windowSurfaceRef, windowSurfaceSize, viewport, frame, frameLoaded } = useClientHost(authManager, desktop, sources.current, windows.presentation)++ // Standard Windows are shown moved by this Desktop's offset, and what is done to them is recorded+ // moved back. Nothing else knows it: a Window works only in what it shows.+ const { offset } = viewport++ const back = { x: offset.x, y: offset.y }++ // A Window rerenders only when what it shows changes: each position keeps one shown form per offset.+ const shownPositions = useMemo(() => new WeakMap<Position, Position>(), [offset.x, offset.y])++ function shownPosition(position: Position) {++ const cached = shownPositions.get(position)++ if (cached) return cached++ const shown = shiftPosition(position, { x: -offset.x, y: -offset.y })++ shownPositions.set(position, shown)++ return shown+ }++ const move = useCallback((record: Process, x: number, y: number) => windows.move(record, x + back.x, y + back.y), [windows.move, back.x, back.y])++ const resize = useCallback((record: Process, width: number, height: number, position: { x: number, y: number } | null) => windows.resize(record, width, height, position && { x: position.x + back.x, y: position.y + back.y }), [windows.resize, back.x, back.y])++ const snap = useCallback((record: Process, position: Position, size: Size) => windows.snap(record, shiftPosition(position, back), size), [windows.snap, back.x, back.y])++ const commitSharedResize = useCallback((geometries: ReadonlyMap<string, WindowRegion>) => windows.sharedResize.commit(new Map([...geometries].map(([identity, region]) => [identity, { ...region, x: region.x + back.x, y: region.y + back.y }]))), [windows.sharedResize.commit, back.x, back.y])const fileWallpaperLoaded = useCallback(() => {@@ -109,7 +143,11 @@ export default function Workspace() {function renderWindows(layer: Layer) {- return windows.panesByLayer[layer].map(({ identity, record, client, presentation, closing, entering, stopping }) => <ProcessWindow+ return windows.panesByLayer[layer].map(({ identity, record, client, presentation, closing, entering, stopping }) => {++ const bounded = boundedGeometry(presentation.position, shownSize(presentation.size), windowSurfaceSize)++ return <ProcessWindowkey={identity}@@ -131,9 +169,9 @@ export default function Workspace() {icon={icon(record)}- position={presentation.position}+ position={presentation.layer === "window" ? shownPosition(bounded.position) : presentation.position}- size={presentation.size}+ size={presentation.layer === "window" ? bounded.size : presentation.size}taskbarPosition={appearance.taskbar.position}@@ -195,17 +233,82 @@ export default function Workspace() {onUnavailable={focus.unavailable}- onMove={windows.move}+ onMove={move}- onResize={windows.resize}+ onResize={resize}- onSnap={windows.snap}+ onSnap={snap}- />)+ />+ })}const taskbarOrientation = appearance.taskbar.position === "top" || appearance.taskbar.position === "bottom" ? "horizontal" : "vertical"+ // Each standard Window where it is on the plane, for the map of views.+ const mappedWindows: MappedWindow[] = windowSurfaceSize.width && windowSurfaceSize.height+ ? windows.panesByLayer.window.filter(pane => !pane.presentation.minimized).map(({ identity, record, presentation }) => {++ const shown = boundedGeometry(presentation.position, shownSize(presentation.size), windowSurfaceSize)++ const region = planeGeometry(resolveWindowGeometry(shown.position, shown.size, windowSurfaceSize), windowSurfaceSize)++ return {+ identity,+ title: presentation.title,+ icon: icon(record),+ region,+ front: fronts.window?.identity === record.identity,+ show: () => show(record),+ close: () => focus.close(record),+ moveTo: center => void windows.move(record, Math.round(center.x - region.width / 2), Math.round(center.y - region.height / 2))+ }+ })+ : []++ // A Window launched from this Desktop opens centered in what it shows, each one stepped a little from+ // the Windows already in view, so none lands exactly on another.+ const place = useCallback(function (size: Size | null): Position {++ const shown = resolveWindowGeometry({ x: 0, y: 0 }, shownSize(size ?? { width: 0, height: 0 }), windowSurfaceSize)++ const inView = mappedWindows.filter(({ region }) =>+ Math.abs(region.x + region.width / 2 - offset.x) < windowSurfaceSize.width / 2 &&+ Math.abs(region.y + region.height / 2 - offset.y) < windowSurfaceSize.height / 2).length++ const step = inView % 8 * appearance.spacing * 2++ return { x: Math.round(offset.x - shown.width / 2 + step), y: Math.round(offset.y - shown.height / 2 + step) }++ }, [mappedWindows, offset.x, offset.y, windowSurfaceSize, appearance.spacing])++ /** Centers the view on a Window at this position and size, as the Desktop shows it. */+ const reveal = useCallback(function (position: Position, size: Size | null) {++ if (!windowSurfaceSize.width || !windowSurfaceSize.height) return++ const shown = boundedGeometry(position, shownSize(size ?? { width: 0, height: 0 }), windowSurfaceSize)++ const region = planeGeometry(resolveWindowGeometry(shown.position, shown.size, windowSurfaceSize), windowSurfaceSize)++ viewport.place({ x: region.x + region.width / 2, y: region.y + region.height / 2 })++ }, [windowSurfaceSize, viewport.place])++ const launchPlacement = useMemo<LaunchPlacement>(() => ({ place, reveal }), [place, reveal])++ // Pressing a Window in the Taskbar brings the view to it, so it is in the middle, whether it was+ // minimized or only out of view. A maximized Window fills every view, so the view stays.+ const show = useCallback(function (record: Process) {++ const window = windows.presentation.projection(record.identity)++ if (window.layer === "window" && !window.maximized) reveal(window.position, window.size)++ windows.show(record)++ }, [windows.presentation, windows.show, reveal])+const taskbarItems = <OverflowRoworientation={taskbarOrientation}className="h-full w-full"@@ -215,8 +318,8 @@ export default function Workspace() {>{/* What a press means is composed here because it is a person's- expectation, not a system operation: the front window hides;- another window is shown and brought forward. */}+ expectation, not a system operation: the view goes to the Window,+ which is shown and brought forward. */}{windows.listed.map(record => {const window = windows.presentation.projection(record.identity)@@ -243,7 +346,7 @@ export default function Workspace() {onMinimize={focus.minimize}- onShow={windows.show}+ onShow={show}onFill={windows.fill}@@ -260,7 +363,9 @@ export default function Workspace() {const shell = hasShellClient? renderWindows("shell")- : <DefaultShell spacing={appearance.spacing} taskbar={appearance.taskbar}>{taskbarItems}</DefaultShell>+ : <LaunchPlacementContext.Provider value={launchPlacement}>+ <DefaultShell spacing={appearance.spacing} taskbar={appearance.taskbar} viewport={viewport} mappedWindows={mappedWindows}>{taskbarItems}</DefaultShell>+ </LaunchPlacementContext.Provider>return <div ref={desktop} tabIndex={-1} aria-label="Desktop" onFocusCapture={focus.remember} className="relative isolate h-full min-h-0 w-full overflow-hidden outline-none" style={{ color: foreground }}>@@ -274,7 +379,7 @@ export default function Workspace() {windows={renderWindows("window")}- sharedResizeBoundaries={<SharedResizeBoundaries {...windows.sharedResize} />}+ sharedResizeBoundaries={<SharedResizeBoundaries {...windows.sharedResize} commit={commitSharedResize} />}overWindows={renderWindows("over")}diff --git a/source/client/view/structure/desktop/launch-placement.ts b/source/client/view/structure/desktop/launch-placement.tsnew file mode 100644index 0000000..ef8a992--- /dev/null+++ b/source/client/view/structure/desktop/launch-placement.ts@@ -0,0 +1,22 @@+import { createContext, useContext } from "react"+import { type Position, type Size } from "@phreshos/core"++/**+ * How this Desktop places what it launches. The Desktop answers from what it shows; the System only+ * records what it is asked.+ */+export interface LaunchPlacement {++ /** Where a new Window should appear, given the size its Program declares, or `null` without one. */+ place(size: Size | null): Position++ /** Moves the view so a Window at this position and size is at its center. */+ reveal(position: Position, size: Size | null): void+}++export const LaunchPlacementContext = createContext<LaunchPlacement>({ place: () => ({ x: 0, y: 0 }), reveal: () => undefined })++export function useLaunchPlacement() {++ return useContext(LaunchPlacementContext)+}diff --git a/source/client/view/structure/desktop/layers/shell/default-shell.tsx b/source/client/view/structure/desktop/layers/shell/default-shell.tsxindex 3dab300..9ceebd7 100644--- a/source/client/view/structure/desktop/layers/shell/default-shell.tsx+++ b/source/client/view/structure/desktop/layers/shell/default-shell.tsx@@ -1,15 +1,19 @@import { type AppearanceTaskbar } from "@phreshos/core"-import { type ReactNode } from "react"+import { useState, type ReactNode } from "react"import SystemErrors from "./dialogs/system-errors"import PermissionRequests from "./dialogs/permission-requests"import StartMenu, { StartMenuButton, StartMenuProvider, useStartMenuOpen } from "./start-menu/start-menu"import SignOut from "./taskbar/sign-out"import Taskbar from "./taskbar/taskbar"+import ViewportControl, { type MappedWindow } from "./taskbar/viewport/viewport-control"+import { type ViewportControl as Viewport } from "../../viewport-offset"/** Built-in Shell entities composed as siblings in the complete Shell layer. */-export default function DefaultShell({ spacing, taskbar, children }: Readonly<{+export default function DefaultShell({ spacing, taskbar, viewport, mappedWindows, children }: Readonly<{spacing: numbertaskbar: AppearanceTaskbar+ viewport: Viewport+ mappedWindows: readonly MappedWindow[]children: ReactNode}>) {@@ -19,7 +23,7 @@ export default function DefaultShell({ spacing, taskbar, children }: Readonly<{<StartMenuProvider spacing={spacing} taskbar={taskbar}>- <DefaultTaskbar spacing={spacing} taskbar={taskbar} horizontal={horizontal}>+ <DefaultTaskbar spacing={spacing} taskbar={taskbar} viewport={viewport} mappedWindows={mappedWindows} horizontal={horizontal}>{children}</DefaultTaskbar>@@ -34,20 +38,25 @@ export default function DefaultShell({ spacing, taskbar, children }: Readonly<{</>}-function DefaultTaskbar({ spacing, taskbar, horizontal, children }: Readonly<{+function DefaultTaskbar({ spacing, taskbar, viewport, mappedWindows, horizontal, children }: Readonly<{spacing: numbertaskbar: AppearanceTaskbar+ viewport: Viewport+ mappedWindows: readonly MappedWindow[]horizontal: booleanchildren: ReactNode}>) {const startMenuOpen = useStartMenuOpen()+ const [mapOpen, setMapOpen] = useState(false)+return <Taskbarleading={<StartMenuButton showLabel={horizontal} />}+ navigation={<ViewportControl viewport={viewport} windows={mappedWindows} taskbar={taskbar} spacing={spacing} onOpenChange={setMapOpen} />}trailing={<SignOut showLabel={horizontal} />}spacing={spacing}taskbar={taskbar}- keepVisible={startMenuOpen}+ keepVisible={startMenuOpen || mapOpen}>{children}</Taskbar>diff --git a/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx b/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsxindex 7edaaf4..c6312f9 100644--- a/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx+++ b/source/client/view/structure/desktop/layers/shell/dialogs/permission-requests.tsx@@ -88,6 +88,7 @@ const permissionPresentation = {logs: { title: "System logs", description: "Read and follow records produced by the System." },appearance: { title: "Appearance", description: "Change the System Appearance." },desktopPreferences: { title: "Desktop preferences", description: "Change this Desktop's preferences." },+ desktopViewport: { title: "Desktop view", description: "Move where this Desktop looks on the plane of Windows." },desktopConnection: { title: "Desktop connection", description: "Access the browser Connection carrying this Desktop and its Session." },authentication: { title: "Authentication", description: "Access and manage owner authentication, browser Connections, and Sessions." }} satisfies Record<PermissionName, Readonly<{ title: string, description: string }>>diff --git a/source/client/view/structure/desktop/layers/shell/start-menu/processes/processes.tsx b/source/client/view/structure/desktop/layers/shell/start-menu/processes/processes.tsxindex 2867bf9..47a4a55 100644--- a/source/client/view/structure/desktop/layers/shell/start-menu/processes/processes.tsx+++ b/source/client/view/structure/desktop/layers/shell/start-menu/processes/processes.tsx@@ -29,9 +29,11 @@ export default function Processes({ terms }: Readonly<{ terms: readonly string[]return <Section label="Processes" count={matching.length} empty={terms.length ? "No matching Processes" : "No Processes"}>{/* A fixed layout keeps the table in its well: a long Process name is cut short instead of widening it. */}- <Table aria-label="Processes" size="small" style={{ minWidth: 0, tableLayout: "fixed" }}>+ {/* Without a heading, the first row has nothing above it to be set apart from. */}+ <Table aria-label="Processes" size="small" className="[&_tbody>tr:first-child>*]:!border-t-0" style={{ minWidth: 0, tableLayout: "fixed" }}>- <Table.Header>+ {/* The columns stay for their widths and names, but the rows need no heading: each row says what it is. */}+ <Table.Header style={{ visibility: "collapse" }}><Table.Column id="process" rowHeader>Process</Table.Column><Table.Column id="endpoints" style={{ width: space.xlarge * 5 }}>Running</Table.Column><Table.Column id="end" aria-label="End" style={{ width: space.xlarge * 2 }}> </Table.Column>diff --git a/source/client/view/structure/desktop/layers/shell/start-menu/programs/programs.tsx b/source/client/view/structure/desktop/layers/shell/start-menu/programs/programs.tsxindex 6d42424..f47f577 100644--- a/source/client/view/structure/desktop/layers/shell/start-menu/programs/programs.tsx+++ b/source/client/view/structure/desktop/layers/shell/start-menu/programs/programs.tsx@@ -6,9 +6,10 @@ import Program from "@client/core/link-manager/auth-manager/program-manager/progimport usePromise from "@libs/react-promise"import Alert from "@client/view/components/alert"import { matchesProgram } from "../search"+import { useLaunchPlacement } from "@client/view/structure/desktop/launch-placement"import Section from "../section"import { categorized, CategoryHeading } from "./categories"-import { Fragment } from "react"+import { Fragment, useRef } from "react"interface ProgramsProps {@@ -49,11 +50,26 @@ export default function Programs({ onChoose, terms }: ProgramsProps) {function ProgramItem({ icon, record, onChoose }: { icon: string, record: Program, onChoose: () => void }) {+ // Read when the launch happens, not when this item first rendered: the view may have moved since.+ const currentPlacement = useLaunchPlacement()++ const placement = useRef(currentPlacement)++ placement.current = currentPlacement++ // A Program that declares where its Window goes keeps it; otherwise the Window opens where this Desktop looks.const launch = usePromise(async function () {onChoose()- await record.open()+ const declared = record.client?.position ?? null++ const size = record.client?.size ?? null++ // A Window that opens where its Program declares is brought into view.+ if (declared) placement.current.reveal(declared, size)++ await record.createProcess(declared ? {} : { client: { position: placement.current.place(size) } })})return <>diff --git a/source/client/view/structure/desktop/layers/shell/taskbar/programs/window-taskbar-item.tsx b/source/client/view/structure/desktop/layers/shell/taskbar/programs/window-taskbar-item.tsxindex e87a39d..362c81f 100644--- a/source/client/view/structure/desktop/layers/shell/taskbar/programs/window-taskbar-item.tsx+++ b/source/client/view/structure/desktop/layers/shell/taskbar/programs/window-taskbar-item.tsx@@ -1,6 +1,7 @@import Process from "@client/core/link-manager/auth-manager/process-manager/process"import { type TaskbarPosition } from "@phreshos/core"import { ContextMenu, Menu } from "@phreshos/react-ui"+import { ArrowDownLeft, ArrowUpRight, Maximize2, Minimize2, X } from "@phreshos/react-ui/icons"import { useDesktopScaleContainer } from "../../../../desktop-scale"import TaskbarItem from "./taskbar-item"import { memo, useCallback } from "react"@@ -10,13 +11,7 @@ export default memo(function ({ record, title, icon, position, active, minimizedconst scaleContainer = useDesktopScaleContainer()- const press = useCallback(function () {-- if (active) onMinimize(record, true)-- else onShow(record)-- }, [active, onMinimize, onShow, record])+ const press = useCallback(() => onShow(record), [onShow, record])const source = useCallback((element: HTMLButtonElement | null) => onElement(record, element), [onElement, record])const changeVisibility = useCallback(() => {@@ -49,13 +44,14 @@ export default memo(function ({ record, title, icon, position, active, minimizedelse if (action === "close") close()}}>- <Menu.Item id="visibility">{minimized ? "Show" : "Minimize"}</Menu.Item>+ {/* The icons are the Window's own title bar controls. */}+ <Menu.Item id="visibility" textValue={minimized ? "Show" : "Minimize"}>{minimized ? <><ArrowUpRight aria-hidden />Show</> : <><ArrowDownLeft aria-hidden />Minimize</>}</Menu.Item>- <Menu.Item id="fill">{maximized ? "Restore" : "Maximize"}</Menu.Item>+ <Menu.Item id="fill" textValue={maximized ? "Restore" : "Maximize"}>{maximized ? <><Minimize2 aria-hidden />Restore</> : <><Maximize2 aria-hidden />Maximize</>}</Menu.Item><Menu.Separator />- <Menu.Item id="close" color="danger">Close</Menu.Item>+ <Menu.Item id="close" color="danger" textValue="Close"><X aria-hidden />Close</Menu.Item></Menu>diff --git a/source/client/view/structure/desktop/layers/shell/taskbar/taskbar.tsx b/source/client/view/structure/desktop/layers/shell/taskbar/taskbar.tsxindex 4355de0..c145b06 100644--- a/source/client/view/structure/desktop/layers/shell/taskbar/taskbar.tsx+++ b/source/client/view/structure/desktop/layers/shell/taskbar/taskbar.tsx@@ -8,7 +8,7 @@ import { cssEasing } from "@client/view/appearance/motion"* The Desktop's Taskbar is a Shell entity; React UI's Toolbar supplies the* control-group semantics and orientation-aware keyboard navigation.*/-export default function Taskbar({ leading, trailing, taskbar, spacing, keepVisible = false, className, style, children, onPointerEnter, "aria-label": label = "Taskbar", ...props }: TaskbarProps) {+export default function Taskbar({ leading, navigation, trailing, taskbar, spacing, keepVisible = false, className, style, children, onPointerEnter, "aria-label": label = "Taskbar", ...props }: TaskbarProps) {const horizontal = taskbar.position === "top" || taskbar.position === "bottom"const orientation = horizontal ? "horizontal" : "vertical"@@ -82,6 +82,12 @@ export default function Taskbar({ leading, trailing, taskbar, spacing, keepVisib<Toolbar.Separator className="shadow-taskbar-separator" />+ {/* Where this Desktop looks, between what starts Programs and the Windows they open. */}+ {navigation && <>+ <Toolbar.Group style={{ flexShrink: 0 }}>{navigation}</Toolbar.Group>+ <Toolbar.Separator className="shadow-taskbar-separator" />+ </>}+<Toolbar.Group style={{ flex: "1 1 0", alignSelf: "stretch", minWidth: 0, minHeight: 0, overflow: "hidden" }}>{children}@@ -103,6 +109,9 @@ interface TaskbarProps extends Omit<SurfaceProps<typeof Toolbar>, "as" | "childrleading: ReactNode+ /** Where this Desktop looks on the plane of standard Windows, between the leading items and the Windows. */+ navigation?: ReactNode+trailing: ReactNodetaskbar: AppearanceTaskbardiff --git a/source/client/view/structure/desktop/layers/shell/taskbar/viewport/viewport-control.tsx b/source/client/view/structure/desktop/layers/shell/taskbar/viewport/viewport-control.tsxnew file mode 100644index 0000000..b7ef734--- /dev/null+++ b/source/client/view/structure/desktop/layers/shell/taskbar/viewport/viewport-control.tsx@@ -0,0 +1,434 @@+import { Button, ContextMenu, Menu, Panel, Surface, Text, useAppearance, useColor, useScale } from "@phreshos/react-ui"+import { LocateFixed, Map as MapIcon, X } from "@phreshos/react-ui/icons"+import { useCallback, useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react"+import { planeReach, type WindowRegion } from "@client/view/components/window-manager/window-geometry"+import { type AppearanceTaskbar } from "@phreshos/core"+import { useReducedMotion } from "@libs/react-motion"+import { motion } from "motion/react"+import { cssEasing } from "@client/view/appearance/motion"+import { surfaceLifecyclePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"+import { shellSurfaceClassName } from "../../shell-surface"+import { wellMaterial } from "../../start-menu/start-menu-panel"+import { type ViewportControl as Viewport } from "../../../../viewport-offset"++/** A standard Window as the map shows it: where it is on the plane. */+export interface MappedWindow {++ identity: string++ title: string++ icon: string++ /** Its top-left corner and size on the plane, whose zero is the center. */+ region: WindowRegion++ /** Whether it is the front Window. */+ front: boolean++ /** Brings the view to the Window and the Window to the front. */+ show(): void++ /** Closes the Window, which exits its Process. */+ close(): void++ /** Moves the Window so its center is at this point of the plane. */+ moveTo(center: { x: number, y: number }): void+}++/**+ * One Taskbar button for where this Desktop looks on the plane of standard+ * Windows. It names the current view when it is not the center, and opens a+ * map of the plane: a grid of whole views, a frame for the view itself+ * above them, and the Windows above both. Choosing a view moves there; dragging the frame+ * moves the view anywhere.+ *+ * The map opens and closes as the Start Menu does: a native popover, which the+ * browser closes when something else on the Desktop is pressed, and which closes+ * itself when focus crosses into a Program frame; either way the press goes on+ * to what it was meant for.+ */+export default function ViewportControl({ viewport, windows, taskbar, spacing, onOpenChange }: Readonly<{+ viewport: Viewport+ windows: readonly MappedWindow[]+ taskbar: AppearanceTaskbar+ spacing: number+ onOpenChange: (open: boolean) => void+}>) {++ const id = useId()++ const trigger = useRef<HTMLButtonElement>(null)++ const surface = useRef<HTMLDivElement>(null)++ const [open, setOpen] = useState(false)++ // Where the map opens, measured from the button when it opens.+ const [anchor, setAnchor] = useState<CSSProperties>({})++ const openAtPressStart = useRef(false)++ const reducedMotion = useReducedMotion()++ const transaction = useAppearance().transaction++ const vertical = taskbar.position === "left" || taskbar.position === "right"++ const centered = viewport.offset.x === 0 && viewport.offset.y === 0++ const place = `${viewport.view.x}, ${viewport.view.y}`++ const close = useCallback(function () {++ if (surface.current?.matches(":popover-open")) surface.current.hidePopover()++ }, [])++ useEffect(function () {++ // Program frames are separate documents, so focus crossing into one is what closes the map there.+ function closeForProgramFrame() {++ if (document.activeElement instanceof HTMLIFrameElement && !surface.current?.contains(document.activeElement)) close()+ }++ window.addEventListener("blur", closeForProgramFrame)++ return () => window.removeEventListener("blur", closeForProgramFrame)++ }, [close])++ function toggle() {++ const element = surface.current++ if (!element || !trigger.current) return++ // A press on the button while the map is open already closed it.+ if (openAtPressStart.current) return close()++ setAnchor(anchorStyle(trigger.current, taskbar, spacing))++ element.showPopover()+ }++ return <>++ <Button ref={trigger} size="small" iconOnly={centered || vertical} color={centered ? undefined : "primary:soft"}+ aria-label={centered ? "Map" : `Map, near ${place}`} aria-controls={id} aria-expanded={open} aria-haspopup="dialog"+ onPressStart={() => { openAtPressStart.current = surface.current?.matches(":popover-open") ?? false }}+ onPress={toggle}>+ <MapIcon />{!centered && !vertical && <span className="tabular-nums">{place}</span>}+ </Button>++ <motion.div+ ref={surface}+ id={id}+ role="dialog"+ popover="auto"+ aria-labelledby={`${id}-label`}+ tabIndex={-1}+ className={`${shellSurfaceClassName} pointer-events-auto fixed hidden open:block`}+ style={{+ ...anchor,+ transitionBehavior: "allow-discrete",+ transitionDuration: reducedMotion ? "0ms" : String(transaction.duration) + "ms",+ transitionTimingFunction: cssEasing(transaction.easing),+ transitionProperty: "display, overlay"+ }}+ initial={false}+ animate={open ? surfaceLifecyclePose.visible : surfaceLifecyclePose.hidden}+ transition={surfacePresenceTransition(reducedMotion, transaction)}+ onBeforeToggle={event => { setOpen(event.newState === "open"); onOpenChange(event.newState === "open") }}+ onToggle={event => { if (event.newState === "open") event.currentTarget.focus() }}+ >++ {/* Always drawn, like the Start Menu, so it leaves as it came. */}+ <Panel><ViewMap labelId={`${id}-label`} viewport={viewport} windows={windows} centered={centered} menus={surface.current} /></Panel>++ </motion.div>++ </>+}++/**+ * Like the Start Menu, the map opens two spacings beyond the Taskbar's edge, starting where the button+ * starts. Taskbar positions name physical screen edges, so every inset stays physical.+ */+function anchorStyle(button: HTMLElement, taskbar: AppearanceTaskbar, spacing: number): CSSProperties {++ // The Desktop's scale preference enlarges what it shows; fixed insets are counted before it.+ const rectangle = button.getBoundingClientRect()++ const scale = button.offsetWidth ? rectangle.width / button.offsetWidth : 1++ const inset = taskbar.size + spacing * 2++ const style = { position: "fixed", top: "auto", right: "auto", bottom: "auto", left: "auto", margin: 0 } satisfies CSSProperties++ if (taskbar.position === "bottom") return { ...style, left: rectangle.left / scale, bottom: inset }++ if (taskbar.position === "top") return { ...style, left: rectangle.left / scale, top: inset }++ if (taskbar.position === "left") return { ...style, left: inset, top: rectangle.top / scale }++ return { ...style, right: inset, top: rectangle.top / scale }+}++/** `menus` is the map's own surface: menus open inside it, since the map is above everything else on the page. */+function ViewMap({ labelId, viewport, windows, centered, menus }: Readonly<{ labelId: string, viewport: Viewport, windows: readonly MappedWindow[], centered: boolean, menus: HTMLElement | null }>) {++ const space = useScale(useAppearance().spacing)++ // The lines between views, as faint as React UI's separators.+ const line = `color-mix(in oklab, ${useColor("foreground").base} 10%, transparent)`++ const { surface } = viewport++ // One view on the map: its width from the spacing, its height in the view's own proportion, both whole pixels so the lines between views stay even.+ const cell = { width: Math.round(space.xlarge * 3.25), height: Math.round(space.xlarge * 3.25 * surface.height / surface.width) }++ const columns = range.maxX - range.minX + 1++ const rows = range.maxY - range.minY + 1++ /** Where a point of the plane falls on the map. */+ const mapX = (planeX: number) => (planeX / surface.width + 0.5 - range.minX) * cell.width++ const mapY = (planeY: number) => (planeY / surface.height + 0.5 - range.minY) * cell.height++ const drag = useRef<{ pointer: { x: number, y: number }, offset: { x: number, y: number }, scale: number } | null>(null)++ // The Window whose title shows, by pointer or focus.+ const [named, setNamed] = useState<MappedWindow | null>(null)++ function grab(event: ReactPointerEvent<HTMLDivElement>) {++ event.currentTarget.setPointerCapture(event.pointerId)++ drag.current = { pointer: { x: event.clientX, y: event.clientY }, offset: viewport.offset, scale: shownScale(event.currentTarget) }+ }++ function follow(event: ReactPointerEvent<HTMLDivElement>) {++ const started = drag.current++ if (!started) return++ // The frame stays on the map: its center goes no further than the outer views' centers.+ viewport.place({+ x: clamp(started.offset.x + (event.clientX - started.pointer.x) / started.scale / cell.width * surface.width, range.minX * surface.width, range.maxX * surface.width),+ y: clamp(started.offset.y + (event.clientY - started.pointer.y) / started.scale / cell.height * surface.height, range.minY * surface.height, range.maxY * surface.height)+ })+ }++ // The panel is as wide as the map; its words wrap under it.+ return <div className="grid" style={{ gap: space.medium, padding: space.large, width: columns * cell.width, boxSizing: "content-box" }}>++ <Text id={labelId} size="medium" style={{ fontWeight: 500 }}>Map</Text>++ <div className="relative">++ {/* The plane, a well recessed into the Panel like the Start Menu's; views and Windows sit on it, and the frame above them. */}+ <Surface depth="recessed" color="background" material={wellMaterial} className="relative overflow-hidden" style={{ width: columns * cell.width, height: rows * cell.height }}>++ {/* One clear cell per view, so the well shows as it does in the Start Menu. */}+ <div className="absolute inset-0 grid" style={{ gridTemplateColumns: `repeat(${columns}, ${cell.width}px)`, gridTemplateRows: `repeat(${rows}, ${cell.height}px)` }}>++ {Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_, column) => {++ const view = { x: range.minX + column, y: range.minY + row }++ const inside = windows.filter(window => viewOf(window.region, surface).x === view.x && viewOf(window.region, surface).y === view.y)++ return <Button key={`${view.x},${view.y}`} size="small" depth="flat" color="transparent" radius={0}+ aria-label={`View ${view.x}, ${view.y}${inside.length ? `, ${inside.map(window => window.title).join(", ")}` : ""}`}+ style={{ width: "100%", height: "100%", paddingInline: 0 }}+ onPress={() => viewport.moveTo(view)} />+ }))}++ </div>++ {/* The lines between views: one at the end of each view, and one pixel short of the map, so the last is left out. */}+ <div aria-hidden="true" className="pointer-events-none absolute left-0 top-0" style={{+ width: columns * cell.width - 1,+ height: rows * cell.height - 1,+ backgroundImage: `linear-gradient(to right, transparent calc(100% - 1px), ${line} calc(100% - 1px)), linear-gradient(to bottom, transparent calc(100% - 1px), ${line} calc(100% - 1px))`,+ backgroundSize: `${cell.width}px 100%, 100% ${cell.height}px`+ }} />++ {/* The view itself, over the views and dragged anywhere on the map. */}+ <Surface aria-hidden="true" color="primary" material={{ opacity: 0.3, backdrop: 0 }} radius="small" className="cursor-grab touch-none active:cursor-grabbing"+ style={{ position: "absolute", left: mapX(viewport.offset.x) - cell.width / 2, top: mapY(viewport.offset.y) - cell.height / 2, width: cell.width, height: cell.height }}+ onPointerDown={grab} onPointerMove={follow} onPointerUp={() => { drag.current = null }} onPointerCancel={() => { drag.current = null }} />++ {/* The Windows above everything, since they are dragged too. */}+ {windows.map(window => <MapWindow key={window.identity} window={window} viewport={viewport} menus={menus} onName={setNamed} mapX={mapX} mapY={mapY} cell={cell} />)}++ </Surface>++ {/* A Window's title above its card; outside the plane, so its edges do not cut it. */}+ {named && <Surface aria-hidden="true" color="foreground" radius="small" className="pointer-events-none absolute whitespace-nowrap"+ style={{ position: "absolute", left: mapX(named.region.x + named.region.width / 2), top: mapY(named.region.y + named.region.height / 2) - space.medium, transform: "translate(-50%, -100%)", paddingBlock: space.xsmall, paddingInline: space.small }}>+ <Text size="xsmall">{named.title}</Text>+ </Surface>}++ </div>++ <div className="flex items-center justify-between" style={{ gap: space.medium }}>++ <Text size="xsmall" tone="secondary">Choose a view or a Window, drag the frame, or drag a Window to move it.</Text>++ <Button size="small" disabled={centered} onPress={viewport.home}>Center</Button>++ </div>++ </div>+}++/**+ * A Window on the map: a small card around its icon where the Window's center is, in a light tint+ * of the secondary color like the Start Menu's cards, and in the primary color when it is the front+ * Window. Its title shows on hover and focus. Pressing it, or Go to in its menu, brings the view to the Window and the Window to the front; Close in its menu closes the Window; dragging it moves the+ * Window anywhere on the map.+ */+function MapWindow({ window, viewport, menus, onName, mapX, mapY, cell }: Readonly<{+ window: MappedWindow+ viewport: Viewport+ menus: HTMLElement | null+ onName: (window: MappedWindow | null) => void+ mapX: (planeX: number) => number+ mapY: (planeY: number) => number+ cell: { width: number, height: number }+}>) {++ const space = useScale(useAppearance().spacing)++ const { surface } = viewport++ const center = { x: window.region.x + window.region.width / 2, y: window.region.y + window.region.height / 2 }++ // Where the card is while it is dragged, until the Window arrives there.+ const [dragged, setDragged] = useState<{ x: number, y: number } | null>(null)++ // A drag that has just ended is not also a press.+ const moved = useRef(false)++ useEffect(() => setDragged(null), [window.region.x, window.region.y])++ const shown = dragged ?? center++ const icon = space.medium + space.xsmall++ const card = icon + space.xsmall * 2++ // The card is a Button, which keeps its pointer events to itself, and the pointer soon leaves so small+ // a card; so the drag listens before the Button does, and then follows the pointer across the page.+ function down(event: ReactPointerEvent<HTMLDivElement>) {++ if (event.button !== 0) return++ const pointer = { x: event.clientX, y: event.clientY }++ const start = center++ const scale = shownScale(event.currentTarget)++ let last: { x: number, y: number } | null = null++ moved.current = false++ function move(event: PointerEvent) {++ const delta = { x: (event.clientX - pointer.x) / scale, y: (event.clientY - pointer.y) / scale }++ // It becomes a drag once the pointer leaves where it went down; until then it may be a press.+ if (!moved.current && Math.hypot(delta.x, delta.y) < space.xsmall) return++ if (!moved.current) onName(null)++ moved.current = true++ // The center stays inside the map's outer views; the Desktop keeps the whole Window on the plane.+ last = {+ x: clamp(start.x + delta.x / cell.width * surface.width, (range.minX - 0.5) * surface.width + 1, (range.maxX + 0.5) * surface.width - 1),+ y: clamp(start.y + delta.y / cell.height * surface.height, (range.minY - 0.5) * surface.height + 1, (range.maxY + 0.5) * surface.height - 1)+ }++ setDragged(last)+ }++ function end(event: PointerEvent) {++ removeEventListener("pointermove", move)+ removeEventListener("pointerup", end)+ removeEventListener("pointercancel", end)++ if (event.type === "pointerup" && last) window.moveTo(last)++ else setDragged(null)+ }++ addEventListener("pointermove", move)+ addEventListener("pointerup", end)+ addEventListener("pointercancel", end)+ }++ return <div className="absolute touch-none" onPointerDownCapture={down}+ style={{ left: mapX(shown.x) - card / 2, top: mapY(shown.y) - card / 2, width: card, height: card }}>++ <ContextMenu>++ <ContextMenu.Trigger>++ <Button size="xsmall" iconOnly depth="flat" color={window.front ? "primary:soft" : "secondary:subtle"} aria-label={window.title}+ onPress={() => { if (!moved.current) window.show() }}+ onHoverStart={() => onName(window)} onHoverEnd={() => onName(null)} onFocus={() => onName(window)} onBlur={() => onName(null)}+ style={{ width: card, height: card, paddingInline: 0 }}>+ <img src={window.icon} alt="" draggable={false} className="object-contain" style={{ width: icon, height: icon }} />+ </Button>++ </ContextMenu.Trigger>++ <ContextMenu.Content portalContainer={menus ?? undefined}>++ <Menu aria-label={`${window.title} window actions`} size="small" onAction={action => {+ if (action === "show") window.show()+ else if (action === "close") window.close()+ }}>++ <Menu.Item id="show" textValue="Go to"><LocateFixed aria-hidden />Go to</Menu.Item>++ <Menu.Separator />++ <Menu.Item id="close" color="danger" textValue="Close"><X aria-hidden />Close</Menu.Item>++ </Menu>++ </ContextMenu.Content>++ </ContextMenu>++ </div>+}++/** How much larger than its own pixels an element is shown: the Desktop's scale preference, which pointer distances include. */+function shownScale(element: HTMLElement) {++ return element.offsetWidth ? element.getBoundingClientRect().width / element.offsetWidth : 1+}++/** The whole view a region's center is in. */+function viewOf(region: WindowRegion, surface: { width: number, height: number }) {++ return { x: Math.round((region.x + region.width / 2) / surface.width), y: Math.round((region.y + region.height / 2) / surface.height) }+}++/** The whole plane: the views its reach covers on each side of the center. */+const range = { minX: -planeReach, maxX: planeReach, minY: -planeReach, maxY: planeReach }++function clamp(value: number, minimum: number, maximum: number) {++ return Math.min(maximum, Math.max(minimum, value))+}diff --git a/source/client/view/structure/desktop/viewport-offset.ts b/source/client/view/structure/desktop/viewport-offset.tsnew file mode 100644index 0000000..855c831--- /dev/null+++ b/source/client/view/structure/desktop/viewport-offset.ts@@ -0,0 +1,44 @@+import { useCallback, useState } from "react"+import { planeReach, type ViewportOffset, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"++/**+ * Where this Desktop looks on the plane of standard Windows: the point shown at+ * the center of its view. It belongs to this connection alone: it starts at zero+ * and is not stored.+ */+export default function useViewportOffset(surface: WindowSurfaceSize) {++ const [offset, setOffset] = useState<ViewportOffset>(origin)++ /** Moves the view to one whole view, counted from the plane's center. */+ const moveTo = useCallback(function (view: ViewportOffset) {++ if (!surface.width || !surface.height) return++ setOffset({ x: within(view.x, planeReach) * surface.width, y: within(view.y, planeReach) * surface.height })++ }, [surface.width, surface.height])++ /** Places the view at any point of the plane, not only whole views; its center stays over the plane's outer views. */+ const place = useCallback((point: ViewportOffset) => setOffset({+ x: Math.round(within(point.x, planeReach * surface.width)),+ y: Math.round(within(point.y, planeReach * surface.height))+ }), [surface.width, surface.height])++ /** Returns the view to the plane's center. */+ const home = useCallback(() => setOffset(origin), [])++ // The nearest whole view from the center, which is what a person counts.+ const view = { x: surface.width ? Math.round(offset.x / surface.width) : 0, y: surface.height ? Math.round(offset.y / surface.height) : 0 }++ return { offset, view, surface, moveTo, place, home }+}++export type ViewportControl = ReturnType<typeof useViewportOffset>++function within(value: number, reach: number) {++ return Math.min(reach, Math.max(-reach, value))+}++const origin: ViewportOffset = Object.freeze({ x: 0, y: 0 })diff --git a/source/client/view/structure/desktop/windows/shared-resize-boundaries.tsx b/source/client/view/structure/desktop/windows/shared-resize-boundaries.tsxindex 68f930a..09d6341 100644--- a/source/client/view/structure/desktop/windows/shared-resize-boundaries.tsx+++ b/source/client/view/structure/desktop/windows/shared-resize-boundaries.tsx@@ -1,6 +1,6 @@import { type PointerEvent as ReactPointerEvent, useState } from "react"import { resizeSharedBoundary, sharedResizeBoundaries, type SharedResizeBoundary, type SharedResizeWindow } from "@client/view/components/window-manager/shared-resize"-import { type WindowRegion } from "@client/view/components/window-manager/window-geometry"+import { planeGeometry, type WindowRegion } from "@client/view/components/window-manager/window-geometry"import { physicalToDesktopPixels, useDesktopScale } from "../desktop-scale"const thickness = 4@@ -82,7 +82,10 @@ export default function SharedResizeBoundaries({ windows, begin, present, commitpresent(result.geometries)- commit(result.geometries)+ // The System records each position from the center of the surface these boundaries divide.+ const surface = handle.closest<HTMLElement>("[data-window-surface]")+ const size = { width: surface?.clientWidth ?? 0, height: surface?.clientHeight ?? 0 }+ commit(new Map([...result.geometries].map(([identity, region]) => [identity, planeGeometry(region, size)])))finish(identities)}diff --git a/source/client/view/structure/desktop/windows/window.tsx b/source/client/view/structure/desktop/windows/window.tsxindex 31088de..6580db9 100644--- a/source/client/view/structure/desktop/windows/window.tsx+++ b/source/client/view/structure/desktop/windows/window.tsx@@ -2,7 +2,7 @@ import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useCallbaimport { useReducedMotion } from "@libs/react-motion"import { surfaceLifecyclePose, surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"import WindowPanel from "./window-panel"-import { absoluteWindowGeometry, constrainWindowGeometry, minimumWindowSize, resolveWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"+import { absoluteWindowGeometry, constrainWindowGeometry, minimumWindowSize, planeGeometry, resolveWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"import { type BeginWindowMoveGesture, type Position, type Size, type TaskbarPosition, type WindowPresentationSurface as WindowSurfaceDefinition, type WindowLayer } from "@phreshos/core"import WindowHeader from "./window-header"import WindowSurface, { windowSurfaceRadius } from "./window-surface"@@ -87,7 +87,7 @@ export default function ({ title, header = true, surface, layer, icon, children,// Hidden windows retain their last presentation while lower-priority state changes.const presented = useRef({ position, size })if (!minimized) presented.current = maximized- ? { position: { x: "0%", y: "0%" }, size: { width: "100%", height: "100%" } }+ ? { position: { x: "-1/2", y: "-1/2" }, size: { width: "1/1", height: "1/1" } }: { position, size }const geometryMotion = useWindowGeometryMotion({@@ -389,7 +389,7 @@ export default function ({ title, header = true, surface, layer, icon, children,return {- position: { x: east ? "1/2" : "0/1", y: south ? "1/2" : "0/1" },+ position: { x: east ? "0/1" : "-1/2", y: south ? "0/1" : "-1/2" },size: { width: west || east ? "1/2" : "1/1", height: north || south ? "1/2" : "1/1" }}@@ -440,7 +440,9 @@ export default function ({ title, header = true, surface, layer, icon, children,start.pointerY = motion.y- request(() => onMove?.(origin.x, origin.y))+ const floating = planeGeometry(origin, bounds!)++ request(() => onMove?.(floating.x, floating.y))if (restoringMaximized) geometryMotion.restoreGesture(current)@@ -520,13 +522,16 @@ export default function ({ title, header = true, surface, layer, icon, children,setSettlingGeometry(current)- if (edge === null) request(() => onMove?.(current.x, current.y))+ // The Desktop paints from the surface's corner; the System records from its center.+ const placed = planeGeometry(current, bounds!)++ if (edge === null) request(() => onMove?.(placed.x, placed.y))// Only the west and north edges move the origin. A drag// on any other reports no position, because none was// chosen — and a position nobody chose would replace a// share with the pixels it happened to resolve to.- else request(() => onResize?.(current.width, current.height, current.x === origin.x && current.y === origin.y ? null : { x: current.x, y: current.y }))+ else request(() => onResize?.(current.width, current.height, current.x === origin.x && current.y === origin.y ? null : { x: placed.x, y: placed.y }))settle()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.tsindex 24fbf52..2a2f3bb 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@@ -1535,10 +1535,12 @@ export default class ProgramManager extends TheLink {if (asked.maximize !== undefined && typeof asked.maximize !== "boolean") throw new Error("A launch client's maximize state must be true or false")- const shift = this.authManager.processManager.processes.size % 8 * 32-const layer = asked.layer ?? client.layer ?? "window"+ // Unset geometry stays zero. The System only records Window values; how a Window is shown, and+ // where a new one appears, is decided by the Desktop, or by whoever launches it and asks.+ const size = asked.size ?? client.size ?? { width: 0, height: 0 }+const defaults = windowLayerDefaults(layer)return {@@ -1547,9 +1549,9 @@ export default class ProgramManager extends TheLink {header: asked.header ?? client.header ?? defaults.header,- position: asked.position ?? client.position ?? { x: 120 + shift, y: 80 + shift },+ position: asked.position ?? client.position ?? { x: 0, y: 0 },- size: asked.size ?? client.size ?? { width: 520, height: 340 },+ size,layer,diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.tsindex 7525319..0f52e52 100644--- a/source/server/core/permissions.ts+++ b/source/server/core/permissions.ts@@ -299,6 +299,9 @@ export const permissionCatalog = new PermissionCatalog({desktopPreferences: {default: []},+ desktopViewport: {+ default: []+ },desktopConnection: {default: []},diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.tsindex 6933f65..cb2246b 100644--- a/tests/client-layer-permissions.test.ts+++ b/tests/client-layer-permissions.test.ts@@ -62,7 +62,7 @@ function fixture() {authentication, connection, session,grantsPermission: async <Name extends PermissionName>(_pane: string, name: Name, values: readonly PermissionValue<Name>[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, process.identity, () => ({ size: { width: 100, height: 100 } }), () => "frame", moveCoordinates(), {} as never)+ const answer = host(auth, process.identity, { state: () => ({ size: { width: 100, height: 100 }, offset: { x: 0, y: 0 } }), move: () => undefined }, () => "frame", moveCoordinates(), {} as never)return {auth, program, process, answer, createProcess, findOrCreateProcess, startup, startEndpoint, command, connection,permissions(value: Permissions) { permissions = value }@@ -154,7 +154,7 @@ test("Client layer authorization validates explicit choices without reinterpretitest.each(restrictedLayers)("Client run streams authorize %s before creating an iterator", async layer => {const f = fixture()const boundary = new ClientProcessBoundary(f.process.identity, { contentWindow: null } as HTMLIFrameElement, f.auth,- () => ({ size: { width: 100, height: 100 } }), {} as never, { begin: vi.fn(), cancelMoveGestures: vi.fn() } as never)+ { state: () => ({ size: { width: 100, height: 100 }, offset: { x: 0, y: 0 } }), move: () => undefined }, {} as never, { begin: vi.fn(), cancelMoveGestures: vi.fn() } as never)const deliver = vi.spyOn(boundary, "deliver").mockResolvedValue()await boundary.own("frame")const program = { identity: f.program.identity, reference: f.program.reference }diff --git a/tests/client-permission-boundary.test.ts b/tests/client-permission-boundary.test.tsindex 01a53f2..5c1ef4f 100644--- a/tests/client-permission-boundary.test.ts+++ b/tests/client-permission-boundary.test.ts@@ -25,7 +25,7 @@ test("Client Program creation requires all before reaching the creation boundaryprocessManager: { processes: new Map([["caller", { identity: "caller", program: program.identity }]]) },grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, "caller", { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)const source = { identity: "created" }for (const operation of ["host-program-create", "host-program-force-create"]) {await expect(answer(operation, source)).rejects.toThrow("Execution is not permitted")@@ -55,7 +55,7 @@ test("Program and Process discovery exposes only the accessible scope", async ()processManager: { processes: new Map([[current.identity, current], [hidden.identity, hidden]]) },grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, current.identity, { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)await expect(answer("host-program-list")).resolves.toEqual([[expect.objectContaining({ identity: owner.identity })]])await expect(answer("host-process-list")).resolves.toEqual([[expect.objectContaining({ identity: current.identity })]])@@ -96,7 +96,7 @@ test("Program permission reads require Program access while owner decisions requprocessManager: { processes: new Map([[current.identity, current]]) },grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, current.identity, { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)const target = { identity: outside.identity, reference: outside.reference }await expect(answer("program-permissions", target, "get", "network")).resolves.toEqual([["https://example.com"]])@@ -124,7 +124,7 @@ test("Program log access follows the Program handle while System logs require lologs: systemLogs,grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, current.identity, { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)const own = { identity: owner.identity, reference: owner.reference }const other = { identity: outside.identity, reference: outside.reference }@@ -149,7 +149,7 @@ test("a Client Context requests only for its own Endpoint Program", async () =>processManager: { processes: new Map([[current.identity, current]]) },requestPermission} as unknown as AuthManager- const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, current.identity, { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)const timeout = 1_000await expect(answer("context-permission-request", "request", "network", ["https://example.com"], timeout))@@ -169,7 +169,7 @@ test("the system-wide permission registry requires all", async () => {permissionManager: { list },grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, current.identity, () => { throw new Error("unused viewport") }, () => null, moveCoordinates(), {} as never)+ const answer = host(auth, current.identity, { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => null, moveCoordinates(), {} as never)await expect(answer("host-permission-requests")).rejects.toThrow("Execution is not permitted")expect(list).not.toHaveBeenCalled()@@ -225,7 +225,7 @@ test.each([},grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => "frame", moveCoordinates(), {} as never)+ const answer = host(auth, "caller", { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => "frame", moveCoordinates(), {} as never)const key = { program: owningProgram, process: "main", endpoint: "server" } as constconst operations = [["service-available", key],@@ -266,7 +266,7 @@ test("Service discovery filters ready addresses only by Service-name authority",},grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)} as unknown as AuthManager- const answer = host(auth, "caller", () => { throw new Error("unused viewport") }, () => "frame", moveCoordinates(), {} as never)+ const answer = host(auth, "caller", { state: () => { throw new Error("unused viewport") }, move: () => { throw new Error("unused viewport") } }, () => "frame", moveCoordinates(), {} as never)await expect(answer("host-service-list")).resolves.toEqual([[]])await expect(answer("host-service-list", { name: "main" })).resolves.toEqual([[]])@@ -312,3 +312,24 @@ function process(identity: string, owner: ProgramSnapshot) {client: null}}++test("Reading the Desktop view is open, and moving it requires desktopViewport", async () => {+ let permissions: Permissions = {}+ const auth = {+ programManager: { programs: new Map([["viewer", { identity: "viewer", get permissions() { return permissions } }]]) },+ processManager: { processes: new Map([["caller", { identity: "caller", program: "viewer" }]]) },+ grantsPermission: async (_pane: string, name: PermissionName, values: never[]) => permissionCatalog.allows(name, values, permissions)+ } as unknown as AuthManager+ const state = { size: { width: 1200, height: 800 }, offset: { x: 0, y: 0 } }+ const move = vi.fn()+ const answer = host(auth, "caller", { state: () => state, move }, () => null, moveCoordinates(), {} as never)++ expect(await answer("desktopViewport")).toEqual([state])+ await expect(answer("moveDesktopViewport", { x: 1200, y: 0 })).rejects.toThrow("Execution is not permitted")+ expect(move).not.toHaveBeenCalled()++ permissions = { desktopViewport: [] }+ expect(await answer("moveDesktopViewport", { x: 1200, y: 0 })).toEqual([])+ expect(move).toHaveBeenCalledWith({ x: 1200, y: 0 })+ await expect(answer("moveDesktopViewport", { x: "far", y: 0 })).rejects.toThrow("finite x and y")+})diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.tsindex af1a4d8..91085b0 100644--- a/tests/client-process-boundary-lifecycle.test.ts+++ b/tests/client-process-boundary-lifecycle.test.ts@@ -43,7 +43,7 @@ test("a Client question expectation survives initial iframe ownership", async ()"process",element,authManager,- () => ({ size: { width: 800, height: 600 } }),+ { state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as ClientTraffic,{ begin() {} } as unknown as WindowPresentationHost)@@ -81,7 +81,7 @@ test("a later Client request cannot overtake its Service subscription registrati"process",{ contentWindow: null } as unknown as HTMLIFrameElement,authManager,- () => ({ size: { width: 800, height: 600 } }),+ { state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as ClientTraffic,{ begin() {} } as unknown as WindowPresentationHost)@@ -125,7 +125,7 @@ test("a registered Service event is delivered without a second permission round-"process",element,authManager,- () => ({ size: { width: 800, height: 600 } }),+ { state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },traffic,{ begin() {} } as unknown as WindowPresentationHost)diff --git a/tests/desktop-replacements.test.tsx b/tests/desktop-replacements.test.tsxindex 0896704..e3df08f 100644--- a/tests/desktop-replacements.test.tsx+++ b/tests/desktop-replacements.test.tsx@@ -30,7 +30,7 @@ vi.mock("@the-link/react", () => ({ReactTunnel: { useFactory: () => ({ useSubscribe() {} }) },useProperty: (property: { value: unknown }) => property.value}))-vi.mock("@client/view/components/desktop-host/client-host", () => ({ default: () => ({}) }))+vi.mock("@client/view/components/desktop-host/client-host", () => ({ default: () => ({ windowSurfaceSize: { width: 0, height: 0 }, viewport: { offset: { x: 0, y: 0 }, view: { x: 0, y: 0 }, surface: { width: 0, height: 0 }, moveTo: () => undefined, place: () => undefined, home: () => undefined } }) }))vi.mock("@client/view/components/program-access", () => ({ default: () => null }))vi.mock("@libs/readiness", () => ({ useRequirement: () => () => {} }))vi.mock("@client/view/structure/desktop/layers/shell/default-shell", () => ({@@ -186,7 +186,7 @@ test("Desktop replaces its default wallpaper with the running Client and restoreexpect(fixture.fallback).not.toHaveBeenCalled()expect(fixture.pane.mock.lastCall?.[0]).toMatchObject({layer: "wallpaper", surface: false, minimized: false, maximized: true, entering: false,- position: { x: 0, y: 0 }, size: { width: "100%", height: "100%" }, depth: 0+ position: { x: "-1/2", y: "-1/2" }, size: { width: "1/1", height: "1/1" }, depth: 0})record.client = nulldiff --git a/tests/permissions.test.ts b/tests/permissions.test.tsindex 33f6644..c4b4837 100644--- a/tests/permissions.test.ts+++ b/tests/permissions.test.ts@@ -35,6 +35,9 @@ test("permissions contract", async () => {desktopPreferences: {default: []},+ desktopViewport: {+ default: []+ },desktopConnection: {default: []},@@ -143,6 +146,7 @@ test("permissions contract", async () => {uploads: catalog.definition("uploads"),appearance: catalog.definition("appearance"),desktopPreferences: catalog.definition("desktopPreferences"),+ desktopViewport: catalog.definition("desktopViewport"),desktopConnection: catalog.definition("desktopConnection"),authentication: catalog.definition("authentication")} as never), /invalid default/)diff --git a/tests/window-geometry.test.ts b/tests/window-geometry.test.tsindex ec7bd0c..0127463 100644--- a/tests/window-geometry.test.ts+++ b/tests/window-geometry.test.ts@@ -3,14 +3,43 @@ import ClientWindow from "@client/core/link-manager/auth-manager/process-managerimport ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"-import { constrainWindowGeometry, minimumWindowSize, resolveWindowGeometry, windowPaintInsets } from "@client/view/components/window-manager/window-geometry"+import { boundedGeometry, constrainWindowGeometry, minimumWindowSize, planeGeometry, resolveWindowGeometry, shiftPosition, windowPaintInsets } from "@client/view/components/window-manager/window-geometry"import { defaultAppearance } from "@phreshos/core"import { TheLink } from "@the-link/core"import { test } from "vitest"+test("a position is the top-left corner on a plane whose zero is the surface's center", () => {+ const surface = { width: 1200, height: 800 }++ // Zero is the center; the surface's own corner is half of it before.+ assert.deepEqual(resolveWindowGeometry({ x: 0, y: 0 }, { width: 100, height: 50 }, surface), { x: 600, y: 400, width: 100, height: 50 })+ assert.deepEqual(resolveWindowGeometry({ x: "-1/2", y: "-1/2" }, { width: "1/1", height: "1/1" }, surface), { x: 0, y: 0, width: 1200, height: 800 })+ assert.deepEqual(resolveWindowGeometry({ x: -50, y: "1/4 - 10" }, { width: 100, height: 50 }, surface), { x: 550, y: 590, width: 100, height: 50 })++ // What the Desktop paints returns to the plane unchanged.+ const region = { x: 180, y: 90, width: 300, height: 200 }+ assert.deepEqual(planeGeometry(region, surface), { x: -420, y: -310, width: 300, height: 200 })+ assert.deepEqual(resolveWindowGeometry(planeGeometry(region, surface), region, surface), region)+})++test("an offset moves a position by pixels and keeps the share of the surface it names", () => {+ assert.deepEqual(shiftPosition({ x: 120, y: -40 }, { x: 1000, y: 0 }), { x: 1120, y: -40 })+ assert.deepEqual(shiftPosition({ x: "-1/2", y: "0/1" }, { x: 1416, y: -820 }), { x: "-50% + 1416", y: -820 })+ assert.deepEqual(shiftPosition({ x: "-50% + 1416", y: 10 }, { x: -1416, y: 0 }), { x: "-50% + 0", y: 10 })++ // What a Desktop shows with its offset returns to the plane unchanged.+ const surface = { width: 1200, height: 800 }+ const stored = { x: "-1/2 + 2400", y: 100 }+ const offset = { x: 2400, y: 0 }+ const shown = resolveWindowGeometry(shiftPosition(stored, { x: -offset.x, y: -offset.y }), { width: 600, height: 400 }, surface)+ assert.deepEqual(shown, { x: 0, y: 500, width: 600, height: 400 })+ const recorded = planeGeometry(shown, surface)+ assert.deepEqual({ x: recorded.x + offset.x, y: recorded.y + offset.y }, { x: 1800, y: 100 })+})+test("a standard presentation enforces its minimum after resolving authoritative geometry", () => {const surface = { width: 1200, height: 800 }- const authoritative = resolveWindowGeometry({ x: 0, y: 0 }, { width: "1/2", height: 1 }, surface)+ const authoritative = resolveWindowGeometry({ x: "-1/2", y: "-1/2" }, { width: "1/2", height: 1 }, surface)assert.deepEqual(authoritative, { x: 0, y: 0, width: 600, height: 1 })assert.deepEqual(constrainWindowGeometry(authoritative, surface, minimumWindowSize), {@@ -24,8 +53,8 @@ test("a standard presentation enforces its minimum after resolving authoritativetest("tiled standard windows share the Appearance gap inside the equally inset surface", () => {const surface = { width: 1000, height: 600 }const half = defaultAppearance.spacing / 2- const left = windowPaintInsets({ x: 0, y: 0 }, { width: "1/2", height: "1/1" }, surface, half)- const right = windowPaintInsets({ x: "1/2", y: 0 }, { width: "1/2", height: "1/1" }, surface, half)+ const left = windowPaintInsets({ x: "-1/2", y: "-1/2" }, { width: "1/2", height: "1/1" }, surface, half)+ const right = windowPaintInsets({ x: 0, y: "-1/2" }, { width: "1/2", height: "1/1" }, surface, half)assert.deepEqual(left, { top: 0, right: half, bottom: 0, left: 0 })assert.deepEqual(right, { top: 0, right: 0, bottom: 0, left: half })@@ -36,12 +65,12 @@ test("settling paint follows released geometry instead of its former boundary coconst surface = { width: 1000, height: 600 }const half = defaultAppearance.spacing / 2const released = { x: 120, y: 90, width: 500, height: 300 }- const former = windowPaintInsets({ x: 0, y: 0 }, { width: 500, height: 300 }, surface, half)+ const former = windowPaintInsets({ x: "-1/2", y: "-1/2" }, { width: 500, height: 300 }, surface, half)assert.deepEqual(former, { top: 0, right: half, bottom: half, left: 0 })assert.deepEqual(- windowPaintInsets({ x: 0, y: 0 }, { width: 500, height: 300 }, surface, half, released),+ windowPaintInsets({ x: "-1/2", y: "-1/2" }, { width: 500, height: 300 }, surface, half, released),{ top: half, right: half, bottom: half, left: half })})@@ -169,3 +198,12 @@ test("window geometry contract", async () => {assert.equal(counterpart.maximized, false)assert.equal(counterpart.header, false)}, 120_000)++test("the Desktop shows a standard Window on its plane, two views from the center, at most two views large", () => {+ const surface = { width: 1000, height: 600 }+ const inside = { x: "-1/2", y: 100 }+ const fitting = { width: "1/2", height: 300 }+ assert.deepEqual(boundedGeometry(inside, fitting, surface), { position: inside, size: fitting })+ assert.deepEqual(boundedGeometry({ x: 9000, y: -4000 }, { width: 500, height: 300 }, surface), { position: { x: 2000, y: -1500 }, size: { width: 500, height: 300 } })+ assert.deepEqual(boundedGeometry({ x: 1000, y: 0 }, { width: "3/1", height: 5000 }, surface), { position: { x: 500, y: 0 }, size: { width: 2000, height: 1200 } })+})diff --git a/tests/window-presentation-layers.test.ts b/tests/window-presentation-layers.test.tsindex 4ed807b..a944cfe 100644--- a/tests/window-presentation-layers.test.ts+++ b/tests/window-presentation-layers.test.ts@@ -21,7 +21,7 @@ test("wallpaper is fixed and rejects both raw operations and move gestures", ()const { presentations } = fixture("wallpaper")expect(presentations.layer("own")).toBe("wallpaper")expect(presentations.projection("own")).toMatchObject({- position: { x: 0, y: 0 }, size: { width: "100%", height: "100%" }, surface: false, interactive: true+ position: { x: "-1/2", y: "-1/2" }, size: { width: "1/1", height: "1/1" }, surface: false, interactive: true})expect(() => presentations.move("own", { x: 1, y: 2 })).toThrow(/does not support raw/)expect(() => presentations.setInteractive("own", false)).toThrow(/does not support raw/)diff --git a/tests/window-presentation.test.ts b/tests/window-presentation.test.tsindex 41c1724..686e328 100644--- a/tests/window-presentation.test.ts+++ b/tests/window-presentation.test.ts@@ -119,7 +119,7 @@ test("a Client boundary initializes each new document exactly once", async () =>"requester",{ contentWindow: null } as unknown as HTMLIFrameElement,{ processManager: { async ownFrame() {}, async releaseFrame() {} } } as never,- () => ({ size: { width: 1, height: 1 } }),+ { state: () => ({ size: { width: 1, height: 1 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as never,{ begin(identity: string) { lifecycle.push(identity) }, cancelMoveGestures() {} } as never)