Allow backgrounding EvenHub apps
This commit is contained in:
1 parent
cde29cc4d0
commit
b9f48c8e16
10 files changed
+376
-252
No files matched your search
@@ -0,0 +1,95 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.WebView;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
/**
|
||||
* Keeps EvenHub app WebViews alive and rendering while the phone shows the
|
||||
* Faceclaw dashboard instead of the app.
|
||||
*
|
||||
* The problem: an EvenHub app only paints (canvas / requestAnimationFrame) and
|
||||
* runs un-throttled timers while its WebView is attached to the window and
|
||||
* VISIBLE. Faceclaw is glasses-first — the phone normally shows its own UI, not
|
||||
* the app — so the app's WebView must render off-screen.
|
||||
*
|
||||
* The trick: a single full-screen overlay FrameLayout is inserted as the FIRST
|
||||
* child of the activity's content view, i.e. BEHIND the NativeScript UI. Every
|
||||
* app WebView lives in it, full-size and VISIBLE, but occluded by the opaque
|
||||
* dashboard on top. Chromium doesn't stop rendering a view merely because a
|
||||
* sibling covers it (only VISIBILITY flags / detachment / zero-size do that),
|
||||
* so the apps keep driving their glasses windows while unseen. Touches go to
|
||||
* the NativeScript UI on top.
|
||||
*
|
||||
* To show one app's UI on the phone, the overlay is raised to the front (and
|
||||
* the chosen WebView to the top of the overlay); hiding sends it back behind.
|
||||
* All view work happens on the main thread (callers are on the NS/JS thread).
|
||||
*
|
||||
* Backgrounding note: when the whole activity is not resumed (phone asleep /
|
||||
* Faceclaw not foregrounded) the platform stops producing frames for these
|
||||
* WebViews regardless — true screen-off rendering is a separate, harder problem.
|
||||
*/
|
||||
public class FaceclawEvenHubWebViewHost {
|
||||
private static FaceclawEvenHubWebViewHost instance;
|
||||
|
||||
private FrameLayout overlay;
|
||||
private boolean shown = false;
|
||||
|
||||
public static synchronized FaceclawEvenHubWebViewHost getInstance() {
|
||||
if (instance == null) instance = new FaceclawEvenHubWebViewHost();
|
||||
return instance;
|
||||
}
|
||||
|
||||
private FrameLayout ensureOverlay(Activity activity) {
|
||||
if (overlay != null) return overlay;
|
||||
ViewGroup content = activity.findViewById(android.R.id.content);
|
||||
overlay = new FrameLayout(activity);
|
||||
// index 0 = behind the NativeScript content view.
|
||||
content.addView(overlay, 0, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
return overlay;
|
||||
}
|
||||
|
||||
/** Add a WebView to the host, full-size and rendering, hidden behind the UI. */
|
||||
public void attach(Activity activity, WebView web) {
|
||||
FrameLayout o = ensureOverlay(activity);
|
||||
web.setVisibility(View.VISIBLE);
|
||||
if (web.getParent() == null) {
|
||||
o.addView(web, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
}
|
||||
// resumeTimers() is process-global; make sure nothing left timers paused.
|
||||
web.resumeTimers();
|
||||
}
|
||||
|
||||
/** Bring an app's WebView to the front so it is visible on the phone. */
|
||||
public void showOnPhone(WebView web) {
|
||||
if (overlay == null) return;
|
||||
web.bringToFront();
|
||||
overlay.bringToFront();
|
||||
shown = true;
|
||||
}
|
||||
|
||||
/** Send the overlay back behind the NativeScript UI. */
|
||||
public void hideOnPhone() {
|
||||
shown = false;
|
||||
if (overlay == null) return;
|
||||
ViewGroup content = (ViewGroup) overlay.getParent();
|
||||
if (content != null) {
|
||||
content.removeView(overlay);
|
||||
content.addView(overlay, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isShown() {
|
||||
return shown;
|
||||
}
|
||||
|
||||
/** Remove and destroy a WebView (its app is closing). */
|
||||
public void detach(WebView web) {
|
||||
if (overlay != null) overlay.removeView(web);
|
||||
web.destroy();
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/**
|
||||
* Phone-side host page for a running EvenHub app: a fullscreen native
|
||||
* WebView showing the app's web UI. The WebView is also the app's runtime —
|
||||
* navigating back closes the app (webview, glasses window, session).
|
||||
*
|
||||
* The WebView is a raw android.webkit.WebView (via Placeholder) rather than
|
||||
* the NativeScript WebView component, so we fully own the WebViewClient
|
||||
* (offline asset serving + bridge-shim injection) without fighting the
|
||||
* component's own client.
|
||||
*/
|
||||
import { Application, CreateViewEventData, Frame, NavigatedData, Page, Utils } from "@nativescript/core";
|
||||
import { getActiveEvenHubSession } from "../apps/evenhub";
|
||||
import { EVENHUB_BRIDGE_INJECT_SCRIPT, EvenHubSession } from "../apps/evenhub/session";
|
||||
|
||||
declare const android: any;
|
||||
declare const com: any;
|
||||
|
||||
let currentPage: Page | null = null;
|
||||
let currentWebView: any = null;
|
||||
let currentSession: EvenHubSession | null = null;
|
||||
|
||||
export function navigatingTo(args: NavigatedData): void {
|
||||
const page = args.object as Page;
|
||||
const session = getActiveEvenHubSession();
|
||||
page.bindingContext = { title: session?.manifest.name ?? "EvenHub" };
|
||||
currentPage = page;
|
||||
}
|
||||
|
||||
export function creatingWebView(args: CreateViewEventData): void {
|
||||
const session = getActiveEvenHubSession();
|
||||
if (!session || session.isClosed()) {
|
||||
setTimeout(() => Frame.topmost()?.goBack(), 0);
|
||||
return;
|
||||
}
|
||||
currentSession = session;
|
||||
|
||||
const context = Application.android?.foregroundActivity ?? 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.pageFinished();
|
||||
},
|
||||
});
|
||||
|
||||
const host = evenHubOriginHost(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 page = currentPage;
|
||||
session.attachPage({
|
||||
evaluateJs: (js: string) => {
|
||||
try {
|
||||
webView.evaluateJavascript(js, null);
|
||||
} catch (error) {
|
||||
console.warn(`evenhub evaluateJs failed: ${error}`);
|
||||
}
|
||||
},
|
||||
closePage: () => {
|
||||
const frame = Frame.topmost();
|
||||
if (frame && page && frame.currentPage === page) {
|
||||
frame.goBack();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
currentWebView = webView;
|
||||
webView.loadUrl(`https://${host}/${session.manifest.entrypoint}`);
|
||||
args.view = webView;
|
||||
}
|
||||
|
||||
export function navigatedFrom(args: NavigatedData): void {
|
||||
if (!args.isBackNavigation) return;
|
||||
const session = currentSession;
|
||||
const webView = currentWebView;
|
||||
currentSession = null;
|
||||
currentWebView = null;
|
||||
currentPage = null;
|
||||
session?.pageGone();
|
||||
if (webView) {
|
||||
try {
|
||||
webView.destroy();
|
||||
} catch (error) {
|
||||
console.warn(`evenhub webview destroy failed: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A distinct (fake, intercepted) https origin per app isolates web storage. */
|
||||
function evenHubOriginHost(session: EvenHubSession): string {
|
||||
const safe = session.manifest.packageId.toLowerCase().replace(/[^a-z0-9.-]/g, "-");
|
||||
return `${safe}.evenhub.invalid`;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
<Page
|
||||
xmlns="http://schemas.nativescript.org/tns.xsd"
|
||||
navigatingTo="navigatingTo"
|
||||
navigatedFrom="navigatedFrom">
|
||||
<ActionBar title="{{ title }}" />
|
||||
<Placeholder creatingView="creatingWebView" />
|
||||
</Page>
|
||||
@@ -101,7 +101,19 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
// items act on the shell directly (workers post messages instead).
|
||||
const openWindowMenu = () => {
|
||||
if (stack.topMatches((layer) => layer instanceof WindowMenuLayer)) return;
|
||||
const items: MenuItem[] = [...(options.menuItems?.() ?? [])];
|
||||
// "Focus app switcher" first: long-press then tap defocuses the app
|
||||
// (hands focus to the sidebar) without closing it — the reliable way out
|
||||
// for apps that consume double-click.
|
||||
const items: MenuItem[] = [
|
||||
{
|
||||
label: "Focus app switcher",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
shell.yieldFocusToSidebar();
|
||||
},
|
||||
},
|
||||
...(options.menuItems?.() ?? []),
|
||||
];
|
||||
items.push({
|
||||
label: "Voice input",
|
||||
onSelect: (ctx) => {
|
||||
|
||||
@@ -86,6 +86,14 @@ export function defaultWindowMenuItems(
|
||||
post: (reply: WorkerAppReply) => void,
|
||||
): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
// Defocus the app (hand focus to the sidebar) without closing it.
|
||||
label: "Focus app switcher",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
post({ type: "yield-focus", windowId });
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Voice input",
|
||||
onSelect: (ctx) => {
|
||||
|
||||
Reference in new issue
Block a user