mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Clean up unused worker threads for closed apps; other performance optimizations
This commit is contained in:
1 parent
9560f3ac8d
commit
2e4d20e130
20 files changed
+360
-13
No files matched your search
@@ -12,8 +12,29 @@ import java.nio.ByteBuffer;
|
||||
* JS/Java bridge, where it used to cost ~150ms per preview.
|
||||
*/
|
||||
public final class PreviewBitmapUtil {
|
||||
private static int[] cachedLut;
|
||||
private static long cachedGammaBits;
|
||||
private static boolean cachedGreen;
|
||||
|
||||
private PreviewBitmapUtil() {}
|
||||
|
||||
/** Reuse the current preview palette; rebuild only when gamma or color changes. */
|
||||
private static synchronized int[] lookupTable(double brightenGamma, boolean green) {
|
||||
long gammaBits = Double.doubleToLongBits(brightenGamma);
|
||||
if (cachedLut != null && cachedGammaBits == gammaBits && cachedGreen == green) {
|
||||
return cachedLut;
|
||||
}
|
||||
int[] lut = new int[256];
|
||||
for (int g = 0; g < 256; g++) {
|
||||
int v = (int) Math.max(0, Math.min(255, Math.round(255 * Math.pow(g / 255.0, brightenGamma))));
|
||||
lut[g] = green ? (0xff000000 | (v << 8)) : (0xff000000 | (v << 16) | (v << 8) | v);
|
||||
}
|
||||
cachedGammaBits = gammaBits;
|
||||
cachedGreen = green;
|
||||
cachedLut = lut;
|
||||
return lut;
|
||||
}
|
||||
|
||||
public static Bitmap fromGray(ByteBuffer gray, int width, int height, double brightenGamma) {
|
||||
return fromGray(gray, width, height, brightenGamma, false);
|
||||
}
|
||||
@@ -23,11 +44,7 @@ public final class PreviewBitmapUtil {
|
||||
if (gray == null || width <= 0 || height <= 0 || gray.remaining() < width * height) {
|
||||
throw new IllegalArgumentException("invalid gray preview buffer");
|
||||
}
|
||||
int[] lut = new int[256];
|
||||
for (int g = 0; g < 256; g++) {
|
||||
int v = (int) Math.max(0, Math.min(255, Math.round(255 * Math.pow(g / 255.0, brightenGamma))));
|
||||
lut[g] = green ? (0xff000000 | (v << 8)) : (0xff000000 | (v << 16) | (v << 8) | v);
|
||||
}
|
||||
int[] lut = lookupTable(brightenGamma, green);
|
||||
byte[] bytes = new byte[width * height];
|
||||
gray.get(bytes);
|
||||
int[] colors = new int[width * height];
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
* focus, tap-then-hold opens the window menu.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -187,6 +188,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: BlocksWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
* focus to the sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -180,6 +181,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FlappyWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
* Safe cards auto-play to the foundations after every move.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -144,6 +145,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FreecellWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getStringSetting } from "../../native/settings-store";
|
||||
import { QUADRANT_LAYOUT, SIX_SLOT_LAYOUT } from "./layout";
|
||||
|
||||
/** Configuration-only query usable by workers without loading widget/UI modules. */
|
||||
export function isTerminalWidgetConfigured(): boolean {
|
||||
const layout = getStringSetting("glanceboard.layout", "2x2") === "2x3" ? SIX_SLOT_LAYOUT : QUADRANT_LAYOUT;
|
||||
// Both layouts store their slots under the original quadrants key. None
|
||||
// of the default slots needs a worker, so absent keys cannot retain one.
|
||||
return layout.slots.some((_, index) =>
|
||||
getStringSetting(`glanceboard.${QUADRANT_LAYOUT.id}.slot.${index}`, "none") === "terminal");
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
* launches.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -152,6 +153,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: MinesweeperWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* guidance text (right pane) updates per GPS fix and ships as small deltas.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -275,6 +276,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "navigation-sensors":
|
||||
handleNavigationSensorEvent(message.event);
|
||||
break;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
* sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -290,6 +291,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: PinballWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* menu, via the phone app's text editor.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -165,6 +166,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isTerminalWidgetConfigured } from "../glanceboard/configuration";
|
||||
import { loadConnections, parseConnectionString } from "./connections";
|
||||
|
||||
/** Keep session-list connections alive for a configured widget, even while it is hidden. */
|
||||
export function hasTerminalBackgroundWork(): boolean {
|
||||
return isTerminalWidgetConfigured() &&
|
||||
loadConnections().some(connection => connection.enabled && parseConnectionString(connection.url) !== null);
|
||||
}
|
||||
@@ -31,6 +31,8 @@
|
||||
* re-attach snapshot resyncs contents and scrollback only once it's needed.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { hasTerminalBackgroundWork } from "./background";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -311,6 +313,14 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
reportIdle();
|
||||
break;
|
||||
case "shutdown":
|
||||
for (const control of controls.values()) stopControl(control);
|
||||
controls.clear();
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
openWindow(message.windowId, message.surfaceId, message.title, message.viewport);
|
||||
break;
|
||||
@@ -424,12 +434,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
// toggles edited in the Settings app, the Add-connection draft typed on the
|
||||
// phone).
|
||||
onSettingsStoreChanged((key) => {
|
||||
if (key.startsWith("glanceboard.")) {
|
||||
reportIdle();
|
||||
return;
|
||||
}
|
||||
if (!key.startsWith("terminal.")) return;
|
||||
switch (key) {
|
||||
case TERMINAL_CONNECTIONS_KEY:
|
||||
// Only once the app has actually been opened.
|
||||
if (controlsInitialized) syncControlsFromSettings();
|
||||
renderHubWindows();
|
||||
reportIdle();
|
||||
return;
|
||||
case NEW_CONNECTION_DRAFT_KEY:
|
||||
// Live keystrokes from the phone editor; repaint the add screen.
|
||||
@@ -438,7 +453,7 @@ onSettingsStoreChanged((key) => {
|
||||
case "terminal.autoReconnect":
|
||||
if (!terminalAutoReconnectSetting.get()) {
|
||||
cancelPendingReconnects();
|
||||
} else if (windows.size > 0) {
|
||||
} else if (windows.size > 0 || hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
if ((control.state?.phase ?? "idle") === "failed") scheduleControlReconnect(control);
|
||||
}
|
||||
@@ -450,6 +465,10 @@ onSettingsStoreChanged((key) => {
|
||||
}
|
||||
});
|
||||
|
||||
function reportIdle(): void {
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) post({ type: "worker-idle" });
|
||||
}
|
||||
|
||||
/** Cancel scheduled retries (auto-reconnect turned off); stale views stay marked. */
|
||||
function cancelPendingReconnects(): void {
|
||||
for (const control of controls.values()) {
|
||||
@@ -521,8 +540,8 @@ function closeWindow(windowId: string): void {
|
||||
windows.delete(windowId);
|
||||
windowIconActivity.delete(windowId);
|
||||
updateHubAnimation();
|
||||
// Auto-reconnect only runs while at least one terminal window is open.
|
||||
if (windows.size === 0) {
|
||||
// A configured widget owns the control connections after the last window closes.
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
cancelControlReconnect(control);
|
||||
}
|
||||
@@ -676,19 +695,18 @@ function noteSessionListRecency(control: ControlConnection, state: G2MirrorState
|
||||
/**
|
||||
* Retry a control connection after a backoff delay. The delay doubles per
|
||||
* scheduled attempt and resets when a connection reaches "connected" (or on
|
||||
* a manual Connect). No-op when auto-reconnect is off, no terminal window is
|
||||
* open, or the connection was disabled/removed meanwhile.
|
||||
* a manual Connect). Windows and a configured widget can both own the client.
|
||||
*/
|
||||
function scheduleControlReconnect(control: ControlConnection): void {
|
||||
if (control.reconnectTimer) return;
|
||||
if (!terminalAutoReconnectSetting.get()) return;
|
||||
if (windows.size === 0) return;
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) return;
|
||||
if (!control.config.enabled) return;
|
||||
const delayMs = control.reconnectDelayMs;
|
||||
control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS);
|
||||
control.reconnectTimer = setTimeout(() => {
|
||||
control.reconnectTimer = null;
|
||||
if (!terminalAutoReconnectSetting.get() || windows.size === 0) return;
|
||||
if (!terminalAutoReconnectSetting.get() || (windows.size === 0 && !hasTerminalBackgroundWork())) return;
|
||||
if (controls.get(control.config.id) !== control || !control.config.enabled) return;
|
||||
if ((control.state?.phase ?? "idle") === "failed") startControl(control);
|
||||
}, delayMs);
|
||||
|
||||
@@ -2228,6 +2228,7 @@ class DashboardController {
|
||||
const host = new WorkerAppHost({
|
||||
appId,
|
||||
worker: createWorker(),
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId); },
|
||||
configureSurface: (surfaceId, visible, heightMode) =>
|
||||
this.configureWindowSurface(surfaceId, visible, heightMode),
|
||||
setSurfaceVisible: (surfaceId, visible) => this.setWindowSurfaceVisible(surfaceId, visible),
|
||||
|
||||
@@ -503,6 +503,7 @@ export class IosPreviewController {
|
||||
? new IosNavigationSensors(event => worker.postMessage({ type: 'navigation-sensors', event })) : undefined
|
||||
const host = new WorkerAppHost({
|
||||
appId, worker, navigationSensors,
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId) },
|
||||
playBuzzerSequence: payload => this.actions.playBuzzerSequence(payload),
|
||||
openUrl: url => { void Utils.openUrl(url) },
|
||||
configureSurface: async (id, visible, heightMode) => {
|
||||
|
||||
@@ -18,6 +18,12 @@ function markChanged(key: string): void {
|
||||
}
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
const listeners = new Set<(key: string) => void>()
|
||||
export function disposeSettingsStore(): void {
|
||||
listeners.clear()
|
||||
if (pollTimer !== null) clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
observed.clear()
|
||||
}
|
||||
function changed(key: string): void {
|
||||
setTimeout(() => { for (const listener of [...listeners]) listener(key) }, 0)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,13 @@ let javaInstance: any = null;
|
||||
let retainedListenerProxy: any = null;
|
||||
const changeListeners = new Set<(key: string) => void>();
|
||||
|
||||
/** Release this isolate's native observer before its worker is terminated. */
|
||||
export function disposeSettingsStore(): void {
|
||||
changeListeners.clear();
|
||||
if (retainedListenerProxy !== null) getJava().unregisterListener(retainedListenerProxy);
|
||||
retainedListenerProxy = null;
|
||||
}
|
||||
|
||||
function getJava(): any {
|
||||
if (javaInstance === null) {
|
||||
const context = Utils.android?.getApplicationContext?.();
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { disposeSettingsStore } from "../../native/settings-store";
|
||||
|
||||
/** Called on the worker after its windows and app-owned resources are closed. */
|
||||
export function finishWorkerShutdown(): void {
|
||||
disposeSettingsStore();
|
||||
global.postMessage({ type: "worker-stopped" });
|
||||
}
|
||||
@@ -15,6 +15,10 @@ import { publishWorkerState } from "./worker-state";
|
||||
* worker→Java directly on Android; iOS posts baked frames to the main host.
|
||||
*/
|
||||
export type WorkerAppMessage =
|
||||
/** Last host window closed: report worker-idle unless background work still owns the worker. */
|
||||
| { type: "check-idle" }
|
||||
/** Release app-wide resources, then acknowledge with worker-stopped. */
|
||||
| { type: "shutdown" }
|
||||
| { type: "navigation-sensors"; event: NavigationSensorEvent }
|
||||
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
|
||||
| { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
|
||||
@@ -34,6 +38,8 @@ export type WorkerAppMessage =
|
||||
| { type: "tool-call"; callId: string; windowId: string; name: string; args: unknown };
|
||||
|
||||
export type WorkerAppReply =
|
||||
| { type: "worker-idle" }
|
||||
| { type: "worker-stopped" }
|
||||
| { type: "buzzer-sequence"; payload: number[] }
|
||||
| { type: "navigation-sensors"; request: NavigationSensorRequest }
|
||||
| { type: "open-url"; url: string }
|
||||
@@ -182,6 +188,8 @@ export type WorkerWindowSpec = {
|
||||
export type WorkerAppHostOptions = {
|
||||
appId: string;
|
||||
worker: Worker;
|
||||
/** Drop this host from the app cache as soon as shutdown begins. */
|
||||
onStopping?: () => void;
|
||||
navigationSensors?: { handle(request: NavigationSensorRequest): void; stop(): void };
|
||||
openUrl?: (url: string) => void;
|
||||
playBuzzerSequence?: (payload: Uint8Array) => Promise<void> | void;
|
||||
@@ -236,12 +244,23 @@ export class WorkerAppHost {
|
||||
*/
|
||||
private workerReady = false;
|
||||
private readonly queuedMessages: WorkerAppMessage[] = [];
|
||||
private stopping = false;
|
||||
private terminated = false;
|
||||
private shutdownTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly publishedStateKeys = new Set<string>();
|
||||
|
||||
constructor(private readonly options: WorkerAppHostOptions) {
|
||||
options.worker.onmessage = (event: MessageEvent) => {
|
||||
const message = event.data as WorkerAppReply | undefined;
|
||||
if (!message) return;
|
||||
if (this.stopping) {
|
||||
if (message.type === "worker-stopped") this.terminate();
|
||||
return;
|
||||
}
|
||||
switch (message.type) {
|
||||
case "worker-idle":
|
||||
if (!this.openWindows.size) this.shutdown();
|
||||
break;
|
||||
case "buzzer-sequence":
|
||||
if (this.openWindows.size) {
|
||||
void Promise.resolve(this.options.playBuzzerSequence?.(new Uint8Array(message.payload)))
|
||||
@@ -357,6 +376,7 @@ export class WorkerAppHost {
|
||||
// Titles are informational for now (sidebar shows icons only).
|
||||
break;
|
||||
case "publish-state":
|
||||
this.publishedStateKeys.add(message.key);
|
||||
publishWorkerState(message.key, message.state);
|
||||
break;
|
||||
case "set-tools":
|
||||
@@ -392,8 +412,33 @@ export class WorkerAppHost {
|
||||
return this.openWindows.size;
|
||||
}
|
||||
|
||||
private shutdown(): void {
|
||||
if (this.stopping) return;
|
||||
this.stopping = true;
|
||||
this.options.onStopping?.();
|
||||
this.queuedMessages.length = 0;
|
||||
this.options.navigationSensors?.stop();
|
||||
shell.setTrayIcon(this.options.appId, null);
|
||||
for (const key of this.publishedStateKeys) publishWorkerState(key, undefined);
|
||||
this.publishedStateKeys.clear();
|
||||
// The idle reply follows all close-window cleanup. Allow the worker to
|
||||
// release app-wide native subscriptions/sockets before killing its isolate.
|
||||
this.shutdownTimer = setTimeout(() => this.terminate(), 5000);
|
||||
this.options.worker.postMessage({ type: "shutdown" } satisfies WorkerAppMessage);
|
||||
}
|
||||
|
||||
private terminate(): void {
|
||||
if (this.terminated) return;
|
||||
this.terminated = true;
|
||||
if (this.shutdownTimer !== null) clearTimeout(this.shutdownTimer);
|
||||
this.shutdownTimer = null;
|
||||
this.options.worker.terminate();
|
||||
}
|
||||
|
||||
/** Open a window of this app and register it with the shell. */
|
||||
openWindow(spec: WorkerWindowSpec): ShellWindow {
|
||||
if (this.stopping) throw new Error(`Worker ${this.options.appId} is shutting down`);
|
||||
let closed = false;
|
||||
const surfaceId = `window:${spec.windowId}`;
|
||||
const heightMode = spec.heightMode ?? "min";
|
||||
this.openWindows.add(spec.windowId);
|
||||
@@ -419,6 +464,8 @@ export class WorkerAppHost {
|
||||
hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
|
||||
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
this.openWindows.delete(spec.windowId);
|
||||
if (!this.openWindows.size) this.options.navigationSensors?.stop();
|
||||
this.windowGestures.delete(spec.windowId);
|
||||
@@ -428,6 +475,7 @@ export class WorkerAppHost {
|
||||
this.failPendingToolCallsFor(spec.windowId);
|
||||
this.post({ type: "close-window", windowId: spec.windowId });
|
||||
this.options.removeSurface(surfaceId);
|
||||
if (!this.openWindows.size) this.post({ type: "check-idle" });
|
||||
},
|
||||
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph, () => this.windowIconActivity.get(spec.windowId) ?? "idle"),
|
||||
handleInput: (event, frameId) => {
|
||||
@@ -473,6 +521,7 @@ export class WorkerAppHost {
|
||||
void this.options
|
||||
.configureSurface(surfaceId, false, heightMode)
|
||||
.then(() => {
|
||||
if (closed || this.stopping) return;
|
||||
if (spec.focus) {
|
||||
shell.focusWindow(spec.windowId);
|
||||
}
|
||||
@@ -511,6 +560,7 @@ export class WorkerAppHost {
|
||||
}
|
||||
|
||||
private post(message: WorkerAppMessage): void {
|
||||
if (this.stopping) return;
|
||||
if (!this.workerReady) {
|
||||
this.queuedMessages.push(message);
|
||||
return;
|
||||
|
||||
+31
-1
@@ -63,11 +63,41 @@ class DisplayListRenderer(private val resources: Map<Int, ByteArray>, private va
|
||||
target.put(x + i % image.width, y + i / image.width, source * (options and 15) / 15)
|
||||
}
|
||||
}
|
||||
private fun copyScreen(screen: Target, composition: Target) {
|
||||
val source = screen.bytes
|
||||
val destination = composition.bytes
|
||||
// Shared backing arrays can overlap and the pixel loop intentionally reads
|
||||
// earlier writes. Keep that behavior, as well as shifted target clipping.
|
||||
if (source === destination || composition.shiftX != 0) {
|
||||
for (y in 0 until screen.height) for (x in 0 until screen.width) composition.put(x, y, screen.get(x, y))
|
||||
return
|
||||
}
|
||||
val width = minOf(screen.width, composition.width)
|
||||
val height = minOf(screen.height, composition.height)
|
||||
val sourceStride = screen.stride
|
||||
val destinationStride = composition.stride
|
||||
var src = screen.offset
|
||||
var dst = composition.offset
|
||||
if (screen.width == composition.width && width and 1 == 0) {
|
||||
source.copyInto(destination, dst, src, src + sourceStride * height)
|
||||
return
|
||||
}
|
||||
val pairs = width / 2
|
||||
for (y in 0 until height) {
|
||||
source.copyInto(destination, dst, src, src + pairs)
|
||||
// The last pixel of an odd-width row shares a byte with padding or
|
||||
// an untouched destination pixel; preserve that low nibble.
|
||||
if (width and 1 != 0) destination[dst + pairs] =
|
||||
((source[src + pairs].toInt() and 240) or (destination[dst + pairs].toInt() and 15)).toByte()
|
||||
src += sourceStride
|
||||
dst += destinationStride
|
||||
}
|
||||
}
|
||||
/** Validate the whole graph before changing any pixels. Resource writes remain call-scoped. */
|
||||
fun render(root: Int, screen: Target, composition: Target): Set<Int> {
|
||||
val references = mutableSetOf<Int>()
|
||||
for (apply in listOf(false, true)) {
|
||||
if (apply) for (y in 0 until screen.height) for (x in 0 until screen.width) composition.put(x, y, screen.get(x, y))
|
||||
if (apply) copyScreen(screen, composition)
|
||||
if (root != DrawProtocol.SCREEN) executeList(root, composition, screen, apply, mutableListOf(), intArrayOf(4096), references)
|
||||
}
|
||||
return references
|
||||
|
||||
@@ -29,6 +29,7 @@ function worker() {
|
||||
scheduleRender() { renderCount++; }, renderAndSubmit() {}, maybeReconnectView() {},
|
||||
// Glanceboard publication is outside the sidebar activity fixture.
|
||||
publishSessionsSnapshot() {},
|
||||
hasTerminalBackgroundWork: () => false,
|
||||
controlsInitialized: true, controls: new Map(), TERMINAL_TOOLS: [],
|
||||
getTerminalFontConfig: () => ({ cellWidth: 6, cellHeight: 12 }),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
function fixture() {
|
||||
const sent = [], stopped = [], removed = [], focused = [], timers = new Map(), published = [];
|
||||
let kills = 0, resolveSurface;
|
||||
const worker = { postMessage: message => sent.push(message), terminate: () => kills++ };
|
||||
const shellWindows = new Map();
|
||||
const load = loader({ global: {}, setTimeout: (fn, ms) => { timers.set(fn, ms); return fn; }, clearTimeout: fn => timers.delete(fn) }, {
|
||||
'../../graphics/image': {}, './chrome-layer': { windowIcon() {} },
|
||||
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
|
||||
'./geometry': { appViewportSize: () => ({ width: 576, height: 288 }) },
|
||||
'../../native/frame-timings': {}, './worker-state': { publishWorkerState: (...args) => published.push(args) },
|
||||
'./shell': { shell: { registerWindow: w => shellWindows.set(w.windowId, w), setTrayIcon() {},
|
||||
focusWindow: id => focused.push(id), isWindowFocused: () => false } },
|
||||
});
|
||||
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts');
|
||||
const host = new WorkerAppHost({ appId: 'game', worker, onStopping: () => stopped.push(host),
|
||||
configureSurface: () => new Promise(resolve => { resolveSurface = resolve; }),
|
||||
setSurfaceVisible() {}, removeSurface: id => removed.push(id), requestShellRender() {} });
|
||||
return { host, sent, stopped, timers, removed, focused, published, get kills() { return kills; },
|
||||
ready: () => worker.onmessage({ data: { type: 'worker-ready' } }),
|
||||
reply: data => worker.onmessage({ data }),
|
||||
open: id => host.openWindow({ windowId: id, title: id, focus: true }),
|
||||
surfaceReady: () => resolveSurface(),
|
||||
};
|
||||
}
|
||||
|
||||
test('last window drains close cleanup, then exits the worker and releases its cached host', () => {
|
||||
const f = fixture(); f.ready(); const a = f.open('a'), b = f.open('b');
|
||||
a.close(); assert.equal(f.sent.some(m => m.type === 'check-idle'), false);
|
||||
b.close(); assert.deepEqual(f.sent.slice(-2).map(m => m.type), ['close-window', 'check-idle']);
|
||||
f.reply({ type: 'publish-state', key: 'test', state: 1 });
|
||||
f.reply({ type: 'worker-idle' });
|
||||
assert.equal(f.stopped.length, 1); assert.equal(f.kills, 0);
|
||||
assert.equal(f.sent.at(-1).type, 'shutdown');
|
||||
assert.deepEqual(f.published.at(-1), ['test', undefined]);
|
||||
f.reply({ type: 'open-window-request', windowId: 'late', title: 'late' });
|
||||
assert.equal(f.host.windowCount(), 0);
|
||||
f.reply({ type: 'worker-stopped' }); f.reply({ type: 'worker-stopped' });
|
||||
assert.equal(f.kills, 1); assert.equal(f.timers.size, 0);
|
||||
assert.throws(() => f.open('reopen'), /shutting down/);
|
||||
});
|
||||
|
||||
test('closing before worker-ready still delivers open/close/idle in order', async () => {
|
||||
const f = fixture(); f.open('loading').close(); assert.equal(f.sent.length, 0);
|
||||
f.ready(); assert.deepEqual(f.sent.map(m => m.type), ['open-window', 'close-window', 'check-idle']);
|
||||
f.surfaceReady(); await flush(); assert.deepEqual(f.focused, []);
|
||||
f.reply({ type: 'worker-idle' }); f.reply({ type: 'worker-stopped' }); assert.equal(f.kills, 1);
|
||||
});
|
||||
|
||||
test('a late idle report cannot kill a reopened window, and background ownership can end later', () => {
|
||||
const f = fixture(); f.ready(); f.open('first').close();
|
||||
// A background worker does not report idle while it still owns connections.
|
||||
assert.equal(f.stopped.length, 0);
|
||||
const reopened = f.open('second'); f.reply({ type: 'worker-idle' });
|
||||
assert.equal(f.stopped.length, 0);
|
||||
reopened.close(); f.reply({ type: 'worker-idle' });
|
||||
assert.equal(f.stopped.length, 1);
|
||||
for (const timeout of [...f.timers.keys()]) timeout();
|
||||
assert.equal(f.kills, 1, 'a hung shutdown cannot leave the thread alive');
|
||||
});
|
||||
|
||||
test('Terminal stays alive only for a configured visible-layout widget and an enabled valid connection', () => {
|
||||
const settings = new Map();
|
||||
const load = loader({}, { '../../native/settings-store': {
|
||||
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
} });
|
||||
const { hasTerminalBackgroundWork } = load('app/apps/terminal/background.ts');
|
||||
settings.set('terminal.connections', JSON.stringify([{ id: 'test', url: 'g2mirror://token@localhost', enabled: true }]));
|
||||
assert.equal(hasTerminalBackgroundWork(), false);
|
||||
settings.set('glanceboard.quadrants.slot.1', 'terminal'); assert.equal(hasTerminalBackgroundWork(), true);
|
||||
settings.set('glanceboard.enabled', false); assert.equal(hasTerminalBackgroundWork(), true, 'configured cards also appear in the Glanceboard app');
|
||||
settings.delete('glanceboard.quadrants.slot.1'); settings.set('glanceboard.quadrants.slot.5', 'terminal');
|
||||
assert.equal(hasTerminalBackgroundWork(), false);
|
||||
settings.set('glanceboard.layout', '2x3'); assert.equal(hasTerminalBackgroundWork(), true);
|
||||
for (const connections of [[], [{ id: 'test', url: 'invalid' }], [{ id: 'test', url: 'g2mirror://token@localhost', enabled: false }]]) {
|
||||
settings.set('terminal.connections', JSON.stringify(connections)); assert.equal(hasTerminalBackgroundWork(), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('worker shutdown unregisters the isolate settings observer before acknowledging', () => {
|
||||
const calls = [];
|
||||
const { finishWorkerShutdown } = loader({ global: { postMessage: message => calls.push(message.type) } }, {
|
||||
'../../native/settings-store': { disposeSettingsStore: () => calls.push('dispose') },
|
||||
})('app/ui/shell/worker-lifecycle.ts');
|
||||
finishWorkerShutdown(); assert.deepEqual(calls, ['dispose', 'worker-stopped']);
|
||||
});
|
||||
|
||||
test('every app worker answers idle checks and shutdown; Terminal releases controls only on shutdown', () => {
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
for (const app of ['blocks', 'flappy', 'freecell', 'minesweeper', 'navigate', 'pinball', 'roam', 'terminal']) {
|
||||
const path = `app/apps/${app}/${app}-app.worker.ts`;
|
||||
const source = ts.createSourceFile(path, fs.readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true);
|
||||
const statements = source.statements.filter(s =>
|
||||
ts.isExpressionStatement(s) && ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage' ||
|
||||
app === 'terminal' && ts.isFunctionDeclaration(s) && s.name?.text === 'reportIdle' ||
|
||||
app === 'terminal' && ts.isExpressionStatement(s) && ts.isCallExpression(s.expression) && s.expression.expression.getText(source) === 'onSettingsStoreChanged');
|
||||
const messages = [], cleanup = []; let background = true, changed;
|
||||
const context = { global: {}, windows: new Map(), controls: new Map([['one', 1], ['two', 2]]),
|
||||
post: message => messages.push(message.type), hasTerminalBackgroundWork: () => background,
|
||||
finishWorkerShutdown: () => cleanup.push('shutdown'), stopControl: value => cleanup.push(value),
|
||||
onSettingsStoreChanged: callback => { changed = callback; },
|
||||
};
|
||||
vm.runInNewContext(ts.transpileModule(statements.map(s => s.getText(source)).join('\n'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
context.global.onmessage({ data: { type: 'check-idle' } });
|
||||
if (app === 'terminal') {
|
||||
assert.deepEqual(messages, []); assert.equal(context.controls.size, 2);
|
||||
background = false; changed('glanceboard.quadrants.slot.1');
|
||||
}
|
||||
assert.deepEqual(messages, ['worker-idle'], app);
|
||||
assert.deepEqual(cleanup, [], 'idle reports must not tear down a concurrently reopened app');
|
||||
context.global.onmessage({ data: { type: 'shutdown' } });
|
||||
assert.deepEqual(cleanup, app === 'terminal' ? [1, 2, 'shutdown'] : ['shutdown']);
|
||||
if (app === 'terminal') assert.equal(context.controls.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('both controllers remove only the retiring host and create a fresh worker on relaunch', () => {
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
for (const platform of ['dashboard', 'ios-preview']) {
|
||||
const path = `app/g2/${platform}-controller.ts`;
|
||||
const source = ts.createSourceFile(path, fs.readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true);
|
||||
const controller = source.statements.find(s => ts.isClassDeclaration(s) && s.name.text.endsWith('Controller'));
|
||||
const method = controller.members.find(s => s.name?.getText(source) === 'ensureWorkerHost');
|
||||
const context = { exports: {}, WorkerAppHost: class { constructor(options) { this.options = options; } } };
|
||||
vm.runInNewContext(ts.transpileModule(`export class Controller { ${method.getText(source)} }`, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
const host = new context.exports.Controller(); host.appHosts = new Map();
|
||||
const first = host.ensureWorkerHost('flappy', () => ({}));
|
||||
assert.equal(host.ensureWorkerHost('flappy', assert.fail), first);
|
||||
first.options.onStopping(); assert.equal(host.appHosts.size, 0);
|
||||
const next = host.ensureWorkerHost('flappy', () => ({})); assert.notEqual(next, first);
|
||||
first.options.onStopping(); assert.equal(host.appHosts.get('flappy'), next);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user