First-pass EvenHub compatibility layer

This commit is contained in:
James Babcock committed 2026-08-11 22:52:32 -07:00
1 parent d7d12afcaa
commit 5d29d91133
19 files changed
+1668 -22

No files matched your search

@@ -0,0 +1,34 @@
package com.faceclaw.app;
import android.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;
/**
* The object injected into a hosted EvenHub app's WebView as
* window.__faceclawEvenHub. The document-start shim (served inline by
* FaceclawEvenHubWebViewClient) wraps it in a promise-returning
* window.flutter_inappwebview.callHandler, which is what the EvenHub SDK
* actually talks to.
*
* JavascriptInterface methods run on a WebView-internal thread; everything
* is bounced to the main thread before touching the NativeScript listener.
*/
public class FaceclawEvenHubJsBridge {
private final FaceclawEvenHubListener listener;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
public FaceclawEvenHubJsBridge(FaceclawEvenHubListener listener) {
this.listener = listener;
}
@JavascriptInterface
public void postMessage(final String handlerName, final String argsJson, final int callId) {
mainHandler.post(new Runnable() {
@Override
public void run() {
listener.onEvenAppMessage(handlerName, argsJson, callId);
}
});
}
}
@@ -0,0 +1,18 @@
package com.faceclaw.app;
/**
* Callbacks from a hosted EvenHub app's WebView to the TypeScript host.
* All methods are delivered on the Android main thread (NativeScript's JS
* thread), regardless of which WebView-internal thread produced them.
*/
public interface FaceclawEvenHubListener {
/**
* The app invoked window.flutter_inappwebview.callHandler(handlerName, ...args).
* argsJson is the JSON-encoded argument array; callId identifies the
* promise to resolve via window.__fcResolve(callId, ok, value).
*/
void onEvenAppMessage(String handlerName, String argsJson, int callId);
/** The WebView finished loading the app's page. */
void onPageFinished(String url);
}
@@ -0,0 +1,147 @@
package com.faceclaw.app;
import android.os.Handler;
import android.os.Looper;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.net.Uri;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
/**
* Serves an unpacked EvenHub app's files to its WebView from a fake per-app
* https origin, entirely offline. HTML responses get the host bridge shim
* injected at the top of the document, guaranteeing
* window.flutter_inappwebview exists before any app JS runs (apps race
* waitForEvenAppBridge against 4-6s timeouts and silently fall back to demo
* modes if the handler appears late).
*
* shouldInterceptRequest runs on a WebView-internal thread; it only touches
* files, never the NativeScript runtime. Requests to other hosts fall
* through to the network (the manifest whitelist is not yet enforced).
*/
public class FaceclawEvenHubWebViewClient extends WebViewClient {
private static final String TAG = "FaceclawEvenHub";
private final String rootDir;
private final String host;
private final String injectScript;
private final FaceclawEvenHubListener listener;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
public FaceclawEvenHubWebViewClient(
String rootDir, String host, String injectScript, FaceclawEvenHubListener listener) {
this.rootDir = rootDir;
this.host = host;
this.injectScript = injectScript;
this.listener = listener;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Uri url = request.getUrl();
if (url == null || !host.equals(url.getHost())) {
return null; // External hosts: normal network handling.
}
String path = url.getPath();
if (path == null || path.isEmpty() || path.equals("/")) {
path = "/index.html";
}
try {
File root = new File(rootDir).getCanonicalFile();
File target = new File(root, path.substring(1)).getCanonicalFile();
if (!target.getPath().startsWith(root.getPath()) || !target.isFile()) {
Log.w(TAG, "404 " + path);
return new WebResourceResponse(
"text/plain", "utf-8",
new ByteArrayInputStream("not found".getBytes(StandardCharsets.UTF_8)));
}
String mime = mimeTypeFor(target.getName());
if (mime.equals("text/html")) {
return new WebResourceResponse(mime, "utf-8", new ByteArrayInputStream(injectIntoHtml(target)));
}
InputStream stream = new FileInputStream(target);
return new WebResourceResponse(mime, null, stream);
} catch (IOException e) {
Log.e(TAG, "serve failed for " + path, e);
return new WebResourceResponse(
"text/plain", "utf-8",
new ByteArrayInputStream("error".getBytes(StandardCharsets.UTF_8)));
}
}
@Override
public void onPageFinished(WebView view, final String url) {
mainHandler.post(new Runnable() {
@Override
public void run() {
listener.onPageFinished(url);
}
});
}
private byte[] injectIntoHtml(File file) throws IOException {
byte[] raw = readAll(file);
String html = new String(raw, StandardCharsets.UTF_8);
String tag = "<script>" + injectScript + "</script>";
// After <head...> if present, else before everything.
int headIndex = indexOfIgnoreCase(html, "<head");
if (headIndex >= 0) {
int close = html.indexOf('>', headIndex);
if (close >= 0) {
return (html.substring(0, close + 1) + tag + html.substring(close + 1))
.getBytes(StandardCharsets.UTF_8);
}
}
return (tag + html).getBytes(StandardCharsets.UTF_8);
}
private static int indexOfIgnoreCase(String haystack, String needle) {
return haystack.toLowerCase(Locale.ROOT).indexOf(needle);
}
private static byte[] readAll(File file) throws IOException {
FileInputStream in = new FileInputStream(file);
try {
byte[] data = new byte[(int) file.length()];
int off = 0;
while (off < data.length) {
int n = in.read(data, off, data.length - off);
if (n < 0) throw new IOException("short read: " + file);
off += n;
}
return data;
} finally {
in.close();
}
}
private static String mimeTypeFor(String name) {
String lower = name.toLowerCase(Locale.ROOT);
if (lower.endsWith(".html") || lower.endsWith(".htm")) return "text/html";
if (lower.endsWith(".js") || lower.endsWith(".mjs")) return "application/javascript";
if (lower.endsWith(".css")) return "text/css";
if (lower.endsWith(".json")) return "application/json";
if (lower.endsWith(".png")) return "image/png";
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
if (lower.endsWith(".gif")) return "image/gif";
if (lower.endsWith(".svg")) return "image/svg+xml";
if (lower.endsWith(".webp")) return "image/webp";
if (lower.endsWith(".ico")) return "image/x-icon";
if (lower.endsWith(".wasm")) return "application/wasm";
if (lower.endsWith(".woff")) return "font/woff";
if (lower.endsWith(".woff2")) return "font/woff2";
if (lower.endsWith(".ttf")) return "font/ttf";
if (lower.endsWith(".txt") || lower.endsWith(".map")) return "text/plain";
return "application/octet-stream";
}
}
+2
View File
@@ -17,6 +17,7 @@ import minesweeperApp from "./minesweeper";
import freecellApp from "./freecell";
import pinballApp from "./pinball";
import debugTestsApp from "./debug-tests";
import evenhubApp from "./evenhub";
import settingsApp from "./settings";
/**
@@ -43,5 +44,6 @@ export const ALL_APPS: readonly AppDefinition[] = [
freecellApp,
pinballApp,
debugTestsApp,
evenhubApp,
settingsApp,
];
+135
View File
@@ -0,0 +1,135 @@
/**
* Phone-side reimplementation of the on-glasses EvenHub page compositor:
* containers render into the 576x288 canvas the stock firmware gives apps.
*
* Known deviations from stock, acceptable for now:
* - Text uses Terminus 24 rather than the firmware's proportional LVGL font,
* so grid-aligned/padded layouts won't line up exactly (see
* notes/evenhub_compatibility.txt section 6 for the extraction plan).
* - List rendering is a plain vertical list; itemWidth-based horizontal
* layouts are not implemented yet.
*/
import { GrayImage } from "../../graphics/image";
import { getFont } from "../../graphics/bdffont";
import {
type EvenHubContainer,
type EvenHubImageContainer,
type EvenHubListContainer,
type EvenHubPage,
type EvenHubTextContainer,
} from "./containers";
export const EVENHUB_SCREEN_WIDTH = 576;
export const EVENHUB_SCREEN_HEIGHT = 288;
const TEXT_WHITE = 255;
const LIST_ROW_PADDING = 4;
function containerFont() {
return getFont("terminus24");
}
/** Chars the font lacks are skipped silently on stock (no tofu); drawText
* already skips unknown glyphs, matching that. */
function paintTextContainer(image: GrayImage, container: EvenHubTextContainer): void {
paintBorder(image, container);
const inset = container.borderWidth + container.paddingLength;
const font = containerFont();
image.drawTextWrapped({
font,
x: container.x + inset,
y: container.y + inset,
width: Math.max(1, container.width - 2 * inset),
text: container.content,
value: TEXT_WHITE,
});
}
function paintBorder(
image: GrayImage,
container: { x: number; y: number; width: number; height: number; borderWidth: number; borderRadius: number },
): void {
for (let i = 0; i < container.borderWidth; i++) {
if (container.borderRadius > 0) {
image.drawRoundedRect(
container.x + i,
container.y + i,
container.width - 2 * i,
container.height - 2 * i,
TEXT_WHITE,
Math.max(0, container.borderRadius - i),
);
} else {
image.drawRect(container.x + i, container.y + i, container.width - 2 * i, container.height - 2 * i, TEXT_WHITE);
}
}
}
function paintImageContainer(image: GrayImage, container: EvenHubImageContainer): void {
if (!container.pixels || container.pixelsWidth <= 0 || container.pixelsHeight <= 0) return;
const source = new GrayImage(container.pixelsWidth, container.pixelsHeight, 0);
source.pixels.set(container.pixels);
// Stock quirk: raw data smaller than the container tiles/repeats to fill it.
for (let ty = 0; ty < container.height; ty += container.pixelsHeight) {
for (let tx = 0; tx < container.width; tx += container.pixelsWidth) {
image.bitBlt(source, container.x + tx, container.y + ty, {
width: Math.min(container.pixelsWidth, container.width - tx),
height: Math.min(container.pixelsHeight, container.height - ty),
});
}
}
}
function paintListContainer(image: GrayImage, container: EvenHubListContainer, focused: boolean): void {
paintBorder(image, container);
const font = containerFont();
const inset = container.borderWidth + container.paddingLength;
const rowHeight = font.lineHeight + LIST_ROW_PADDING;
const left = container.x + inset;
const top = container.y + inset;
const width = Math.max(1, container.width - 2 * inset);
const visibleRows = Math.max(1, Math.floor((container.height - 2 * inset) / rowHeight));
// Keep the selection in view.
let firstRow = 0;
if (container.selectedIndex >= visibleRows) firstRow = container.selectedIndex - visibleRows + 1;
for (let row = 0; row < visibleRows; row++) {
const index = firstRow + row;
if (index >= container.itemNames.length) break;
const y = top + row * rowHeight;
const selected = index === container.selectedIndex;
if (selected && focused) {
image.fillRect(left, y, width, rowHeight - 1, 40);
}
if (selected && container.selectBorder) {
image.drawRect(left, y, width, rowHeight - 1, TEXT_WHITE);
}
image.drawText(font, left + 2, y + Math.floor(LIST_ROW_PADDING / 2), container.itemNames[index]!, TEXT_WHITE);
}
}
/** Containers with a zOrderIndex sort by it; the rest keep declaration order. */
function paintOrder(containers: EvenHubContainer[]): EvenHubContainer[] {
const anyZ = containers.some((c) => c.zOrderIndex !== undefined);
if (!anyZ) return containers;
return [...containers].sort((a, b) => (a.zOrderIndex ?? 0) - (b.zOrderIndex ?? 0));
}
/** Render a page into a fresh app-viewport image (positioned by the shell). */
export function compositePage(page: EvenHubPage | null, size: { width: number; height: number }, focused: boolean): GrayImage {
const image = new GrayImage(size.width, size.height, 0);
if (!page) return image;
for (const container of paintOrder(page.containers)) {
switch (container.kind) {
case "image":
paintImageContainer(image, container);
break;
case "text":
paintTextContainer(image, container);
break;
case "list":
paintListContainer(image, container, focused);
break;
}
}
return image;
}
+192
View File
@@ -0,0 +1,192 @@
/**
* EvenHub page-container model and lenient JSON parsing.
*
* Hosts and apps in the wild emit both camelCase and protobuf names
* (Container_ID), and numbers sometimes arrive as strings, so all field
* reads go through loose key matching (the SDK's pickLoose behavior).
*/
export type EvenHubTextContainer = {
kind: "text";
id: number;
name: string;
x: number;
y: number;
width: number;
height: number;
borderWidth: number;
borderRadius: number;
paddingLength: number;
isEventCapture: boolean;
zOrderIndex: number | undefined;
content: string;
};
export type EvenHubImageContainer = {
kind: "image";
id: number;
name: string;
x: number;
y: number;
width: number;
height: number;
zOrderIndex: number | undefined;
/** Decoded 8bpp grayscale, set by updateImageRawData; null until first update. */
pixels: Uint8Array | null;
pixelsWidth: number;
pixelsHeight: number;
};
export type EvenHubListContainer = {
kind: "list";
id: number;
name: string;
x: number;
y: number;
width: number;
height: number;
borderWidth: number;
borderRadius: number;
paddingLength: number;
isEventCapture: boolean;
zOrderIndex: number | undefined;
itemNames: string[];
itemWidth: number;
selectBorder: boolean;
/** Selection is host-local: scroll moves it with no app round-trip. */
selectedIndex: number;
};
export type EvenHubContainer = EvenHubTextContainer | EvenHubImageContainer | EvenHubListContainer;
export type EvenHubPage = {
/** In declaration order (lists, images, texts); z-sorted at paint time. */
containers: EvenHubContainer[];
};
function normalizeKey(key: string): string {
return key.replace(/_/g, "").toLowerCase();
}
function pickLoose(obj: Record<string, unknown>, key: string): unknown {
if (key in obj) return obj[key];
const wanted = normalizeKey(key);
for (const k of Object.keys(obj)) {
if (normalizeKey(k) === wanted) return obj[k];
}
return undefined;
}
export function readNumber(obj: Record<string, unknown>, key: string, fallback: number): number {
const value = pickLoose(obj, key);
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string") {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return fallback;
}
export function readOptionalNumber(obj: Record<string, unknown>, key: string): number | undefined {
const value = readNumber(obj, key, Number.NaN);
return Number.isNaN(value) ? undefined : value;
}
export function readString(obj: Record<string, unknown>, key: string, fallback: string): string {
const value = pickLoose(obj, key);
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
return fallback;
}
export function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
}
function parseTextContainer(json: Record<string, unknown>): EvenHubTextContainer {
return {
kind: "text",
id: readNumber(json, "containerID", 0),
name: readString(json, "containerName", ""),
x: readNumber(json, "xPosition", 0),
y: readNumber(json, "yPosition", 0),
width: readNumber(json, "width", 0),
height: readNumber(json, "height", 0),
borderWidth: readNumber(json, "borderWidth", 0),
borderRadius: readNumber(json, "borderRadius", 0),
paddingLength: readNumber(json, "paddingLength", 0),
isEventCapture: readNumber(json, "isEventCapture", 0) !== 0,
zOrderIndex: readOptionalNumber(json, "zOrderIndex"),
content: readString(json, "content", ""),
};
}
function parseImageContainer(json: Record<string, unknown>): EvenHubImageContainer {
return {
kind: "image",
id: readNumber(json, "containerID", 0),
name: readString(json, "containerName", ""),
x: readNumber(json, "xPosition", 0),
y: readNumber(json, "yPosition", 0),
width: readNumber(json, "width", 0),
height: readNumber(json, "height", 0),
zOrderIndex: readOptionalNumber(json, "zOrderIndex"),
pixels: null,
pixelsWidth: 0,
pixelsHeight: 0,
};
}
function parseListContainer(json: Record<string, unknown>): EvenHubListContainer {
const itemContainer = asRecord(pickLoose(json, "itemContainer"));
const itemNamesRaw = pickLoose(itemContainer, "itemName");
const itemNames = Array.isArray(itemNamesRaw) ? itemNamesRaw.map(String) : [];
return {
kind: "list",
id: readNumber(json, "containerID", 0),
name: readString(json, "containerName", ""),
x: readNumber(json, "xPosition", 0),
y: readNumber(json, "yPosition", 0),
width: readNumber(json, "width", 0),
height: readNumber(json, "height", 0),
borderWidth: readNumber(json, "borderWidth", 0),
borderRadius: readNumber(json, "borderRadius", 0),
paddingLength: readNumber(json, "paddingLength", 0),
isEventCapture: readNumber(json, "isEventCapture", 0) !== 0,
zOrderIndex: readOptionalNumber(json, "zOrderIndex"),
itemNames,
itemWidth: readNumber(itemContainer, "itemWidth", 0),
selectBorder: readNumber(itemContainer, "isItemSelectBorderEn", 0) !== 0,
selectedIndex: 0,
};
}
/**
* Parse a CreateStartUpPageContainer / RebuildPageContainer payload into a
* page. Containers keep declaration order within and across the three arrays
* (lists, then images, then texts — texts last so info panels and capture
* containers sit above image tiles when no zOrderIndex is given).
*/
export function parsePage(data: Record<string, unknown>): EvenHubPage {
const containers: EvenHubContainer[] = [];
const lists = pickLoose(data, "listObject");
if (Array.isArray(lists)) {
for (const item of lists) containers.push(parseListContainer(asRecord(item)));
}
const images = pickLoose(data, "imageObject");
if (Array.isArray(images)) {
for (const item of images) containers.push(parseImageContainer(asRecord(item)));
}
const texts = pickLoose(data, "textObject");
if (Array.isArray(texts)) {
for (const item of texts) containers.push(parseTextContainer(asRecord(item)));
}
return { containers };
}
/** The container that owns gesture events (exactly one per valid page). */
export function eventCaptureContainer(page: EvenHubPage): EvenHubContainer | undefined {
return page.containers.find(
(container) => container.kind !== "image" && container.isEventCapture,
);
}
+133
View File
@@ -0,0 +1,133 @@
/**
* EvenHub .ehpk package unpacking.
*
* The .ehpk produced by `evenhub pack` (@evenrealities/evenhub-cli) is a
* custom record container holding the app's dist/ tree plus app.json, each
* entry zstd-compressed and XORed with the repeating ASCII key
* "EVEN REALITIES" (key index resets per field). Format details are in
* ../../../../ehpk-unpacker/ehpk_unpack.py, the reference implementation
* this ports. The trailing record is a SHA-512 of everything before it —
* an integrity check only, not a signature; we skip verifying it.
*/
import { decompress } from "fzstd";
const XOR_KEY = "EVEN REALITIES";
const RECORD_FILE = 0xe4;
const RECORD_DIR = 0xe5;
const RECORD_FOOTER = 0xe3;
export type EhpkArchive = {
/** Relative path (e.g. "app.json", "dist/index.html") to contents. */
files: Map<string, Uint8Array>;
};
/** The app.json manifest fields Faceclaw cares about (both spec generations). */
export type EvenHubManifest = {
packageId: string;
name: string;
version: string;
/** Entry file relative to dist/ (default index.html). */
entrypoint: string;
/** Hosts the app declares it will reach; not yet enforced. */
networkWhitelist: string[];
raw: Record<string, unknown>;
};
function unxor(data: Uint8Array, start: number, length: number): Uint8Array {
const out = new Uint8Array(length);
for (let i = 0; i < length; i++) {
out[i] = data[start + i]! ^ XOR_KEY.charCodeAt(i % XOR_KEY.length);
}
return out;
}
export function utf8Decode(bytes: Uint8Array): string {
let out = "";
let i = 0;
while (i < bytes.length) {
const b = bytes[i]!;
if (b < 0x80) {
out += String.fromCharCode(b);
i += 1;
} else if (b < 0xe0) {
out += String.fromCharCode(((b & 0x1f) << 6) | (bytes[i + 1]! & 0x3f));
i += 2;
} else if (b < 0xf0) {
out += String.fromCharCode(((b & 0x0f) << 12) | ((bytes[i + 1]! & 0x3f) << 6) | (bytes[i + 2]! & 0x3f));
i += 3;
} else {
const cp =
((b & 0x07) << 18) | ((bytes[i + 1]! & 0x3f) << 12) | ((bytes[i + 2]! & 0x3f) << 6) | (bytes[i + 3]! & 0x3f);
out += String.fromCodePoint(cp);
i += 4;
}
}
return out;
}
export function parseEhpk(data: Uint8Array): EhpkArchive {
if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b) {
throw new Error("not an EHPK file");
}
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
const firstRecord = view.getUint32(8, true);
const files = new Map<string, Uint8Array>();
let p = firstRecord;
while (p < data.length) {
const type = data[p]!;
if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba) {
throw new Error(`ehpk: bad record magic at ${p}`);
}
if (type === RECORD_FILE) {
const compressedLength = view.getUint32(p + 4, true);
const uncompressedLength = view.getUint32(p + 8, true);
const nameLength = view.getUint16(p + 14, true);
const name = utf8Decode(unxor(data, p + 16, nameLength));
const blob = unxor(data, p + 16 + nameLength, compressedLength);
const content = decompress(blob, new Uint8Array(uncompressedLength));
if (content.length !== uncompressedLength) {
throw new Error(`ehpk: ${name}: expected ${uncompressedLength} bytes, got ${content.length}`);
}
files.set(name, content);
p += 16 + nameLength + compressedLength;
} else if (type === RECORD_DIR) {
const nameLength = view.getUint16(p + 6, true);
p += 8 + nameLength;
} else if (type === RECORD_FOOTER) {
break;
} else {
throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`);
}
}
return { files };
}
/**
* Parse app.json, accepting both the older manifest shape (permissions as a
* {"network": [...]} map) and the current one (array of {name, whitelist?}).
*/
export function parseManifest(appJsonText: string): EvenHubManifest {
const raw = JSON.parse(appJsonText) as Record<string, unknown>;
const packageId = String(raw.package_id ?? raw.packageId ?? "unknown.package");
const name = String(raw.name ?? packageId);
const version = String(raw.version ?? "0");
const entrypoint = String(raw.entrypoint ?? "index.html");
const networkWhitelist: string[] = [];
const permissions = raw.permissions;
if (Array.isArray(permissions)) {
for (const perm of permissions) {
if (perm && typeof perm === "object" && (perm as Record<string, unknown>).name === "network") {
const whitelist = (perm as Record<string, unknown>).whitelist;
if (Array.isArray(whitelist)) networkWhitelist.push(...whitelist.map(String));
}
}
} else if (permissions && typeof permissions === "object") {
const network = (permissions as Record<string, unknown>).network;
if (Array.isArray(network)) networkWhitelist.push(...network.map(String));
}
return { packageId, name, version, entrypoint, networkWhitelist, raw };
}
+92
View File
@@ -0,0 +1,92 @@
/**
* The glasses-side window for a running EvenHub app: a layer that paints the
* session's composited page and forwards gestures to it. heightMode "medium"
* makes the content area exactly the 576x288 surface EvenHub apps expect.
*/
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,
type InProcessWindow,
} from "../../ui/shell/in-process-window";
import { shell } from "../../ui/shell/shell";
import { EvenHubSession } from "./session";
class EvenHubAppLayer implements Layer {
constructor(private readonly session: EvenHubSession) {}
paint(ctx: LayerContext): GrayImage {
const size = ctx.stack.getBaseSize();
return this.session.paint(size, ctx.stack.isFocused());
}
handleInput(event: DashboardInputEvent): void {
// Everything goes to the app; long-press never reaches here (the window
// menu intercepts it), which is the guaranteed way out since EvenHub
// apps own double-click.
this.session.handleGesture(event);
}
}
/** 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,
): InProcessWindow {
const created = createInProcessWindow({
appId: "evenhub",
windowId,
title: session.manifest.name,
iconLetter: session.manifest.name.charAt(0).toUpperCase() || "E",
closeable: true,
heightMode: "medium",
actions: options.actions,
baseLayer: new EvenHubAppLayer(session),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
options.onClosed();
session.windowClosed();
},
});
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));
}
},
});
// FOREGROUND_ENTER/EXIT for the app on shell focus changes.
const baseSetForeground = created.window.setForeground;
created.window.setForeground = (foreground) => {
baseSetForeground?.(foreground);
session.setForeground(foreground);
};
return created;
}
+94
View File
@@ -0,0 +1,94 @@
/**
* EvenHub compatibility host: runs apps built for Even Realities' EvenHub
* API (webview apps talking to the glasses through the phone) inside
* Faceclaw. Launched by picking an .ehpk file in the Files app; the app gets
* a phone WebView (its runtime + phone UI) and a 576x288 glasses window
* composited by Faceclaw instead of the stock firmware.
*
* 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";
const EVENHUB_WINDOW_ID = "evenhub:app";
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.
*/
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" });
}
const evenhubApp: AppDefinition = {
appId: "evenhub",
title: "EvenHub",
icon: "package",
// Launching happens by opening an .ehpk in Files; the grid entry would
// have nothing to open.
showInLauncher: false,
launch: async (ctx) => {
const existing = shell.getWindows().find((window) => window.appId === "evenhub");
if (existing) {
shell.focusWindow(existing.windowId);
ctx.requestShellRender();
} else {
ctx.appendLog("EvenHub apps launch from .ehpk files in the Files app");
}
},
};
export default evenhubApp;
+576
View File
@@ -0,0 +1,576 @@
/**
* One running EvenHub app: the host side of the SDK's
* flutter_inappwebview.callHandler('evenAppMessage', ...) contract, the page
* container state, and the glue between the phone WebView and the glasses
* window. Wire shapes were captured empirically from even_hub_sdk 0.0.12
* (see notes/evenhub_compatibility.txt).
*
* Wire contract summary:
* - Web -> host: callHandler('evenAppMessage', '<json>') where the JSON is
* {type: "call_even_app_method", method, data?}. The handler's return
* value resolves the app-side promise (no response postMessage).
* - Host -> web: call window._listenEvenAppMessage({type:
* "listen_even_app_data", method, data}); for method "evenHubEvent", data
* is {type: "sysEvent"|"textEvent"|"listEvent", jsonData: {...}}.
* - Return values: createStartUpPageContainer -> int 0..3;
* updateImageRawData -> int 0..3 or enum string; rebuild/textUpgrade/
* shutDown/setLocalStorage -> boolean; getLocalStorage -> string;
* getUserInfo/getGlassesInfo -> plain JSON objects (not strings).
*/
import { ApplicationSettings } from "@nativescript/core";
import { GrayImage } from "../../graphics/image";
import { getFont } from "../../graphics/bdffont";
import { type DashboardInputEvent } from "../../ui/layers";
import {
asRecord,
eventCaptureContainer,
parsePage,
readNumber,
readOptionalNumber,
readString,
type EvenHubImageContainer,
type EvenHubListContainer,
type EvenHubPage,
} from "./containers";
import { compositePage } from "./compositor";
import { type EvenHubManifest } from "./ehpk";
const UPNG = require("upng-js");
/** OsEventTypeList values (PB ordinals). */
const CLICK_EVENT = 0;
const SCROLL_TOP_EVENT = 1;
const SCROLL_BOTTOM_EVENT = 2;
const DOUBLE_CLICK_EVENT = 3;
const FOREGROUND_ENTER_EVENT = 4;
const FOREGROUND_EXIT_EVENT = 5;
const SYSTEM_EXIT_EVENT = 7;
/**
* Injected into every served HTML document at document start (before any app
* JS): the promise-returning flutter_inappwebview.callHandler the EvenHub
* SDK expects, backed by the FaceclawEvenHubJsBridge Java object. Kept in
* ES5 so it runs on any webview.
*/
export const EVENHUB_BRIDGE_INJECT_SCRIPT = `
(function () {
if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) return;
var pending = {};
var nextId = 1;
window.__fcResolve = function (id, ok, value) {
var entry = pending[id];
if (!entry) return;
delete pending[id];
(ok ? entry[0] : entry[1])(value);
};
window.flutter_inappwebview = {
callHandler: function (name) {
var args = Array.prototype.slice.call(arguments, 1);
return new Promise(function (resolve, reject) {
var id = nextId++;
pending[id] = [resolve, reject];
window.__faceclawEvenHub.postMessage(String(name), JSON.stringify(args), id);
});
}
};
})();
`;
/** 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 = {
/** 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;
};
export type EvenHubWindowHooks = {
requestRender: () => void;
closeWindow: () => void;
/** Push the on-glasses exit confirm; answers come back via exitDialogAnswer. */
openExitDialog: () => void;
};
export class EvenHubSession {
readonly manifest: EvenHubManifest;
readonly distDir: string;
private page: EvenHubPage | null = null;
private pageCreated = false;
private pageHandle: EvenHubPageHandle | null = null;
private windowHooks: EvenHubWindowHooks | null = null;
private closed = false;
private launchContextPushed = false;
private systemExitSent = false;
private graceCloseTimer: ReturnType<typeof setTimeout> | null = null;
private log: (message: string) => void;
constructor(manifest: EvenHubManifest, distDir: string, log: (message: string) => void) {
this.manifest = manifest;
this.distDir = distDir;
this.log = log;
}
// ----- phone page wiring -----
attachPage(handle: EvenHubPageHandle): void {
this.pageHandle = handle;
}
/** The WebView finished loading the app: push the one-shot launch context. */
pageFinished(): void {
if (this.launchContextPushed) return;
this.launchContextPushed = true;
// Launched to drive the glasses (from the on-glasses file browser), so
// apps that branch on this should take their glasses path.
this.pushMessage("evenAppLaunchSource", { launchSource: "glassesMenu" });
this.pushMessage("deviceStatusChanged", {
sn: "FACECLAW-G2",
connectType: "connected",
isWearing: true,
batteryLevel: 100,
isCharging: false,
isInCase: false,
});
}
/** 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 {
this.windowHooks = hooks;
}
windowClosed(): void {
this.windowHooks = null;
this.close();
}
paint(size: { width: number; height: number }, focused: boolean): GrayImage {
if (!this.pageCreated || !this.page) {
const image = new GrayImage(size.width, size.height, 0);
const font = getFont("terminus24");
image.drawText(font, 16, 16, `Loading ${this.manifest.name}...`, 255);
image.drawText(font, 16, 16 + 2 * font.lineHeight, "(waiting for the app to build its page)", 120);
return image;
}
return compositePage(this.page, size, focused);
}
/**
* Route a gesture to the app, emulating stock hardware: clicks and
* double-clicks arrive as sysEvent (never textEvent) with zero-valued
* fields elided the way protobuf JSON elides them; list selection moves
* locally with events only for clicks and boundary scrolls.
*/
handleGesture(event: DashboardInputEvent): void {
if (!this.page) return;
const capture = this.page ? eventCaptureContainer(this.page) : undefined;
switch (event.type) {
case "click":
if (capture?.kind === "list") {
this.emitListEvent(capture, CLICK_EVENT);
} else {
this.emitSysEvent(CLICK_EVENT, gestureSource(event.source));
}
break;
case "double-click":
this.emitSysEvent(DOUBLE_CLICK_EVENT, gestureSource(event.source));
break;
case "scroll-up":
case "scroll-down": {
const eventType = event.type === "scroll-up" ? SCROLL_TOP_EVENT : SCROLL_BOTTOM_EVENT;
if (capture?.kind === "list") {
this.scrollList(capture, eventType);
} else {
this.emitSysEvent(eventType, 0);
}
break;
}
default:
break;
}
}
private scrollList(list: EvenHubListContainer, eventType: number): void {
const delta = eventType === SCROLL_TOP_EVENT ? 1 : -1;
const next = list.selectedIndex + delta;
if (next < 0 || next >= list.itemNames.length) {
// At a boundary the selection stays put and the app hears about it.
this.emitListEvent(list, eventType);
return;
}
list.selectedIndex = next;
this.windowHooks?.requestRender();
}
setForeground(foreground: boolean): void {
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) -----
/**
* Handle one callHandler('evenAppMessage', ...) invocation. argsJson is the
* JSON array of handler arguments; args[0] is the SDK's message JSON string
* (kept lenient: a bare object works too).
*/
handleBridgeCall(handlerName: string, argsJson: string, callId: number): void {
void (async () => {
let result: unknown = null;
try {
if (handlerName !== "evenAppMessage") throw new Error(`unknown handler ${handlerName}`);
const args = JSON.parse(argsJson) as unknown[];
const first = args[0];
const message = asRecord(typeof first === "string" ? JSON.parse(first) : first);
const method = readString(message, "method", "");
const data = asRecord(message.data);
result = await this.dispatch(method, data);
} catch (error) {
this.log(`evenhub bridge call failed: ${error}`);
this.resolveCall(callId, false, String(error));
return;
}
this.resolveCall(callId, true, result);
})();
}
private async dispatch(method: string, data: Record<string, unknown>): Promise<unknown> {
switch (method) {
case "createStartUpPageContainer":
return this.createStartUpPage(data);
case "rebuildPageContainer":
return this.rebuildPage(data);
case "textContainerUpgrade":
return this.textUpgrade(data);
case "updateImageRawData":
return this.updateImage(data);
case "shutDownPageContainer":
return this.shutDown(readNumber(data, "exitMode", 0));
case "setLocalStorage":
ApplicationSettings.setString(this.storageKey(readString(data, "key", "")), readString(data, "value", ""));
return true;
case "getLocalStorage":
return ApplicationSettings.getString(this.storageKey(readString(data, "key", "")), "");
case "getUserInfo":
return { uid: 0, name: "Faceclaw", avatar: "", country: "" };
case "getGlassesInfo":
return {
model: "g2",
sn: "FACECLAW-G2",
status: {
sn: "FACECLAW-G2",
connectType: "connected",
isWearing: true,
batteryLevel: 100,
isCharging: false,
isInCase: false,
},
};
// Unsupported surface (mic, IMU, location, pickers): fail politely.
case "audioControl":
case "imuControl":
case "startAppLocationUpdates":
case "stopAppLocationUpdates":
return false;
case "getAppLocation":
case "pickImageFromAlbum":
case "captureImageFromCamera":
return null;
default:
this.log(`evenhub: unhandled method ${method}`);
return null;
}
}
/** EhStartUpPageCreateResult: 0 success, 1 invalid, 2 oversize, 3 outOfMemory. */
private async createStartUpPage(data: Record<string, unknown>): Promise<number> {
if (this.pageCreated) {
// One-shot per session on stock: a second call blocks ~2s, then fails.
await delay(DUPLICATE_CREATE_DELAY_MS);
return 1;
}
const page = parsePage(data);
this.warnOnInvalidPage(page);
this.page = page;
this.pageCreated = true;
this.windowHooks?.requestRender();
return 0;
}
private rebuildPage(data: Record<string, unknown>): boolean {
// Also serves as create for apps that fall back to rebuild-on-error.
const page = parsePage(data);
this.warnOnInvalidPage(page);
this.page = page;
this.pageCreated = true;
this.windowHooks?.requestRender();
return true;
}
private warnOnInvalidPage(page: EvenHubPage): void {
// Stock rejects these outright; we accept-and-log until rejection is
// proven necessary for compatibility.
const captures = page.containers.filter((c) => c.kind !== "image" && c.isEventCapture).length;
if (captures !== 1) this.log(`evenhub: page has ${captures} event-capture containers (stock requires exactly 1)`);
const texts = page.containers.filter((c) => c.kind === "text").length;
const images = page.containers.filter((c) => c.kind === "image").length;
if (texts > 8 || images > 4) this.log(`evenhub: page exceeds stock limits (${texts} text, ${images} image)`);
}
private textUpgrade(data: Record<string, unknown>): boolean {
const id = readNumber(data, "containerID", -1);
const name = readString(data, "containerName", "");
const container = this.page?.containers.find((c) => c.kind === "text" && c.id === id && c.name === name);
if (!container || container.kind !== "text") return false;
const content = readString(data, "content", "");
const offset = readOptionalNumber(data, "contentOffset");
const length = readOptionalNumber(data, "contentLength");
if (offset !== undefined && length !== undefined) {
container.content = container.content.slice(0, offset) + content + container.content.slice(offset + length);
} else {
container.content = content;
}
this.windowHooks?.requestRender();
return true;
}
/** BleEhSendImageResult: 0 success, 1 imageException, 2 sizeInvalid, 3 sendFailed. */
private updateImage(data: Record<string, unknown>): number {
const id = readNumber(data, "containerID", -1);
const container = this.page?.containers.find((c) => c.kind === "image" && c.id === id);
if (!container || container.kind !== "image") return 3;
const bytes = imagePayloadBytes(data.imageData ?? data.rawData ?? asRecord(data).mapRawData);
if (!bytes || bytes.length === 0) return 1;
const decoded = decodeImageBytes(bytes, container);
if (!decoded) return 1;
container.pixels = decoded.pixels;
container.pixelsWidth = decoded.width;
container.pixelsHeight = decoded.height;
this.windowHooks?.requestRender();
return 0;
}
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();
return true;
}
// Immediate exit. Resolve first (the return travels via evaluateJs, and
// close() only tears the webview down after its own delay).
setTimeout(() => this.close(), 200);
return true;
}
private storageKey(key: string): string {
return `evenhub:${this.manifest.packageId}:ls:${key}`;
}
// ----- pushes (host -> web) -----
private resolveCall(callId: number, ok: boolean, value: unknown): void {
this.pageHandle?.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(
`window._listenEvenAppMessage && window._listenEvenAppMessage(${JSON.stringify(message)})`,
);
}
private pushEvenHubEvent(payloadType: "sysEvent" | "textEvent" | "listEvent", jsonData: Record<string, unknown>): void {
this.pushMessage("evenHubEvent", { type: payloadType, jsonData: elideZeroFields(jsonData) });
}
private emitSysEvent(eventType: number, eventSource: number): void {
this.pushEvenHubEvent("sysEvent", { eventType, eventSource });
}
private emitListEvent(list: EvenHubListContainer, eventType: number): void {
this.pushEvenHubEvent("listEvent", {
containerID: list.id,
containerName: list.name,
currentSelectItemIndex: list.selectedIndex,
currentSelectItemName: list.itemNames[list.selectedIndex] ?? "",
eventType,
});
}
// ----- teardown -----
/** Close everything: glasses window, phone page, 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);
this.systemExitSent = true;
}
const hooks = this.windowHooks;
this.windowHooks = null;
hooks?.closeWindow();
const page = this.pageHandle;
this.pageHandle = null;
if (page) {
// Give in-flight resolves/pushes a beat to reach the webview first.
setTimeout(() => page.closePage(), 100);
}
}
isClosed(): boolean {
return this.closed;
}
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** ring/left-arm/right-arm -> PB EventSourceType. */
function gestureSource(source: "ring" | "left-arm" | "right-arm"): number {
switch (source) {
case "right-arm":
return 1;
case "ring":
return 2;
case "left-arm":
return 3;
}
}
/**
* Protobuf JSON elides zero-valued fields, and apps depend on it (they test
* eventType === 0 || eventType === undefined). Emit the same shape.
*/
function elideZeroFields(obj: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (value === undefined || value === 0 || value === "") continue;
out[key] = value;
}
return out;
}
/** Accept the payload forms seen on the wire: number[], JSON-ified typed
* array ({"0": 1, ...}), or base64 string. */
function imagePayloadBytes(raw: unknown): Uint8Array | null {
if (Array.isArray(raw)) {
const out = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) out[i] = Number(raw[i]) & 0xff;
return out;
}
if (typeof raw === "string") return base64Decode(raw);
if (raw && typeof raw === "object") {
const record = raw as Record<string, unknown>;
const keys = Object.keys(record);
const out = new Uint8Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const value = record[String(i)];
if (typeof value !== "number") return null;
out[i] = value & 0xff;
}
return out;
}
return null;
}
const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64Decode(text: string): Uint8Array | null {
const clean = text.replace(/[\s=]+$/g, "").replace(/\s+/g, "");
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
let bits = 0;
let bitCount = 0;
let outIndex = 0;
for (const char of clean) {
const value = BASE64_ALPHABET.indexOf(char);
if (value < 0) return null;
bits = (bits << 6) | value;
bitCount += 6;
if (bitCount >= 8) {
bitCount -= 8;
out[outIndex++] = (bits >> bitCount) & 0xff;
}
}
return out.subarray(0, outIndex);
}
/**
* Decode an image payload: PNG (what the SDK-era apps send — the host does
* the gray conversion), or raw grayscale sized to the container (8bpp, or
* 4bpp packed two pixels per byte, high nibble first).
*/
function decodeImageBytes(
bytes: Uint8Array,
container: EvenHubImageContainer,
): { pixels: Uint8Array; width: number; height: number } | null {
if (bytes.length > 4 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
try {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
const decoded = UPNG.decode(buffer);
const frames = UPNG.toRGBA8(decoded) as ArrayBuffer[];
if (!frames.length) return null;
const rgba = new Uint8Array(frames[0]!);
const pixels = new Uint8Array(decoded.width * decoded.height);
for (let i = 0; i < pixels.length; i++) {
const offset = i * 4;
const alpha = (rgba[offset + 3] ?? 0) / 255;
pixels[i] = Math.round(
(0.2126 * (rgba[offset] ?? 0) + 0.7152 * (rgba[offset + 1] ?? 0) + 0.0722 * (rgba[offset + 2] ?? 0)) * alpha,
);
}
return { pixels, width: decoded.width, height: decoded.height };
} catch (error) {
console.warn(`evenhub: PNG decode failed: ${error}`);
return null;
}
}
const area = container.width * container.height;
if (bytes.length === area) {
return { pixels: Uint8Array.from(bytes), width: container.width, height: container.height };
}
if (bytes.length === Math.ceil(area / 2)) {
const pixels = new Uint8Array(area);
for (let i = 0; i < area; i++) {
const byte = bytes[i >> 1]!;
const nibble = i % 2 === 0 ? byte >> 4 : byte & 0x0f;
pixels[i] = nibble * 17;
}
return { pixels, width: container.width, height: container.height };
}
return null;
}
+15 -1
View File
@@ -16,12 +16,15 @@ export const FILES_WINDOW_ID = "files";
export const FILES_SURFACE_ID = "window:files";
const TEXT_FILE = /\.(txt|md|log)$/i;
const EHPK_FILE = /\.ehpk$/i;
export type FilesAppOptions = InProcessAppOptions & {
/** Open a text document as its own shell window (also used by the share intent). */
openDocumentWindow: (title: string, text: string) => void;
/** Open an image file as its own shell window. */
openImageWindow: (title: string, path: string) => void;
/** Launch an EvenHub app package (.ehpk) through the EvenHub host. */
openEhpkApp: (path: string) => void;
};
/**
@@ -32,7 +35,7 @@ export type FilesAppOptions = InProcessAppOptions & {
export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow {
let created: InProcessWindow | null = null;
const browser = new FileBrowserLayer({
isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name),
isSupportedFile: (name) => TEXT_FILE.test(name) || EHPK_FILE.test(name) || isDecodableImageFile(name),
// The browser handles double-click itself (up a level), so it is not
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
onLeave: () => shell.yieldFocusToSidebar(),
@@ -131,6 +134,17 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
},
];
}
if (EHPK_FILE.test(entry.name)) {
return [
{
label: "Run app",
onSelect: (ctx) => {
ctx.stack.pop();
options.openEhpkApp(entry.path);
},
},
];
}
if (isDecodableImageFile(entry.name)) {
return [
{
+6
View File
@@ -1,4 +1,5 @@
import { type AppContext, type AppDefinition } from "../app-definition";
import { openEvenHubPackage } from "../evenhub";
import {
createFilesAppWindow,
createImageDocumentWindow,
@@ -43,6 +44,11 @@ const filesApp: AppDefinition = {
...options,
openDocumentWindow: (title, text) => openTextDocumentWindow(ctx, title, text),
openImageWindow: (title, path) => openImageDocumentWindow(ctx, title, path),
openEhpkApp: (path) => {
void openEvenHubPackage(ctx, path).catch((error) => {
ctx.appendLog(`evenhub launch failed: ${error}`);
});
},
}),
),
// A document arriving via Android's Share intent opens as its own window.
+21 -21
View File
@@ -19,7 +19,7 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.2.6.10.bin",
"baseSha256": "f4dfb0b49ad3de3c2daf17f8a27a157c3dc98411d6a0d3ab2cfd0918f41b9afa",
"outputSha256": "20cba9377ea207c8c0a6fd936f32db9ecaf23da023cdf43a770b22b355107d1f",
"outputSha256": "ade1ca6b3329c66efe03c513d300058ef11f2112d81665fd648c54ac4c2887d6",
"patches": [
{
"offset": 1449549,
@@ -42,61 +42,61 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1447919,
"old": "7ef7fefd",
"new": "baf20cfb",
"new": "baf22cfb",
"desc": "bl snapshot_side @ 0x4db968"
},
{
"offset": 1448931,
"old": "7ef704fc",
"new": "baf212f9",
"new": "baf232f9",
"desc": "bl snapshot_side @ 0x4dbd5c"
},
{
"offset": 1165461,
"old": "45f0cefd",
"new": "fff2bdfa",
"new": "fff2ddfa",
"desc": "bl image_deferred (deferred consumer -> FIFO restore + worker, both lenses)"
},
{
"offset": 1186287,
"old": "d9f7d4ff",
"new": "fbf296f9",
"new": "fbf2e8f9",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1183983,
"old": "f4f75aff",
"new": "fbf252fb",
"new": "fbf2a4fb",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 926945,
"old": "08f068fa",
"new": "3af375f8",
"new": "3af3c7f8",
"desc": "bl faceclaw_display_start @ 0x45c65a (fail-open double-tap takeover)"
},
{
"offset": 927137,
"old": "08f008fa",
"new": "3af315f8",
"new": "3af367f8",
"desc": "bl faceclaw_display_start @ 0x45c71a (fail-open double-tap takeover)"
},
{
"offset": 822553,
"old": "28f003f8",
"new": "54f363f8",
"desc": "bl evenhub_longpress (replaces force-quit dialog)"
"new": "54f3b5f8",
"desc": "bl evenhub_longpress (Faceclaw lease gates custom event vs stock dialog)"
},
{
"offset": 823369,
"old": "1cf09bfb",
"new": "53f3e7fe",
"new": "53f343ff",
"desc": "bl ring_release (forward ring release-long-press)"
},
{
"offset": 1474137,
"old": "7fb50600",
"new": "b4f24fbf",
"new": "b4f2a1bf",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
@@ -114,13 +114,13 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1198787,
"old": "dff770fb",
"new": "f7f278fc",
"new": "f7f2cafc",
"desc": "bl faceclaw_send_wear_event @ 0x49ec3c (outside onboarding)"
},
{
"offset": 1198881,
"old": "dff741fb",
"new": "f7f249fc",
"new": "f7f29bfc",
"desc": "bl faceclaw_send_wear_event @ 0x49ec9a (outside onboarding)"
},
{
@@ -132,43 +132,43 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 4301227,
"old": "",
"new": "02fb01f044f6d341c0f24701084700bf084644f61751c0f24701084770b500284ed001684ef66362ccf2ff02914218bf70bd90f8081190f8095142f6c52c8d42c0f2500c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b149f29942c0f244022146bde87040104770bd00bf70b54ff6fd03c0f2450314460d46984743f6fc71c2f200010e6831466ff39601b1f1005f0ad131684ef66362ccf2ff02914218bf0026412d03d070bd0026412dfbd1002cf9d04af26951c0f2450105468847002e01462846efd00129edd196f807120029e9d02168002948bf70bd47f25d02c0f2580208469047284670bd00bf2de9f04f99b043f6fc76c2f20006d6f8009048466ff39600b0f1005f40f04d81d9f800004ef66367ccf2ff07b84240f0448199f82802002800f02d81d9f82442002c00f0288140f2b870c2f20000d0f8008004a801f006f9b8f1000f00f0fb8140f2030c45f24075cff6807ca4f1600008f160026ff0bf03c0f20205016ed4182166416ec0336166816eab42a166c16ee166016f2167416f6167816fa167c16fe167d0f88010c4f88010d0f88410c4f88410d0f88810c4f88810d0f88c10c4f88c10d0f89010c4f89010d0f89410c4f89410d0f89810c4f89810d0f89c10c4f89c10d0f8a010c4f8a010d0f8a410c4f8a410d0f8a810c4f8a810d0f8ac10c4f8ac10d0f8b010c4f8b010d0f8b410c4f8b410d0f8b810c4f8b810d0f8bc10c4f8bc1050f8c01fc4f8c0104168c4f8c4108168c4f8c810c168c4f8cc100169c4f8d0104169c4f8d4108169c4f8d810c169c4f8dc10016ac4f8e010416ac4f8e410816ac4f8e810c16ac4f8ec10016bc4f8f010416bc4f8f410816bc4f8f810c16bc4f8fc10016cc4f80011416cc4f80411816cc4f80811c16cc4f80c11016dc4f81011416dc4f81411816dc4f81811c16dc4f81c117ff462afd6f800e00eea0c00b0f1005f40f08180def80000b8427cd19ef8ce00002840f050819ef8dc00002100288df8141000f0b08105aa505c002800f0838153185878002800f059819878002800f05781d878002800f055811879002800f053815879002800f051819879002800f04f81d879002800f04d81187a002800f04b81587a002800f04981987a002800f04781d87a002800f04581187b002800f04381587b002800f04181987b002800f03f81d87b002800f03d81187c002800f03b81587c002800f03981987c002800f03781d87c002800f0358114315029abd155e199f82a0270b1d9f82c0240b144f63421c2f207010968401a002800f3fb80002089f82a024cf61520c0f2460019b0bde8f04f004744f6d341c0f247014ff40c708847002800f0cc804ff6d051cff6ff7100224318463183f8302283f8312283f8322283f8332283f8342283f8352283f8362283f8372283f8382283f8392283f83a2283f83b2283f83c2283f83d2283f83e2283f83f2283f8402283f8412283f8422283f8432283f8442283f8452283f8462283f8472283f8482283f8492283f84a2283f84b2283f84c2283f84d2283f84e2283f84f2283f8502283f8512283f8522283f8532283f8542283f8552283f8562283f8572283f8582283f8592283f85a2283f85b2283f85c2283f85d2283f85e2283f85f2283f8602283f8612283f8622283f8632283f8642283f8652283f8662283f8672283f8682283f8692283f86a2283f86b2283f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f875227ff470af012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e0002089f82802c9f8240289f82a02012089f829024cf61520c0f24600804714e000203060002089f82802c9f824024ff4163045f20f11069005a8c0f24701cdf814808847012089f82a0204a801f017f8c9f8d40019b0bde8f08f013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e0093112e00a3110e00b310ee00c310ce00d310ae00e3108e00f3106e0103104e0113102e0123100e013314f2921d84ff0520050541dd00a4445204e29507018d04f204d29907014d052204c29d07010d044204b2910710cd045204a29507108d052204929907104d020204829d07140f08d8600208df8630001219ef8dd00002870d0002205ab985c00284fd09f18787838b3b87838b3f87838b3387938b3787938b3b87938b3f87938b3387a38b3787a38b3b87a38b3f87a38b3387b38b3787b38b3b87b38b3f87b38b3387c38b3787c38b3b87c38b3f87c38b31432502ad2d13ce0013222e0023220e003321ee004321ce005321ae0063218e0073216e0083214e0093212e00a3210e00b320ee00c320ce00d320ae00e3208e00f3206e0103204e0113202e0123200e013324f2a15d84ff05300985411d013444b204e2a58700cd049204d2a987008d050204c2ad87004d020204b2a187140f0608100208df8630001319ef8de0000286cd0002105aa505c00284fd05318587838b3987838b3d87838b3187938b3587938b3987938b3d87938b3187a38b3587a38b3987a38b3d87a38b3187b38b3587b38b3987b38b3d87b38b3187c38b3587c38b3987c38b3d87c38b314315029d2d138e0013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e0093112e00a3110e00b310ee00c310ce00d310ae00e3108e00f3106e0103104e0113102e0123100e013314f2911d84ff0440050540dd00a4455204e29507008d050204d29907004d020204c29d07040f0ec8000208df8630001219ef8df0000284dd0002105aa505c002800f0bc8053185878002800f092809878002800f09080d878002800f08e801879002800f08c805879002800f08a809879002800f08880d879002800f08680187a002800f08480587a002800f08280987a002800f08080d87a00287ed0187b00287dd0587b00287cd0987b00287bd0d87b00287ad0187c002879d0587c002878d0987c002877d0d87c002876d014315029b4d1d0e0002940f0d180002105aa505c002800f0b88053185878002800f08e809878002800f08c80d878002800f08a801879002800f088805879002800f086809879002800f08480d879002800f08280187a002800f08080587a00287ed0987a00287dd0d87a00287cd0187b00287bd0587b00287ad0987b002879d0d87b002878d0187c002877d0587c002876d0987c002875d0d87c002874d014315029b6d181e0013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e00Line truncated
"new": "02fb01f044f6d341c0f24701084700bf084644f61751c0f24701084770b500284ed001684ef66362ccf2ff02914218bf70bd90f8081190f8095142f6c52c8d42c0f2500c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b149f29942c0f244022146bde87040104770bd00bf70b54ff6fd03c0f2450314460d46984743f6fc71c2f200010e6831466ff39601b1f1005f0ad131684ef66362ccf2ff02914218bf0026412d03d070bd0026412dfbd1002cf9d04af26951c0f2450105468847002e01462846efd00129edd196f807120029e9d02168002948bf70bd47f25d02c0f2580208469047284670bd00bf2de9f04f99b043f6fc76c2f20006d6f8009048466ff39600b0f1005f40f04d81d9f800004ef66367ccf2ff07b84240f0448199f82802002800f02d81d9f82442002c00f0288140f2b870c2f20000d0f8008004a801f006f9b8f1000f00f0fb8140f2030c45f24075cff6807ca4f1600008f160026ff0bf03c0f20205016ed4182166416ec0336166816eab42a166c16ee166016f2167416f6167816fa167c16fe167d0f88010c4f88010d0f88410c4f88410d0f88810c4f88810d0f88c10c4f88c10d0f89010c4f89010d0f89410c4f89410d0f89810c4f89810d0f89c10c4f89c10d0f8a010c4f8a010d0f8a410c4f8a410d0f8a810c4f8a810d0f8ac10c4f8ac10d0f8b010c4f8b010d0f8b410c4f8b410d0f8b810c4f8b810d0f8bc10c4f8bc1050f8c01fc4f8c0104168c4f8c4108168c4f8c810c168c4f8cc100169c4f8d0104169c4f8d4108169c4f8d810c169c4f8dc10016ac4f8e010416ac4f8e410816ac4f8e810c16ac4f8ec10016bc4f8f010416bc4f8f410816bc4f8f810c16bc4f8fc10016cc4f80011416cc4f80411816cc4f80811c16cc4f80c11016dc4f81011416dc4f81411816dc4f81811c16dc4f81c117ff462afd6f800e00eea0c00b0f1005f40f08180def80000b8427cd19ef8ce00002840f050819ef8dc00002100288df8141000f0b08105aa505c002800f0838153185878002800f059819878002800f05781d878002800f055811879002800f053815879002800f051819879002800f04f81d879002800f04d81187a002800f04b81587a002800f04981987a002800f04781d87a002800f04581187b002800f04381587b002800f04181987b002800f03f81d87b002800f03d81187c002800f03b81587c002800f03981987c002800f03781d87c002800f0358114315029abd155e199f82a0270b1d9f82c0240b144f63421c2f207010968401a002800f3fb80002089f82a024cf61520c0f2460019b0bde8f04f004744f6d341c0f247014ff40c708847002800f0cc804ff6d051cff6ff7100224318463183f8302283f8312283f8322283f8332283f8342283f8352283f8362283f8372283f8382283f8392283f83a2283f83b2283f83c2283f83d2283f83e2283f83f2283f8402283f8412283f8422283f8432283f8442283f8452283f8462283f8472283f8482283f8492283f84a2283f84b2283f84c2283f84d2283f84e2283f84f2283f8502283f8512283f8522283f8532283f8542283f8552283f8562283f8572283f8582283f8592283f85a2283f85b2283f85c2283f85d2283f85e2283f85f2283f8602283f8612283f8622283f8632283f8642283f8652283f8662283f8672283f8682283f8692283f86a2283f86b2283f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f875227ff470af012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e0002089f82802c9f8240289f82a02012089f829024cf61520c0f24600804714e000203060002089f82802c9f824024ff4163045f20f11069005a8c0f24701cdf814808847012089f82a0204a801f017f8c9f8d40019b0bde8f08f013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e0093112e00a3110e00b310ee00c310ce00d310ae00e3108e00f3106e0103104e0113102e0123100e013314f2921d84ff0520050541dd00a4445204e29507018d04f204d29907014d052204c29d07010d044204b2910710cd045204a29507108d052204929907104d020204829d07140f08d8600208df8630001219ef8dd00002870d0002205ab985c00284fd09f18787838b3b87838b3f87838b3387938b3787938b3b87938b3f87938b3387a38b3787a38b3b87a38b3f87a38b3387b38b3787b38b3b87b38b3f87b38b3387c38b3787c38b3b87c38b3f87c38b31432502ad2d13ce0013222e0023220e003321ee004321ce005321ae0063218e0073216e0083214e0093212e00a3210e00b320ee00c320ce00d320ae00e3208e00f3206e0103204e0113202e0123200e013324f2a15d84ff05300985411d013444b204e2a58700cd049204d2a987008d050204c2ad87004d020204b2a187140f0608100208df8630001319ef8de0000286cd0002105aa505c00284fd05318587838b3987838b3d87838b3187938b3587938b3987938b3d87938b3187a38b3587a38b3987a38b3d87a38b3187b38b3587b38b3987b38b3d87b38b3187c38b3587c38b3987c38b3d87c38b314315029d2d138e0013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e0093112e00a3110e00b310ee00c310ce00d310ae00e3108e00f3106e0103104e0113102e0123100e013314f2911d84ff0440050540dd00a4455204e29507008d050204d29907004d020204c29d07040f0ec8000208df8630001219ef8df0000284dd0002105aa505c002800f0bc8053185878002800f092809878002800f09080d878002800f08e801879002800f08c805879002800f08a809879002800f08880d879002800f08680187a002800f08480587a002800f08280987a002800f08080d87a00287ed0187b00287dd0587b00287cd0987b00287bd0d87b00287ad0187c002879d0587c002878d0987c002877d0d87c002876d014315029b4d1d0e0002940f0d180002105aa505c002800f0b88053185878002800f08e809878002800f08c80d878002800f08a801879002800f088805879002800f086809879002800f08480d879002800f08280187a002800f08080587a00287ed0987a00287dd0d87a00287cd0187b00287bd0587b00287ad0987b002879d0d87b002878d0187c002877d0587c002876d0987c002875d0d87c002874d014315029b6d181e0013122e0023120e003311ee004311ce005311ae0063118e0073116e0083114e00Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 777711,
"old": "44c33500",
"new": "e3113600",
"new": "9f123600",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "c4c33500",
"new": "63123600",
"new": "1f133600",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 777831,
"old": "44c33504",
"new": "e3113604",
"new": "9f123604",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 777835,
"old": "df8110c9",
"new": "4c88426b",
"new": "bf1e07ba",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "c1be0fb1",
"new": "79b1f28b",
"new": "49a16905",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 777715,
"old": "c1be0fb1",
"new": "79b1f28b",
"new": "49a16905",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+2
View File
@@ -52,6 +52,8 @@ export const ICON_SVGS = {
'<svg viewBox="0 0 24 24" fill="none"><line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/></svg>',
music:
'<svg viewBox="0 0 24 24" fill="none"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>',
package:
'<svg viewBox="0 0 24 24" fill="none"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>',
activity:
'<svg viewBox="0 0 24 24" fill="none"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/></svg>',
bell:
+71
View File
@@ -118,6 +118,77 @@ export function writeTextToDownloads(filename: string, text: string): string | n
}
}
/** Read a whole file as bytes; null when unreadable. */
export function readBinaryFile(path: string): Uint8Array | null {
try {
const file = new java.io.File(path);
if (!file.isFile()) return null;
const bytes = java.nio.file.Files.readAllBytes(file.toPath());
try {
// The V8 runtime can wrap a ByteBuffer's memory directly; copy out of it
// so the result outlives the Java array.
const arrayBuffer = (ArrayBuffer as any).from(java.nio.ByteBuffer.wrap(bytes));
return new Uint8Array(arrayBuffer).slice();
} catch {
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[i] & 0xff;
}
return out;
}
} catch (error) {
console.warn(`readBinaryFile failed for ${path}: ${error}`);
return null;
}
}
/** Write bytes to a file, creating parent directories; false on failure. */
export function writeBinaryFile(path: string, bytes: Uint8Array): boolean {
try {
const file = new java.io.File(path);
const parent = file.getParentFile();
if (parent) parent.mkdirs();
const stream = new java.io.FileOutputStream(file);
try {
// An ArrayBuffer marshals to java.nio.ByteBuffer (the same conversion
// submitSurfaceFrame relies on), so write through the channel.
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
stream.getChannel().write(buffer);
} finally {
stream.close();
}
return true;
} catch (error) {
console.warn(`writeBinaryFile failed for ${path}: ${error}`);
return false;
}
}
/** Recursively delete a file or directory tree (best effort). */
export function deletePathRecursively(path: string): void {
try {
const root = new java.io.File(path);
if (!root.exists()) return;
if (root.isDirectory()) {
const children = root.listFiles();
if (children) {
for (let i = 0; i < children.length; i++) {
deletePathRecursively(String(children[i].getAbsolutePath()));
}
}
}
root.delete();
} catch (error) {
console.warn(`deletePathRecursively failed for ${path}: ${error}`);
}
}
/** The app-private files directory (no permissions needed). */
export function appFilesDirPath(): string {
const context = Utils.android.getApplicationContext();
return String(context.getFilesDir().getAbsolutePath());
}
/** Read a UTF-8 text file (size-capped); null when unreadable or too large. */
export function readTextFile(path: string): string | null {
try {
+115
View File
@@ -0,0 +1,115 @@
/**
* 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`;
}
+7
View File
@@ -0,0 +1,7 @@
<Page
xmlns="http://schemas.nativescript.org/tns.xsd"
navigatingTo="navigatingTo"
navigatedFrom="navigatedFrom">
<ActionBar title="{{ title }}" />
<Placeholder creatingView="creatingWebView" />
</Page>
+7
View File
@@ -11,6 +11,7 @@
"@nativescript/core": "~9.0.0",
"@nativescript/theme": "^3.1.0",
"@xterm/headless": "^6.0.0",
"fzstd": "^0.1.1",
"lodash": "^4.18.1",
"lz4js": "^0.2.0",
"pako": "^2.1.0",
@@ -2506,6 +2507,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/fzstd": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/fzstd/-/fzstd-0.1.1.tgz",
"integrity": "sha512-dkuVSOKKwh3eas5VkJy1AW1vFpet8TA/fGmVA5krThl8YcOVE/8ZIoEA1+U1vEn5ckxxhLirSdY837azmbaNHA==",
"license": "MIT"
},
"node_modules/gensync": {
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+1
View File
@@ -10,6 +10,7 @@
"@nativescript/core": "~9.0.0",
"@nativescript/theme": "^3.1.0",
"@xterm/headless": "^6.0.0",
"fzstd": "^0.1.1",
"lodash": "^4.18.1",
"lz4js": "^0.2.0",
"pako": "^2.1.0",