forked from Blendman974/faceclaw
Terminal feature; raw screenshots.
This commit is contained in:
1 parent
d2a942f5a3
commit
fab6f6689e
19 files changed
+1075
-10
No files matched your search
@@ -0,0 +1,73 @@
|
||||
import type { Terminal as XtermTerminal } from "@xterm/headless";
|
||||
|
||||
// xterm-headless expects a few browser globals (navigator for platform
|
||||
// sniffing, window for timer/scheduling lookups) that the NativeScript
|
||||
// runtime doesn't define. Provide minimal stand-ins before the library is
|
||||
// evaluated (hence require, not a hoisted import).
|
||||
const runtimeGlobal = globalThis as any;
|
||||
if (typeof runtimeGlobal.navigator === "undefined") {
|
||||
runtimeGlobal.navigator = {
|
||||
userAgent: "NativeScript",
|
||||
platform: "Android",
|
||||
language: "en",
|
||||
languages: ["en"],
|
||||
};
|
||||
}
|
||||
if (typeof runtimeGlobal.window === "undefined") {
|
||||
runtimeGlobal.window = runtimeGlobal;
|
||||
}
|
||||
if (typeof runtimeGlobal.self === "undefined") {
|
||||
runtimeGlobal.self = runtimeGlobal;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const { Terminal } = require("@xterm/headless") as typeof import("@xterm/headless");
|
||||
|
||||
/**
|
||||
* Headless terminal emulator for g2mirror streams: feed it the raw
|
||||
* VT100/xterm bytes from snapshot/output messages and read back the visible
|
||||
* text grid. Formatting (color/bold/inverse) is deliberately dropped for
|
||||
* now — we only mirror the text.
|
||||
*/
|
||||
export class TerminalEmulator {
|
||||
private readonly term: XtermTerminal;
|
||||
|
||||
constructor(
|
||||
readonly cols: number,
|
||||
readonly rows: number,
|
||||
) {
|
||||
this.term = new Terminal({
|
||||
cols,
|
||||
rows,
|
||||
scrollback: 0,
|
||||
allowProposedApi: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply terminal bytes. onProcessed fires once the emulator has actually
|
||||
* parsed them (xterm buffers writes internally), so schedule repaints there.
|
||||
*/
|
||||
write(data: Uint8Array, onProcessed: () => void): void {
|
||||
this.term.write(data, onProcessed);
|
||||
}
|
||||
|
||||
/** Full reset; snapshots are defined as repainting from a cleared screen. */
|
||||
reset(): void {
|
||||
this.term.reset();
|
||||
}
|
||||
|
||||
visibleLines(): string[] {
|
||||
const buffer = this.term.buffer.active;
|
||||
const lines: string[] = [];
|
||||
for (let row = 0; row < this.rows; row++) {
|
||||
const line = buffer.getLine(buffer.viewportY + row);
|
||||
lines.push(line ? line.translateToString(true) : "");
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
cursor(): { x: number; y: number } {
|
||||
const buffer = this.term.buffer.active;
|
||||
return { x: buffer.cursorX, y: buffer.cursorY };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import { getFont } from "~/graphics/bdffont";
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "~/graphics/image";
|
||||
import {
|
||||
G2MirrorClient,
|
||||
type G2MirrorSession,
|
||||
type G2MirrorState,
|
||||
} from "~/native/g2mirror-client";
|
||||
import {
|
||||
terminalAuthTokenSetting,
|
||||
terminalHostSetting,
|
||||
terminalPortSetting,
|
||||
textSettingMenuItem,
|
||||
} from "../dashboard-settings";
|
||||
import { TOP_LEFT_MENU_LAYOUT } from "../dashboard";
|
||||
import { MenuLayer } from "../menu";
|
||||
import { type DashboardInputEvent, type Layer, type LayerActions, type LayerContext } from "../layers";
|
||||
|
||||
// Terminus-12 has a 6x12 cell, so the full 576x288 lens is a 96x24 grid —
|
||||
// this is the size we declare in the g2mirror init handshake, fixed per
|
||||
// websocket connection.
|
||||
const terminalFont = getFont("terminus12");
|
||||
const CELL_WIDTH = 6;
|
||||
const CELL_HEIGHT = 12;
|
||||
const TERMINAL_COLS = G2_LENS_WIDTH / CELL_WIDTH;
|
||||
const TERMINAL_ROWS = G2_LENS_HEIGHT / CELL_HEIGHT;
|
||||
const DEVICE_NAME = "Faceclaw G2";
|
||||
|
||||
const HUB_ROW_HEIGHT = 20;
|
||||
const HUB_LIST_TOP = 64;
|
||||
|
||||
type HubItem = {
|
||||
label: string;
|
||||
onSelect: (ctx: LayerContext) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The Terminal app hub: connection status, list of live g2mirror sessions,
|
||||
* and the app-local settings menu. Selecting a session attaches and opens
|
||||
* the full-screen readonly terminal view.
|
||||
*/
|
||||
export class TerminalAppLayer implements Layer {
|
||||
private client: G2MirrorClient | null = null;
|
||||
private clientState: G2MirrorState | null = null;
|
||||
private selectedIndex = 0;
|
||||
private lastCtx: LayerContext | null = null;
|
||||
private activeViewLayer: TerminalViewLayer | null = null;
|
||||
private unsubscribers: Array<() => void> = [];
|
||||
|
||||
constructor(private readonly actions: LayerActions) {
|
||||
selfTestEmulator();
|
||||
this.startClient();
|
||||
}
|
||||
|
||||
private startClient(): void {
|
||||
this.stopClient();
|
||||
const host = terminalHostSetting.get().trim();
|
||||
if (!host) return;
|
||||
const port = parseInt(terminalPortSetting.get(), 10) || 8737;
|
||||
const client = new G2MirrorClient({
|
||||
host,
|
||||
port,
|
||||
authToken: terminalAuthTokenSetting.get(),
|
||||
deviceName: DEVICE_NAME,
|
||||
cols: TERMINAL_COLS,
|
||||
rows: TERMINAL_ROWS,
|
||||
});
|
||||
this.client = client;
|
||||
this.clientState = client.state();
|
||||
this.unsubscribers.push(
|
||||
client.onStateChange((state) => {
|
||||
this.clientState = state;
|
||||
this.actions.requestRender();
|
||||
}),
|
||||
client.onSessionAttached(() => {
|
||||
this.openViewLayer();
|
||||
}),
|
||||
client.onSessionDetached(() => {
|
||||
this.closeViewLayer();
|
||||
}),
|
||||
);
|
||||
client.start();
|
||||
}
|
||||
|
||||
private stopClient(): void {
|
||||
for (const unsubscribe of this.unsubscribers.splice(0)) {
|
||||
unsubscribe();
|
||||
}
|
||||
this.client?.stop();
|
||||
this.client = null;
|
||||
this.clientState = null;
|
||||
}
|
||||
|
||||
private openViewLayer(): void {
|
||||
const ctx = this.lastCtx;
|
||||
if (!ctx || !this.client || this.activeViewLayer) return;
|
||||
const viewLayer = new TerminalViewLayer(this.client, this.actions, () => {
|
||||
if (this.activeViewLayer === viewLayer) {
|
||||
this.activeViewLayer = null;
|
||||
}
|
||||
});
|
||||
this.activeViewLayer = viewLayer;
|
||||
ctx.stack.push(viewLayer);
|
||||
this.actions.requestRender();
|
||||
}
|
||||
|
||||
private closeViewLayer(): void {
|
||||
const ctx = this.lastCtx;
|
||||
const viewLayer = this.activeViewLayer;
|
||||
if (!ctx || !viewLayer) return;
|
||||
ctx.stack.popIfTop((layer) => layer === viewLayer);
|
||||
this.actions.requestRender();
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
this.lastCtx = ctx;
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
image.drawText(terminalFont, 18, 14, "Terminal", 220);
|
||||
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
|
||||
image.drawText(terminalFont, 24, 38, this.statusLine(), 170);
|
||||
|
||||
let listTop = HUB_LIST_TOP;
|
||||
if (!terminalHostSetting.get().trim()) {
|
||||
image.drawText(terminalFont, 24, 56, "To set up a server, see:", 150);
|
||||
image.drawText(terminalFont, 24, 70, "https://github.com/jimrandomh/g2mirror", 190);
|
||||
listTop += 32;
|
||||
}
|
||||
|
||||
const items = this.hubItems();
|
||||
this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, items.length - 1));
|
||||
for (let index = 0; index < items.length; index++) {
|
||||
const y = listTop + index * HUB_ROW_HEIGHT;
|
||||
if (y + HUB_ROW_HEIGHT > G2_LENS_HEIGHT - 40) break;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
image.fillRoundedRect(20, y - 2, G2_LENS_WIDTH - 40, HUB_ROW_HEIGHT - 1, 15);
|
||||
image.drawRoundedRect(20, y - 2, G2_LENS_WIDTH - 40, HUB_ROW_HEIGHT - 1, 45);
|
||||
}
|
||||
image.drawText(terminalFont, 32, y + 2, items[index]!.label, selected ? 255 : 200);
|
||||
}
|
||||
|
||||
image.drawText(terminalFont, 24, G2_LENS_HEIGHT - 36, "Double-click to go back", 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
|
||||
this.lastCtx = ctx;
|
||||
const items = this.hubItems();
|
||||
switch (event.type) {
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
case "scroll-up":
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.selectedIndex = Math.min(items.length - 1, this.selectedIndex + 1);
|
||||
return;
|
||||
case "click": {
|
||||
const item = items[Math.max(0, Math.min(this.selectedIndex, items.length - 1))];
|
||||
item?.onSelect(ctx);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.stopClient();
|
||||
}
|
||||
|
||||
private statusLine(): string {
|
||||
const host = terminalHostSetting.get().trim();
|
||||
if (!host) {
|
||||
return "No host configured. Open Settings below.";
|
||||
}
|
||||
return this.clientState?.status ?? "Not connected.";
|
||||
}
|
||||
|
||||
private hubItems(): HubItem[] {
|
||||
const items: HubItem[] = [];
|
||||
const state = this.clientState;
|
||||
const phase = state?.phase ?? "idle";
|
||||
|
||||
if (phase === "connected" || phase === "attached") {
|
||||
for (const session of state?.sessions ?? []) {
|
||||
items.push({
|
||||
label: sessionLabel(session),
|
||||
onSelect: () => {
|
||||
this.client?.connectSession(session.socket);
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!state?.sessions.length) {
|
||||
items.push({
|
||||
label: "(no live sessions; run g2mirror <command>)",
|
||||
onSelect: () => {
|
||||
this.client?.listSessions();
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (phase === "idle" || phase === "failed") {
|
||||
items.push({
|
||||
label: terminalHostSetting.get().trim() ? "Connect" : "Connect (host not set)",
|
||||
onSelect: () => {
|
||||
this.startClient();
|
||||
},
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
label: "Settings",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(createTerminalSettingsMenuLayer());
|
||||
},
|
||||
});
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
/** Full-screen readonly mirror of the attached session. */
|
||||
class TerminalViewLayer implements Layer {
|
||||
private readonly emulator: import("./terminal-emulator").TerminalEmulator;
|
||||
private receivedData = false;
|
||||
private unsubscribeData: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly client: G2MirrorClient,
|
||||
private readonly actions: LayerActions,
|
||||
private readonly onClosed: () => void,
|
||||
) {
|
||||
// Lazy import keeps xterm out of the startup path; it is only needed
|
||||
// once a terminal is actually viewed.
|
||||
const { TerminalEmulator } = require("./terminal-emulator") as typeof import("./terminal-emulator");
|
||||
this.emulator = new TerminalEmulator(TERMINAL_COLS, TERMINAL_ROWS);
|
||||
this.unsubscribeData = client.onTerminalData((data, kind) => {
|
||||
if (kind === "snapshot") {
|
||||
this.emulator.reset();
|
||||
}
|
||||
this.receivedData = true;
|
||||
this.emulator.write(data, () => this.actions.requestRender());
|
||||
});
|
||||
client.view();
|
||||
}
|
||||
|
||||
paint(): GrayImage {
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
if (!this.receivedData) {
|
||||
image.drawText(terminalFont, 24, 130, "Waiting for terminal output...", 170);
|
||||
image.drawText(terminalFont, 24, 150, "Double-click to go back", 110);
|
||||
return image;
|
||||
}
|
||||
const cursor = this.emulator.cursor();
|
||||
image.fillRect(cursor.x * CELL_WIDTH, cursor.y * CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT, 70);
|
||||
const lines = this.emulator.visibleLines();
|
||||
for (let row = 0; row < lines.length; row++) {
|
||||
const line = lines[row]!;
|
||||
if (line.length === 0) continue;
|
||||
image.drawText(terminalFont, 0, row * CELL_HEIGHT, line, 200);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
|
||||
// Readonly for now: protocol v1 has no keyboard input, so scrolls and
|
||||
// clicks are ignored rather than forwarded.
|
||||
if (event.type === "double-click") {
|
||||
ctx.stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.unsubscribeData?.();
|
||||
this.unsubscribeData = null;
|
||||
// Let the wrapped app resize back for the person at the real keyboard,
|
||||
// and free the session for other clients.
|
||||
this.client.unview();
|
||||
this.client.disconnectSession();
|
||||
this.onClosed();
|
||||
}
|
||||
}
|
||||
|
||||
// One-time check that the xterm-headless emulator evaluates and parses in
|
||||
// this JS runtime, run at app open so a broken dependency surfaces in the log
|
||||
// immediately instead of mid-session-attach.
|
||||
let emulatorSelfTested = false;
|
||||
function selfTestEmulator(): void {
|
||||
if (emulatorSelfTested) return;
|
||||
emulatorSelfTested = true;
|
||||
try {
|
||||
const { TerminalEmulator } = require("./terminal-emulator") as typeof import("./terminal-emulator");
|
||||
const emulator = new TerminalEmulator(8, 2);
|
||||
emulator.write(Uint8Array.from([0x68, 0x69, 0x1b, 0x5b, 0x31, 0x6d, 0x21]), () => {
|
||||
console.log(`terminal emulator self-test: ${JSON.stringify(emulator.visibleLines())}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("terminal emulator failed to load:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function createTerminalSettingsMenuLayer(): MenuLayer {
|
||||
return new MenuLayer(
|
||||
"Terminal > Settings",
|
||||
[
|
||||
textSettingMenuItem(terminalHostSetting),
|
||||
textSettingMenuItem(terminalPortSetting),
|
||||
textSettingMenuItem(terminalAuthTokenSetting),
|
||||
],
|
||||
TOP_LEFT_MENU_LAYOUT,
|
||||
);
|
||||
}
|
||||
|
||||
function sessionLabel(session: G2MirrorSession): string {
|
||||
const hint = session.cwdHint.replace(/^_+/, "").replace(/_+/g, "/");
|
||||
return `${hint || "session"} (pid ${session.pid})`;
|
||||
}
|
||||
@@ -34,6 +34,24 @@ type ConfigSettingOptions<TValue, TId extends string> = {
|
||||
formatValue?: (value: TValue) => string;
|
||||
};
|
||||
|
||||
// Fired after any setting's set(); lets phone-side UI that depends on
|
||||
// settings toggled from the glasses (e.g. the raw-screenshot button) update
|
||||
// without waiting for an unrelated snapshot emit.
|
||||
const settingChangeListeners = new Set<() => void>();
|
||||
|
||||
export function onAnySettingChanged(listener: () => void): () => void {
|
||||
settingChangeListeners.add(listener);
|
||||
return () => {
|
||||
settingChangeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function notifySettingChanged(): void {
|
||||
for (const listener of Array.from(settingChangeListeners)) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ConfigSetting<TValue, TId extends string = string> {
|
||||
readonly id: TId;
|
||||
readonly label: string;
|
||||
@@ -69,6 +87,7 @@ export class ConfigSettingBoolean<TId extends string = string> extends ConfigSet
|
||||
|
||||
set(value: boolean): boolean {
|
||||
ApplicationSettings.setBoolean(this.storageKey, value);
|
||||
notifySettingChanged();
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -107,6 +126,7 @@ export class ConfigSettingEnum<TValue extends string, TId extends string = strin
|
||||
set(value: TValue): TValue {
|
||||
const normalized = this.normalizer(value);
|
||||
ApplicationSettings.setString(this.storageKey, normalized);
|
||||
notifySettingChanged();
|
||||
return normalized;
|
||||
}
|
||||
|
||||
@@ -141,6 +161,7 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
|
||||
set(value: string): string {
|
||||
const normalized = this.normalizer(value);
|
||||
ApplicationSettings.setString(this.storageKey, normalized);
|
||||
notifySettingChanged();
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -239,6 +260,40 @@ export const voiceControlEnabledSetting = new ConfigSettingBoolean({
|
||||
defaultValue: false,
|
||||
});
|
||||
|
||||
export const rawScreenshotsEnabledSetting = new ConfigSettingBoolean({
|
||||
id: "raw-screenshots-enabled",
|
||||
label: "Take raw screenshots",
|
||||
storageKey: "developer.rawScreenshots",
|
||||
defaultValue: false,
|
||||
});
|
||||
|
||||
export const terminalHostSetting = new ConfigSettingString({
|
||||
id: "terminal-host",
|
||||
label: "Host",
|
||||
storageKey: "terminal.host",
|
||||
defaultValue: "",
|
||||
editorTitle: "g2mirror host (tailscale IP)",
|
||||
glassesEditTitle: "Edit terminal host",
|
||||
});
|
||||
|
||||
export const terminalPortSetting = new ConfigSettingString({
|
||||
id: "terminal-port",
|
||||
label: "Port",
|
||||
storageKey: "terminal.port",
|
||||
defaultValue: "8737",
|
||||
editorTitle: "g2mirror port",
|
||||
glassesEditTitle: "Edit terminal port",
|
||||
});
|
||||
|
||||
export const terminalAuthTokenSetting = new ConfigSettingString({
|
||||
id: "terminal-auth-token",
|
||||
label: "Auth token",
|
||||
storageKey: "terminal.authToken",
|
||||
defaultValue: "",
|
||||
editorTitle: "g2mirror auth token",
|
||||
glassesEditTitle: "Edit terminal auth token",
|
||||
});
|
||||
|
||||
export const nightscoutSiteUrlSetting = new ConfigSettingString({
|
||||
id: "nightscout-site-url",
|
||||
label: "Nightscout site URL",
|
||||
|
||||
@@ -40,6 +40,7 @@ export let dashboardState: DashboardState = {
|
||||
};
|
||||
|
||||
const dashboardActions: LayerActions = {
|
||||
requestRender: () => {},
|
||||
disconnect: () => {},
|
||||
startTextSettingEdit: () => {},
|
||||
endTextSettingEdit: () => {},
|
||||
|
||||
@@ -7,6 +7,7 @@ import { MenuLayer } from "../menu";
|
||||
import { NotificationsListLayer } from "../notifications";
|
||||
import { createNightscoutSettingsMenuLayer, createSettingsMenuLayer } from "./settings-menus";
|
||||
import { TelepromptLayer } from "../apps/teleprompt";
|
||||
import { TerminalAppLayer } from "../apps/terminal";
|
||||
import { StopwatchLayer } from "../apps/stopwatch";
|
||||
import { TranscribeLayer } from "../apps/transcribe";
|
||||
import { ScreenTestLayer } from "../apps/screen-test";
|
||||
@@ -100,6 +101,12 @@ function createAppsMenuLayer(): MenuLayer {
|
||||
layer.start(ctx);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Terminal",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new TerminalAppLayer(ctx.actions));
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Screen test",
|
||||
onSelect: (ctx) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { dashboardState, TOP_LEFT_MENU_LAYOUT } from "../dashboard";
|
||||
import { batteryDisplayModeSetting, dashboardSlotIds, enumSettingMenuItem, showSignalStrengthSetting, showAndroidNotificationsSetting, showBatteryIndicatorsSetting, showFaceclawLogoSetting, systemCardNameSetting, textSettingMenuItem, toggleSettingMenuItem, voiceControlEnabledSetting, dashboardSlotSettings, nightscoutSiteUrlSetting, nightscoutApiTokenSetting, screenTimeoutSetting } from "../dashboard-settings";
|
||||
import { batteryDisplayModeSetting, dashboardSlotIds, enumSettingMenuItem, rawScreenshotsEnabledSetting, showSignalStrengthSetting, showAndroidNotificationsSetting, showBatteryIndicatorsSetting, showFaceclawLogoSetting, systemCardNameSetting, textSettingMenuItem, toggleSettingMenuItem, voiceControlEnabledSetting, dashboardSlotSettings, nightscoutSiteUrlSetting, nightscoutApiTokenSetting, screenTimeoutSetting } from "../dashboard-settings";
|
||||
import { MenuLayer } from "../menu";
|
||||
|
||||
export function createSettingsMenuLayer(): MenuLayer {
|
||||
@@ -30,6 +30,22 @@ export function createSettingsMenuLayer(): MenuLayer {
|
||||
ctx.stack.push(createIntegrationsMenuLayer());
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Developer",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(createDeveloperSettingsMenuLayer());
|
||||
},
|
||||
},
|
||||
],
|
||||
TOP_LEFT_MENU_LAYOUT,
|
||||
);
|
||||
}
|
||||
|
||||
function createDeveloperSettingsMenuLayer(): MenuLayer {
|
||||
return new MenuLayer(
|
||||
"Settings > Developer",
|
||||
[
|
||||
toggleSettingMenuItem(rawScreenshotsEnabledSetting),
|
||||
],
|
||||
TOP_LEFT_MENU_LAYOUT,
|
||||
);
|
||||
|
||||
+17
-3
@@ -11,6 +11,8 @@ export type DashboardInputEvent =
|
||||
| { type: "unknown"; kind: string; eventSource: number; eventType: number };
|
||||
|
||||
export type LayerActions = {
|
||||
/** Ask for a dashboard repaint+transmit, e.g. when async data arrives. */
|
||||
requestRender: () => void;
|
||||
disconnect: () => Promise<void> | void;
|
||||
startTextSettingEdit: (setting: ConfigSettingString) => Promise<void> | void;
|
||||
endTextSettingEdit: () => Promise<void> | void;
|
||||
@@ -24,6 +26,14 @@ export type LayerActions = {
|
||||
|
||||
export type PaintBelow = () => GrayImage;
|
||||
|
||||
function notifyRemoved(layer: Layer | undefined): void {
|
||||
try {
|
||||
layer?.onRemoved?.();
|
||||
} catch (error) {
|
||||
console.warn("layer onRemoved failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
export interface LayerContext {
|
||||
readonly stack: LayerStack;
|
||||
readonly actions: LayerActions;
|
||||
@@ -33,6 +43,8 @@ export interface Layer {
|
||||
readonly paintOverBase?: boolean;
|
||||
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage;
|
||||
handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> | void;
|
||||
/** Called when the layer leaves the stack by any path (pop or clearToBase). */
|
||||
onRemoved?(): void;
|
||||
}
|
||||
|
||||
export class LayerStack {
|
||||
@@ -53,21 +65,23 @@ export class LayerStack {
|
||||
|
||||
pop(): void {
|
||||
if (this.layers.length > 1) {
|
||||
this.layers.pop();
|
||||
notifyRemoved(this.layers.pop());
|
||||
}
|
||||
}
|
||||
|
||||
/** Pop the top layer only if it matches; returns whether a layer was popped. */
|
||||
popIfTop(predicate: (layer: Layer) => boolean): boolean {
|
||||
if (this.layers.length > 1 && predicate(this.layers[this.layers.length - 1]!)) {
|
||||
this.layers.pop();
|
||||
notifyRemoved(this.layers.pop());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
clearToBase(): void {
|
||||
this.layers.splice(1);
|
||||
for (const layer of this.layers.splice(1)) {
|
||||
notifyRemoved(layer);
|
||||
}
|
||||
}
|
||||
|
||||
isAtBase(): boolean {
|
||||
|
||||
Reference in new issue
Block a user