Skip to content

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

A Window opened by another opens over it, unless its Program says where

zohayrslilehae0befc74884
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 3b4c998..191865c 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
@@ -10,9 +10,10 @@ import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
import { isValue, layers } from "./config"
-import { parseLaunch, withProcessDefaults, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, parseRelativeValue, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type Position, type ProgramCommandChunk, type ProgramDefinition, type Size, type Value } from "@phreshos/core"
+import { parseLaunch, withProcessDefaults, parseProgramDefinition, parseProgramInstallOptions, parseProgramUninstallOptions, type ProgramInstallOptions, type ProgramUninstallOptions, type ClientLaunch, type Launch, type Position, type ProgramCommandChunk, type ProgramDefinition, type Size, type Value } from "@phreshos/core"
import type { OpenTarget } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
+import { overWindow, weighted, type PlacedWindow } from "./window-placement"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
import Entry, { type ProgramRecord } from "./entry"
@@ -1436,7 +1437,7 @@ export default class ProgramManager extends TheLink {
// One interpretation of a Process launch, used both when it is created now
// and when a future startup launch is persisted. Runtime-only facts such as
// name occupancy and capacity remain in `start`.
- private resolveLaunch(program: Program, value: unknown) {
+ private resolveLaunch(program: Program, value: unknown, near: PlacedWindow | null = null) {
const launch = this.launchOf(program, value)
@@ -1462,7 +1463,7 @@ export default class ProgramManager extends TheLink {
// Resolving the Window here validates the same launch grammar even when
// the launch is being stored for a later boot. Only the original launch
// is persisted; system defaults are derived again when it actually runs.
- const windowShape = program.client ? this.clientShape(program, askedClient) : null
+ const windowShape = program.client ? this.clientShape(program, askedClient, near) : null
const shape = client ? windowShape : null
@@ -1487,7 +1488,7 @@ export default class ProgramManager extends TheLink {
return { options, server, client, shape, windowShape, intent }
}
- private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, prepared?: ReturnType<ProgramManager["resolveLaunch"]>, opened: OpenTarget | null = null) {
+ private async start(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null, transitionOwnsIdentity = false, prepared?: ReturnType<ProgramManager["resolveLaunch"]>, opened: OpenTarget | null = null, near: PlacedWindow | null = null) {
if (!transitionOwnsIdentity && this.changing.has(program.identity)) throw new Error("This program is changing and cannot create a process")
@@ -1499,7 +1500,7 @@ export default class ProgramManager extends TheLink {
// Every launch takes the Program's Process defaults first: its name, replacement, and options.
launch = this.launchOf(program, launch)
- const resolved = prepared ?? this.resolveLaunch(program, launch)
+ const resolved = prepared ?? this.resolveLaunch(program, launch, near)
const { options, server, client } = resolved
@@ -1564,9 +1565,14 @@ export default class ProgramManager extends TheLink {
}
/** Starts one Process of a Program with its default launch, to open one target. */
- public async open(program: Program, target: OpenTarget) {
+ /** Opens a target in a new Process; the window that asked, if one did, is where it opens from. */
+ public async open(program: Program, target: OpenTarget, asker: Process | null = null) {
- return await this.start(program, {}, undefined, null, false, undefined, target)
+ const window = asker?.client ? asker.clientEndpoint?.window : null
+
+ const near = window?.layer === "window" ? { position: window.position, size: window.size } : null
+
+ return await this.start(program, {}, undefined, null, false, undefined, target, near)
}
/** Creates one fresh execution runtime for a Server endpoint. */
@@ -1580,7 +1586,12 @@ export default class ProgramManager extends TheLink {
}
/** Resolves and validates one client endpoint incarnation. */
- public clientShape(program: Program, asked: ClientLaunch = {}): StandardShape {
+ /**
+ * The window a client launch opens: each setting as the launch says, else as the Program says,
+ * else as the System chooses by the situation. `near` is a window this one opens from, as one that
+ * asked to open something.
+ */
+ public clientShape(program: Program, asked: ClientLaunch = {}, near: PlacedWindow | null = null): StandardShape {
const client = program.client
@@ -1614,7 +1625,8 @@ export default class ProgramManager extends TheLink {
const layer = asked.layer ?? client.layer ?? "window"
// What neither the launch nor the Program says, the System fills the same way in every layer,
- // knowing nothing of any screen: a square of fixed pixels, centered on the plane's zero.
+ // knowing nothing of any screen: a square of fixed pixels, centered over the window it opens
+ // from, or else on the plane's zero.
const size = asked.size ?? client.size ?? defaultWindowSize
return {
@@ -1623,7 +1635,7 @@ export default class ProgramManager extends TheLink {
header: asked.header ?? client.header ?? true,
- position: asked.position ?? client.position ?? centered(size),
+ position: asked.position ?? client.position ?? (near ? overWindow(near, size) : centered(size)),
size,
@@ -1658,20 +1670,7 @@ function centered(size: Size): Position {
/** Minus half of a value, pixels and share alike: `500` gives `-250`, `"1/2"` gives `"-25%"`. */
function half(value: Value): Value {
- const parsed = parseRelativeValue(value)
-
- if (!parsed) return 0
-
- // Adding zero turns a halved zero's sign away: -0 is still no distance.
- const share = -parsed.relative / 2 + 0
-
- const pixels = -parsed.pixels / 2 + 0
-
- if (share === 0) return pixels
-
- if (pixels === 0) return `${share * 100}%`
-
- return `${share * 100}% ${pixels < 0 ? "-" : "+"} ${Math.abs(pixels)}`
+ return weighted([[value, -0.5]])
}
// What a launcher may say at the start. Named rather than ordered,
diff --git a/source/server/core/link-manager/auth-manager/program-manager/window-placement.ts b/source/server/core/link-manager/auth-manager/program-manager/window-placement.ts
new file mode 100644
index 0000000..8aafef7
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/program-manager/window-placement.ts
@@ -0,0 +1,45 @@
+import { parseRelativeValue, type Position, type Size, type Value } from "@phreshos/core"
+
+/** A standard window as placement reads it: where its corner is, how large it is. */
+export type PlacedWindow = Readonly<{ position: Position, size: Size }>
+
+/** Where a window of this size stands centered over another standard window. */
+export function overWindow(window: PlacedWindow, size: Size): Position {
+
+ // Its corner, moved by half the asker's size and back by half its own: pixels and shares alike.
+ return {
+ x: weighted([[window.position.x, 1], [window.size.width, 0.5], [size.width, -0.5]]),
+ y: weighted([[window.position.y, 1], [window.size.height, 0.5], [size.height, -0.5]])
+ }
+}
+
+/** The sum of values, each scaled by its weight, as one value: pixels, a share, or both. */
+export function weighted(terms: readonly (readonly [Value, number])[]): Value {
+
+ let share = 0
+
+ let pixels = 0
+
+ for (const [value, weight] of terms) {
+
+ const parsed = parseRelativeValue(value)
+
+ if (!parsed) continue
+
+ share += parsed.relative * weight
+
+ pixels += parsed.pixels * weight
+ }
+
+ // Rounded past what a screen can show, so sums of halves leave no float dust; adding zero turns a
+ // zero's sign away: -0 is still no distance.
+ share = Math.round(share * 1e6) / 1e6 + 0
+
+ pixels = Math.round(pixels * 1e3) / 1e3 + 0
+
+ if (share === 0) return pixels
+
+ if (pixels === 0) return `${share * 100}%`
+
+ return `${share * 100}% ${pixels < 0 ? "-" : "+"} ${Math.abs(pixels)}`
+}
diff --git a/source/server/core/opening-manager.ts b/source/server/core/opening-manager.ts
index 1d96319..edcf058 100644
--- a/source/server/core/opening-manager.ts
+++ b/source/server/core/opening-manager.ts
@@ -63,8 +63,11 @@ export default class OpeningManager extends TheLink {
const chosen = [defaults[target.type], defaults[`${target.type.slice(0, target.type.indexOf("/"))}/*`]]
.find(program => program !== undefined && programs.includes(program))
+ // A window that asks has the new window open over it.
+ const asker = from?.endpoint === "client" ? from.process : null
+
if (chosen) {
- await this.launch(chosen, target)
+ await this.launch(chosen, target, asker)
return
}
@@ -84,7 +87,7 @@ export default class OpeningManager extends TheLink {
const cancelEndpoint = from ? from.endpoint === "server" ? from.process.onServerStop(end) : from.process.onClientStop(end)
: signal ? (signal.addEventListener("abort", end), () => signal.removeEventListener("abort", end)) : () => undefined
- this.pendingRequests.set(identity, { snapshot, settle, cancelEndpoint, timer: null, resolving: false })
+ this.pendingRequests.set(identity, { snapshot, asker, settle, cancelEndpoint, timer: null, resolving: false })
await Promise.all([
this.authManager.processManager.announceHost("opening", null, "request", "system", snapshot).catch(() => undefined),
@@ -125,7 +128,7 @@ export default class OpeningManager extends TheLink {
if ((options as { always?: unknown } | undefined)?.always === true) await this.setDefault(request.snapshot.target.type, program)
- await this.launch(program, request.snapshot.target)
+ await this.launch(program, request.snapshot.target, request.asker)
await this.finish(request, program)
}
catch (error) {
@@ -221,13 +224,13 @@ export default class OpeningManager extends TheLink {
return this.authManager.linkManager.application.store
}
- private async launch(program: string, target: OpenTarget) {
+ private async launch(program: string, target: OpenTarget, asker: Process | null) {
const entry = this.authManager.programManager.programs.get(program)
if (!entry?.installed) throw new Error("That Program is not installed")
- await this.authManager.programManager.open(entry.program, target)
+ await this.authManager.programManager.open(entry.program, target, asker)
}
private claim(identity: unknown) {
@@ -267,6 +270,8 @@ export default class OpeningManager extends TheLink {
interface PendingOpenRequest {
readonly snapshot: OpenRequestSnapshot
+ /** The Process whose window asked, which the new window opens over. */
+ readonly asker: Process | null
readonly settle: (program: string | null) => void
readonly cancelEndpoint: () => void
timer: ReturnType<typeof setTimeout> | null
diff --git a/tests/opening.test.ts b/tests/opening.test.ts
index 79b541d..11d0290 100644
--- a/tests/opening.test.ts
+++ b/tests/opening.test.ts
@@ -43,7 +43,7 @@ test("a default Program opens it at once, with no request", async () => {
await manager.open(png, null)
- expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "paint" }), png)
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "paint" }), png, null)
expect(manager.requests()).toEqual([])
})
@@ -52,11 +52,11 @@ test("a family's default opens every type in it, and an exact type's default win
stored.set("opening-defaults", { "image/*": "preview" })
await manager.open({ type: "image/jpeg", uri: "file:///a.jpg" }, null)
- expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "preview" }), { type: "image/jpeg", uri: "file:///a.jpg" })
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "preview" }), { type: "image/jpeg", uri: "file:///a.jpg" }, null)
stored.set("opening-defaults", { "image/*": "preview", "image/png": "paint" })
await manager.open(png, null)
- expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "paint" }), png)
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "paint" }), png, null)
expect(manager.requests()).toEqual([])
})
@@ -92,11 +92,30 @@ test("without a default, a request waits; choosing always opens it and makes the
await manager.choose(request!.identity, "preview", { always: true })
await opening
- expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "preview" }), png)
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ identity: "preview" }), png, null)
expect(await manager.defaults()).toEqual({ "image/png": { identity: "preview" } })
expect(manager.pending(request!.identity)).toBe(false)
})
+test("a window that asks is where the new one opens from, even once a request is decided; a Server is not", async () => {
+ const { manager, open, stored } = fixture()
+ const asker = { record: () => ({ identity: "asker" }), program: { record: () => ({ identity: "files" }) }, onClientStop: () => () => undefined, onServerStop: () => () => undefined } as never
+ stored.set("opening-defaults", { "image/png": "paint" })
+
+ await manager.open(png, { process: asker, endpoint: "client" })
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "paint" }), png, asker)
+
+ await manager.open(png, { process: asker, endpoint: "server" })
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "paint" }), png, null)
+
+ stored.clear()
+ const opening = manager.open(png, { process: asker, endpoint: "client" })
+ await vi.waitFor(() => expect(manager.requests()).toHaveLength(1))
+ await manager.choose(manager.requests()[0]!.identity, "preview", {})
+ await opening
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({ identity: "preview" }), png, asker)
+})
+
test("a cancelled request opens nothing and tells the one who asked", async () => {
const { manager, open } = fixture()
diff --git a/tests/window-placement.test.ts b/tests/window-placement.test.ts
new file mode 100644
index 0000000..aa793c1
--- /dev/null
+++ b/tests/window-placement.test.ts
@@ -0,0 +1,20 @@
+import { expect, test } from "vitest"
+import { overWindow, weighted } from "@server/core/link-manager/auth-manager/program-manager/window-placement"
+
+test("a window opens centered over another, in pixels", () => {
+ expect(overWindow({ position: { x: -400, y: -300 }, size: { width: 800, height: 600 } }, { width: 400, height: 200 })).toEqual({ x: -200, y: -100 })
+})
+
+test("a window opens centered over one placed by shares of the view, keeping them shares", () => {
+ // The asker fills the left half: its center is a quarter in from the left.
+ expect(overWindow({ position: { x: "-50%", y: "-50%" }, size: { width: "1/2", height: "1/1" } }, { width: 400, height: 300 }))
+ .toEqual({ x: "-25% - 200", y: -150 })
+ expect(overWindow({ position: { x: -300, y: 0 }, size: { width: 600, height: 400 } }, { width: "1/2", height: "1/2" }))
+ .toEqual({ x: "-25%", y: "-25% + 200" })
+})
+
+test("a weighted sum stays one value, with no float dust and no negative zero", () => {
+ expect(weighted([["1/3", 0.5], ["1/3", 0.5]])).toBe("33.3333%")
+ expect(weighted([[0, -0.5]])).toBe(0)
+ expect(Object.is(weighted([[0, -0.5]]), -0)).toBe(false)
+})