Port navigate and weather

This commit is contained in:
James Babcock committed 2026-09-18 23:46:27 -07:00
1 parent 2b3e068a23
commit 9e18745e53
33 files changed
+630 -60

No files matched your search

-2
View File
@@ -4,8 +4,6 @@ const unavailable: Record<string, string> = {
notifications: 'Phone notification integration is not available on iOS yet.',
transcribe: 'Voice capture and transcription are not available on iOS yet.',
microphones: 'Glasses microphone capture is not available on iOS yet.',
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: 'Open a local .ehpk file in Files to run an EvenHub app. The EvenHub store is not available on iOS yet.',
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { ensureFineLocationPermission } from "../../g2/android-permissions";
import { ensureFineLocationPermission } from "../../native/location-permissions";
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
const navigateApp: AppDefinition = {
+23 -20
View File
@@ -64,7 +64,7 @@ import {
GESTURE_SHORT_THEN_LONG_PRESS,
type InputEvent,
} from "../../ui/gestures";
import { LocationTracker, type TrackedLocation } from "../../native/location-tracker";
import { LocationTracker, type TrackedLocation } from "./navigation-sensors";
import {
fetchRoute,
fetchStaticMapGray,
@@ -76,8 +76,8 @@ import {
type RouteProfile,
type StaticMapCamera,
} from "../../native/mapbox";
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "../../native/compass";
import { magneticDeclinationDegrees } from "../../native/geomagnetic";
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "./navigation-sensors";
import { magneticDeclinationDegrees, handleNavigationSensorEvent } from "./navigation-sensors";
import { calibrateHeading, normalizeHeading } from "../compass/calibration";
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower";
import { drawManeuverGlyph } from "./maneuver-icons";
@@ -184,6 +184,8 @@ let lastRerouteAtMs = 0;
let rerouteInFlight = false;
/** Bumped on every new route/mode so stale map fetches can be discarded. */
let routeGeneration = 0;
/** Invalidates GPS/geocoding/routing work when the route is replaced or closed. */
let navigationGeneration = 0;
/**
* Where to go: free text to geocode (optionally shown under a saved
@@ -239,7 +241,6 @@ let compassActive = false;
let unsubscribeCompass: (() => void) | null = null;
/** Wearer's true heading (degrees clockwise from north) as last drawn, or null before compass data arrives. */
let headHeadingDeg: number | null = null;
let declinationCache: { latitude: number; longitude: number; degrees: number | null } | null = null;
let tickTimer: ReturnType<typeof setInterval> | null = null;
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
@@ -274,6 +275,9 @@ post({ type: "worker-ready" });
global.onmessage = (event: { data: WorkerAppMessage }) => {
const message = event.data;
switch (message.type) {
case "navigation-sensors":
handleNavigationSensorEvent(message.event);
break;
case "open-window":
window = {
windowId: message.windowId,
@@ -390,6 +394,8 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
render();
throw new Error(statusMessage);
}
const generation = ++navigationGeneration;
const checkCurrent = () => { if (generation !== navigationGeneration) throw new Error("Navigation cancelled."); };
const hadActiveRoute = phase === "navigating" && follower !== null;
const previous = {
destination,
@@ -404,6 +410,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
render();
ensureTracking();
const fix = await waitForFix();
checkCurrent();
phase = "routing";
let picked: GeocodeCandidate;
@@ -420,6 +427,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
statusMessage = `Finding ${query}...`;
render();
candidates = await geocodeForward(query, fix, 5);
checkCurrent();
if (!candidates.length) {
throw new Error(`No places found matching "${query}".`);
}
@@ -432,6 +440,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
statusMessage = `Routing to ${destinationName}...`;
render();
const route = await fetchRoute(fix, destination, profile);
checkCurrent();
adoptRoute(route);
// Saved destinations already have a row of their own on the idle page;
// everything else (voice, assistant, a re-picked recent) goes on the
@@ -447,6 +456,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
if (window) post({ type: "focus-window", windowId: window.windowId });
return startSummary(picked, candidates, route);
} catch (error) {
if (generation !== navigationGeneration) throw error;
const message = String((error as Error)?.message ?? error);
statusMessage = message;
// A failed new destination shouldn't kill guidance that was already
@@ -484,6 +494,7 @@ function adoptRoute(route: Route): void {
}
function stopNavigation(finalStatus: string): void {
++navigationGeneration;
phase = "idle";
statusMessage = finalStatus;
follower = null;
@@ -533,14 +544,16 @@ function handleFix(fix: TrackedLocation): void {
async function maybeReroute(fix: TrackedLocation): Promise<void> {
if (rerouteInFlight || !destination) return;
if (Date.now() - lastRerouteAtMs < REROUTE_MIN_INTERVAL_MS) return;
const generation = navigationGeneration;
rerouteInFlight = true;
lastRerouteAtMs = Date.now();
statusMessage = "Rerouting...";
render();
try {
const route = await fetchRoute(fix, destination, profile);
if (phase === "navigating") adoptRoute(route);
if (generation === navigationGeneration && phase === "navigating") adoptRoute(route);
} catch (error) {
if (generation !== navigationGeneration) return;
statusMessage = `Reroute failed: ${String((error as Error)?.message ?? error)}`;
render();
} finally {
@@ -601,7 +614,9 @@ function handleCompassEvent(event: CompassEvent): void {
// Wearer-fit offset from the Compass app's calibration, then declination
// from our own GPS fix: the map is always true-north referenced.
const magnetic = calibrateHeading(event.headingDegrees);
const heading = normalizeHeading(magnetic + (currentDeclination() ?? 0));
const correction = currentDeclination();
if (correction === null) return; // Keep the travel-direction arrow until true north is known.
const heading = normalizeHeading(magnetic + correction);
if (headHeadingDeg !== null && angularDistance(heading, headHeadingDeg) < HEADING_STEP_DEG) return;
headHeadingDeg = heading;
render();
@@ -609,19 +624,7 @@ function handleCompassEvent(event: CompassEvent): void {
/** Declination at the last fix; it only varies over tens of kilometres, so cache per coarse position. */
function currentDeclination(): number | null {
if (!lastFix) return null;
if (
!declinationCache ||
Math.abs(declinationCache.latitude - lastFix.latitude) > 0.5 ||
Math.abs(declinationCache.longitude - lastFix.longitude) > 0.5
) {
declinationCache = {
latitude: lastFix.latitude,
longitude: lastFix.longitude,
degrees: magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude),
};
}
return declinationCache.degrees;
return lastFix ? magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude) : null;
}
function angularDistance(a: number, b: number): number {
@@ -1123,7 +1126,7 @@ function tokenSetupEntries(): IdleEntry[] {
detail: "Get a free token in the phone browser",
run: () => {
statusMessage = openUrlOnPhone(MAPBOX_TOKENS_URL)
? "Opened mapbox.com on your phone. Copy your public token (pk...) and pick Edit token."
? "Opening mapbox.com on your phone. Copy your public token (pk...) and pick Edit token."
: "Could not open a browser on the phone. Visit account.mapbox.com/access-tokens to get a token.";
},
},
@@ -0,0 +1,11 @@
import { type TrackedLocation } from '../../native/location-types'
import { type CompassEvent } from '../../native/compass-types'
export type NavigationSensorRequest =
| { action: 'start'; id: number; intervalMs: number }
| { action: 'stop'; id: number }
| { action: 'compass'; enabled: boolean }
export type NavigationSensorEvent =
| { kind: 'location'; id: number; location: TrackedLocation }
| { kind: 'error'; id: number; message: string }
| { kind: 'compass'; event: CompassEvent; declination: number | null }
@@ -0,0 +1,45 @@
import { type LocationTrackerCallbacks } from '../../native/location-types'
import { type CompassEvent } from '../../native/compass-types'
import { type NavigationSensorEvent, type NavigationSensorRequest } from './navigation-sensors-messages'
export { type TrackedLocation } from '../../native/location-types'
export { COMPASS_CHANGED, type CompassEvent } from '../../native/compass-types'
declare const global: any
const listeners = new Set<(event: CompassEvent) => void>()
const trackers = new Map<number, LocationTracker>()
let nextId = 0
let declination: number | null = null
function send(request: NavigationSensorRequest): void {
global.postMessage({ type: 'navigation-sensors', request })
}
export class LocationTracker {
private id = 0
constructor(private readonly callbacks: LocationTrackerCallbacks) {}
isRunning(): boolean { return this.id !== 0 }
start(intervalMs = 1000): void {
if (this.id) return
this.id = ++nextId; trackers.set(this.id, this)
send({ action: 'start', id: this.id, intervalMs })
}
stop(): void {
if (!this.id) return
const id = this.id; this.id = 0; trackers.delete(id)
send({ action: 'stop', id })
}
receive(event: NavigationSensorEvent): void {
if (event.kind === 'location') this.callbacks.onLocation(event.location)
else if (event.kind === 'error') { this.stop(); this.callbacks.onError(event.message) }
}
}
export function handleNavigationSensorEvent(event: NavigationSensorEvent): void {
if (event.kind === 'compass') {
declination = event.declination
for (const listener of [...listeners]) listener(event.event)
} else trackers.get(event.id)?.receive(event)
}
export function addCompassListener(listener: (event: CompassEvent) => void): () => void {
listeners.add(listener)
return () => { listeners.delete(listener) }
}
export function setCompassEnabled(enabled: boolean, _owner?: string): void { send({ action: 'compass', enabled }) }
export function magneticDeclinationDegrees(_latitude: number, _longitude: number): number | null { return declination }
+13
View File
@@ -0,0 +1,13 @@
import { type NavigationSensorEvent } from './navigation-sensors-messages'
export { LocationTracker, type TrackedLocation } from '../../native/location-tracker'
export { addCompassListener, setCompassEnabled, COMPASS_CHANGED, type CompassEvent } from '../../native/compass'
import { magneticDeclinationDegrees as calculate } from '../../native/geomagnetic'
let cached: { latitude: number; longitude: number; degrees: number | null } | null = null
export function magneticDeclinationDegrees(latitude: number, longitude: number): number | null {
if (!cached || Math.abs(latitude - cached.latitude) > 0.5 || Math.abs(longitude - cached.longitude) > 0.5)
cached = { latitude, longitude, degrees: calculate(latitude, longitude) }
return cached.degrees
}
/** Android delivers native callbacks directly on the worker's Looper. */
export function handleNavigationSensorEvent(_event: NavigationSensorEvent): void {}
+7 -3
View File
@@ -1,4 +1,4 @@
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
import { ensureLocationPermission, hasLocationPermission } from "../../native/location-permissions";
import { weatherBridge } from "../../native/weather";
import { WeatherLayer } from "./weather";
import {
@@ -13,12 +13,13 @@ export const WEATHER_SURFACE_ID = "window:weather";
/** Local current conditions and forecast from the National Weather Service. */
export function createWeatherAppWindow(options: InProcessAppOptions): InProcessWindow {
let closed = false;
let requestingPermission = false;
let unsubscribe: (() => void) | null = null;
let app: InProcessWindow;
const requestUpdate = () => {
if (requestingPermission) return;
if (closed || requestingPermission) return;
if (hasLocationPermission()) {
weatherBridge.start();
return;
@@ -26,9 +27,10 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
requestingPermission = true;
void ensureLocationPermission().then((granted) => {
requestingPermission = false;
if (closed) return;
if (granted) weatherBridge.start();
app.requestRender();
});
}).catch((error) => { requestingPermission = false; console.warn(`Weather permission: ${error}`); });
};
app = createInProcessWindow({
@@ -52,7 +54,9 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
reconfigureSurface: options.reconfigureSurface,
onClosed: () => {
closed = true;
unsubscribe?.();
unsubscribe = null;
weatherBridge.stop();
+7 -1
View File
@@ -1,3 +1,5 @@
import { IosNavigationSensors } from '../native/ios-navigation-sensors'
import { Utils } from '@nativescript/core'
import { bindCompassSession, receiveCompassEvent } from '../native/compass.ios'
import { Dialogs, File, knownFolders, path, type ImageSource } from '@nativescript/core'
import { iosBluetooth } from '../native/ios-bluetooth'
@@ -331,8 +333,12 @@ export class IosPreviewController {
private ensureWorkerHost(appId: string, create: () => Worker): WorkerAppHost {
const existing = this.appHosts.get(appId)
if (existing) return existing
const worker = create()
const navigationSensors = appId === 'navigate'
? new IosNavigationSensors(event => worker.postMessage({ type: 'navigation-sensors', event })) : undefined
const host = new WorkerAppHost({
appId, worker: create(),
appId, worker, navigationSensors,
openUrl: url => { void Utils.openUrl(url) },
configureSurface: async (id, visible, heightMode) => {
this.compositor.configureSurface(id, { ...appViewportRect(heightMode, appId), zOrder: 0, transparency: 'opaque' })
this.compositor.setSurfaceVisible(id, visible)
+12
View File
@@ -0,0 +1,12 @@
import { GrayImage } from '../graphics/image'
import { toData, fromData } from './kotlin-data'
declare const FaceclawGraphics: any
/** Native image decoding and grayscale conversion, safe on a rendering worker. */
export function decodeImageBytes(bytes: ArrayBuffer, width: number, height: number): GrayImage | null {
const data = FaceclawGraphics.decodeImageWidthHeight(toData(new Uint8Array(bytes)), width, height)
if (!data) return null
const image = new GrayImage(width, height, 0)
image.pixels.set(fromData(data))
return image
}
+7
View File
@@ -0,0 +1,7 @@
import { grayImageFromPacket } from './image-files'
import { type GrayImage } from '../graphics/image'
declare const com: any
export function decodeImageBytes(bytes: ArrayBuffer, width: number, height: number): GrayImage | null {
return grayImageFromPacket(com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(bytes, width, height))
}
+56
View File
@@ -0,0 +1,56 @@
import { LocationTracker } from './location-tracker.ios'
import { ensureFineLocationPermission } from './location-permissions.ios'
import { addCompassListener, setCompassEnabled } from './compass.ios'
import { getDeclinationDegrees, refreshDeclination } from '../apps/compass/declination'
import { type NavigationSensorEvent, type NavigationSensorRequest } from '../apps/navigate/navigation-sensors-messages'
/** Core Location stays on main; the shared Navigate worker receives only JSON. */
export class IosNavigationSensors {
private generation = 0
private id = 0
private tracker: LocationTracker | null = null
private offCompass: (() => void) | null = null
private readonly owner = 'worker:navigate'
constructor(private readonly reply: (event: NavigationSensorEvent) => void) {}
handle(request: NavigationSensorRequest): void {
if (request.action === 'compass') {
if (request.enabled && !this.offCompass) {
refreshDeclination()
this.offCompass = addCompassListener(event => this.reply({ kind: 'compass', event, declination: getDeclinationDegrees() }))
} else if (!request.enabled) { this.offCompass?.(); this.offCompass = null }
setCompassEnabled(request.enabled, this.owner)
} else if (request.action === 'stop') {
if (request.id === this.id) this.stopLocation()
} else {
this.stopLocation(); this.id = request.id
const generation = this.generation
void ensureFineLocationPermission().then(granted => {
if (generation !== this.generation) return
if (!granted) throw new Error('Precise location is required for navigation. Enable it in the phone’s Settings, then retry.')
refreshDeclination()
this.tracker = new LocationTracker({
onLocation: location => {
if (generation === this.generation) this.reply({ kind: 'location', id: request.id, location })
},
onError: message => {
if (generation !== this.generation) return
this.stopLocation(); this.reply({ kind: 'error', id: request.id, message })
},
})
this.tracker.start(request.intervalMs)
}).catch(error => {
if (generation !== this.generation) return
this.stopLocation(); this.reply({ kind: 'error', id: request.id, message: String(error.message ?? error) })
})
}
}
private stopLocation(): void {
++this.generation; this.id = 0
this.tracker?.stop(); this.tracker = null
}
stop(): void {
this.stopLocation()
this.offCompass?.(); this.offCompass = null
setCompassEnabled(false, this.owner)
}
}
+5
View File
@@ -1,3 +1,4 @@
import { decodeImageBytes } from './image-bytes.ios'
import * as protocol from '../g2/ble-protocol.ios'
import { CfwTransport, parseCfwAcks } from '../g2/cfw-transport.ios'
import { SurfaceCompositor } from '../graphics/surface-compositor.ios'
@@ -36,5 +37,9 @@ export function runKotlinProtocolSmokeTest(): void {
payload: new Uint8Array([8, 15, 16, 0, 82, 3, 8, 231, 2, 162, 6, 12, 67, 77, 1, 3, 2, 3, 140, 0, 152, 186, 220, 254]) })
if (compass?.headingDegrees !== 359 || compass.diagnostics?.sampleTimeMs !== 0xfedcba98)
throw new Error('Kotlin compass notification mismatch')
const png = NSData.alloc().initWithBase64EncodedStringOptions('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEklEQVR4nGP4z8DAAMIM/4EAAB/uBfsL2WiLAAAAAElFTkSuQmCC', 0 as NSDataBase64DecodingOptions)
const decoded = decodeImageBytes(interop.bufferFromData(png), 2, 2)
assert(!!decoded && Array.from(decoded.pixels).join(',') === '54,182,18,255', 'native map image orientation and grayscale')
assert(decodeImageBytes(new ArrayBuffer(0), 2, 2) === null, 'invalid map image')
console.log('FACECLAW_KOTLIN_PROTOCOL_PASS iOS')
}
+4
View File
@@ -3,3 +3,7 @@ export const hasLocationPermission = (): boolean => FaceclawLocation.shared().ha
export function ensureLocationPermission(): Promise<boolean> {
return new Promise(resolve => FaceclawLocation.shared().requestPermission(resolve))
}
export function ensureFineLocationPermission(): Promise<boolean> {
return new Promise(resolve => FaceclawLocation.shared().requestPrecisePermission(resolve))
}
+1 -1
View File
@@ -1 +1 @@
export { ensureLocationPermission, hasLocationPermission } from '../g2/android-permissions'
export { ensureLocationPermission, ensureFineLocationPermission, hasLocationPermission } from '../g2/android-permissions'
+25
View File
@@ -0,0 +1,25 @@
import { type LocationTrackerCallbacks } from './location-types'
export { type TrackedLocation, type LocationTrackerCallbacks } from './location-types'
declare const FaceclawLocationUpdates: any
/** Owned by the main-thread iOS sensor host; JSON fixes are relayed to app workers. */
export class LocationTracker {
private native: any = null
constructor(private readonly callbacks: LocationTrackerCallbacks) {}
isRunning(): boolean { return this.native !== null }
start(intervalMs = 1000): void {
if (this.native) return
const native = this.native = FaceclawLocationUpdates.new()
native.eventHandler = (json: string) => {
if (this.native !== native) return
const event = JSON.parse(json)
if (event.error) { this.stop(); this.callbacks.onError(event.error) }
else this.callbacks.onLocation(event)
}
native.startTracking(intervalMs)
}
stop(): void {
const native = this.native; this.native = null
native?.stop()
}
}
+2 -16
View File
@@ -9,22 +9,8 @@ import { Utils } from "@nativescript/core";
declare const com: any;
declare const global: any;
export type TrackedLocation = {
latitude: number;
longitude: number;
/** Meters, or null when the fix doesn't report accuracy. */
accuracyMeters: number | null;
/** Degrees clockwise from true north, or null (common when stationary). */
bearingDeg: number | null;
/** Meters per second, or null. */
speedMps: number | null;
timestampMs: number;
};
export type LocationTrackerCallbacks = {
onLocation: (location: TrackedLocation) => void;
onError: (message: string) => void;
};
import { type LocationTrackerCallbacks } from "./location-types";
export { type LocationTrackerCallbacks, type TrackedLocation } from "./location-types";
export class LocationTracker {
private tracker: any = null;
+23
View File
@@ -0,0 +1,23 @@
export type CurrentLocation = {
latitude: number;
longitude: number;
accuracyMeters: number | null;
timestampMs: number;
};
export type TrackedLocation = {
latitude: number;
longitude: number;
/** Meters, or null when the fix doesn't report accuracy. */
accuracyMeters: number | null;
/** Degrees clockwise from true north, or null (common when stationary). */
bearingDeg: number | null;
/** Meters per second, or null. */
speedMps: number | null;
timestampMs: number;
};
export type LocationTrackerCallbacks = {
onLocation: (location: TrackedLocation) => void;
onError: (message: string) => void;
};
+19
View File
@@ -0,0 +1,19 @@
import { type CurrentLocation } from './location-types'
export { type CurrentLocation } from './location-types'
declare const FaceclawLocationUpdates: any
/** Main-thread one-shot lookup, independent of navigation and compass managers. */
export function getCurrentLocation(): Promise<CurrentLocation> {
return new Promise((resolve, reject) => {
const provider = FaceclawLocationUpdates.new()
provider.eventHandler = (json: string) => {
try {
const event = JSON.parse(json)
if (event.error) reject(new Error(event.error))
else resolve(event)
} catch (error) { reject(error) }
finally { provider.stop() }
}
provider.startOnce()
})
}
+2 -6
View File
@@ -2,12 +2,8 @@ import { Utils } from "@nativescript/core";
declare const com: any;
export type CurrentLocation = {
latitude: number;
longitude: number;
accuracyMeters: number | null;
timestampMs: number;
};
import { type CurrentLocation } from "./location-types";
export { type CurrentLocation } from "./location-types";
/** Resolve one current foreground location using Android's LocationManager. */
export function getCurrentLocation(): Promise<CurrentLocation> {
+2 -7
View File
@@ -6,11 +6,9 @@
*/
import { GrayImage } from "../graphics/image";
import { getStringSetting } from "./settings-store";
import { grayImageFromPacket } from "./image-files";
import { decodeImageBytes } from "./image-bytes";
import { fetchWithUserAgent } from "../util/http";
declare const com: any;
declare const global: any;
export const MAPBOX_TOKEN_SETTING_KEY = "maps.mapboxApiKey";
const SEARCH_ROOT = "https://api.mapbox.com/search/searchbox/v1";
@@ -231,10 +229,7 @@ export async function fetchStaticMapGray(options: {
}
throw new Error(`Mapbox static map failed (HTTP ${response.status}).`);
}
if (!global.isAndroid) throw new Error("Map decoding is only available on Android.");
const image = grayImageFromPacket(
com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(bytes, Math.round(options.width), Math.round(options.height)),
);
const image = decodeImageBytes(bytes, Math.round(options.width), Math.round(options.height));
if (!image) throw new Error("Failed to decode the Mapbox map image.");
return image;
}
+9
View File
@@ -0,0 +1,9 @@
import { Utils } from '@nativescript/core'
declare const global: any
export function openUrlOnPhone(url: string): boolean {
if (!/^https?:\/\//i.test(url)) return false
if (NSThread.isMainThread) void Utils.openUrl(url)
else global.postMessage({ type: 'open-url', url })
return true
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { hasLocationPermission } from "../g2/android-permissions";
import { hasLocationPermission } from "./location-permissions";
import { getCurrentLocation, type CurrentLocation } from "./location";
import { fetchWithUserAgent } from "../util/http";
import { USER_AGENT } from "../version";
+14
View File
@@ -1,3 +1,4 @@
import { type NavigationSensorRequest, type NavigationSensorEvent } from "../../apps/navigate/navigation-sensors-messages";
import { GrayImage } from "../../graphics/image";
import { windowIcon } from "./chrome-layer";
import { type IconActivity, type IconName } from "../../graphics/icons";
@@ -14,6 +15,7 @@ import { publishWorkerState } from "./worker-state";
* worker→Java directly on Android; iOS posts baked frames to the main host.
*/
export type WorkerAppMessage =
| { type: "navigation-sensors"; event: NavigationSensorEvent }
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
| { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
| { type: "close-window"; windowId: string }
@@ -32,6 +34,8 @@ export type WorkerAppMessage =
| { type: "tool-call"; callId: string; windowId: string; name: string; args: unknown };
export type WorkerAppReply =
| { type: "navigation-sensors"; request: NavigationSensorRequest }
| { type: "open-url"; url: string }
| { type: "surface-frame"; surfaceId: string; width: number; height: number; pixels: string }
| {
/**
@@ -177,6 +181,8 @@ export type WorkerWindowSpec = {
export type WorkerAppHostOptions = {
appId: string;
worker: Worker;
navigationSensors?: { handle(request: NavigationSensorRequest): void; stop(): void };
openUrl?: (url: string) => void;
/** Create/refresh a window surface on the compositor (no-op when disconnected). */
configureSurface: (surfaceId: string, visible: boolean, heightMode: WindowHeightMode) => Promise<void>;
setSurfaceVisible: (surfaceId: string, visible: boolean) => void;
@@ -234,6 +240,12 @@ export class WorkerAppHost {
const message = event.data as WorkerAppReply | undefined;
if (!message) return;
switch (message.type) {
case "navigation-sensors":
if (this.openWindows.size) this.options.navigationSensors?.handle(message.request);
break;
case "open-url":
if (this.openWindows.size && /^https?:\/\//i.test(message.url)) this.options.openUrl?.(message.url);
break;
case "surface-frame": {
if (!global.isIOS || !this.options.submitPixels || !this.openWindows.has(message.surfaceId.replace(/^window:/, ""))) break;
const { width, height } = message;
@@ -361,6 +373,7 @@ export class WorkerAppHost {
}
};
options.worker.onerror = (error) => {
options.navigationSensors?.stop();
console.error(`worker app ${options.appId} error: ${JSON.stringify(error)}`);
};
}
@@ -397,6 +410,7 @@ export class WorkerAppHost {
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
close: () => {
this.openWindows.delete(spec.windowId);
if (!this.openWindows.size) this.options.navigationSensors?.stop();
this.windowGestures.delete(spec.windowId);
this.windowIconActivity.delete(spec.windowId);
// Withdraw this window's tools and fail any in-flight calls to it.