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

+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.