Skip to content

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

Each Desktop focuses its own standard Window: the one last raised while in its view

zohayrslileh731d9dd17e89
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index b0c847d..8284e78 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -1105,6 +1105,8 @@ export default class ClientProcessBoundary extends TheLink {
if (drawing.front !== before.front) this.deliver("host-presentation", "front", drawing.front).catch(() => undefined)
+ if (drawing.focused !== before.focused) this.deliver("host-presentation", "focus", drawing.focused).catch(() => undefined)
+
if (drawing.interactive !== before.interactive) this.deliver("host-presentation", "changeInteractive", drawing.interactive).catch(() => undefined)
if (JSON.stringify(drawing.surface) !== JSON.stringify(before.surface)) this.deliver("host-presentation", "changeSurface", drawing.surface).catch(() => undefined)
diff --git a/source/client/view/components/desktop-host/presentation.ts b/source/client/view/components/desktop-host/presentation.ts
index b165d03..5b64d9c 100644
--- a/source/client/view/components/desktop-host/presentation.ts
+++ b/source/client/view/components/desktop-host/presentation.ts
@@ -1,7 +1,7 @@
import {
parsePresentationSurface,
parsePresentationTransaction,
- type WindowLayer,
+ type PresentationState,
type PresentationMovePoint,
type PresentationGeometry,
type PresentationAnchor,
@@ -45,15 +45,7 @@ export interface DesktopMoveGesture {
}
/** How one Client is actually drawn on this Desktop, as its presentation reads it. */
-export type PresentationState = Readonly<{
- layer: WindowLayer
- anchor: PresentationAnchor
- position: PresentationPosition
- size: PresentationSize
- front: boolean
- interactive: boolean
- surface: PresentationSurface
-}>
+export type { PresentationState }
/** Local commands available to the current Client representation. */
export interface PresentationHost {
diff --git a/source/client/view/components/window-manager/presentations.ts b/source/client/view/components/window-manager/presentations.ts
index c5d0ed5..d02ae9e 100644
--- a/source/client/view/components/window-manager/presentations.ts
+++ b/source/client/view/components/window-manager/presentations.ts
@@ -72,6 +72,8 @@ export default class Presentations implements PresentationHost {
private revision = 0
/** How far this Desktop's view is moved across the plane, in pixels. */
private offset = { x: 0, y: 0 }
+ /** The Process whose standard Window this Desktop focuses. */
+ private focusedProcess: string | null = null
private changed: (windows: ReadonlyMap<string, PresentedWindow>) => void = () => undefined
public constructor(initial: ReadonlyMap<string, PresentationEntry>, private readonly client: (process: string) => ClientState | null) {
@@ -146,6 +148,13 @@ export default class Presentations implements PresentationHost {
this.notify()
}
+ /** Which standard Window this Desktop focuses, as its Desktop decides; drawings in other layers always are. */
+ public focus(process: string | null) {
+ if (process === this.focusedProcess) return
+ this.focusedProcess = process
+ this.notify()
+ }
+
/** Hears every change to what this Desktop draws, so a Client can learn how its own drawing changed. */
public observe(listener: () => void) {
this.observers.add(listener)
@@ -172,6 +181,7 @@ export default class Presentations implements PresentationHost {
position: { x: box.x + inside.x - width / 2 + from.x, y: box.y + inside.y - height / 2 + from.y },
size: { width: frame.offsetWidth, height: frame.offsetHeight },
front: frontmost(this.windows, state.layer) === identity,
+ focused: state.layer !== "window" || this.focusedProcess === process,
interactive: state.interactive,
surface: state.surface
}
diff --git a/source/client/view/components/window-manager/window-manager.ts b/source/client/view/components/window-manager/window-manager.ts
index dfbc717..0893d09 100644
--- a/source/client/view/components/window-manager/window-manager.ts
+++ b/source/client/view/components/window-manager/window-manager.ts
@@ -160,24 +160,6 @@ export default function useWindows(authManager: AuthManager) {
// 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])
- // Resolve the front window of every layer in one pass.
- const fronts: Record<Layer, Process | null> = { wallpaper: null, under: null, window: null, over: null, shell: null }
-
- for (const process of records) {
-
- const live = incarnation(process, process.client!)
-
- const window = presentations.get(live.identity)
-
- if (!window || window.minimized) continue
-
- const best = fronts[window.layer]
-
- const bestWindow = best && presentations.get(incarnation(best, best.client!).identity)
-
- if (!bestWindow || bestWindow.depth <= window.depth) fronts[window.layer] = process
- }
-
// 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.
@@ -225,11 +207,19 @@ export default function useWindows(authManager: AuthManager) {
// 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" || window.depth === summit(window.layer)) return Promise.resolve()
+ 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()
@@ -421,7 +411,7 @@ export default function useWindows(authManager: AuthManager) {
panesByLayer,
- fronts,
+ raisedHere,
presentation,
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index b209f99..2db710d 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -6,6 +6,7 @@ import useViewportOffset from "./viewport-offset"
import useViewSize from "./view-size"
import DesktopLayers, { desktopMargins } from "./layers/desktop-layers"
import useDesktopFocus from "./desktop-focus"
+import useFocusedWindow from "./focused-window"
import programIcon from "./programs/program-icon"
import ProgramAccessProbe, { type ProgramAccess } from "../../components/program-access"
import DefaultShell from "./layers/shell/default-shell"
@@ -207,10 +208,6 @@ export default function Workspace() {
const focus = useDesktopFocus(desktop, windows, appearance.taskbar.overlay)
- // Resolved once per desktop render. Asking inside every window and
- // taskbar item would repeat the same linear scan for each process.
- const fronts = windows.fronts
-
function icon(record: { program: string }) {
return programIcon(application.doors.program, assetOf(record.program))
@@ -327,7 +324,8 @@ export default function Workspace() {
depth={presentation.depth}
- active={fronts[layer]?.identity === record.identity}
+ // Only a standard Window is shown unfocused; every other drawing is always focused.
+ active={layer !== "window" || focusedWindow === record.identity}
minimized={presentation.minimized}
@@ -383,6 +381,24 @@ export default function Workspace() {
const taskbarOrientation = appearance.taskbar.position === "top" || appearance.taskbar.position === "bottom" ? "horizontal" : "vertical"
+ // Which standard Window this Desktop focuses: the one last raised while any part of it lies where this
+ // Desktop looks. Programs learn it through their presentation.
+ const focusedWindow = useFocusedWindow(windows.panesByLayer.window.filter(pane => !pane.closing).map(({ record, presentation }) => {
+
+ const shown = boundedGeometry(presentation.position, presentation.size, viewSize)
+
+ const region = planeGeometry(resolveWindowGeometry(shown.position, shown.size, viewSize), viewSize)
+
+ const inView = viewSize.width > 0 && viewSize.height > 0 &&
+ region.x < offset.x + viewSize.width / 2 && region.x + region.width > offset.x - viewSize.width / 2 &&
+ region.y < offset.y + viewSize.height / 2 && region.y + region.height > offset.y - viewSize.height / 2
+
+ return { identity: record.identity, depth: presentation.depth, available: !presentation.minimized, inView }
+
+ }), windows.raisedHere)
+
+ useLayoutEffect(() => windows.presentation.focus(focusedWindow), [windows.presentation, focusedWindow])
+
// Each standard Window where it is on the plane, minimized or not, for the map of views.
const mappedWindows: MappedWindow[] = viewSize.width && viewSize.height
? windows.panesByLayer.window.filter(pane => !pane.closing).map(({ identity, record, presentation }) => {
@@ -396,7 +412,7 @@ export default function Workspace() {
title: presentation.title,
icon: icon(record),
region,
- front: fronts.window?.identity === record.identity,
+ focused: focusedWindow === record.identity,
minimized: presentation.minimized,
maximized: presentation.maximized,
goTo: () => goTo(record),
@@ -513,7 +529,7 @@ export default function Workspace() {
position={appearance.taskbar.position}
- active={fronts.window?.identity === record.identity}
+ active={focusedWindow === record.identity}
minimized={window.minimized}
diff --git a/source/client/view/structure/desktop/focused-window.ts b/source/client/view/structure/desktop/focused-window.ts
new file mode 100644
index 0000000..658d4fe
--- /dev/null
+++ b/source/client/view/structure/desktop/focused-window.ts
@@ -0,0 +1,80 @@
+import { useLayoutEffect, useRef, useState } from "react"
+
+/** A standard Window as focus weighs it on this Desktop. */
+export interface FocusCandidate {
+ identity: string
+ /** Its rank among standard Windows; raising it gives it the greatest. */
+ depth: number
+ /** Shown, neither minimized nor leaving. */
+ available: boolean
+ /** Any part of it lies where this Desktop looks. */
+ inView: boolean
+}
+
+export interface FocusState {
+ focused: string | null
+ /** Each Window's depth when focus last looked, to tell a raise from a Window that stayed put. */
+ depths: ReadonlyMap<string, number>
+}
+
+export const noFocus: FocusState = { focused: null, depths: new Map() }
+
+/**
+ * Which standard Window this Desktop focuses: the one last raised while in its view. A Window raised
+ * where this Desktop does not look is raised, not focused. One raised here (`raisedHere`) may not
+ * change the order at all, being in front already, so it is named rather than found by its depth.
+ * When the focused one is minimized or gone, focus falls to the front Window still in view, or none.
+ */
+export function followFocus(previous: FocusState, candidates: readonly FocusCandidate[], raisedHere: string | null = null): FocusState {
+
+ const available = candidates.filter(candidate => candidate.available)
+
+ const front = available.reduce<FocusCandidate | null>((best, candidate) => !best || best.depth <= candidate.depth ? candidate : best, null)
+
+ // Raised since focus last looked: in front now, and deeper than it was, or new.
+ const raised = front && front.depth > (previous.depths.get(front.identity) ?? -Infinity) ? front : null
+
+ const named = raisedHere === null ? null : available.find(candidate => candidate.identity === raisedHere) ?? null
+
+ const chosen = [named, raised].find(candidate => candidate?.inView) ?? null
+
+ let focused = chosen?.identity ?? previous.focused
+
+ if (!available.some(candidate => candidate.identity === focused)) {
+ const inView = available.filter(candidate => candidate.inView)
+ focused = inView.reduce<FocusCandidate | null>((best, candidate) => !best || best.depth <= candidate.depth ? candidate : best, null)?.identity ?? null
+ }
+
+ return { focused, depths: new Map(candidates.map(candidate => [candidate.identity, candidate.depth])) }
+}
+
+/** Follows which standard Window this Desktop focuses, as its Windows and its view change. */
+export default function useFocusedWindow(candidates: readonly FocusCandidate[], raisedHere: Readonly<{ identity: string }> | null): string | null {
+
+ const [state, setState] = useState<FocusState>(noFocus)
+
+ // Each raise here counts once: a Window that moves later was not raised again.
+ const counted = useRef<object | null>(null)
+
+ // Looked at again whenever a Window's rank, presence, or place in view changes, or this Desktop raises one.
+ const key = candidates.map(candidate => `${candidate.identity}:${candidate.depth}:${candidate.available ? 1 : 0}${candidate.inView ? 1 : 0}`).join(" ")
+
+ useLayoutEffect(function () {
+
+ const fresh = raisedHere && raisedHere !== counted.current ? raisedHere.identity : null
+
+ counted.current = raisedHere
+
+ setState(previous => {
+
+ const next = followFocus(previous, candidates, fresh)
+
+ const same = next.focused === previous.focused && next.depths.size === previous.depths.size && [...next.depths].every(([identity, depth]) => previous.depths.get(identity) === depth)
+
+ return same ? previous : next
+ })
+
+ }, [key, raisedHere])
+
+ return state.focused
+}
diff --git a/source/client/view/structure/desktop/layers/shell/taskbar/map/map-control.tsx b/source/client/view/structure/desktop/layers/shell/taskbar/map/map-control.tsx
index 736b354..990016f 100644
--- a/source/client/view/structure/desktop/layers/shell/taskbar/map/map-control.tsx
+++ b/source/client/view/structure/desktop/layers/shell/taskbar/map/map-control.tsx
@@ -30,8 +30,8 @@ export interface MappedWindow {
/** Its top-left corner and size on the plane, whose zero is the center. */
region: WindowRegion
- /** Whether it is the front Window. */
- front: boolean
+ /** Whether this Desktop focuses it. */
+ focused: boolean
minimized: boolean
@@ -690,7 +690,7 @@ function MapWindow({ window, viewport, menus, mapX, mapY, cell }: Readonly<{
<ContextMenu.Trigger>
{/* The front Window is apricot; a minimized one fades; a maximized one carries the title bar's maximize mark. */}
- <Button size="xsmall" iconOnly depth="flat" color={window.front ? "primary:soft" : "secondary:subtle"}
+ <Button size="xsmall" iconOnly depth="flat" color={window.focused ? "primary:soft" : "secondary:subtle"}
aria-label={windowState(window) ? `${window.title}, ${windowState(window)}` : window.title}
onPress={() => { if (!moved.current) window.goTo() }}
style={{ width: card, height: card, paddingInline: 0, opacity: window.minimized ? 0.45 : 1 }}>
@@ -712,7 +712,7 @@ function MapWindow({ window, viewport, menus, mapX, mapY, cell }: Readonly<{
</Tooltip>
- {window.maximized && <Surface aria-hidden="true" color={window.front ? "primary" : "secondary"} radius="full" className="pointer-events-none grid place-items-center"
+ {window.maximized && <Surface aria-hidden="true" color={window.focused ? "primary" : "secondary"} radius="full" className="pointer-events-none grid place-items-center"
style={{ position: "absolute", top: -mark / 3, right: -mark / 3, width: mark, height: mark, opacity: window.minimized ? 0.45 : 1 }}>
<Maximize2 style={{ width: mark * 0.6, height: mark * 0.6 }} strokeWidth={2.5} />
</Surface>}
diff --git a/tests/focused-window.test.ts b/tests/focused-window.test.ts
new file mode 100644
index 0000000..5df573d
--- /dev/null
+++ b/tests/focused-window.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from "vitest"
+import { followFocus, noFocus, type FocusCandidate } from "@client/view/structure/desktop/focused-window"
+
+const window = (identity: string, depth: number, inView = true, available = true): FocusCandidate => ({ identity, depth, inView, available })
+
+test("a Desktop opens focusing the front Window among those it looks at", () => {
+ expect(followFocus(noFocus, [window("a", 1), window("b", 2), window("c", 3, false)]).focused).toBe("b")
+ expect(followFocus(noFocus, [window("a", 1, false)]).focused).toBe(null)
+})
+
+test("a Window raised in view is focused; one raised where this Desktop does not look is not", () => {
+ const opened = followFocus(noFocus, [window("a", 1), window("b", 2, false)])
+ expect(opened.focused).toBe("a")
+
+ // Another Desktop raises b, out of this one's view: raised, not focused here.
+ const elsewhere = followFocus(opened, [window("a", 1), window("b", 3, false)])
+ expect(elsewhere.focused).toBe("a")
+
+ // Then a Window this Desktop sees: focused here too.
+ const seen = followFocus(elsewhere, [window("a", 4), window("b", 3, false)])
+ expect(seen.focused).toBe("a")
+ const other = followFocus({ focused: "b", depths: seen.depths }, [window("a", 5), window("b", 3, false)])
+ expect(other.focused).toBe("a")
+})
+
+test("a new Window that opens in view is focused", () => {
+ const opened = followFocus(noFocus, [window("a", 1)])
+ expect(followFocus(opened, [window("a", 1), window("b", 2)]).focused).toBe("b")
+ expect(followFocus(opened, [window("a", 1), window("b", 2, false)]).focused).toBe("a")
+})
+
+test("raising here a Window already in front focuses it, though no order changes", () => {
+ // b was raised by another Desktop while out of view, then this Desktop's view came to it.
+ const state = { focused: "a", depths: new Map([["a", 1], ["b", 2]]) }
+ const candidates = [window("a", 1), window("b", 2)]
+ expect(followFocus(state, candidates).focused).toBe("a")
+ expect(followFocus(state, candidates, "b").focused).toBe("b")
+ // Named where this Desktop does not look, it is not focused.
+ expect(followFocus(state, [window("a", 1), window("b", 2, false)], "b").focused).toBe("a")
+})
+
+test("a Window coming to the front without being raised takes no focus", () => {
+ const state = { focused: "a", depths: new Map([["a", 1], ["b", 2], ["c", 3]]) }
+ // c is minimized: b is in front now, but nobody raised it.
+ expect(followFocus(state, [window("a", 1), window("b", 2), window("c", 3, true, false)]).focused).toBe("a")
+})
+
+test("when the focused Window is minimized or gone, focus falls to the front one still in view, or none", () => {
+ const state = { focused: "c", depths: new Map([["a", 1], ["b", 2], ["c", 3]]) }
+ expect(followFocus(state, [window("a", 1), window("b", 2), window("c", 3, true, false)]).focused).toBe("b")
+ expect(followFocus(state, [window("a", 1), window("b", 2, false)]).focused).toBe("a")
+ expect(followFocus(state, [window("a", 1, false)]).focused).toBe(null)
+})