Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/a-closed-scene-lets-its-context-go.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@fnndsc/orrery": patch
"@fnndsc/argus": patch
---

A closed image viewer, volume viewer, SLAB scene or /bin diagram gives its graphics contexts back at once.

A closed image viewer loses the seven WebGL contexts Cornerstone's pool holds for it; a volume viewer cleans its niivue up and loses its context; a SLAB scene deletes each vtk object it made, its render window and its interactor (which kept listening on the document), then loses its context, and one whose first render fails lets all of that go before the failure is passed on; an orrery scene's renderer is disposed, then its context lost, then its canvas removed, once however often it is closed. A split Files pane closed with a /bin diagram on stage disposes the diagram. Until now each closed scene held its contexts until garbage was collected, and Chromium keeps sixteen. The layout's dividers no longer leave two window listeners behind at every render, and a listing's field lets go of its observers and listeners when the next render replaces it or its pane closes. The smoke suite has a `scene-disposal` lane, on the run's own synthesized series, volume and feed whatever the environment names: it reloads the page with every WebGL context watched from the first; over ten rounds it opens and closes the image viewer, its SLAB scene and a /bin diagram, checking each context drew and is lost while still held, before any collection; it shows the primary DAG and the universe again on the context already seen, none made; it reads the heap after every round (the last within a tenth of the first round's, no climb over the last five) and the page's listeners; and it keeps one viewer drawing while another beside it closes. `SMOKE_ONLY` and `SMOKE_SKIP` take scenario names or their starts, never a pattern, and a scenario `SMOKE_ONLY` names that never ran, or ran and skipped every part, is a red.
2 changes: 2 additions & 0 deletions apps/argus/src/app/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,8 @@ function filesInstance_build(context: BrowserContext, hooks: BrowserHooks, parts
kind: 'files',
mount,
dispose: (): void => {
// A view on stage goes with its pane: a /bin diagram's scene and its context are let go here too.
panel.content_release();
panels.delete(id);
parts.rootedHistory.delete(id);
parts.indicated.delete(id);
Expand Down
10 changes: 8 additions & 2 deletions apps/argus/src/app/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ export class LayoutManager {
private tree: LayoutNode | null = null;
private focusedPane: string | null = null;
private renderObserver: (() => void) | null = null;
/** The scaffold's owner: aborted when the next render replaces it, so its dividers' window listeners go with it. */
private scaffold: AbortController = new AbortController();
/** The pane focused before the current one (tmux `;`). */
private previousFocus: string | null = null;

Expand Down Expand Up @@ -464,6 +466,9 @@ export class LayoutManager {
for (const mount of this.mounts.values()) {
mount.remove();
}
// The scaffold being replaced lets go of the window: each divider listens there for its drag.
this.scaffold.abort();
this.scaffold = new AbortController();
this.root.replaceChildren(this.node_render(this.tree, ''));
this.focus_reconcile();
this.renderObserver?.();
Expand Down Expand Up @@ -537,6 +542,7 @@ export class LayoutManager {
dragging = true;
event.preventDefault();
});
const signal: AbortSignal = this.scaffold.signal;
window.addEventListener('mousemove', (event: MouseEvent): void => {
if (!dragging) return;
const bounds: DOMRect = split.getBoundingClientRect();
Expand All @@ -547,13 +553,13 @@ export class LayoutManager {
node.ratio = Math.min(0.85, Math.max(0.15, along));
first.style.flex = `${node.ratio} 1 0`;
second.style.flex = `${1 - node.ratio} 1 0`;
});
}, { signal });
window.addEventListener('mouseup', (): void => {
if (!dragging) return;
dragging = false;
this.ratio_remember(path, node.ratio);
this.renderObserver?.();
});
}, { signal });
}

/** Marks one pane focused and repaints the rings. */
Expand Down
22 changes: 18 additions & 4 deletions apps/argus/src/features/files/panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export class FilesPanel {
get container(): FilesFace['container'] { return screen.container; },
get contentRelease(): FilesFace['contentRelease'] { return screen.contentRelease; },
set contentRelease(value: FilesFace['contentRelease']) { screen.contentRelease = value; },
contentRelease_run: (): void => { screen.contentRelease?.(); },
contentRelease_run: (): void => { screen.content_release(); },
content_show: (...args: Parameters<FilesFace['content_show']>): void => { screen.content_show(...args); },
get contentShown(): FilesFace['contentShown'] { return screen.contentShown; },
set contentShown(value: FilesFace['contentShown']) { screen.contentShown = value; },
Expand Down Expand Up @@ -568,6 +568,21 @@ export class FilesPanel {
/** Releases whatever the current content view mounted (a diagram scene). */
private contentRelease: (() => void) | null = null;

/**
* Lets go of what the content view on stage mounted (a diagram's scene),
* once: the release is taken before it runs, so a view replaced, a CLOSE
* pressed and the pane closed never run it twice. The pane's own disposal
* calls it, so a view on stage when its pane closes goes with the pane.
*
* @example
* panel.content_release();
*/
public content_release(): void {
const held_release: (() => void) | null = this.contentRelease;
this.contentRelease = null;
held_release?.call(this);
}

/**
* Presents rendered markup in place of the grid — a /bin entry's
* description, a pipeline's summary — with a CLOSE pill returning to the
Expand All @@ -584,7 +599,7 @@ export class FilesPanel {
html: string,
options: { diagram?: boolean; release?: () => void } = {},
): HTMLElement | null {
this.contentRelease?.();
this.content_release();
this.contentRelease = options.release ?? null;
this.contentShown = true;
this.container.parentElement?.classList.add('content-view');
Expand Down Expand Up @@ -634,8 +649,7 @@ export class FilesPanel {

/** Returns from a content view to the most recent listing. */
public listing_restore(): void {
this.contentRelease?.();
this.contentRelease = null;
this.content_release();
if (this.lastListings.length > 0) {
this.listings_render(this.lastListings);
} else {
Expand Down
4 changes: 4 additions & 0 deletions apps/argus/src/features/image/cornerstoneEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { type Cornerstone, type CornerstoneTools, type Loaded, cornerstone_load,
import { CornerstoneMetadata } from './cornerstoneMetadata.js';
import { CornerstoneProbe } from './cornerstoneProbe.js';
import { IMAGE_TOOLS, type ImageColormap, type ImageEngine, type ImageEngineHost, type ImageEngineState, type ImageLayout, type ImageTool } from './engine.js';
import { cornerstoneContexts_find, glContexts_lose, type GlContext } from './glContexts.js';
import { refusal_explain } from './refusal.js';
import type { SlabScene } from './slabScene.js';
import { byteUrl_absolute } from '../../calypso/routes.js';
Expand Down Expand Up @@ -1170,8 +1171,11 @@ export class CornerstoneEngine implements ImageEngine {
for (const layout of ['single', 'mpr', '3d']) {
this.libraries.tools.ToolGroupManager.destroyToolGroup(`${this.engineId_get()}-${layout}`);
}
// Cornerstone's destroy frees what its pool drew and leaves each of its contexts to the collector.
const contexts: GlContext[] = cornerstoneContexts_find(this.renderingEngine);
this.renderingEngine.destroy();
this.renderingEngine = null;
glContexts_lose(contexts);
}
this.field?.replaceChildren();
}
Expand Down
111 changes: 111 additions & 0 deletions apps/argus/src/features/image/glContexts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* @file The WebGL contexts an image engine draws with, found and let go when
* it closes.
*
* A browser keeps only so many WebGL contexts (Chromium, sixteen) and drops
* the oldest when another is made. vtk's delete and Cornerstone's destroy
* free what they drew but leave each context to the collector, so a closed
* viewer's contexts counted against every viewer opened after it until
* garbage was collected: Cornerstone alone keeps a pool of seven per engine.
* They are found while the engine stands and lost once it is gone.
*
* Key components:
* - glContext_find: the context a vtk render window's first view draws with.
* - cornerstoneContexts_find: every context of a Cornerstone engine's pool.
* - glContexts_lose: lets each go.
*
* Typical usage:
* ```ts
* const contexts: GlContext[] = cornerstoneContexts_find(engine);
* engine.destroy();
* glContexts_lose(contexts);
* ```
*
* Dependencies: none; each reader takes what it is given as unknown and
* checks its shape, since neither library publishes these parts' types.
*
* @module
*/

/** A WebGL context, as much of it as letting it go needs. */
export type GlContext = Pick<WebGLRenderingContext, 'getExtension'>;

/**
* Calls a method a value has, by name, or answers undefined.
*
* @param value - The value.
* @param method - The method's name.
* @returns What it answered.
*/
function method_call(value: unknown, method: string): unknown {
if (typeof value !== 'object' || value === null || !(method in value)) return undefined;
const called: unknown = Reflect.get(value, method);
return typeof called === 'function' ? Reflect.apply(called, value, []) : undefined;
}

/**
* Whether a value is a WebGL context that can be let go.
*
* @param value - The value.
* @returns True for one.
*/
function glContext_is(value: unknown): value is GlContext {
return typeof value === 'object' && value !== null && 'getExtension' in value && typeof value.getExtension === 'function';
}

/**
* The context a vtk render window's first view draws with.
*
* @param views - The render window's views (`renderWindow.getViews()`).
* @returns The context, or null when it has none.
*
* @example
* ```ts
* const gl: GlContext | null = glContext_find(renderWindow.getViews());
* ```
*/
export function glContext_find(views: unknown): GlContext | null {
if (!Array.isArray(views)) return null;
const gl: unknown = method_call(views[0], 'getContext');
return glContext_is(gl) ? gl : null;
}

/**
* Every context in a Cornerstone engine's pool: each offscreen window's
* OpenGL window and its context. The engine a caller holds stands in front
* of the one that renders (its `_implementation`); either is read.
*
* @param engine - The rendering engine, or null.
* @returns The contexts; none for an engine with no pool.
*
* @example
* ```ts
* const contexts: GlContext[] = cornerstoneContexts_find(this.renderingEngine);
* ```
*/
export function cornerstoneContexts_find(engine: unknown): GlContext[] {
if (typeof engine !== 'object' || engine === null) return [];
if (!('contextPool' in engine)) return '_implementation' in engine && engine._implementation !== engine ? cornerstoneContexts_find(engine._implementation) : [];
const windows: unknown = method_call(engine.contextPool, 'getAllContexts');
if (!Array.isArray(windows)) return [];
const contexts: GlContext[] = [];
for (const window of windows) {
const gl: unknown = method_call(method_call(window, 'getOpenGLRenderWindow'), 'getContext');
if (glContext_is(gl)) contexts.push(gl);
}
return contexts;
}

/**
* Lets each context go: lost at once, never left for the collector.
*
* @param contexts - The contexts.
*
* @example
* ```ts
* glContexts_lose(contexts);
* ```
*/
export function glContexts_lose(contexts: ReadonlyArray<GlContext | null>): void {
for (const gl of contexts) gl?.getExtension('WEBGL_lose_context')?.loseContext();
}
34 changes: 33 additions & 1 deletion apps/argus/src/features/image/niivueEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*
* @module
*/
import { glContexts_lose, type GlContext } from './glContexts.js';
import { refusal_explain } from './refusal.js';
import { byteUrl_absolute } from '../../calypso/routes.js';
import {
Expand Down Expand Up @@ -53,6 +54,8 @@ export class NiivueEngine implements ImageEngine {
private slices: number = 0;
private refused: number = 0;
private disposed: boolean = false;
/** The niivue made for the canvas, from its making: what dispose lets go, whether or not its volume came. */
private made: Niivue | null = null;

/**
* @param host - The pane's lendings.
Expand Down Expand Up @@ -85,13 +88,16 @@ export class NiivueEngine implements ImageEngine {
crosshairWidth: 0.4,
crosshairWidthUnit: 'percent',
});
this.made = nv;
nv.onLocationChange = (location: unknown): void => {
const message: { vox?: number[]; string?: string } = location as { vox?: number[]; string?: string };
const z: number | undefined = message.vox?.[2];
if (z !== undefined) this.slice = z + 1;
this.host.readout_set(`${this.slices > 0 ? `SLICE ${this.slice} OF ${this.slices} · ` : ''}${message.string ?? ''}`);
};
await nv.attachToCanvas(canvas);
// Let go while it attached: the context it made goes now, since no later dispose will come.
if (this.disposed_is()) { this.made_release(); return; }
const name: string = this.path.split('/').pop() ?? 'volume.nii.gz';
try {
// Absolute, resolved against the page: the source's URL is relative to
Expand All @@ -109,7 +115,7 @@ export class NiivueEngine implements ImageEngine {
return;
}
this.host.progress_set(null);
if (this.disposed) return;
if (this.disposed_is()) { this.made_release(); return; }
this.nv = nv;
const dims: number[] | undefined = (nv.volumes[0] as { dims?: number[] } | undefined)?.dims;
this.slices = dims?.[3] ?? 0;
Expand Down Expand Up @@ -191,5 +197,31 @@ export class NiivueEngine implements ImageEngine {
public dispose(): void {
this.disposed = true;
this.nv = null;
this.made_release();
}

/**
* Whether the viewer was let go: read afresh after each wait, since a
* dispose can come while the open awaits.
*
* @returns True once disposed.
*/
private disposed_is(): boolean {
return this.disposed;
}

/**
* Lets the niivue go, once: its listeners and observers (its cleanup),
* then its WebGL context, which its cleanup leaves to the collector. A
* browser keeps only so many contexts, and a closed volume's counted
* against every viewer opened after it.
*/
private made_release(): void {
const nv: Niivue | null = this.made;
this.made = null;
if (nv === null) return;
const gl: GlContext | null = nv._gl;
try { nv.cleanup(); } catch { /* torn down already */ }
glContexts_lose([gl]);
}
}
Loading
Loading