iOS porting: EvenHub app compatibility first pass

This commit is contained in:
James Babcock committed 2026-09-08 14:47:58 -07:00
1 parent 79b6c276f8
commit 44bd1d8a2d
24 files changed
+843 -24

No files matched your search

+7
View File
@@ -18,6 +18,11 @@ const RECORD_FILE = 0xe4;
const RECORD_DIR = 0xe5;
const RECORD_FOOTER = 0xe3;
/** Archive paths are relative to one package, never to the phone container. */
export function safeEhpkPath(value: string): boolean {
return !!value && !/[\\\u0000:]/.test(value) && value.split('/').every(part => !!part && part !== '.' && part !== '..');
}
export type EhpkArchive = {
/** Relative path (e.g. "app.json", "dist/index.html") to contents. */
files: Map<string, Uint8Array>;
@@ -90,6 +95,7 @@ export function parseEhpk(data: Uint8Array): EhpkArchive {
const uncompressedLength = view.getUint32(p + 8, true);
const nameLength = view.getUint16(p + 14, true);
const name = utf8Decode(unxor(data, p + 16, nameLength));
if (!safeEhpkPath(name)) throw new Error(`ehpk: invalid file path ${name}`);
const blob = unxor(data, p + 16 + nameLength, compressedLength);
const content = decompress(blob, new Uint8Array(uncompressedLength));
if (content.length !== uncompressedLength) {
@@ -119,6 +125,7 @@ export function parseManifest(appJsonText: string): EvenHubManifest {
const name = String(raw.name ?? packageId);
const version = String(raw.version ?? "0");
const entrypoint = String(raw.entrypoint ?? "index.html");
if (!safeEhpkPath(entrypoint)) throw new Error('Invalid EHPK entrypoint');
const permissions = parsePermissions(raw.permissions);
const privacyPolicyUrl = firstSafeHttpsUrl(
+17 -11
View File
@@ -66,16 +66,15 @@ export async function launchPackage(
): Promise<void> {
const data = readBinaryFile(ehpkPath);
if (!data) {
ctx.appendLog(`evenhub: could not read ${ehpkPath}`);
return;
throw new Error('Could not read the EHPK file.');
}
const archive = parseEhpk(data);
const appJson = archive.files.get("app.json");
if (!appJson) {
ctx.appendLog("evenhub: package has no app.json");
return;
throw new Error('The EHPK package has no app.json.');
}
const manifest = parseManifest(utf8Decode(appJson));
if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.');
const appId = options.appId ?? "evenhub";
if (options.singleton) {
const existing = Array.from(running.values()).find((app) => app.appId === appId);
@@ -88,16 +87,18 @@ export async function launchPackage(
// 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}`;
if (!safeId || safeId === '.' || safeId === '..') throw new Error('Invalid EHPK package ID');
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial}` : ''}`;
deletePathRecursively(baseDir);
for (const [name, content] of Array.from(archive.files)) {
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
ctx.appendLog(`evenhub: failed to write ${name}`);
return;
deletePathRecursively(baseDir);
throw new Error(`Could not unpack ${name}.`);
}
}
await startApp(ctx, manifest, `${baseDir}/dist`, "", appId);
try { await startApp(ctx, manifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined); }
catch (error) { deletePathRecursively(baseDir); throw error; }
}
/**
@@ -111,6 +112,7 @@ async function startApp(
distDir: string,
remoteUrl: string,
appId: string,
cleanup?: () => void,
): Promise<void> {
const windowId = `evenhub:app:${nextSerial++}`;
const session = new EvenHubSession(manifest, distDir, ctx.appendLog, remoteUrl);
@@ -123,6 +125,7 @@ async function startApp(
phoneShownWindowId = null;
}
webView.destroy();
cleanup?.();
running.delete(windowId);
},
});
@@ -130,9 +133,11 @@ async function startApp(
ensureBackHandler();
ctx.appendLog(`evenhub: launching ${manifest.name} ${manifest.version} (${manifest.packageId})`);
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
);
try {
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
);
} catch (error) { session.close(); throw error; }
}
/**
@@ -210,6 +215,7 @@ export function closeRunningPackage(packageId: string): void {
export function showOnPhone(windowId: string): void {
const app = running.get(windowId);
if (!app) return;
if (phoneShownWindowId && phoneShownWindowId !== windowId) hidePhone();
app.webView.showOnPhone();
phoneShownWindowId = windowId;
}
+5
View File
@@ -0,0 +1,5 @@
import { Utils } from '@nativescript/core'
/** Open outside the app runtime; this page has no EvenHub bridge. */
export function openPrivacyPolicyOnPhone(url: string, _appName: string): void {
if (/^https:\/\//i.test(url)) Utils.openUrl(url)
}
+14 -3
View File
@@ -334,6 +334,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
private windowHooks: EvenHubWindowHooks | null = null;
private closed = false;
private launchContextPushed = false;
private loadError = '';
private systemExitSent = false;
/** The one-shot launch FOREGROUND_ENTER has been delivered (page exists). */
private launchEnterSent = false;
@@ -383,6 +384,11 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
this.webViewHandle = handle;
}
webViewFailed(message: string): void {
if (this.closed) return;
this.loadError = message; this.log(`evenhub: ${message}`); this.windowHooks?.requestRender();
}
/** The WebView finished loading the app: push the one-shot launch context. */
webViewLoaded(): void {
if (this.launchContextPushed) return;
@@ -416,11 +422,12 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
// Focus changes always trigger a repaint of the foreground window, so paint
// is a reliable place to sample shell input-focus for lifecycle events.
this.updateShellFocus(focused);
if (!this.pageCreated || !this.page) {
if (this.loadError || !this.pageCreated || !this.page) {
const image = new GrayImage(size.width, size.height, 0);
const font = EvenHubFont.get();
font.drawText(image, 16, 16, `Loading ${this.manifest.name}...`, 255);
font.drawText(image, 16, 16 + 2 * font.lineHeight, "(waiting for the app to build its page)", 120);
font.drawText(image, 16, 16, `${this.loadError ? 'Could not run' : 'Loading'} ${this.manifest.name}...`, 255);
font.drawTextWrapped(image, 16, 16 + 2 * font.lineHeight, Math.max(1, size.width - 32),
this.loadError || "(waiting for the app to build its page)", 120);
return image;
}
return compositePage(this.page, size, focused);
@@ -604,6 +611,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* flows (foreground + screen on + no assistant modal).
*/
private audioControl(data: Record<string, unknown>): boolean {
if (global.isIOS) return false; // EvenHub PCM routing is not ported yet.
if (!permissionsIncludeMicrophone(this.manifest.permissions)) {
this.log("evenhub: audioControl denied (app declares no microphone permission)");
return false;
@@ -634,6 +642,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
/** getAppLocation(): one-shot fix, or null on denial/error (SDK contract). */
private async getAppLocation(): Promise<AppLocation | null> {
if (global.isIOS) return null;
if (!this.declaresLocation()) return null;
if (!(await ensureFineLocationPermission())) return null;
try {
@@ -657,6 +666,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* Navigate app's foreground-service-backed tracking.
*/
private async startLocationUpdates(data: Record<string, unknown>): Promise<boolean> {
if (global.isIOS) return false;
if (!this.declaresLocation()) return false;
if (!(await ensureFineLocationPermission())) return false;
if (this.closed) return false;
@@ -697,6 +707,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* to the foreground app. reportFrq is one of 100..1000 (step 100).
*/
private imuControl(data: Record<string, unknown>): boolean {
if (global.isIOS) return false;
const enable = readEnableFlag(data);
const freq = clampImuFreq(readOptionalNumber(data, "reportFrq") ?? readOptionalNumber(data, "reportFreq") ?? 100);
// Payload field spelling isn't fully captured; log once per toggle.
+43
View File
@@ -0,0 +1,43 @@
import { EVENHUB_BRIDGE_INJECT_SCRIPT, buildFaceclawExtensionsScript, type EvenHubSession } from './session'
import { FACECLAW_VERSION } from '../../version'
import type { EvenHubWebView } from './webview'
declare const FaceclawEvenHubWebView: any
export const IOS_EVENHUB_TRANSPORT_SCRIPT = `
window.__faceclawEvenHub = { postMessage: function(name, args, id) {
window.webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:name, args:args, id:id});
}};
(function() {
['log','warn','error'].forEach(function(level) {
var original = console[level];
console[level] = function() {
original.apply(console, arguments);
window.webkit.messageHandlers.faceclaw.postMessage({kind:'console', message:Array.prototype.map.call(arguments, String).join(' ').slice(0,4000)});
};
});
window.addEventListener('error', function(e) { console.error(e.message); });
window.addEventListener('unhandledrejection', function(e) { console.error(String(e.reason)); });
})();
`
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
if (session.remoteUrl) throw new Error('On iOS, open a local .ehpk package from Files.')
const host = FaceclawEvenHubWebView.new()
host.packageIdentifier = session.manifest.packageId
host.eventHandler = (json: string) => {
try {
const event = JSON.parse(json)
if (event.kind === 'call' && typeof event.name === 'string' && typeof event.args === 'string' && Number.isSafeInteger(event.id))
session.handleBridgeCall(event.name, event.args, event.id)
else if (event.kind === 'loaded') session.webViewLoaded()
else if (event.kind === 'error') session.webViewFailed(String(event.message))
else if (event.kind === 'console') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
}
// Defer loading until manager.ts has attached the session/window handles.
const loading = setTimeout(() => host.startEntrypointScript(session.distDir, session.manifest.entrypoint,
IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)), 0)
return { native: host, evaluateJs: js => host.evaluate(js),
destroy: () => { clearTimeout(loading); host.destroy() },
showOnPhone: () => host.showOnPhone(), hideOnPhone: () => host.hideOnPhone() }
}
+4 -3
View File
@@ -45,7 +45,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) || isFontFile(name) || (!global.isIOS && (isDecodableImageFile(name) || EHPK_FILE.test(name))),
isSupportedFile: (name) => TEXT_FILE.test(name) || isFontFile(name) || EHPK_FILE.test(name) || (!global.isIOS && 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(),
@@ -170,7 +170,7 @@ function confirmEhpkPermissions(ctx: LayerContext, entry: DirectoryEntry, procee
* window for viewable types, empty for everything else (metadata only).
*/
function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileInfoAction[] {
if (global.isIOS && !TEXT_FILE.test(entry.name) && !isFontFile(entry.name)) return [];
if (global.isIOS && !TEXT_FILE.test(entry.name) && !isFontFile(entry.name) && !EHPK_FILE.test(entry.name)) return [];
if (TEXT_FILE.test(entry.name)) {
return [
{
@@ -192,7 +192,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
];
}
if (EHPK_FILE.test(entry.name)) {
return [
const actions: FileInfoAction[] = [
{
label: "Run app",
onSelect: (ctx) => {
@@ -210,6 +210,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
},
},
];
return global.isIOS ? actions.slice(0, 1) : actions;
}
if (isDecodableImageFile(entry.name)) {
return [
+1
View File
@@ -64,6 +64,7 @@ const filesApp: AppDefinition = {
openEhpkApp: (path) => {
void openEvenHubPackage(ctx, path).catch((error) => {
ctx.appendLog(`evenhub launch failed: ${error}`);
openTextDocumentWindow(ctx, 'Could not run app', String(error));
});
},
installEhpkApp: async (path) => {
+1 -1
View File
@@ -8,7 +8,7 @@ const unavailable: Record<string, string> = {
navigate: 'Navigation location tracking is not available on iOS yet.',
weather: 'Weather location access is not available on iOS yet.',
calendar: 'Calendar access is not available on iOS yet.',
evenhub: 'The EvenHub store and app runtime are not available on iOS yet.',
evenhub: 'Open a local .ehpk file in Files to run an EvenHub app. The EvenHub store is not available on iOS yet.',
}
export function iosAppUnavailableReason(appId: string): string | null {
return unavailable[appId] ?? null
+3 -5
View File
@@ -22,12 +22,10 @@
import { File, knownFolders } from "@nativescript/core";
import { getTextWidth } from "@evenrealities/pretext";
import { EVENHUB_RUNTIME_FONT_FILENAME, isEvenHubFontAsset } from "../g2/firmware-fonts";
import { toUint8Array } from "../util/array-util";
import { lvglMetrics, lvglGlyph } from "../native/lvgl-font";
import { GrayImage, grayToNibble, type FwTextFont, type PlacedFwText, type PlacedFwTextGlyph } from "./image";
import { TtfFont } from "./ttf-font";
declare const com: any;
const CJK_ASSET_PATH = "fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin";
/**
@@ -124,7 +122,7 @@ export class EvenHubFont implements FwTextFont {
this.glyphs.set(Number(key), asset.glyphs[key]!);
}
this.cjkPath = knownFolders.currentApp().getFile(CJK_ASSET_PATH).path;
const metrics = toUint8Array(com.faceclaw.app.LvglFontFile.getMetrics(this.cjkPath));
const metrics = lvglMetrics(this.cjkPath);
if (metrics.length < 2) {
throw new Error("The bundled Source Han Sans font could not be loaded.");
}
@@ -388,7 +386,7 @@ export class EvenHubFont implements FwTextFont {
private getCjkGlyph(codePoint: number): CjkGlyph | null {
const cached = this.cjkGlyphs.get(codePoint);
if (cached !== undefined) return cached;
const bytes = toUint8Array(com.faceclaw.app.LvglFontFile.getGlyph(this.cjkPath, codePoint));
const bytes = lvglGlyph(this.cjkPath, codePoint);
if (bytes.length < 8) {
this.cjkGlyphs.set(codePoint, null);
return null;
+53
View File
@@ -0,0 +1,53 @@
/** Reader for the bundled Source Han Sans serialized LVGL font. Matches
* Android LvglFontFile's metrics/glyph byte format, without a Java dependency. */
export class LvglFont {
readonly metrics: Uint8Array
private readonly view: DataView
private readonly ids = new Map<number, number>()
private readonly bitmaps: number
private readonly descriptors: number
constructor(private readonly bytes: Uint8Array) {
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (bytes.length < 64 || bytes.slice(0, 4).some(v => v !== 90)) throw new Error('Missing LVGL font header')
const height = this.u16(0x38), baseline = height - this.u16(0x3a)
const descriptor = this.pointer(this.u32(0x34))
this.bitmaps = this.pointer(this.u32(descriptor)); this.descriptors = this.pointer(this.u32(descriptor + 4))
const cmaps = this.pointer(this.u32(descriptor + 8)), packed = this.u16(descriptor + 18), count = packed & 0x1ff
if (!height || baseline < 0 || !count || ((packed >>> 9) & 15) !== 4 || (packed >>> 14) !== 3) throw new Error('Unsupported LVGL font')
this.metrics = new Uint8Array([height, baseline])
for (let i = 0; i < count; i++) {
const at = cmaps + i * 20, start = this.u32(at), length = this.u16(at + 4), first = this.u16(at + 6)
const unicodePtr = this.u32(at + 8), offsetsPtr = this.u32(at + 12), listLength = this.u16(at + 16), type = this.u8(at + 18)
if (type === 2 || type === 0) {
const offsets = type === 0 ? this.pointer(offsetsPtr) : 0
for (let n = 0; n < length; n++) {
const offset = type === 0 ? this.u8(offsets + n) : n
if (n && !offset) continue
this.ids.set(start + n, first + offset)
}
} else if (type === 1 || type === 3) {
const unicode = this.pointer(unicodePtr), offsets = offsetsPtr ? this.pointer(offsetsPtr) : -1
for (let n = 0; n < listLength; n++) {
const offset = offsets < 0 ? n : type === 1 ? this.u16(offsets + n * 2) : this.u8(offsets + n)
if (n && !offset) continue
this.ids.set(start + this.u16(unicode + n * 2), first + offset)
}
} else throw new Error('Unsupported LVGL cmap')
}
}
glyph(codePoint: number): Uint8Array {
const id = this.ids.get(codePoint)
if (!id) return new Uint8Array()
const at = this.descriptors + id * 16, bitmap = this.bitmaps + this.u32(at)
const width = this.u16(at + 8), height = this.u16(at + 10), length = width && height ? (Math.floor(width / 2) + 1) * height : 0
this.check(bitmap, length)
const result = new Uint8Array(8 + length)
result.set(this.bytes.subarray(at + 8, at + 16)); result.set(this.bytes.subarray(bitmap, bitmap + length), 8)
return result
}
private check(at: number, size: number): void { if (at < 0 || at + size > this.bytes.length) throw new Error('Truncated LVGL font') }
private pointer(address: number): number { const at = address - 0x80100000; this.check(at, 1); return at }
private u8(at: number): number { this.check(at, 1); return this.bytes[at] }
private u16(at: number): number { return this.view.getUint16(at, true) }
private u32(at: number): number { return this.view.getUint32(at, true) }
}
+16
View File
@@ -0,0 +1,16 @@
import { LvglFont } from '../graphics/lvgl-font'
import { readBinaryFile } from './file-access'
const cache = new Map<string, LvglFont>()
function load(path: string): LvglFont {
let font = cache.get(path)
if (!font) {
const bytes = readBinaryFile(path)
if (!bytes) throw new Error('Cannot read LVGL font')
font = new LvglFont(bytes)
if (cache.size >= 2) cache.delete(cache.keys().next().value!)
cache.set(path, font)
}
return font
}
export function lvglMetrics(path: string): Uint8Array { return load(path).metrics }
export function lvglGlyph(path: string, codePoint: number): Uint8Array { return load(path).glyph(codePoint) }
+4
View File
@@ -0,0 +1,4 @@
import { toUint8Array } from '../util/array-util'
declare const com: any
export function lvglMetrics(path: string): Uint8Array { return toUint8Array(com.faceclaw.app.LvglFontFile.getMetrics(path)) }
export function lvglGlyph(path: string, codePoint: number): Uint8Array { return toUint8Array(com.faceclaw.app.LvglFontFile.getGlyph(path, codePoint)) }