Skip to content

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

16.1 KB
Raw Blame
import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"
import Process from "@client/core/link-manager/auth-manager/process-manager/process"
import { type Layer, type Position, type Size, type Value, type WindowGeometry } from "@phreshos/core"
import { useCallback, useLayoutEffect, useRef, useState } from "react"
import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"
import Presentations, { type PresentedWindow } from "./presentations"
import { isDesktopReplacementLayer } from "@shared/window-layers"
import { type SharedResizeWindow } from "./shared-resize"
import { type WindowRegion } from "./window-geometry"

/**
 * Everything this Desktop draws: every Process with a running Client, in its layer. A standard Window
 * follows the System's Window and shows this Desktop's own actions on it at once; a drawing in another
 * layer is its Program's, drawn as the Program says.
 *
 * Departure is representation. Stopping a Client invalidates its live Window
 * state. The last desktop-owned representation is kept until its exit
 * animation reports done, while the iframe leaves as soon as the stop is
 * confirmed.
 */
export default function useWindows(authManager: AuthManager) {

    const peer = authManager.processManager

    const [processes, setProcesses] = useState(() => [...peer.processes.values()])

    const incarnationIds = useRef(new WeakMap<ClientState, string>())

    const nextIncarnation = useRef(0)

    const incarnation = useCallback(function (record: Process, client: ClientState): WindowIncarnation {

        let identity = incarnationIds.current.get(client)

        if (!identity) {

            identity = `${record.identity}:${nextIncarnation.current++}`

            incarnationIds.current.set(client, identity)
        }

        return captureWindowIncarnation(identity, record, client)

    }, [])

    const initialIncarnations = useRef<Map<string, WindowIncarnation> | null>(null)

    if (!initialIncarnations.current) initialIncarnations.current = new Map(processes.flatMap(record => record.client ? [[record.identity, incarnation(record, record.client)] as const] : []))

    const initialClients = initialIncarnations.current

    const presentationController = useRef<Presentations | null>(null)

    if (!presentationController.current) presentationController.current = new Presentations(initialClients, process => peer.processes.get(process)?.client ?? null)

    const presentation = presentationController.current

    const [presentations, setPresentations] = useState(presentation.windows)

    presentation.listen(setPresentations)

    const previousClients = useRef(initialClients)

    // Client states already present when this desktop mounts are restored,
    // not launched, so their representations must not replay an entrance.
    const inheritedClients = useRef(new WeakSet([...initialClients.values()].map(({ client }) => client)))

    const [leaving, setLeaving] = useState<LeavingWindow[]>([])

    // A close press asks the core to terminate the Process. Keep that request
    // visible until the Process actually leaves the authoritative collection.
    const stopping = useRef(new Set<string>())

    const [, redrawStopping] = useState(0)

    // The order the desktop draws in: a window is added when it first
    // appears and taken out when its departure has played, and nothing
    // else moves it. Held rather than derived, because the two lists it
    // orders are not one list, and their concatenation is not this.
    const [order, setOrder] = useState<string[]>(() => [...initialClients.values()].map(({ identity }) => identity))

    // Departures are derived at the moment the truth arrives — the same
    // event updates both lists in one batch, so no render ever shows a
    // window in neither.
    const subscriber = useCallback((...results: unknown[]) => {

        const [list] = results as [Process[]]

        const present = new Set(list.map(process => process.identity))

        const currentClients = new Map(list.flatMap(record => record.client ? [[record.identity, incarnation(record, record.client)] as const] : []))

        let settled = false

        for (const identity of stopping.current) {

            if (present.has(identity)) continue

            stopping.current.delete(identity)

            settled = true
        }

        if (settled) redrawStopping(revision => revision + 1)

        const gone = [...previousClients.current.values()].filter(previous => currentClients.get(previous.record.identity)?.client !== previous.client)

        // Window state ends before the Process collection announces departure.
        // Use the layer captured while this incarnation was live; consulting
        // the retained Window handle here would abort the collection broadcast.
        const departed = new Set(gone.filter(({ layer }) => isDesktopReplacementLayer(layer)).map(({ identity }) => identity))

        // The controller now forgets the ended Client, but an ordinary
        // departure still owns one immutable visual snapshot until its exit
        // animation completes.
        const animated = gone
            .filter(({ identity }) => !departed.has(identity))
            .flatMap(window => {
                const retained = captureLeavingWindow(window, presentation.windows)
                return retained ? [retained] : []
            })

        presentation.reconcile(currentClients)

        if (animated.length) setLeaving(function (current) {

            const retained = new Set(current.map(({ identity }) => identity))

            return [...current, ...animated.filter(({ identity }) => !retained.has(identity))]
        })

        setOrder(function (current) {

            const retained = new Set(current)

            const added = [...currentClients.values()].filter(({ identity }) => !retained.has(identity)).map(({ identity }) => identity)

            return added.length || departed.size ? [...current.filter(identity => !departed.has(identity)), ...added] : current
        })

        previousClients.current = currentClients

        setProcesses(list)

    }, [incarnation])

    useLayoutEffect(() => peer.subscribeProcesses(subscriber), [peer, subscriber])

    const records = processes.filter(process => process.client)

    // Everything that is shown, in the layer it is shown in — and the
    // taskbar's list, which is the `window` layer and nothing else. The
    // taskbar shows windows, not processes: every entry in it is a thing
    // you can focus, minimise and restore, and a row whose entries do
    // not all answer the same press is one row teaching two rules.
    const listed = records.filter(process => process.client!.window.layer === "window")

    // The greatest depth *in one layer*. Bringing a window forward
    // brings it forward among its own kind; a program in `over` opening
    // does not push a window's number up.
    const summit = useCallback((layer: Layer) => [...peer.processes.values()].reduce((highest, process) => process.client?.window.layer === layer ? Math.max(highest, process.client.window.depth) : highest, 0), [peer])

    // A pointer gesture must retain its visible result until the authoritative
    // request settles. Returning failure as data keeps ignored button presses
    // handled while allowing the gesture owner to restore authoritative state.
    const settle = useCallback(async function (request: Promise<void>) {

        try {

            await request

            return true
        }

        catch {

            return false
        }
    }, [])

    const close = useCallback(function (process: Process) {

        if (stopping.current.has(process.identity)) return

        stopping.current.add(process.identity)

        redrawStopping(revision => revision + 1)

        process.exit().catch(() => {

            stopping.current.delete(process.identity)

            redrawStopping(revision => revision + 1)
        })

    }, [])

    const closed = useCallback(function (identity: string) {

        setLeaving(current => current.filter(entry => entry.identity !== identity))

        setOrder(current => current.filter(entry => entry !== identity))

        presentation.remove(identity)

    }, [])

    // This Desktop's actions on a standard Window: each shows at once, and the System's answer follows
    // when it settles. They answer with the request, so whoever asked can wait for the System.
    // The last standard Window this Desktop raised, each raise its own record: a Window already in front
    // changes no order, yet raising it here still says where this Desktop's person turned.
    const [raisedHere, setRaisedHere] = useState<Readonly<{ identity: string }> | null>(null)

    const raise = useCallback(function (process: Process) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve()

        setRaisedHere({ identity: process.identity })

        if (window.depth === summit(window.layer)) return Promise.resolve()

        // Shown in front at once; the System's ranking follows when it answers.
        const request = window.raise()

        presentation.anticipate(process.identity, { front: true }, request)

        return request

    }, [summit, presentation])

    const minimize = useCallback(function (process: Process, minimized: boolean) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve()

        const request = window.minimize(minimized)

        presentation.anticipate(process.identity, { minimized }, request)

        return request

    }, [presentation])

    const maximize = useCallback(function (process: Process, maximized: boolean) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve()

        const request = window.maximize(maximized)

        presentation.anticipate(process.identity, { maximized }, request)

        return request

    }, [presentation])

    // What a person means by showing a Window: shown, if it was minimized, and in front.
    const bringForward = useCallback(function (process: Process) {

        if (presentation.projection(process.identity).minimized) minimize(process, false).catch(() => undefined)

        raise(process).catch(() => undefined)

    }, [minimize, raise, presentation])

    const move = useCallback(function (process: Process, x: Value, y: Value) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve(false)

        return settle(window.move({ x, y }))

    }, [settle])

    const resize = useCallback(function (process: Process, width: Value, height: Value, position: Position | null) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve(false)

        if (!position) {
            return settle(window.resize({ width, height }))

        }

        const geometry = { ...position, width, height }

        return settle(window.setGeometry(geometry))

    }, [settle])

    const snap = useCallback(function (process: Process, position: Position, size: Size) {

        const window = process.client?.window

        if (!window || window.layer !== "window") return Promise.resolve(false)

        const geometry = { ...position, ...size }

        return settle(window.setGeometry(geometry))

    }, [settle])

    // Every window on the desktop, in one list and one order.
    //
    // A closing client incarnation keeps the place it had. A restarted
    // Client receives a new Desktop presentation identity even when
    // the surrounding Process and its Client Endpoint-owned Window
    // remain the same.
    const rank = new Map(order.map((identity, index) => [identity, index]))

    const panes = [

        ...records.map(record => {

            const live = incarnation(record, record.client!)

            return { ...live, presentation: presentations.get(live.identity)!, closing: false, stopping: stopping.current.has(record.identity), entering: !inheritedClients.current.has(live.client) }
        }),

        ...leaving.map(window => ({ ...window, 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))

    const panesByLayer: Record<Layer, typeof panes> = { wallpaper: [], under: [], window: [], over: [], shell: [] }

    for (const pane of panes) {

        panesByLayer[pane.presentation.layer].push(pane)
    }

    const sharedResizeWindows: SharedResizeWindow[] = panesByLayer.window.flatMap(function (pane) {

        if (pane.closing || pane.stopping || pane.presentation.minimized || pane.presentation.maximized) return []

        const geometry = presentation.representedGeometry(pane.record.identity)

        if (!geometry) return []

        return [{ identity: pane.record.identity, geometry, depth: pane.presentation.depth }]
    })

    const presentSharedResize = useCallback(function (geometries: ReadonlyMap<string, WindowRegion>) {

        for (const [identity, geometry] of geometries) presentation.presentGeometry(identity, geometry)

    }, [presentation])

    const beginSharedResize = useCallback(function (identities: readonly string[]) {

        const geometries = new Map<string, WindowRegion>()

        for (const identity of identities) {

            const geometry = presentation.beginGeometry(identity)

            if (geometry) {

                geometries.set(identity, geometry)

                continue
            }

            for (const started of geometries.keys()) presentation.cancelGeometry(started)

            return null
        }

        return geometries

    }, [presentation])

    const finishSharedResize = useCallback(function (identities: readonly string[]) {

        for (const identity of identities) presentation.finishGeometry(identity)

    }, [presentation])

    const cancelSharedResize = useCallback(function (identities: readonly string[]) {

        for (const identity of identities) presentation.cancelGeometry(identity)

    }, [presentation])

    const commitSharedResize = useCallback(function (geometries: ReadonlyMap<string, WindowGeometry>) {

        for (const [identity, region] of geometries) {

            const process = peer.processes.get(identity)

            const window = process?.client?.window

            if (!window || window.layer !== "window") continue

            window.setGeometry({ ...region }).catch(() => undefined)
        }

    }, [peer])

    return {

        records,

        listed,

        panesByLayer,

        raisedHere,

        presentation,

        sharedResize: {
            windows: sharedResizeWindows,
            begin: beginSharedResize,
            present: presentSharedResize,
            commit: commitSharedResize,
            finish: finishSharedResize,
            cancel: cancelSharedResize
        },

        close,

        closed,

        raise,

        minimize,

        maximize,

        bringForward,

        move,

        // A resize that moved no origin is only a resize: writing the
        // pixels a share resolved to would silence the share, and the
        // window would stop following the surface it was sized against.
        resize,

        // A snap names a share of the surface rather than pixels, so
        // every client resolves it in its own space.
        snap
    }
}

export type DesktopWindows = ReturnType<typeof useWindows>

export interface WindowIncarnation {

    identity: string

    record: Process

    client: ClientState

    layer: Layer
}

export interface LeavingWindow extends WindowIncarnation {

    presentation: PresentedWindow
}

export function captureWindowIncarnation(identity: string, record: Process, client: ClientState): WindowIncarnation {

    return { identity, record, client, layer: client.window.layer }
}

export function captureLeavingWindow(window: WindowIncarnation, presentations: ReadonlyMap<string, PresentedWindow>): LeavingWindow | null {

    const presentation = presentations.get(window.identity)

    return presentation ? { ...window, presentation } : null
}