Allow backgrounding EvenHub apps

This commit is contained in:
James Babcock committed 2026-08-16 20:59:42 -07:00
1 parent cde29cc4d0
commit b9f48c8e16
10 files changed
+376 -252

No files matched your search

+5 -24
View File
@@ -5,8 +5,6 @@
*/
import { GrayImage } from "../../graphics/image";
import { type DashboardInputEvent, type Layer, type LayerContext } from "../../ui/layers";
import { MenuLayer } from "../../ui/menu";
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
import {
createInProcessWindow,
type InProcessAppOptions,
@@ -31,27 +29,11 @@ class EvenHubAppLayer implements Layer {
}
}
/** The stock exit confirm shown for shutDownPageContainer(1). */
class ExitConfirmLayer extends MenuLayer {
constructor(session: EvenHubSession, appName: string) {
let answered = false;
const answer = (ctx: LayerContext, exit: boolean) => {
if (answered) return;
answered = true;
ctx.stack.pop();
session.exitDialogAnswer(exit);
};
super(`Exit ${appName}?`, [
{ label: "No", onSelect: (ctx) => answer(ctx, false) },
{ label: "Yes", onSelect: (ctx) => answer(ctx, true) },
], WINDOW_MENU_LAYOUT);
}
}
export function createEvenHubWindow(
windowId: string,
session: EvenHubSession,
options: InProcessAppOptions,
onShowPhone: () => void,
): InProcessWindow {
const created = createInProcessWindow({
appId: "evenhub",
@@ -60,6 +42,9 @@ export function createEvenHubWindow(
iconLetter: session.manifest.name.charAt(0).toUpperCase() || "E",
closeable: true,
heightMode: "medium",
// Glasses-first: the app runs without the phone showing it; this reveals
// its phone UI (config pages, etc.) over the dashboard on demand.
menuItems: () => [{ label: "Show phone UI", onSelect: (ctx) => { ctx.stack.pop(); onShowPhone(); } }],
actions: options.actions,
baseLayer: new EvenHubAppLayer(session),
submitFrame: options.submitFrame,
@@ -74,11 +59,7 @@ export function createEvenHubWindow(
session.attachWindow({
requestRender: created.requestRender,
closeWindow: () => shell.closeWindow(windowId),
openExitDialog: () => {
if (!created.stack.topMatches((layer) => layer instanceof ExitConfirmLayer)) {
created.stack.push(new ExitConfirmLayer(session, session.manifest.name));
}
},
focusSwitcher: () => shell.yieldFocusToSidebar(),
});
// FOREGROUND_ENTER/EXIT for the app on shell focus changes.
+5 -58
View File
@@ -7,74 +7,21 @@
*
* Design notes: notes/evenhub_compatibility.txt.
*/
import { Frame } from "@nativescript/core";
import { type AppContext, type AppDefinition } from "../app-definition";
import { shell } from "../../ui/shell/shell";
import {
appFilesDirPath,
deletePathRecursively,
readBinaryFile,
writeBinaryFile,
} from "../../native/file-access";
import { parseEhpk, parseManifest, utf8Decode } from "./ehpk";
import { EvenHubSession } from "./session";
import { createEvenHubWindow } from "./evenhub-window";
import { EvenHubStoreLayer } from "./store-layer";
import { launchPackage } from "./manager";
import { createInProcessWindow, type InProcessWindow } from "../../ui/shell/in-process-window";
const EVENHUB_WINDOW_ID = "evenhub:app";
const EVENHUB_STORE_WINDOW_ID = "evenhub:store";
const EVENHUB_STORE_SURFACE_ID = "window:evenhub:store";
let activeSession: EvenHubSession | null = null;
export function getActiveEvenHubSession(): EvenHubSession | null {
return activeSession;
}
/**
* Unpack an .ehpk and launch it: glasses window plus the phone WebView page.
* Only one EvenHub app runs at a time for now; opening another closes the
* previous one.
* Unpack an .ehpk and launch it as a concurrent EvenHub app (own glasses
* window + persistent WebView). The phone stays on the dashboard; see manager.
*/
export async function openEvenHubPackage(ctx: AppContext, ehpkPath: string): Promise<void> {
const data = readBinaryFile(ehpkPath);
if (!data) {
ctx.appendLog(`evenhub: could not read ${ehpkPath}`);
return;
}
const archive = parseEhpk(data);
const appJson = archive.files.get("app.json");
if (!appJson) {
ctx.appendLog("evenhub: package has no app.json");
return;
}
const manifest = parseManifest(utf8Decode(appJson));
if (activeSession && !activeSession.isClosed()) {
activeSession.close();
}
// Unpack fresh into app-private storage, keyed by package id.
const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_");
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}`;
deletePathRecursively(baseDir);
for (const [name, content] of archive.files) {
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
ctx.appendLog(`evenhub: failed to write ${name}`);
return;
}
}
const session = new EvenHubSession(manifest, `${baseDir}/dist`, ctx.appendLog);
activeSession = session;
ctx.appendLog(`evenhub: launching ${manifest.name} ${manifest.version} (${manifest.packageId})`);
await ctx.launchInProcessApp(EVENHUB_WINDOW_ID, `window:${EVENHUB_WINDOW_ID}`, (options) =>
createEvenHubWindow(EVENHUB_WINDOW_ID, session, options),
);
Frame.topmost()?.navigate({ moduleName: "phone-ui/evenhub-page" });
export function openEvenHubPackage(ctx: AppContext, ehpkPath: string): Promise<void> {
return launchPackage(ctx, ehpkPath);
}
const evenhubApp: AppDefinition = {
+118
View File
@@ -0,0 +1,118 @@
/**
* Registry of running EvenHub apps. Each launched package gets its own glasses
* window, session, and persistent WebView — they run concurrently and keep
* driving their windows in the background (the shell delivers FOREGROUND_ENTER/
* EXIT as focus changes; the WebView host keeps them rendering while unseen).
*
* Glasses-first: launching does NOT take over the phone screen. The phone
* stays on the Faceclaw dashboard; an app's phone UI is shown on demand
* (window menu -> "Show phone UI"), overlaying the dashboard, and the Back
* button returns to it. Apps are kept alive until explicitly closed (no memory
* eviction yet).
*/
import { Application } from "@nativescript/core";
import { type AppContext } from "../app-definition";
import {
appFilesDirPath,
deletePathRecursively,
readBinaryFile,
writeBinaryFile,
} from "../../native/file-access";
import { parseEhpk, parseManifest, utf8Decode } from "./ehpk";
import { EvenHubSession } from "./session";
import { createEvenHubWindow } from "./evenhub-window";
import { createEvenHubWebView, type EvenHubWebView } from "./webview";
type RunningApp = {
windowId: string;
session: EvenHubSession;
webView: EvenHubWebView;
};
const running = new Map<string, RunningApp>();
let nextSerial = 1;
let phoneShownWindowId: string | null = null;
let backHandlerRegistered = false;
/** Intercept Android Back while an app's phone UI is overlaying the dashboard. */
function ensureBackHandler(): void {
if (backHandlerRegistered) return;
backHandlerRegistered = true;
Application.android?.on("activityBackPressed", (args: { cancel: boolean }) => {
if (phoneShownWindowId) {
args.cancel = true;
hidePhone();
}
});
}
/**
* Unpack an .ehpk and launch it as a new concurrent app: a glasses window plus
* a persistent WebView. Does not disturb other running apps or the phone screen.
*/
export async function launchPackage(ctx: AppContext, ehpkPath: string): Promise<void> {
const data = readBinaryFile(ehpkPath);
if (!data) {
ctx.appendLog(`evenhub: could not read ${ehpkPath}`);
return;
}
const archive = parseEhpk(data);
const appJson = archive.files.get("app.json");
if (!appJson) {
ctx.appendLog("evenhub: package has no app.json");
return;
}
const manifest = parseManifest(utf8Decode(appJson));
// Unpack fresh into app-private storage, keyed by package id.
const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_");
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}`;
deletePathRecursively(baseDir);
for (const [name, content] of Array.from(archive.files)) {
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
ctx.appendLog(`evenhub: failed to write ${name}`);
return;
}
}
const windowId = `evenhub:app:${nextSerial++}`;
const session = new EvenHubSession(manifest, `${baseDir}/dist`, ctx.appendLog);
const webView = createEvenHubWebView(session);
session.attachWebView({
evaluateJs: webView.evaluateJs,
destroy: () => {
if (phoneShownWindowId === windowId) {
webView.hideOnPhone();
phoneShownWindowId = null;
}
webView.destroy();
running.delete(windowId);
},
});
running.set(windowId, { windowId, session, webView });
ensureBackHandler();
ctx.appendLog(`evenhub: launching ${manifest.name} ${manifest.version} (${manifest.packageId})`);
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
createEvenHubWindow(windowId, session, options, () => showOnPhone(windowId)),
);
}
/** Overlay one app's phone UI over the dashboard (from its window menu). */
export function showOnPhone(windowId: string): void {
const app = running.get(windowId);
if (!app) return;
app.webView.showOnPhone();
phoneShownWindowId = windowId;
}
/** Return the phone to the dashboard (Back, or the shown app closing). */
export function hidePhone(): void {
if (!phoneShownWindowId) return;
running.get(phoneShownWindowId)?.webView.hideOnPhone();
phoneShownWindowId = null;
}
export function runningAppCount(): number {
return running.size;
}
+35 -47
View File
@@ -76,23 +76,21 @@ export const EVENHUB_BRIDGE_INJECT_SCRIPT = `
})();
`;
/** How long after SYSTEM_EXIT the webview stays alive so the app can save. */
const EXIT_GRACE_MS = 1500;
/** Stock blocks a repeated createStartUpPageContainer ~2s before failing it. */
const DUPLICATE_CREATE_DELAY_MS = 2000;
export type EvenHubPageHandle = {
export type EvenHubWebViewHandle = {
/** Run JS inside the app's WebView (must be called on the main thread). */
evaluateJs: (js: string) => void;
/** Tear the phone page down (navigate back if it is current). */
closePage: () => void;
/** Detach and destroy the WebView (the app is closing). */
destroy: () => void;
};
export type EvenHubWindowHooks = {
requestRender: () => void;
closeWindow: () => void;
/** Push the on-glasses exit confirm; answers come back via exitDialogAnswer. */
openExitDialog: () => void;
/** Hand focus to the app switcher (used to decline an app's quit request). */
focusSwitcher: () => void;
};
export class EvenHubSession {
@@ -101,12 +99,13 @@ export class EvenHubSession {
private page: EvenHubPage | null = null;
private pageCreated = false;
private pageHandle: EvenHubPageHandle | null = null;
private webViewHandle: EvenHubWebViewHandle | null = null;
private windowHooks: EvenHubWindowHooks | null = null;
private closed = false;
private launchContextPushed = false;
private systemExitSent = false;
private graceCloseTimer: ReturnType<typeof setTimeout> | null = null;
/** Shell focus state; true from launch (apps open focused). */
private foreground = true;
private log: (message: string) => void;
constructor(manifest: EvenHubManifest, distDir: string, log: (message: string) => void) {
@@ -115,14 +114,14 @@ export class EvenHubSession {
this.log = log;
}
// ----- phone page wiring -----
// ----- webview wiring -----
attachPage(handle: EvenHubPageHandle): void {
this.pageHandle = handle;
attachWebView(handle: EvenHubWebViewHandle): void {
this.webViewHandle = handle;
}
/** The WebView finished loading the app: push the one-shot launch context. */
pageFinished(): void {
webViewLoaded(): void {
if (this.launchContextPushed) return;
this.launchContextPushed = true;
// Launched to drive the glasses (from the on-glasses file browser), so
@@ -138,12 +137,6 @@ export class EvenHubSession {
});
}
/** The phone page went away (back navigation); the webview is gone too. */
pageGone(): void {
this.pageHandle = null;
this.close();
}
// ----- glasses window wiring -----
attachWindow(hooks: EvenHubWindowHooks): void {
@@ -213,24 +206,18 @@ export class EvenHubSession {
this.windowHooks?.requestRender();
}
/**
* Shell focus changes drive foreground/background. The initial ENTER is
* deferred until the page exists (a just-launched app is focused before it
* has built its page); createStartUpPage emits it then.
*/
setForeground(foreground: boolean): void {
if (this.foreground === foreground) return;
this.foreground = foreground;
if (!this.pageCreated) return;
this.emitSysEvent(foreground ? FOREGROUND_ENTER_EVENT : FOREGROUND_EXIT_EVENT, 0);
}
/** The on-glasses exit confirm was answered. */
exitDialogAnswer(exit: boolean): void {
if (exit) {
this.emitSysEvent(SYSTEM_EXIT_EVENT, 0);
this.systemExitSent = true;
// Give the app a beat to persist state; it usually calls
// shutDownPageContainer(0) well before this fires.
this.graceCloseTimer = setTimeout(() => this.close(), EXIT_GRACE_MS);
} else {
this.emitSysEvent(FOREGROUND_EXIT_EVENT, 0);
}
}
// ----- bridge calls (web -> host) -----
/**
@@ -317,6 +304,8 @@ export class EvenHubSession {
this.warnOnInvalidPage(page);
this.page = page;
this.pageCreated = true;
// The launch focus arrived before the page existed; deliver the ENTER now.
if (this.foreground) this.emitSysEvent(FOREGROUND_ENTER_EVENT, 0);
this.windowHooks?.requestRender();
return 0;
}
@@ -376,10 +365,13 @@ export class EvenHubSession {
private shutDown(exitMode: number): boolean {
if (exitMode === 1) {
// Stock pops an on-glasses confirm and tells the app its page is gone.
this.emitSysEvent(FOREGROUND_ENTER_EVENT, 0);
this.windowHooks?.openExitDialog();
this.windowHooks?.requestRender();
// The app asked to quit (stock would pop an on-glasses confirm). We
// decline and hand focus to the app switcher instead, leaving the app
// running — so an app's double-tap-to-quit becomes double-tap-to-defocus.
// No FOREGROUND_EXIT: focusing the sidebar doesn't background the app
// (native Faceclaw apps behave the same), and refocusing the same window
// wouldn't re-fire ENTER, which would leave a pause-on-exit app stuck.
this.windowHooks?.focusSwitcher();
return true;
}
// Immediate exit. Resolve first (the return travels via evaluateJs, and
@@ -395,14 +387,14 @@ export class EvenHubSession {
// ----- pushes (host -> web) -----
private resolveCall(callId: number, ok: boolean, value: unknown): void {
this.pageHandle?.evaluateJs(
this.webViewHandle?.evaluateJs(
`window.__fcResolve && window.__fcResolve(${callId}, ${ok ? "true" : "false"}, ${JSON.stringify(value ?? null)})`,
);
}
private pushMessage(method: string, data: unknown): void {
const message = { type: "listen_even_app_data", method, data };
this.pageHandle?.evaluateJs(
this.webViewHandle?.evaluateJs(
`window._listenEvenAppMessage && window._listenEvenAppMessage(${JSON.stringify(message)})`,
);
}
@@ -427,14 +419,10 @@ export class EvenHubSession {
// ----- teardown -----
/** Close everything: glasses window, phone page, session. Idempotent. */
/** Close everything: glasses window, WebView, session. Idempotent. */
close(): void {
if (this.closed) return;
this.closed = true;
if (this.graceCloseTimer) {
clearTimeout(this.graceCloseTimer);
this.graceCloseTimer = null;
}
if (!this.systemExitSent) {
// Best effort: lets the app's teardown handlers run before the webview dies.
this.emitSysEvent(SYSTEM_EXIT_EVENT, 0);
@@ -443,11 +431,11 @@ export class EvenHubSession {
const hooks = this.windowHooks;
this.windowHooks = null;
hooks?.closeWindow();
const page = this.pageHandle;
this.pageHandle = null;
if (page) {
const webView = this.webViewHandle;
this.webViewHandle = null;
if (webView) {
// Give in-flight resolves/pushes a beat to reach the webview first.
setTimeout(() => page.closePage(), 100);
setTimeout(() => webView.destroy(), 100);
}
}
+97
View File
@@ -0,0 +1,97 @@
/**
* Constructs the Android WebView that runs one EvenHub app and attaches it to
* the persistent keep-alive host (FaceclawEvenHubWebViewHost), decoupled from
* any phone Page. The WebView is created at launch and lives until the app's
* glasses window closes — it renders the app to the glasses whether or not the
* phone is currently showing it (see the host for the off-screen-render trick).
*
* A raw android.webkit.WebView (not the NativeScript component) is used so we
* fully own the WebViewClient: offline asset serving from a fake per-app origin
* plus document-start injection of the flutter_inappwebview bridge shim.
*/
import { Application, Utils } from "@nativescript/core";
import { EVENHUB_BRIDGE_INJECT_SCRIPT, type EvenHubSession } from "./session";
declare const android: any;
declare const com: any;
export type EvenHubWebView = {
evaluateJs: (js: string) => void;
destroy: () => void;
showOnPhone: () => void;
hideOnPhone: () => void;
/** The native android.webkit.WebView, for the host. */
native: unknown;
};
/** A distinct (fake, intercepted) https origin per app isolates web storage. */
function originHost(session: EvenHubSession): string {
const safe = session.manifest.packageId.toLowerCase().replace(/[^a-z0-9.-]/g, "-");
return `${safe}.evenhub.invalid`;
}
/**
* Build the app's WebView, wire it to the session, attach it to the keep-alive
* host, and start loading. Must run on the main thread.
*/
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
const activity = Application.android?.foregroundActivity ?? Application.android?.startActivity;
const context = activity ?? Utils.android.getApplicationContext();
const webView = new android.webkit.WebView(context);
const settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(false);
settings.setMediaPlaybackRequiresUserGesture(false);
const listener = new com.faceclaw.app.FaceclawEvenHubListener({
onEvenAppMessage: (handlerName: string, argsJson: string, callId: number) => {
session.handleBridgeCall(String(handlerName), String(argsJson), Number(callId));
},
onPageFinished: () => {
session.webViewLoaded();
},
});
const host = originHost(session);
webView.setWebViewClient(
new com.faceclaw.app.FaceclawEvenHubWebViewClient(session.distDir, host, EVENHUB_BRIDGE_INJECT_SCRIPT, listener),
);
webView.addJavascriptInterface(new com.faceclaw.app.FaceclawEvenHubJsBridge(listener), "__faceclawEvenHub");
// Surface the app's console in logcat (tag FaceclawEvenHubConsole).
const ChromeClient = (android.webkit.WebChromeClient as any).extend({
onConsoleMessage: (message: any): boolean => {
android.util.Log.i(
"FaceclawEvenHubConsole",
`${message.message()} (${message.sourceId()}:${message.lineNumber()})`,
);
return true;
},
});
webView.setWebChromeClient(new ChromeClient());
const nativeHost = com.faceclaw.app.FaceclawEvenHubWebViewHost.getInstance();
nativeHost.attach(activity, webView);
webView.loadUrl(`https://${host}/${session.manifest.entrypoint}`);
return {
native: webView,
evaluateJs: (js: string) => {
try {
webView.evaluateJavascript(js, null);
} catch (error) {
console.warn(`evenhub evaluateJs failed: ${error}`);
}
},
destroy: () => {
try {
nativeHost.detach(webView);
} catch (error) {
console.warn(`evenhub webview destroy failed: ${error}`);
}
},
showOnPhone: () => nativeHost.showOnPhone(webView),
hideOnPhone: () => nativeHost.hideOnPhone(),
};
}