forked from Blendman974/faceclaw
Add a Navigate app (requires a Mapbox API token)
This commit is contained in:
1 parent
3c2f53ed75
commit
bde70ac380
16 files changed
+2096
-4
No files matched your search
@@ -18,8 +18,9 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
|
||||
<!-- Approximate foreground location is sufficient for the Weather app. -->
|
||||
<!-- Precise location for turn-by-turn navigation (Navigate app); pre-31
|
||||
it also covers BLE scanning. Weather only needs coarse. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/>
|
||||
@@ -31,6 +32,7 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<!-- Needed to resolve other apps' notification small icons (Icon TYPE_RESOURCE):
|
||||
package visibility filtering otherwise makes Icon.loadDrawable fail with
|
||||
@@ -79,7 +81,7 @@
|
||||
android:name="com.faceclaw.app.FaceclawForegroundService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="connectedDevice|microphone" />
|
||||
android:foregroundServiceType="connectedDevice|microphone|location" />
|
||||
<service
|
||||
android:name="com.faceclaw.app.FaceclawMediaNotificationListenerService"
|
||||
android:enabled="true"
|
||||
|
||||
@@ -111,6 +111,13 @@ public class FaceclawForegroundService extends Service {
|
||||
if (hasRecordAudioPermission()) {
|
||||
type |= ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
|
||||
}
|
||||
// The location type keeps while-in-use location flowing to the
|
||||
// Navigate app when the phone screen locks. Only claimed once the
|
||||
// permission exists: on API 34+ claiming it without the permission
|
||||
// makes startForeground throw.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && hasFineLocationPermission()) {
|
||||
type |= ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@@ -118,4 +125,9 @@ public class FaceclawForegroundService extends Service {
|
||||
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private boolean hasFineLocationPermission() {
|
||||
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
/**
|
||||
* Continuous location updates for turn-by-turn navigation. Unlike
|
||||
* FaceclawLocationProvider (one-shot, coarse, for Weather), this streams GPS
|
||||
* fixes with bearing and speed until stopped.
|
||||
*
|
||||
* Callbacks are delivered on the Looper of the thread that constructed the
|
||||
* tracker, so a worker isolate receives them on its own thread (the same
|
||||
* convention as FaceclawSseRequest).
|
||||
*/
|
||||
public final class FaceclawLocationTracker implements LocationListener {
|
||||
private final Context context;
|
||||
private final LocationManager locationManager;
|
||||
private final Handler callbackHandler;
|
||||
|
||||
private FaceclawLocationTrackerListener listener;
|
||||
private boolean running;
|
||||
|
||||
public FaceclawLocationTracker(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
|
||||
Looper looper = Looper.myLooper();
|
||||
this.callbackHandler = new Handler(looper != null ? looper : Looper.getMainLooper());
|
||||
}
|
||||
|
||||
public void setListener(FaceclawLocationTrackerListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
/** Begin streaming fixes at roughly the requested interval. */
|
||||
public void start(long intervalMs) {
|
||||
callbackHandler.post(() -> startOnCallbackThread(intervalMs));
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
callbackHandler.post(() -> {
|
||||
if (!running) {
|
||||
return;
|
||||
}
|
||||
running = false;
|
||||
try {
|
||||
locationManager.removeUpdates(this);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void startOnCallbackThread(long intervalMs) {
|
||||
if (running) {
|
||||
return;
|
||||
}
|
||||
if (locationManager == null) {
|
||||
deliverError("Android location service is unavailable.");
|
||||
return;
|
||||
}
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
deliverError("Precise location permission is required for navigation.");
|
||||
return;
|
||||
}
|
||||
|
||||
String provider = chooseProvider();
|
||||
if (provider == null) {
|
||||
deliverError("Turn on Location on your phone, then retry.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
running = true;
|
||||
locationManager.requestLocationUpdates(provider, Math.max(500L, intervalMs), 0f, this,
|
||||
callbackHandler.getLooper());
|
||||
// Seed with the freshest cached fix so the UI has a position
|
||||
// before the first live fix (GPS cold starts can take a while).
|
||||
Location cached = locationManager.getLastKnownLocation(provider);
|
||||
if (cached == null) {
|
||||
cached = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
}
|
||||
if (cached != null) {
|
||||
deliverLocation(cached);
|
||||
}
|
||||
} catch (SecurityException error) {
|
||||
running = false;
|
||||
deliverError("Precise location permission is required for navigation.");
|
||||
} catch (Throwable error) {
|
||||
running = false;
|
||||
deliverError("Unable to start location updates.");
|
||||
}
|
||||
}
|
||||
|
||||
private String chooseProvider() {
|
||||
try {
|
||||
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
return LocationManager.GPS_PROVIDER;
|
||||
}
|
||||
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
|
||||
return LocationManager.NETWORK_PROVIDER;
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLocationChanged(Location location) {
|
||||
deliverLocation(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderDisabled(String provider) {
|
||||
deliverError("Location was turned off on the phone.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderEnabled(String provider) {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) {
|
||||
}
|
||||
|
||||
private void deliverLocation(Location location) {
|
||||
FaceclawLocationTrackerListener current = listener;
|
||||
if (current == null || location == null) {
|
||||
return;
|
||||
}
|
||||
current.onLocation(
|
||||
location.getLatitude(),
|
||||
location.getLongitude(),
|
||||
location.hasAccuracy() ? location.getAccuracy() : -1f,
|
||||
location.hasBearing() ? location.getBearing() : -1f,
|
||||
location.hasSpeed() ? location.getSpeed() : -1f,
|
||||
location.getTime());
|
||||
}
|
||||
|
||||
private void deliverError(String message) {
|
||||
FaceclawLocationTrackerListener current = listener;
|
||||
if (current != null) {
|
||||
current.onError(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
/** Continuous location callbacks for the TypeScript navigation bridge. */
|
||||
public interface FaceclawLocationTrackerListener {
|
||||
/**
|
||||
* A new fix. bearingDeg/speedMps are -1 when the fix doesn't carry them
|
||||
* (common when stationary); accuracyMeters is -1 when unknown.
|
||||
*/
|
||||
void onLocation(double latitude, double longitude, float accuracyMeters,
|
||||
float bearingDeg, float speedMps, long timestampMs);
|
||||
|
||||
void onError(String message);
|
||||
}
|
||||
@@ -50,6 +50,34 @@ public final class ImageFileLoader {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode an in-memory image file (PNG/JPEG/WebP bytes, e.g. a fetched
|
||||
* map tile) and downscale to fit within maxWidth x maxHeight. Takes a
|
||||
* ByteBuffer because NativeScript marshals a JS ArrayBuffer to one.
|
||||
*/
|
||||
public static byte[] loadGrayFromBytes(java.nio.ByteBuffer buffer, int maxWidth, int maxHeight) {
|
||||
if (buffer == null || maxWidth <= 0 || maxHeight <= 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
try {
|
||||
java.nio.ByteBuffer source = buffer.duplicate();
|
||||
source.rewind();
|
||||
byte[] data = new byte[source.remaining()];
|
||||
source.get(data);
|
||||
if (data.length == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
|
||||
if (bitmap == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
return bitmapToGrayPacket(bitmap, maxWidth, maxHeight);
|
||||
} catch (Exception | OutOfMemoryError e) {
|
||||
Log.w(TAG, "byte-array image decode failed", e);
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap to fit within maxWidth x maxHeight (preserving aspect,
|
||||
* never upscaling) and convert it to the grayscale packet format.
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Shell-side nav.* assistant tools. The Navigate app's own tools are
|
||||
* window-scoped ("open" tier), but the core use case is "navigate to X" with
|
||||
* the app closed — so these always-available wrappers launch the app first,
|
||||
* wait for its tools to register, and forward the call.
|
||||
*/
|
||||
import { ensureFineLocationPermission } from "../g2/android-permissions";
|
||||
import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
|
||||
|
||||
const APP_TOOL_PREFIX = "app.navigate.";
|
||||
const TOOL_APPEAR_TIMEOUT_MS = 5_000;
|
||||
const TOOL_APPEAR_POLL_MS = 150;
|
||||
|
||||
let registered = false;
|
||||
|
||||
export function registerNavigateTools(
|
||||
launchApp: (appId: string) => Promise<void>,
|
||||
registry: ToolRegistry = toolRegistry,
|
||||
): void {
|
||||
if (registered) return;
|
||||
registered = true;
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "nav.start_navigation",
|
||||
description:
|
||||
"Start turn-by-turn navigation on the glasses to a destination given as free text (place name, business, or address near the user). Opens the Navigate app. Returns the resolved destination, distance, and ETA; if the wrong place was resolved, call again with a more specific query.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
destination: { type: "string", description: "Where to navigate to." },
|
||||
profile: {
|
||||
type: "string",
|
||||
enum: ["driving", "walking", "cycling"],
|
||||
description: "Travel mode (default driving).",
|
||||
},
|
||||
},
|
||||
required: ["destination"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
// Launch + GPS fix + geocode + route can add up; stay above the app
|
||||
// tool's own 14 s budget.
|
||||
timeoutMs: 25_000,
|
||||
},
|
||||
async (args) => {
|
||||
const destination = String(args?.destination ?? "").trim();
|
||||
if (!destination) return err("nav.start_navigation requires a destination");
|
||||
// Fire the permission prompt early; the phone shows it while we work.
|
||||
void ensureFineLocationPermission().catch(() => {});
|
||||
const forwarded = await callAppTool(launchApp, registry, "start_route", {
|
||||
query: destination,
|
||||
profile: args?.profile,
|
||||
});
|
||||
return forwarded;
|
||||
},
|
||||
);
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "nav.stop_navigation",
|
||||
description: "Stop the current glasses navigation session, if one is active.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
},
|
||||
async () => {
|
||||
if (!registry.listTools().some((tool) => tool.name === `${APP_TOOL_PREFIX}stop_route`)) {
|
||||
return ok("Navigation is not active.");
|
||||
}
|
||||
return registry.callTool(`${APP_TOOL_PREFIX}stop_route`, {});
|
||||
},
|
||||
);
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "nav.route_status",
|
||||
description:
|
||||
"Get the current navigation status: next maneuver, distance remaining, and ETA. Reports inactive when nothing is being navigated.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
proactive: true,
|
||||
},
|
||||
async () => {
|
||||
if (!registry.listTools().some((tool) => tool.name === `${APP_TOOL_PREFIX}route_status`)) {
|
||||
return ok("Navigation is not active.");
|
||||
}
|
||||
return registry.callTool(`${APP_TOOL_PREFIX}route_status`, {});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Launch the Navigate app if needed, wait for its tool, and forward the call. */
|
||||
async function callAppTool(
|
||||
launchApp: (appId: string) => Promise<void>,
|
||||
registry: ToolRegistry,
|
||||
unprefixedName: string,
|
||||
args: unknown,
|
||||
): Promise<ToolResult> {
|
||||
const fullName = `${APP_TOOL_PREFIX}${unprefixedName}`;
|
||||
if (!registry.listTools().some((tool) => tool.name === fullName)) {
|
||||
await launchApp("navigate");
|
||||
const deadline = Date.now() + TOOL_APPEAR_TIMEOUT_MS;
|
||||
while (!registry.listTools().some((tool) => tool.name === fullName)) {
|
||||
if (Date.now() > deadline) {
|
||||
return err("The Navigate app did not start in time.");
|
||||
}
|
||||
await sleep(TOOL_APPEAR_POLL_MS);
|
||||
}
|
||||
}
|
||||
return registry.callTool(fullName, args);
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function ok(content: string): ToolResult {
|
||||
return { ok: true, content };
|
||||
}
|
||||
|
||||
function err(error: string): ToolResult {
|
||||
return { ok: false, error };
|
||||
}
|
||||
@@ -4,10 +4,12 @@ const PERMISSION_REQUEST_CODE = 4242;
|
||||
const VOICE_PERMISSION_REQUEST_CODE = 4243;
|
||||
const CALENDAR_PERMISSION_REQUEST_CODE = 4244;
|
||||
const LOCATION_PERMISSION_REQUEST_CODE = 4245;
|
||||
const FINE_LOCATION_PERMISSION_REQUEST_CODE = 4246;
|
||||
const POST_NOTIFICATIONS_PERMISSION = "android.permission.POST_NOTIFICATIONS";
|
||||
const RECORD_AUDIO_PERMISSION = "android.permission.RECORD_AUDIO";
|
||||
const READ_CALENDAR_PERMISSION = "android.permission.READ_CALENDAR";
|
||||
const ACCESS_COARSE_LOCATION_PERMISSION = "android.permission.ACCESS_COARSE_LOCATION";
|
||||
const ACCESS_FINE_LOCATION_PERMISSION = "android.permission.ACCESS_FINE_LOCATION";
|
||||
|
||||
function getActivity(): androidx.appcompat.app.AppCompatActivity {
|
||||
const activity = Application.android.foregroundActivity ?? Application.android.startActivity;
|
||||
@@ -126,6 +128,33 @@ export async function ensureCalendarPermission(): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether precise (GPS) foreground location access has been granted. */
|
||||
export function hasFineLocationPermission(): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
return isPermissionGranted(ACCESS_FINE_LOCATION_PERMISSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt for precise foreground location access (navigation needs GPS fixes
|
||||
* with bearing). Requests coarse alongside fine so Android's "approximate
|
||||
* only" choice degrades gracefully rather than denying outright; resolves
|
||||
* true only when precise access is actually held.
|
||||
*/
|
||||
export async function ensureFineLocationPermission(): Promise<boolean> {
|
||||
if (!global.isAndroid) return false;
|
||||
try {
|
||||
await ensurePermissions(
|
||||
[ACCESS_FINE_LOCATION_PERMISSION, ACCESS_COARSE_LOCATION_PERMISSION],
|
||||
FINE_LOCATION_PERMISSION_REQUEST_CODE,
|
||||
"Location",
|
||||
);
|
||||
} catch {
|
||||
// Fall through: the user may have granted approximate-only, which still
|
||||
// reports as a denial of fine. Re-check what is actually held.
|
||||
}
|
||||
return hasFineLocationPermission();
|
||||
}
|
||||
|
||||
/** Whether approximate foreground location access has been granted. */
|
||||
export function hasLocationPermission(): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
OsEventTypeName,
|
||||
} from "./events";
|
||||
import { loadDeviceAddresses } from "./device-addresses";
|
||||
import { ensureBlePermissions, ensureVoicePermissions } from "./android-permissions";
|
||||
import { ensureBlePermissions, ensureFineLocationPermission, ensureVoicePermissions } from "./android-permissions";
|
||||
import { FaceclawCommunicatorBridge, type FrameMetrics, type RawInputEvent } from "../native/faceclaw-communicator";
|
||||
import * as frameTimings from "../native/frame-timings";
|
||||
import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service";
|
||||
@@ -26,6 +26,7 @@ import { voiceControlBridge } from "../native/voice-control";
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
|
||||
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
|
||||
import { registerSystemTools } from "../assistant/system-tools";
|
||||
import { registerNavigateTools } from "../assistant/navigate-tools";
|
||||
import { WorkerAppHost } from "../ui/shell/worker-window";
|
||||
import { createLauncherWindow, LAUNCHER_SURFACE_ID } from "../ui/shell/launcher-app";
|
||||
import {
|
||||
@@ -241,6 +242,8 @@ class DashboardController {
|
||||
// The always-available assistant tools (calendar, media, notifications,
|
||||
// glasses state) register once at startup, independent of any connection.
|
||||
registerSystemTools();
|
||||
// nav.* tools launch the Navigate app on demand, so they need launchApp.
|
||||
registerNavigateTools((appId) => this.launchApp(appId));
|
||||
shell.configure({
|
||||
actions: {
|
||||
...sharedActions,
|
||||
@@ -272,6 +275,7 @@ class DashboardController {
|
||||
{ appId: "notifications", label: "Notifications", icon: "bell" },
|
||||
{ appId: "calendar", label: "Calendar", icon: "calendar" },
|
||||
{ appId: "weather", label: "Weather", icon: "cloud-sun" },
|
||||
{ appId: "navigate", label: "Navigate", icon: "map" },
|
||||
{ appId: "debug-tests", label: "Debug tests", icon: "flask-conical" },
|
||||
{ appId: "settings", label: "Settings", icon: "settings" },
|
||||
],
|
||||
@@ -1192,6 +1196,8 @@ class DashboardController {
|
||||
worker = new Worker("../workers/timer-app.worker");
|
||||
} else if (appId === "terminal") {
|
||||
worker = new Worker("../workers/terminal-app.worker");
|
||||
} else if (appId === "navigate") {
|
||||
worker = new Worker("../workers/navigate-app.worker");
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -1300,6 +1306,20 @@ class DashboardController {
|
||||
this.appendLog("launched timer:main");
|
||||
return;
|
||||
}
|
||||
if (appId === "navigate") {
|
||||
// Navigation needs precise location; prompt on the phone while the
|
||||
// window opens (the worker can't show permission dialogs).
|
||||
void ensureFineLocationPermission().catch(() => {});
|
||||
const existing = shell.getWindows().find((window) => window.appId === "navigate");
|
||||
if (existing) {
|
||||
shell.focusWindow(existing.windowId);
|
||||
this.requestShellRender();
|
||||
return;
|
||||
}
|
||||
host.openWindow({ windowId: "navigate:main", title: "Navigate", iconLetter: "N", icon: "map", focus: true });
|
||||
this.appendLog("launched navigate:main");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create/refresh a window surface on the compositor, if connected. */
|
||||
|
||||
@@ -52,6 +52,8 @@ export const ICON_SVGS = {
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>',
|
||||
mic:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M12 19v3"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><rect x="9" y="2" width="6" height="13" rx="3"/></svg>',
|
||||
map:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z"/><path d="M15 5.764v15"/><path d="M9 3.236v15"/></svg>',
|
||||
nightscout:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="70.29 0 371.43 512"><g fill="#fff"><path d="M245.67.33c-26.83 1.88-48.51 7.53-71.01 18.48-12.93 6.31-23.82 13.24-35.58 22.6-6.52 5.14-22.75 21.43-28 27.95C89.04 97 76.06 127.65 71.22 163.38c-1.12 8.6-1.27 37.06-.25 47.85 3.46 35.53 12.16 69.02 27.33 105.37 18.83 45.25 49.17 93.31 88.52 140.44 12.17 14.56 33.39 37.72 39.76 43.47 15.17 13.54 36.19 15.27 52.94 4.33 4.38-2.85 10.44-8.76 23.62-23.06 31.2-33.75 58.18-69.33 78.8-103.84 25.1-42 40.72-78.7 50.8-119.37 8.91-35.89 11.35-74.52 6.57-103.08-3.16-18.94-7.99-33.7-17-51.92C401.59 61.68 366.77 29.76 323 12.5 300.04 3.49 269.34-1.35 245.67.33m21.99 29.42c12.83.66 31.61 4.94 45.2 10.28 35.99 14.15 65.87 41.64 82.97 76.25 8.76 17.71 13.34 33.24 15.58 52.69.66 5.9.76 10.38.56 22.14-.25 14.81-.51 18.17-2.44 31.82-8.35 58.95-36.6 121.71-83.08 184.27-21.38 28.71-57.93 70.3-65 73.86-3 1.53-7.99 1.58-10.94.2-7.13-3.41-42.56-43.62-64.65-73.3-33.09-44.39-55.79-86.33-70.3-129.81-11.5-34.61-16.59-65.16-15.83-95.9.41-17.36 2.44-29.52 7.53-45.15 18.43-56.71 68.87-98.65 127.77-106.39 7.18-.92 19.6-1.68 24.13-1.43 1.68.12 5.5.32 8.5.47"/><path d="M247.05 58.51c-11.56.97-23.31 3.41-33.49 6.87-6.36 2.19-18.94 8.2-24.89 11.96-13.49 8.4-26.27 20.26-36.35 33.7l-1.43 1.93 3.31-1.27c8.65-3.26 18.73-4.84 30.7-4.84 13.03 0 22.5 1.73 33.7 6.21 6.67 2.65 12.78 6.11 18.78 10.64 5.09 3.87 13.64 12.52 16.44 16.65.97 1.43 1.88 2.6 2.04 2.6s1.17-1.27 2.29-2.85c5.14-7.18 14.86-16.14 22.91-21.02 21.18-12.98 50.34-16.09 74.68-7.94l4.94 1.68-1.58-2.29c-7.33-10.69-22.25-24.48-35.28-32.78-14.86-9.42-32.93-15.93-51.26-18.48-7.04-.97-18.74-1.33-25.51-.77"/><path d="M178.07 133.9c-20.46 2.39-36.04 13.44-44.64 31.66-3.41 7.13-4.89 13.44-5.19 21.99-.71 18.68 4.99 41.39 14.91 59.41 20.46 37.16 57.27 62 98.55 66.53 11.5 1.27 28.56.46 40.37-1.99 22.7-4.63 44.29-15.88 61.39-31.97 6.82-6.41 16.29-17.97 21.18-25.81 15.17-24.38 22.55-57.88 17.26-78.29-1.43-5.65-4.73-12.98-7.99-17.71-3.41-5.04-9.88-11.45-14.91-14.76-5.14-3.41-12.78-6.57-19.14-7.89-5.29-1.17-19.9-1.32-24.69-.31-19.7 4.28-34.61 16.75-41.03 34.31-3.82 10.33-3.67 8.55-3.87 51.57-.15 42.2-.1 41.08-3 42.45-.81.36-5.09.56-11.66.56h-10.44l-1.63-1.48-1.68-1.48-.31-39.4c-.31-42.76-.2-41.44-3.31-50.7-3.56-10.69-11.61-21.23-21.02-27.59-10.9-7.32-25.41-10.68-39.15-9.1m12.22 6.06c10.74 1.22 20.31 5.85 28.61 13.74 6.67 6.36 11 13.54 13.64 22.65 1.02 3.61 1.17 5.14 1.12 12.98 0 8.2-.1 9.26-1.37 13.39-4.17 13.49-12.73 23.82-25.04 30.24-11.05 5.7-23.62 7.02-35.79 3.72-13.69-3.77-25.76-14.15-31.87-27.59-6.11-13.29-5.5-30.29 1.53-43.12 7.94-14.61 21.94-24.08 38.33-26.01 4.88-.56 5.95-.56 10.84 0m141.66 0c23.57 2.7 41.39 20.41 44.13 43.88 2.44 20.72-9.52 41.54-28.86 50.34-13.08 5.9-29.17 5.65-41.74-.66-13.18-6.62-22.55-18.17-26.52-32.73-1.48-5.5-1.37-18.33.2-24.18 1.48-5.4 4.48-11.86 7.43-15.93 2.49-3.56 9.06-10.03 12.62-12.47 6.01-4.12 14.91-7.43 22.04-8.2 5.82-.61 5.66-.61 10.7-.05"/><path d="M180.62 168.47c-11.2 2.39-18.58 13.39-16.39 24.54 3.26 16.59 23.42 22.81 35.33 10.89 10.28-10.33 7.28-27.44-5.96-33.7-4.08-1.89-9.01-2.55-12.98-1.73m141.92.2c-8.4 1.83-14.91 8.81-16.29 17.41-1.02 6.26 1.37 13.29 6.11 17.92 13.69 13.49 36.8 2.9 35.48-16.29a21.05 21.05 0 0 0-17.1-19.24c-3.37-.61-4.64-.61-8.2.2M163.15 318.02c8.4 16.8 18.12 33.55 28.71 49.48 7.18 10.84 9.01 13.29 9.52 12.98 1.37-.87 26.32-39.81 25.81-40.27-.05-.05-3.05-.81-6.72-1.63-19.9-4.58-39.35-13.44-55.89-25.45-2.19-1.63-4.43-3.21-4.99-3.61-.71-.51.41 2.14 3.56 8.5m183.57-4.68c-13.39 9.82-30.9 18.48-46.98 23.11-10.33 2.95-23.47 5.19-35.63 6.01l-5.75.36-3.82 6.82c-8.5 15.22-21.69 35.99-31.05 48.97-2.34 3.26-4.28 6.06-4.28 6.21 0 1.27 23.21 28.4 33.49 39.2l3.26 3.41 3.46-3.67c37.01-39.71 67.55-82.62 88.42-124.31 4.17-8.3 4.89-9.98 4.33-9.93-.21 0-2.65 1.73-5.45 3.82"/></g></svg>',
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Continuous GPS updates for navigation, backed by the Java
|
||||
* FaceclawLocationTracker. Usable from any isolate; callbacks arrive on the
|
||||
* calling isolate's own thread (the tracker captures the constructing
|
||||
* thread's Looper).
|
||||
*/
|
||||
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;
|
||||
};
|
||||
|
||||
export class LocationTracker {
|
||||
private tracker: any = null;
|
||||
private running = false;
|
||||
|
||||
constructor(private readonly callbacks: LocationTrackerCallbacks) {}
|
||||
|
||||
isRunning(): boolean {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
start(intervalMs = 1000): void {
|
||||
if (!global.isAndroid) {
|
||||
this.callbacks.onError("Location tracking is only available on Android.");
|
||||
return;
|
||||
}
|
||||
if (this.running) return;
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) {
|
||||
this.callbacks.onError("Android application context unavailable.");
|
||||
return;
|
||||
}
|
||||
this.tracker = new com.faceclaw.app.FaceclawLocationTracker(context);
|
||||
const listener = new com.faceclaw.app.FaceclawLocationTrackerListener({
|
||||
onLocation: (
|
||||
latitude: number,
|
||||
longitude: number,
|
||||
accuracyMeters: number,
|
||||
bearingDeg: number,
|
||||
speedMps: number,
|
||||
timestampMs: number,
|
||||
) => {
|
||||
if (!this.running) return;
|
||||
this.callbacks.onLocation({
|
||||
latitude: Number(latitude),
|
||||
longitude: Number(longitude),
|
||||
accuracyMeters: Number(accuracyMeters) >= 0 ? Number(accuracyMeters) : null,
|
||||
bearingDeg: Number(bearingDeg) >= 0 ? Number(bearingDeg) : null,
|
||||
speedMps: Number(speedMps) >= 0 ? Number(speedMps) : null,
|
||||
timestampMs: Number(timestampMs),
|
||||
});
|
||||
},
|
||||
onError: (message: string) => {
|
||||
if (!this.running) return;
|
||||
this.callbacks.onError(String(message));
|
||||
},
|
||||
});
|
||||
// The Java tracker retains the listener proxy for the stream's lifetime.
|
||||
this.tracker.setListener(listener);
|
||||
this.running = true;
|
||||
this.tracker.start(intervalMs);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.running) return;
|
||||
this.running = false;
|
||||
try {
|
||||
this.tracker?.stop();
|
||||
this.tracker?.setListener(null);
|
||||
} catch (error) {
|
||||
console.warn(`location tracker stop failed: ${error}`);
|
||||
}
|
||||
this.tracker = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Mapbox REST client for the Navigate app: Search Box forward geocoding
|
||||
* (spoken destination → coordinates), Directions (route + maneuvers), and
|
||||
* Static Images (the rendered map pane). Workers use this directly; the
|
||||
* public token lives in settings under "maps.mapboxApiKey".
|
||||
*/
|
||||
import { GrayImage } from "../graphics/image";
|
||||
import { getStringSetting } from "./settings-store";
|
||||
import { grayImageFromPacket } from "./image-files";
|
||||
|
||||
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";
|
||||
const DIRECTIONS_ROOT = "https://api.mapbox.com/directions/v5";
|
||||
const STATIC_ROOT = "https://api.mapbox.com/styles/v1";
|
||||
/** Classic dark style; readable after gray conversion. Swappable for a custom Studio style later. */
|
||||
const MAP_STYLE = "mapbox/dark-v11";
|
||||
const FETCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
export type RouteProfile = "driving" | "walking" | "cycling";
|
||||
|
||||
export type GeocodeCandidate = {
|
||||
name: string;
|
||||
placeFormatted: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
/** Straight-line meters from the proximity point, when Mapbox reports it. */
|
||||
distanceMeters: number | null;
|
||||
};
|
||||
|
||||
export type RouteStep = {
|
||||
distanceMeters: number;
|
||||
durationSec: number;
|
||||
/** Road name for this step ("" when unnamed). */
|
||||
name: string;
|
||||
/** Human-readable instruction for the maneuver that starts this step. */
|
||||
instruction: string;
|
||||
maneuverType: string;
|
||||
maneuverModifier: string;
|
||||
/** Roundabout exit number, when applicable. */
|
||||
exit: number | null;
|
||||
/** Maneuver point [lon, lat]. */
|
||||
location: [number, number];
|
||||
};
|
||||
|
||||
export type Route = {
|
||||
distanceMeters: number;
|
||||
durationSec: number;
|
||||
/** Full route geometry as [lon, lat] pairs. */
|
||||
coordinates: Array<[number, number]>;
|
||||
steps: RouteStep[];
|
||||
};
|
||||
|
||||
export function getMapboxToken(): string {
|
||||
return getStringSetting(MAPBOX_TOKEN_SETTING_KEY, "") ?? "";
|
||||
}
|
||||
|
||||
export function isMapboxConfigured(): boolean {
|
||||
return getMapboxToken().length > 0;
|
||||
}
|
||||
|
||||
/** Resolve a free-text destination near the given location. */
|
||||
export async function geocodeForward(
|
||||
query: string,
|
||||
proximity: { longitude: number; latitude: number } | null,
|
||||
limit = 5,
|
||||
): Promise<GeocodeCandidate[]> {
|
||||
const params: Record<string, string> = {
|
||||
q: query,
|
||||
access_token: requireToken(),
|
||||
limit: String(limit),
|
||||
language: "en",
|
||||
};
|
||||
if (proximity) {
|
||||
params.proximity = `${round6(proximity.longitude)},${round6(proximity.latitude)}`;
|
||||
}
|
||||
const body = await fetchJson(`${SEARCH_ROOT}/forward?${queryString(params)}`, "Mapbox search");
|
||||
const features = Array.isArray(body?.features) ? body.features : [];
|
||||
const candidates: GeocodeCandidate[] = [];
|
||||
for (const feature of features) {
|
||||
const properties = feature?.properties;
|
||||
const coordinates = properties?.coordinates;
|
||||
const longitude = toFinite(coordinates?.longitude);
|
||||
const latitude = toFinite(coordinates?.latitude);
|
||||
if (longitude === null || latitude === null) continue;
|
||||
candidates.push({
|
||||
name: String(properties?.name ?? "").trim() || "(unnamed)",
|
||||
placeFormatted: String(properties?.place_formatted ?? "").trim(),
|
||||
longitude,
|
||||
latitude,
|
||||
distanceMeters: toFinite(properties?.distance),
|
||||
});
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
/** Fetch a route with turn-by-turn steps. */
|
||||
export async function fetchRoute(
|
||||
origin: { longitude: number; latitude: number },
|
||||
destination: { longitude: number; latitude: number },
|
||||
profile: RouteProfile,
|
||||
): Promise<Route> {
|
||||
const coords =
|
||||
`${round6(origin.longitude)},${round6(origin.latitude)};` +
|
||||
`${round6(destination.longitude)},${round6(destination.latitude)}`;
|
||||
const params = queryString({
|
||||
access_token: requireToken(),
|
||||
steps: "true",
|
||||
geometries: "geojson",
|
||||
overview: "full",
|
||||
language: "en",
|
||||
});
|
||||
const body = await fetchJson(
|
||||
`${DIRECTIONS_ROOT}/mapbox/${profile}/${coords}?${params}`,
|
||||
"Mapbox directions",
|
||||
);
|
||||
if (body?.code && body.code !== "Ok") {
|
||||
throw new Error(`No route found (${body.code}).`);
|
||||
}
|
||||
const route = body?.routes?.[0];
|
||||
if (!route) throw new Error("Mapbox returned no routes.");
|
||||
|
||||
const coordinates: Array<[number, number]> = [];
|
||||
for (const pair of route.geometry?.coordinates ?? []) {
|
||||
const lon = toFinite(pair?.[0]);
|
||||
const lat = toFinite(pair?.[1]);
|
||||
if (lon !== null && lat !== null) coordinates.push([lon, lat]);
|
||||
}
|
||||
if (coordinates.length < 2) throw new Error("Mapbox returned an empty route geometry.");
|
||||
|
||||
const steps: RouteStep[] = [];
|
||||
for (const leg of route.legs ?? []) {
|
||||
for (const step of leg.steps ?? []) {
|
||||
const maneuver = step?.maneuver ?? {};
|
||||
const lon = toFinite(maneuver.location?.[0]);
|
||||
const lat = toFinite(maneuver.location?.[1]);
|
||||
steps.push({
|
||||
distanceMeters: toFinite(step?.distance) ?? 0,
|
||||
durationSec: toFinite(step?.duration) ?? 0,
|
||||
name: String(step?.name ?? "").trim(),
|
||||
instruction: String(maneuver.instruction ?? "").trim(),
|
||||
maneuverType: String(maneuver.type ?? "").trim(),
|
||||
maneuverModifier: String(maneuver.modifier ?? "").trim(),
|
||||
exit: toFinite(maneuver.exit),
|
||||
location: [lon ?? coordinates[0]![0], lat ?? coordinates[0]![1]],
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!steps.length) throw new Error("Mapbox returned a route without steps.");
|
||||
|
||||
return {
|
||||
distanceMeters: toFinite(route.distance) ?? 0,
|
||||
durationSec: toFinite(route.duration) ?? 0,
|
||||
coordinates,
|
||||
steps,
|
||||
};
|
||||
}
|
||||
|
||||
export type StaticMapCamera =
|
||||
| { kind: "center"; longitude: number; latitude: number; zoom: number; bearingDeg: number }
|
||||
/** Fit the overlay path (route overview). */
|
||||
| { kind: "auto" };
|
||||
|
||||
/**
|
||||
* Fetch a rendered map image and decode it to grayscale. routePath (when
|
||||
* given) is drawn as a bright route line; the URL has an 8 KB cap so pass a
|
||||
* clipped/simplified polyline, not a 200-mile route.
|
||||
*/
|
||||
export async function fetchStaticMapGray(options: {
|
||||
camera: StaticMapCamera;
|
||||
width: number;
|
||||
height: number;
|
||||
routePath?: Array<[number, number]>;
|
||||
}): Promise<GrayImage> {
|
||||
const overlays: string[] = [];
|
||||
if (options.routePath && options.routePath.length >= 2) {
|
||||
// Wide light route line with slight transparency so the road grid
|
||||
// underneath still reads.
|
||||
overlays.push(`path-6+ffffff-0.85(${encodeURIComponent(encodePolyline(options.routePath))})`);
|
||||
}
|
||||
const overlay = overlays.length ? `${overlays.join(",")}/` : "";
|
||||
const camera =
|
||||
options.camera.kind === "auto"
|
||||
? "auto"
|
||||
: `${round6(options.camera.longitude)},${round6(options.camera.latitude)},` +
|
||||
`${options.camera.zoom.toFixed(2)},${Math.round(normalizeBearing(options.camera.bearingDeg))}`;
|
||||
const size = `${Math.round(options.width)}x${Math.round(options.height)}`;
|
||||
const params = queryString({
|
||||
access_token: requireToken(),
|
||||
logo: "false",
|
||||
attribution: "false",
|
||||
});
|
||||
const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${params}`;
|
||||
|
||||
const response = await fetchWithTimeout(url, "Mapbox static map");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Mapbox static map failed (HTTP ${response.status}).`);
|
||||
}
|
||||
const bytes = await response.arrayBuffer();
|
||||
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)),
|
||||
);
|
||||
if (!image) throw new Error("Failed to decode the Mapbox map image.");
|
||||
return image;
|
||||
}
|
||||
|
||||
/** Encode [lon, lat] pairs as a precision-5 polyline (Static Images path overlay format). */
|
||||
export function encodePolyline(coordinates: Array<[number, number]>): string {
|
||||
let output = "";
|
||||
let lastLat = 0;
|
||||
let lastLon = 0;
|
||||
for (const [lon, lat] of coordinates) {
|
||||
const latE5 = Math.round(lat * 1e5);
|
||||
const lonE5 = Math.round(lon * 1e5);
|
||||
output += encodePolylineValue(latE5 - lastLat) + encodePolylineValue(lonE5 - lastLon);
|
||||
lastLat = latE5;
|
||||
lastLon = lonE5;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function encodePolylineValue(value: number): string {
|
||||
let v = value < 0 ? ~(value << 1) : value << 1;
|
||||
let output = "";
|
||||
while (v >= 0x20) {
|
||||
output += String.fromCharCode((0x20 | (v & 0x1f)) + 63);
|
||||
v >>= 5;
|
||||
}
|
||||
output += String.fromCharCode(v + 63);
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual query-string builder: the NativeScript runtime's URLSearchParams
|
||||
* doesn't populate from an object initializer, silently yielding an empty
|
||||
* query (observed as Mapbox HTTP 401 "Missing or empty access_token").
|
||||
*/
|
||||
function queryString(params: Record<string, string>): string {
|
||||
return Object.keys(params)
|
||||
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key]!)}`)
|
||||
.join("&");
|
||||
}
|
||||
|
||||
function requireToken(): string {
|
||||
const token = getMapboxToken();
|
||||
if (!token) {
|
||||
throw new Error("Set a Mapbox token in Settings > API Keys first.");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
async function fetchJson(url: string, label: string): Promise<any> {
|
||||
const response = await fetchWithTimeout(url, label);
|
||||
if (!response.ok) {
|
||||
let detail = "";
|
||||
try {
|
||||
const body = await response.json();
|
||||
detail = String(body?.message ?? "");
|
||||
} catch {
|
||||
// Non-JSON error body; the status code is enough.
|
||||
}
|
||||
throw new Error(`${label} failed (HTTP ${response.status}${detail ? `: ${detail}` : ""}).`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, label: string): Promise<Response> {
|
||||
const request = fetch(url);
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
timeoutHandle = setTimeout(() => reject(new Error(`${label} timed out.`)), FETCH_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([request, timeout]);
|
||||
} finally {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBearing(bearingDeg: number): number {
|
||||
return ((bearingDeg % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
function round6(value: number): string {
|
||||
return value.toFixed(6);
|
||||
}
|
||||
|
||||
function toFinite(value: unknown): number | null {
|
||||
const num = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(num) ? num : null;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Maneuver arrow glyphs for turn-by-turn guidance, drawn with GrayImage
|
||||
* primitives from the Directions maneuver type + modifier (no image assets).
|
||||
*/
|
||||
import { GrayImage } from "../graphics/image";
|
||||
|
||||
/**
|
||||
* Draw the glyph for a maneuver into a size x size box at (x, y).
|
||||
* Roundabout exit numbers are the caller's job (drawn as text next to it).
|
||||
*/
|
||||
export function drawManeuverGlyph(
|
||||
image: GrayImage,
|
||||
x: number,
|
||||
y: number,
|
||||
size: number,
|
||||
maneuverType: string,
|
||||
modifier: string,
|
||||
value = 245,
|
||||
): void {
|
||||
const type = maneuverType.toLowerCase();
|
||||
if (type === "arrive") {
|
||||
drawArriveFlag(image, x, y, size, value);
|
||||
return;
|
||||
}
|
||||
if (type === "roundabout" || type === "rotary" || type === "roundabout turn" || type === "exit roundabout" || type === "exit rotary") {
|
||||
drawRoundabout(image, x, y, size, value);
|
||||
return;
|
||||
}
|
||||
drawArrow(image, x, y, size, modifier.toLowerCase(), value);
|
||||
}
|
||||
|
||||
/** Normalized path points (0..1 box coords, y down) for each arrow shape. */
|
||||
function arrowPath(modifier: string): Array<[number, number]> {
|
||||
switch (modifier) {
|
||||
case "uturn":
|
||||
return [
|
||||
[0.68, 0.92],
|
||||
[0.68, 0.42],
|
||||
[0.62, 0.28],
|
||||
[0.5, 0.22],
|
||||
[0.38, 0.28],
|
||||
[0.32, 0.42],
|
||||
[0.32, 0.88],
|
||||
];
|
||||
case "sharp left":
|
||||
return [
|
||||
[0.6, 0.92],
|
||||
[0.6, 0.42],
|
||||
[0.2, 0.72],
|
||||
];
|
||||
case "left":
|
||||
return [
|
||||
[0.62, 0.92],
|
||||
[0.62, 0.42],
|
||||
[0.14, 0.42],
|
||||
];
|
||||
case "slight left":
|
||||
return [
|
||||
[0.56, 0.92],
|
||||
[0.56, 0.5],
|
||||
[0.32, 0.16],
|
||||
];
|
||||
case "sharp right":
|
||||
return [
|
||||
[0.4, 0.92],
|
||||
[0.4, 0.42],
|
||||
[0.8, 0.72],
|
||||
];
|
||||
case "right":
|
||||
return [
|
||||
[0.38, 0.92],
|
||||
[0.38, 0.42],
|
||||
[0.86, 0.42],
|
||||
];
|
||||
case "slight right":
|
||||
return [
|
||||
[0.44, 0.92],
|
||||
[0.44, 0.5],
|
||||
[0.68, 0.16],
|
||||
];
|
||||
case "straight":
|
||||
default:
|
||||
return [
|
||||
[0.5, 0.92],
|
||||
[0.5, 0.12],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function drawArrow(image: GrayImage, x: number, y: number, size: number, modifier: string, value: number): void {
|
||||
const path = arrowPath(modifier).map(([px, py]): [number, number] => [x + px * size, y + py * size]);
|
||||
const thickness = Math.max(2, Math.round(size / 14));
|
||||
for (let i = 1; i < path.length; i++) {
|
||||
drawThickLine(image, path[i - 1]!, path[i]!, thickness, value);
|
||||
}
|
||||
const tip = path[path.length - 1]!;
|
||||
const prev = path[path.length - 2]!;
|
||||
drawArrowHead(image, prev, tip, Math.max(5, size * 0.22), thickness, value);
|
||||
}
|
||||
|
||||
function drawRoundabout(image: GrayImage, x: number, y: number, size: number, value: number): void {
|
||||
const cx = x + size * 0.5;
|
||||
const cy = y + size * 0.58;
|
||||
const radius = size * 0.24;
|
||||
const thickness = Math.max(2, Math.round(size / 14));
|
||||
// Circle from line segments.
|
||||
const segments = 20;
|
||||
let last: [number, number] | null = null;
|
||||
for (let i = 0; i <= segments; i++) {
|
||||
const angle = (i / segments) * Math.PI * 2;
|
||||
const point: [number, number] = [cx + radius * Math.cos(angle), cy + radius * Math.sin(angle)];
|
||||
if (last) drawThickLine(image, last, point, thickness, value);
|
||||
last = point;
|
||||
}
|
||||
// Exit arrow upward out of the circle.
|
||||
const from: [number, number] = [cx, cy - radius];
|
||||
const to: [number, number] = [cx, y + size * 0.08];
|
||||
drawThickLine(image, from, to, thickness, value);
|
||||
drawArrowHead(image, from, to, Math.max(5, size * 0.2), thickness, value);
|
||||
}
|
||||
|
||||
function drawArriveFlag(image: GrayImage, x: number, y: number, size: number, value: number): void {
|
||||
const poleX = Math.round(x + size * 0.36);
|
||||
const top = Math.round(y + size * 0.12);
|
||||
const bottom = Math.round(y + size * 0.92);
|
||||
const thickness = Math.max(2, Math.round(size / 16));
|
||||
drawThickLine(image, [poleX, top], [poleX, bottom], thickness, value);
|
||||
// Flag: two stacked rows of alternating blocks reads as checkered at 4bpp.
|
||||
const flagWidth = Math.round(size * 0.42);
|
||||
const rowHeight = Math.max(3, Math.round(size * 0.11));
|
||||
const blocks = 3;
|
||||
const blockWidth = Math.max(3, Math.round(flagWidth / blocks));
|
||||
for (let row = 0; row < 2; row++) {
|
||||
for (let block = 0; block < blocks; block++) {
|
||||
const bright = (row + block) % 2 === 0;
|
||||
image.fillRect(
|
||||
poleX + thickness + block * blockWidth,
|
||||
top + row * rowHeight,
|
||||
blockWidth,
|
||||
rowHeight,
|
||||
bright ? value : Math.round(value * 0.35),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawArrowHead(
|
||||
image: GrayImage,
|
||||
from: [number, number],
|
||||
tip: [number, number],
|
||||
headLength: number,
|
||||
thickness: number,
|
||||
value: number,
|
||||
): void {
|
||||
const angle = Math.atan2(tip[1] - from[1], tip[0] - from[0]);
|
||||
const spread = Math.PI / 5.5;
|
||||
for (const side of [-1, 1]) {
|
||||
const barbAngle = angle + Math.PI + side * spread;
|
||||
const barb: [number, number] = [
|
||||
tip[0] + headLength * Math.cos(barbAngle),
|
||||
tip[1] + headLength * Math.sin(barbAngle),
|
||||
];
|
||||
drawThickLine(image, tip, barb, thickness, value);
|
||||
}
|
||||
}
|
||||
|
||||
function drawThickLine(
|
||||
image: GrayImage,
|
||||
from: [number, number],
|
||||
to: [number, number],
|
||||
thickness: number,
|
||||
value: number,
|
||||
): void {
|
||||
// Stamp a small square along the line; plenty at glyph scale.
|
||||
const dx = to[0] - from[0];
|
||||
const dy = to[1] - from[1];
|
||||
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy))));
|
||||
const half = Math.floor(thickness / 2);
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const px = Math.round(from[0] + (dx * i) / steps);
|
||||
const py = Math.round(from[1] + (dy * i) / steps);
|
||||
image.fillRect(px - half, py - half, thickness, thickness, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Client-side route following: snap GPS fixes to the route polyline, track
|
||||
* progress toward the next maneuver, and detect off-route/arrival. Pure
|
||||
* geometry over the Directions response — no network, no Android.
|
||||
*/
|
||||
import type { Route } from "../native/mapbox";
|
||||
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
/** Perpendicular distance that counts as off the route. */
|
||||
const OFF_ROUTE_THRESHOLD_M = 50;
|
||||
/** Consecutive off-route fixes before declaring a reroute is needed. */
|
||||
const OFF_ROUTE_FIX_COUNT = 3;
|
||||
/** Within this many meters of the destination counts as arrived. */
|
||||
const ARRIVAL_THRESHOLD_M = 35;
|
||||
/** How far behind the last known progress the snap search may look. */
|
||||
const SNAP_BACKTRACK_SEGMENTS = 8;
|
||||
/** How far ahead of the last known progress the snap search may look. */
|
||||
const SNAP_LOOKAHEAD_SEGMENTS = 120;
|
||||
|
||||
export type RouteProgress = {
|
||||
/** Snapped position [lon, lat]. */
|
||||
snapped: [number, number];
|
||||
/** Meters traveled along the route. */
|
||||
alongMeters: number;
|
||||
/** Perpendicular meters from the fix to the route. */
|
||||
crossTrackMeters: number;
|
||||
/** Index of the upcoming maneuver in route.steps (its instruction is what to show). */
|
||||
nextStepIndex: number;
|
||||
/** Meters until the upcoming maneuver. */
|
||||
metersToNextManeuver: number;
|
||||
remainingMeters: number;
|
||||
remainingSec: number;
|
||||
offRoute: boolean;
|
||||
arrived: boolean;
|
||||
};
|
||||
|
||||
export class RouteFollower {
|
||||
readonly route: Route;
|
||||
/** Cumulative meters from the origin to each geometry vertex. */
|
||||
private readonly vertexMeters: number[];
|
||||
/** Meters along the route at which each step's maneuver occurs. */
|
||||
private readonly stepStartMeters: number[];
|
||||
private readonly totalMeters: number;
|
||||
private lastSegmentIndex = 0;
|
||||
private offRouteStreak = 0;
|
||||
|
||||
constructor(route: Route) {
|
||||
this.route = route;
|
||||
this.vertexMeters = new Array(route.coordinates.length);
|
||||
let along = 0;
|
||||
this.vertexMeters[0] = 0;
|
||||
for (let i = 1; i < route.coordinates.length; i++) {
|
||||
along += haversineMeters(route.coordinates[i - 1]!, route.coordinates[i]!);
|
||||
this.vertexMeters[i] = along;
|
||||
}
|
||||
this.totalMeters = along;
|
||||
|
||||
// Each step's maneuver happens where the previous step's travel ends, so
|
||||
// the maneuver point of step k sits at the sum of steps 0..k-1 distances.
|
||||
// (Slight drift vs the geometry is fine at guidance granularity.)
|
||||
this.stepStartMeters = new Array(route.steps.length);
|
||||
let stepAlong = 0;
|
||||
for (let i = 0; i < route.steps.length; i++) {
|
||||
this.stepStartMeters[i] = Math.min(stepAlong, this.totalMeters);
|
||||
stepAlong += route.steps[i]!.distanceMeters;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ingest a GPS fix and return current guidance state. */
|
||||
update(longitude: number, latitude: number): RouteProgress {
|
||||
const fix: [number, number] = [longitude, latitude];
|
||||
const snap = this.snapToRoute(fix);
|
||||
this.lastSegmentIndex = snap.segmentIndex;
|
||||
|
||||
if (snap.crossTrackMeters > OFF_ROUTE_THRESHOLD_M) {
|
||||
this.offRouteStreak++;
|
||||
} else {
|
||||
this.offRouteStreak = 0;
|
||||
}
|
||||
|
||||
const remainingMeters = Math.max(0, this.totalMeters - snap.alongMeters);
|
||||
const arrived =
|
||||
remainingMeters < ARRIVAL_THRESHOLD_M &&
|
||||
haversineMeters(fix, this.route.coordinates[this.route.coordinates.length - 1]!) <
|
||||
ARRIVAL_THRESHOLD_M * 2;
|
||||
|
||||
// The next maneuver is the first one still ahead of us. Step 0 is
|
||||
// "depart", which is behind us as soon as we move; arrival is last.
|
||||
let nextStepIndex = this.route.steps.length - 1;
|
||||
for (let i = 1; i < this.route.steps.length; i++) {
|
||||
if (this.stepStartMeters[i]! > snap.alongMeters + 5) {
|
||||
nextStepIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
snapped: snap.snapped,
|
||||
alongMeters: snap.alongMeters,
|
||||
crossTrackMeters: snap.crossTrackMeters,
|
||||
nextStepIndex,
|
||||
metersToNextManeuver: Math.max(0, this.stepStartMeters[nextStepIndex]! - snap.alongMeters),
|
||||
remainingMeters,
|
||||
remainingSec: this.remainingSeconds(snap.alongMeters, nextStepIndex),
|
||||
offRoute: this.offRouteStreak >= OFF_ROUTE_FIX_COUNT,
|
||||
arrived,
|
||||
};
|
||||
}
|
||||
|
||||
totalRouteMeters(): number {
|
||||
return this.totalMeters;
|
||||
}
|
||||
|
||||
/**
|
||||
* The route geometry from just behind the current position to aheadMeters
|
||||
* past it — the slice worth drawing on a follow-mode map.
|
||||
*/
|
||||
routeSliceAround(alongMeters: number, behindMeters: number, aheadMeters: number): Array<[number, number]> {
|
||||
const from = Math.max(0, alongMeters - behindMeters);
|
||||
const to = Math.min(this.totalMeters, alongMeters + aheadMeters);
|
||||
const slice: Array<[number, number]> = [];
|
||||
for (let i = 0; i < this.route.coordinates.length; i++) {
|
||||
const at = this.vertexMeters[i]!;
|
||||
if (at < from) continue;
|
||||
if (at > to) break;
|
||||
slice.push(this.route.coordinates[i]!);
|
||||
}
|
||||
return slice.length >= 2 ? slice : this.route.coordinates.slice(0, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest point on the polyline, biased to search near the last known
|
||||
* segment first so parallel roads and overlaps resolve forward along the
|
||||
* route. Falls back to a whole-route search when the local window misses.
|
||||
*/
|
||||
private snapToRoute(fix: [number, number]): {
|
||||
snapped: [number, number];
|
||||
alongMeters: number;
|
||||
crossTrackMeters: number;
|
||||
segmentIndex: number;
|
||||
} {
|
||||
const windowStart = Math.max(0, this.lastSegmentIndex - SNAP_BACKTRACK_SEGMENTS);
|
||||
const windowEnd = Math.min(
|
||||
this.route.coordinates.length - 2,
|
||||
this.lastSegmentIndex + SNAP_LOOKAHEAD_SEGMENTS,
|
||||
);
|
||||
const local = this.nearestOnSegments(fix, windowStart, windowEnd);
|
||||
if (local && local.crossTrackMeters <= OFF_ROUTE_THRESHOLD_M * 2) {
|
||||
return local;
|
||||
}
|
||||
const global = this.nearestOnSegments(fix, 0, this.route.coordinates.length - 2);
|
||||
return global ?? local ?? {
|
||||
snapped: this.route.coordinates[0]!,
|
||||
alongMeters: 0,
|
||||
crossTrackMeters: Number.POSITIVE_INFINITY,
|
||||
segmentIndex: 0,
|
||||
};
|
||||
}
|
||||
|
||||
private nearestOnSegments(
|
||||
fix: [number, number],
|
||||
firstSegment: number,
|
||||
lastSegment: number,
|
||||
): { snapped: [number, number]; alongMeters: number; crossTrackMeters: number; segmentIndex: number } | null {
|
||||
let best: { snapped: [number, number]; alongMeters: number; crossTrackMeters: number; segmentIndex: number } | null =
|
||||
null;
|
||||
// Planar approximation in a locally scaled lon/lat frame; fine for
|
||||
// segment-scale distances.
|
||||
const cosLat = Math.cos((fix[1] * Math.PI) / 180);
|
||||
for (let i = firstSegment; i <= lastSegment; i++) {
|
||||
const a = this.route.coordinates[i]!;
|
||||
const b = this.route.coordinates[i + 1]!;
|
||||
const ax = (a[0] - fix[0]) * cosLat;
|
||||
const ay = a[1] - fix[1];
|
||||
const bx = (b[0] - fix[0]) * cosLat;
|
||||
const by = b[1] - fix[1];
|
||||
const dx = bx - ax;
|
||||
const dy = by - ay;
|
||||
const lengthSq = dx * dx + dy * dy;
|
||||
const t = lengthSq > 0 ? clamp01(-(ax * dx + ay * dy) / lengthSq) : 0;
|
||||
const px = ax + t * dx;
|
||||
const py = ay + t * dy;
|
||||
const distanceMeters = Math.sqrt(px * px + py * py) * ((Math.PI / 180) * EARTH_RADIUS_M);
|
||||
if (best === null || distanceMeters < best.crossTrackMeters) {
|
||||
const segmentLength = this.vertexMeters[i + 1]! - this.vertexMeters[i]!;
|
||||
best = {
|
||||
snapped: [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])],
|
||||
alongMeters: this.vertexMeters[i]! + t * segmentLength,
|
||||
crossTrackMeters: distanceMeters,
|
||||
segmentIndex: i,
|
||||
};
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private remainingSeconds(alongMeters: number, nextStepIndex: number): number {
|
||||
// Whole steps still ahead, plus a proportional share of the step we're in.
|
||||
let seconds = 0;
|
||||
for (let i = nextStepIndex; i < this.route.steps.length; i++) {
|
||||
seconds += this.route.steps[i]!.durationSec;
|
||||
}
|
||||
const currentStep = this.route.steps[nextStepIndex - 1];
|
||||
if (currentStep && currentStep.distanceMeters > 0) {
|
||||
const stepStart = this.stepStartMeters[nextStepIndex - 1]!;
|
||||
const fractionRemaining = clamp01(1 - (alongMeters - stepStart) / currentStep.distanceMeters);
|
||||
seconds += currentStep.durationSec * fractionRemaining;
|
||||
}
|
||||
return seconds;
|
||||
}
|
||||
}
|
||||
|
||||
export function haversineMeters(a: [number, number], b: [number, number]): number {
|
||||
const dLat = ((b[1] - a[1]) * Math.PI) / 180;
|
||||
const dLon = ((b[0] - a[0]) * Math.PI) / 180;
|
||||
const lat1 = (a[1] * Math.PI) / 180;
|
||||
const lat2 = (b[1] * Math.PI) / 180;
|
||||
const h =
|
||||
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
|
||||
return 2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(h)));
|
||||
}
|
||||
|
||||
/** Initial bearing (degrees clockwise from north) from a to b. */
|
||||
export function bearingDegrees(a: [number, number], b: [number, number]): number {
|
||||
const lat1 = (a[1] * Math.PI) / 180;
|
||||
const lat2 = (b[1] * Math.PI) / 180;
|
||||
const dLon = ((b[0] - a[0]) * Math.PI) / 180;
|
||||
const y = Math.sin(dLon) * Math.cos(lat2);
|
||||
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
|
||||
const degrees = (Math.atan2(y, x) * 180) / Math.PI;
|
||||
return (degrees + 360) % 360;
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
return Math.max(0, Math.min(1, value));
|
||||
}
|
||||
@@ -331,6 +331,16 @@ export const anthropicApiKeySetting = new ConfigSettingString({
|
||||
formatValue: (value) => (value ? `${value.slice(0, 6)}...` : "(not set)"),
|
||||
});
|
||||
|
||||
export const mapboxApiKeySetting = new ConfigSettingString({
|
||||
id: "mapbox-api-key",
|
||||
label: "Mapbox token",
|
||||
storageKey: "maps.mapboxApiKey",
|
||||
defaultValue: "",
|
||||
editorTitle: "Mapbox public token (pk.…)",
|
||||
glassesEditTitle: "Edit Mapbox token",
|
||||
formatValue: (value) => (value ? `${value.slice(0, 6)}...` : "(not set)"),
|
||||
});
|
||||
|
||||
export const terminalHostSetting = new ConfigSettingString({
|
||||
id: "terminal-host",
|
||||
label: "Host",
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
batteryDisplayModeSetting,
|
||||
brightnessSetting,
|
||||
elevenLabsApiKeySetting,
|
||||
mapboxApiKeySetting,
|
||||
openAiApiKeySetting,
|
||||
enumSettingMenuItem,
|
||||
firmwareDebugFlagsSetting,
|
||||
@@ -68,6 +69,7 @@ function settingsSections(): SettingsSection[] {
|
||||
textSettingMenuItem(elevenLabsApiKeySetting),
|
||||
textSettingMenuItem(openAiApiKeySetting),
|
||||
textSettingMenuItem(anthropicApiKeySetting),
|
||||
textSettingMenuItem(mapboxApiKeySetting),
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,892 @@
|
||||
/**
|
||||
* Navigate app worker: voice/tool-set destination, Mapbox routing, and
|
||||
* turn-by-turn guidance with a live map pane.
|
||||
*
|
||||
* The BLE frame budget shapes the layout (see notes/navigate-app-design.md):
|
||||
* the map bitmap (left pane) refreshes on a slow staleness policy, while the
|
||||
* guidance text (right pane) updates per GPS fix and ships as small deltas.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { GrayImage } from "../graphics/image";
|
||||
import { getDefaultSmallFont, getFont } from "../graphics/bdffont";
|
||||
import * as frameTimings from "../native/frame-timings";
|
||||
import type { DashboardInputEvent } from "../ui/layers";
|
||||
import { defaultWindowMenuItems, WindowMenu } from "../ui/window-menu";
|
||||
import type { WorkerAppMessage, WorkerAppReply } from "../ui/shell/worker-window";
|
||||
import type { ToolSpec, ToolResult } from "../assistant/tool-registry";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../ui/gestures";
|
||||
import { LocationTracker, type TrackedLocation } from "../native/location-tracker";
|
||||
import {
|
||||
fetchRoute,
|
||||
fetchStaticMapGray,
|
||||
geocodeForward,
|
||||
isMapboxConfigured,
|
||||
type GeocodeCandidate,
|
||||
type Route,
|
||||
type RouteProfile,
|
||||
type StaticMapCamera,
|
||||
} from "../native/mapbox";
|
||||
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "../navigate/route-follower";
|
||||
import { drawManeuverGlyph } from "../navigate/maneuver-icons";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const MAP_SIZE = 260;
|
||||
const PANEL_X = MAP_SIZE + 10;
|
||||
/** Map refetch policy knobs (design doc: never per-fix, only when stale). */
|
||||
const BEARING_BUCKET_DEG = 15;
|
||||
const MOVE_REFRESH_FRACTION = 0.15;
|
||||
const IDLE_REFRESH_MS = 5_000;
|
||||
const IDLE_REFRESH_MIN_MOVE_M = 10;
|
||||
const MAP_RETRY_BACKOFF_MS = 5_000;
|
||||
const REROUTE_MIN_INTERVAL_MS = 20_000;
|
||||
const FIRST_FIX_TIMEOUT_MS = 10_000;
|
||||
const LOCATION_INTERVAL_MS = 1_000;
|
||||
/** Above this speed a GPS bearing is trustworthy for heading-up. */
|
||||
const BEARING_MIN_SPEED_MPS = 2.5;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
const smallFont = getDefaultSmallFont();
|
||||
|
||||
type NavPhase = "idle" | "acquiring" | "routing" | "navigating" | "arrived";
|
||||
type MapMode = "follow" | "overview";
|
||||
|
||||
type NavWindow = {
|
||||
windowId: string;
|
||||
surfaceId: string;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
foreground: boolean;
|
||||
focused: boolean;
|
||||
menu: WindowMenu | null;
|
||||
lastSubmittedFingerprint: string;
|
||||
};
|
||||
|
||||
const NAVIGATE_TOOLS: ToolSpec[] = [
|
||||
{
|
||||
name: "start_route",
|
||||
description:
|
||||
"Start turn-by-turn navigation to a destination. Give the destination as free text (a place name, business, or address); it is resolved near the user's current location. Returns the resolved destination, distance, and estimated time. If the wrong place was picked, call again with a more specific query.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: { type: "string", description: "Destination to search for, e.g. 'Golden Gate Park' or '410 Townsend St'." },
|
||||
profile: {
|
||||
type: "string",
|
||||
enum: ["driving", "walking", "cycling"],
|
||||
description: "Travel mode (default driving).",
|
||||
},
|
||||
},
|
||||
required: ["query"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
// Under the 15 s host backstop; first GPS fix + two API calls can be slow.
|
||||
timeoutMs: 14_000,
|
||||
},
|
||||
{
|
||||
name: "stop_route",
|
||||
description: "Stop the current navigation session.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
availability: "open",
|
||||
},
|
||||
{
|
||||
name: "route_status",
|
||||
description:
|
||||
"Get the current navigation status: next maneuver, distance to it, remaining distance/time, and ETA.",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
availability: "open",
|
||||
},
|
||||
];
|
||||
|
||||
// Singleton window; navigation state outlives foreground/background flips.
|
||||
let window: NavWindow | null = null;
|
||||
let screenOn = true;
|
||||
|
||||
let phase: NavPhase = "idle";
|
||||
let statusMessage = "";
|
||||
let destinationName = "";
|
||||
let destinationPlace = "";
|
||||
let destination: { longitude: number; latitude: number } | null = null;
|
||||
let profile: RouteProfile = "driving";
|
||||
let follower: RouteFollower | null = null;
|
||||
let progress: RouteProgress | null = null;
|
||||
let lastFix: TrackedLocation | null = null;
|
||||
let lastBearingDeg = 0;
|
||||
let lastRerouteAtMs = 0;
|
||||
let rerouteInFlight = false;
|
||||
/** Bumped on every new route/mode so stale map fetches can be discarded. */
|
||||
let routeGeneration = 0;
|
||||
|
||||
let mapMode: MapMode = "follow";
|
||||
let zoomOffset = 0;
|
||||
let mapImage: GrayImage | null = null;
|
||||
let mapFetchedKey = "";
|
||||
let mapInFlight = false;
|
||||
let mapLastFetchAtMs = 0;
|
||||
let mapLastFetchCenter: [number, number] | null = null;
|
||||
let mapNextRetryAtMs = 0;
|
||||
let mapLastError = "";
|
||||
|
||||
let tickTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
|
||||
|
||||
const tracker = new LocationTracker({
|
||||
onLocation: (fix) => handleFix(fix),
|
||||
onError: (message) => {
|
||||
statusMessage = message;
|
||||
if (phase === "acquiring") phase = "idle";
|
||||
render();
|
||||
},
|
||||
});
|
||||
|
||||
function post(message: WorkerAppReply): void {
|
||||
global.postMessage(message);
|
||||
}
|
||||
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
surfaceId: message.surfaceId,
|
||||
viewportWidth: message.viewport.width,
|
||||
viewportHeight: message.viewport.height,
|
||||
foreground: false,
|
||||
focused: false,
|
||||
menu: null,
|
||||
lastSubmittedFingerprint: "",
|
||||
};
|
||||
post({ type: "set-tools", windowId: message.windowId, tools: NAVIGATE_TOOLS });
|
||||
break;
|
||||
case "close-window":
|
||||
stopNavigation("");
|
||||
window = null;
|
||||
break;
|
||||
case "input":
|
||||
if (!window || window.windowId !== message.windowId) {
|
||||
frameTimings.finishFrame(message.frameId, "discarded: unknown navigate window");
|
||||
break;
|
||||
}
|
||||
window.focused = message.focused;
|
||||
handleInput(window, message.event as DashboardInputEvent, message.frameId);
|
||||
break;
|
||||
case "text-input":
|
||||
// Voice input / typed text sets a destination directly.
|
||||
if (message.text.trim()) {
|
||||
void startNavigation(message.text.trim(), profile).catch(() => {});
|
||||
}
|
||||
break;
|
||||
case "render":
|
||||
if (!window) break;
|
||||
window.focused = message.focused;
|
||||
render();
|
||||
break;
|
||||
case "foreground":
|
||||
if (!window) break;
|
||||
window.foreground = message.foreground;
|
||||
window.focused = message.focused;
|
||||
if (window.foreground) {
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
}
|
||||
break;
|
||||
case "screen":
|
||||
screenOn = message.on;
|
||||
if (screenOn && window?.foreground) {
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
}
|
||||
break;
|
||||
case "tool-call": {
|
||||
const callId = message.callId;
|
||||
Promise.resolve(handleNavigateTool(message.name, message.args))
|
||||
.then((result) => post({ type: "tool-result", callId, result }))
|
||||
.catch((error) =>
|
||||
post({
|
||||
type: "tool-result",
|
||||
callId,
|
||||
result: { ok: false, error: String((error as Error)?.message ?? error) },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Navigation state machine
|
||||
|
||||
async function startNavigation(query: string, requestedProfile: RouteProfile): Promise<string> {
|
||||
if (!isMapboxConfigured()) {
|
||||
statusMessage = "Set a Mapbox token in Settings > API Keys.";
|
||||
phase = "idle";
|
||||
render();
|
||||
throw new Error(statusMessage);
|
||||
}
|
||||
const hadActiveRoute = phase === "navigating" && follower !== null;
|
||||
const previous = {
|
||||
destination,
|
||||
destinationName,
|
||||
destinationPlace,
|
||||
profile,
|
||||
};
|
||||
try {
|
||||
profile = requestedProfile;
|
||||
phase = "acquiring";
|
||||
statusMessage = `Locating you for "${query}"...`;
|
||||
render();
|
||||
ensureTracking();
|
||||
const fix = await waitForFix();
|
||||
|
||||
phase = "routing";
|
||||
statusMessage = `Finding ${query}...`;
|
||||
render();
|
||||
const candidates = await geocodeForward(query, fix, 5);
|
||||
if (!candidates.length) {
|
||||
throw new Error(`No places found matching "${query}".`);
|
||||
}
|
||||
const picked = candidates[0]!;
|
||||
destination = { longitude: picked.longitude, latitude: picked.latitude };
|
||||
destinationName = picked.name;
|
||||
destinationPlace = picked.placeFormatted;
|
||||
|
||||
statusMessage = `Routing to ${picked.name}...`;
|
||||
render();
|
||||
const route = await fetchRoute(fix, destination, profile);
|
||||
adoptRoute(route);
|
||||
if (window) post({ type: "focus-window", windowId: window.windowId });
|
||||
return startSummary(picked, candidates, route);
|
||||
} catch (error) {
|
||||
const message = String((error as Error)?.message ?? error);
|
||||
statusMessage = message;
|
||||
// A failed new destination shouldn't kill guidance that was already
|
||||
// running; fall back to the ongoing route (and its destination, which
|
||||
// the geocode step may have partially overwritten).
|
||||
if (hadActiveRoute) {
|
||||
phase = "navigating";
|
||||
destination = previous.destination;
|
||||
destinationName = previous.destinationName;
|
||||
destinationPlace = previous.destinationPlace;
|
||||
profile = previous.profile;
|
||||
} else {
|
||||
phase = "idle";
|
||||
}
|
||||
stopTrackingIfIdle();
|
||||
render();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function adoptRoute(route: Route): void {
|
||||
follower = new RouteFollower(route);
|
||||
progress = null;
|
||||
phase = "navigating";
|
||||
mapMode = "follow";
|
||||
zoomOffset = 0;
|
||||
statusMessage = "";
|
||||
routeGeneration++;
|
||||
resetMapState();
|
||||
ensureTracking();
|
||||
ensureTickTimer();
|
||||
if (lastFix) handleFix(lastFix);
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
}
|
||||
|
||||
function stopNavigation(finalStatus: string): void {
|
||||
phase = "idle";
|
||||
statusMessage = finalStatus;
|
||||
follower = null;
|
||||
progress = null;
|
||||
destination = null;
|
||||
destinationName = "";
|
||||
destinationPlace = "";
|
||||
routeGeneration++;
|
||||
resetMapState();
|
||||
stopTrackingIfIdle();
|
||||
ensureTickTimer();
|
||||
}
|
||||
|
||||
function handleFix(fix: TrackedLocation): void {
|
||||
lastFix = fix;
|
||||
if (fix.bearingDeg !== null && (fix.speedMps ?? 0) >= BEARING_MIN_SPEED_MPS) {
|
||||
lastBearingDeg = fix.bearingDeg;
|
||||
}
|
||||
for (const waiter of firstFixWaiters.splice(0)) waiter(fix);
|
||||
|
||||
if (phase !== "navigating" || !follower) return;
|
||||
progress = follower.update(fix.longitude, fix.latitude);
|
||||
|
||||
if (progress.arrived) {
|
||||
phase = "arrived";
|
||||
statusMessage = "";
|
||||
stopTrackingIfIdle();
|
||||
ensureTickTimer();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (progress.offRoute) {
|
||||
void maybeReroute(fix);
|
||||
}
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
}
|
||||
|
||||
async function maybeReroute(fix: TrackedLocation): Promise<void> {
|
||||
if (rerouteInFlight || !destination) return;
|
||||
if (Date.now() - lastRerouteAtMs < REROUTE_MIN_INTERVAL_MS) return;
|
||||
rerouteInFlight = true;
|
||||
lastRerouteAtMs = Date.now();
|
||||
statusMessage = "Rerouting...";
|
||||
render();
|
||||
try {
|
||||
const route = await fetchRoute(fix, destination, profile);
|
||||
if (phase === "navigating") adoptRoute(route);
|
||||
} catch (error) {
|
||||
statusMessage = `Reroute failed: ${String((error as Error)?.message ?? error)}`;
|
||||
render();
|
||||
} finally {
|
||||
rerouteInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureTracking(): void {
|
||||
if (!tracker.isRunning()) tracker.start(LOCATION_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function stopTrackingIfIdle(): void {
|
||||
if (phase === "idle" || phase === "arrived") {
|
||||
tracker.stop();
|
||||
firstFixWaiters = [];
|
||||
}
|
||||
}
|
||||
|
||||
function waitForFix(): Promise<TrackedLocation> {
|
||||
if (lastFix && Date.now() - lastFix.timestampMs < 60_000) {
|
||||
return Promise.resolve(lastFix);
|
||||
}
|
||||
return new Promise<TrackedLocation>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
firstFixWaiters = firstFixWaiters.filter((waiter) => waiter !== onFix);
|
||||
reject(new Error("Couldn't get a GPS fix yet; try again in a moment."));
|
||||
}, FIRST_FIX_TIMEOUT_MS);
|
||||
const onFix = (fix: TrackedLocation) => {
|
||||
clearTimeout(timer);
|
||||
resolve(fix);
|
||||
};
|
||||
firstFixWaiters.push(onFix);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureTickTimer(): void {
|
||||
const shouldRun = phase === "navigating";
|
||||
if (shouldRun && tickTimer === null) {
|
||||
tickTimer = setInterval(() => {
|
||||
maybeRefreshMap();
|
||||
render(); // ETA/minute updates; fingerprint dedup keeps the wire quiet.
|
||||
}, 2_000);
|
||||
} else if (!shouldRun && tickTimer !== null) {
|
||||
clearInterval(tickTimer);
|
||||
tickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Map pane
|
||||
|
||||
function resetMapState(): void {
|
||||
mapImage = null;
|
||||
mapFetchedKey = "";
|
||||
mapInFlight = false;
|
||||
mapLastFetchAtMs = 0;
|
||||
mapLastFetchCenter = null;
|
||||
mapNextRetryAtMs = 0;
|
||||
mapLastError = "";
|
||||
}
|
||||
|
||||
function currentPosition(): [number, number] | null {
|
||||
if (progress) return progress.snapped;
|
||||
if (lastFix) return [lastFix.longitude, lastFix.latitude];
|
||||
return null;
|
||||
}
|
||||
|
||||
function currentBearing(): number {
|
||||
if (lastFix && lastFix.bearingDeg !== null && (lastFix.speedMps ?? 0) >= BEARING_MIN_SPEED_MPS) {
|
||||
return lastFix.bearingDeg;
|
||||
}
|
||||
if (lastBearingDeg) return lastBearingDeg;
|
||||
// Fall back to the direction the route heads from here.
|
||||
if (follower && progress) {
|
||||
const slice = follower.routeSliceAround(progress.alongMeters, 0, 120);
|
||||
if (slice.length >= 2) return bearingDegrees(slice[0]!, slice[slice.length - 1]!);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function currentZoom(): number {
|
||||
let zoom: number;
|
||||
if (profile === "walking") {
|
||||
zoom = 16.5;
|
||||
} else if (progress && progress.metersToNextManeuver < 250) {
|
||||
zoom = 16.5;
|
||||
} else if (progress && progress.metersToNextManeuver < 1000) {
|
||||
zoom = 15.5;
|
||||
} else {
|
||||
zoom = 14.5;
|
||||
}
|
||||
return Math.max(11, Math.min(18, zoom + zoomOffset));
|
||||
}
|
||||
|
||||
function metersPerPixel(zoom: number, latitude: number): number {
|
||||
return (156543.03392 * Math.cos((latitude * Math.PI) / 180)) / Math.pow(2, zoom);
|
||||
}
|
||||
|
||||
function desiredMapView(): { camera: StaticMapCamera; key: string; path: Array<[number, number]> } | null {
|
||||
if (mapMode === "overview" && follower) {
|
||||
return {
|
||||
camera: { kind: "auto" },
|
||||
key: `auto|${routeGeneration}`,
|
||||
path: simplifyPath(follower.route.coordinates, 100),
|
||||
};
|
||||
}
|
||||
const position = currentPosition();
|
||||
if (!position) return null;
|
||||
const zoom = currentZoom();
|
||||
const bearing = Math.round(currentBearing() / BEARING_BUCKET_DEG) * BEARING_BUCKET_DEG;
|
||||
const path =
|
||||
follower && progress
|
||||
? simplifyPath(follower.routeSliceAround(progress.alongMeters, 250, 3000), 80)
|
||||
: [];
|
||||
return {
|
||||
camera: { kind: "center", longitude: position[0], latitude: position[1], zoom, bearingDeg: bearing },
|
||||
key: `c|${zoom.toFixed(2)}|${bearing}|${routeGeneration}`,
|
||||
path,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Refetch the map only when meaningfully stale: camera key changed (zoom /
|
||||
* bearing bucket / mode / route), moved a good fraction of the viewport, or
|
||||
* a few seconds passed while moving. Single-flight with failure backoff.
|
||||
*/
|
||||
function maybeRefreshMap(): void {
|
||||
if (!window || !window.foreground || !screenOn) return;
|
||||
if (mapInFlight || Date.now() < mapNextRetryAtMs) return;
|
||||
if (!isMapboxConfigured()) return;
|
||||
const view = desiredMapView();
|
||||
if (!view) return;
|
||||
|
||||
let stale = mapImage === null || view.key !== mapFetchedKey;
|
||||
if (!stale && view.camera.kind === "center" && mapLastFetchCenter) {
|
||||
const moved = haversineMeters(mapLastFetchCenter, [view.camera.longitude, view.camera.latitude]);
|
||||
const viewportMeters = MAP_SIZE * metersPerPixel(view.camera.zoom, view.camera.latitude);
|
||||
if (moved > viewportMeters * MOVE_REFRESH_FRACTION) stale = true;
|
||||
else if (Date.now() - mapLastFetchAtMs > IDLE_REFRESH_MS && moved > IDLE_REFRESH_MIN_MOVE_M) stale = true;
|
||||
}
|
||||
if (!stale) return;
|
||||
|
||||
mapInFlight = true;
|
||||
const generation = routeGeneration;
|
||||
fetchStaticMapGray({
|
||||
camera: view.camera,
|
||||
width: MAP_SIZE,
|
||||
height: MAP_SIZE,
|
||||
routePath: view.path.length >= 2 ? view.path : undefined,
|
||||
})
|
||||
.then((image) => {
|
||||
mapInFlight = false;
|
||||
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
|
||||
boostContrast(image);
|
||||
mapImage = image;
|
||||
mapFetchedKey = view.key;
|
||||
mapLastFetchAtMs = Date.now();
|
||||
mapLastFetchCenter = view.camera.kind === "center" ? [view.camera.longitude, view.camera.latitude] : null;
|
||||
mapLastError = "";
|
||||
render();
|
||||
})
|
||||
.catch((error) => {
|
||||
mapInFlight = false;
|
||||
mapNextRetryAtMs = Date.now() + MAP_RETRY_BACKOFF_MS;
|
||||
mapLastError = String((error as Error)?.message ?? error);
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
/** Keep every Nth point (ends always included) to bound the overlay URL size. */
|
||||
function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[number, number]> {
|
||||
if (path.length <= maxPoints) return path;
|
||||
const step = (path.length - 1) / (maxPoints - 1);
|
||||
const out: Array<[number, number]> = [];
|
||||
for (let i = 0; i < maxPoints; i++) {
|
||||
out.push(path[Math.round(i * step)]!);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Stretch the dark-style render so roads survive 4bpp quantization. */
|
||||
function boostContrast(image: GrayImage): void {
|
||||
for (let i = 0; i < image.pixels.length; i++) {
|
||||
const value = image.pixels[i]!;
|
||||
image.pixels[i] = Math.max(0, Math.min(255, Math.round((value - 12) * 1.7)));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tools
|
||||
|
||||
async function handleNavigateTool(name: string, args: any): Promise<ToolResult> {
|
||||
switch (name) {
|
||||
case "start_route": {
|
||||
const query = String(args?.query ?? "").trim();
|
||||
if (!query) return { ok: false, error: "start_route requires a destination query" };
|
||||
const requested = String(args?.profile ?? "driving");
|
||||
const routeProfile: RouteProfile =
|
||||
requested === "walking" || requested === "cycling" ? requested : "driving";
|
||||
try {
|
||||
const summary = await startNavigation(query, routeProfile);
|
||||
return { ok: true, content: summary };
|
||||
} catch (error) {
|
||||
return { ok: false, error: String((error as Error)?.message ?? error) };
|
||||
}
|
||||
}
|
||||
case "stop_route":
|
||||
if (phase === "idle") return { ok: true, content: "Navigation was not active." };
|
||||
stopNavigation("Navigation stopped.");
|
||||
render();
|
||||
return { ok: true, content: "Navigation stopped." };
|
||||
case "route_status":
|
||||
return { ok: true, content: describeRouteStatus() };
|
||||
default:
|
||||
return { ok: false, error: `Unknown navigate tool: ${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
function startSummary(picked: GeocodeCandidate, candidates: GeocodeCandidate[], route: Route): string {
|
||||
const parts = [
|
||||
`Navigating to ${picked.name}${picked.placeFormatted ? ` (${picked.placeFormatted})` : ""}: ` +
|
||||
`${formatDistance(route.distanceMeters)}, about ${formatDurationLong(route.durationSec)}, ` +
|
||||
`arriving ${formatClock(Date.now() + route.durationSec * 1000)}.`,
|
||||
];
|
||||
const alternates = candidates.slice(1, 3);
|
||||
if (alternates.length) {
|
||||
parts.push(
|
||||
`Other matches: ${alternates
|
||||
.map((c) => `${c.name}${c.placeFormatted ? ` (${c.placeFormatted})` : ""}`)
|
||||
.join("; ")}. Call start_route with a more specific query to pick one of these instead.`,
|
||||
);
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function describeRouteStatus(): string {
|
||||
if (phase === "arrived") return `Arrived at ${destinationName}.`;
|
||||
if (phase !== "navigating" || !follower) return "Navigation is not active.";
|
||||
if (!progress) return `Navigating to ${destinationName}; waiting for a GPS fix.`;
|
||||
const step = follower.route.steps[progress.nextStepIndex]!;
|
||||
return (
|
||||
`Next: ${step.instruction || step.maneuverType} in ${formatDistance(progress.metersToNextManeuver)}. ` +
|
||||
`${formatDistance(progress.remainingMeters)} and ${formatDurationLong(progress.remainingSec)} remaining; ` +
|
||||
`ETA ${formatClock(Date.now() + progress.remainingSec * 1000)}.`
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Input
|
||||
|
||||
function windowMenu(win: NavWindow): WindowMenu {
|
||||
if (!win.menu) {
|
||||
win.menu = new WindowMenu({
|
||||
size: { width: win.viewportWidth, height: win.viewportHeight },
|
||||
paintBase: () => paintContent(win),
|
||||
isFocused: () => win.focused,
|
||||
});
|
||||
}
|
||||
return win.menu;
|
||||
}
|
||||
|
||||
function handleInput(win: NavWindow, event: DashboardInputEvent, frameId: number): void {
|
||||
if (win.menu?.isOpen()) {
|
||||
win.menu
|
||||
.handleInput(event)
|
||||
.catch((error) => console.error(`navigate menu input failed: ${error}`))
|
||||
.then(() => renderAndSubmit(win, frameId));
|
||||
return;
|
||||
}
|
||||
if (event.type === "long-press") {
|
||||
const items = [...defaultWindowMenuItems(win.windowId, post)];
|
||||
if (phase === "navigating" || phase === "arrived") {
|
||||
items.unshift({
|
||||
label: "Stop navigation",
|
||||
onSelect: (ctx: any) => {
|
||||
ctx.stack.pop();
|
||||
stopNavigation("Navigation stopped.");
|
||||
render();
|
||||
},
|
||||
});
|
||||
}
|
||||
windowMenu(win).open(items);
|
||||
renderAndSubmit(win, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type === "double-click") {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate yielded focus");
|
||||
post({ type: "yield-focus", windowId: win.windowId });
|
||||
return;
|
||||
}
|
||||
if (event.type === "click") {
|
||||
if (phase === "navigating") {
|
||||
mapMode = mapMode === "follow" ? "overview" : "follow";
|
||||
resetMapState();
|
||||
maybeRefreshMap();
|
||||
} else if (phase === "arrived") {
|
||||
stopNavigation("");
|
||||
} else {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate ignored click");
|
||||
return;
|
||||
}
|
||||
renderAndSubmit(win, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
if (phase === "navigating" && mapMode === "follow") {
|
||||
zoomOffset = Math.max(-3, Math.min(2, zoomOffset + (event.type === "scroll-up" ? 0.5 : -0.5)));
|
||||
maybeRefreshMap();
|
||||
renderAndSubmit(win, frameId);
|
||||
} else {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate ignored scroll");
|
||||
}
|
||||
return;
|
||||
}
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate ignored input");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Painting
|
||||
|
||||
function paint(win: NavWindow): GrayImage {
|
||||
if (win.menu?.isOpen()) return win.menu.paint();
|
||||
return paintContent(win);
|
||||
}
|
||||
|
||||
function paintContent(win: NavWindow): GrayImage {
|
||||
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
|
||||
if (phase === "idle" || phase === "acquiring" || phase === "routing") {
|
||||
paintIdle(image);
|
||||
} else {
|
||||
paintNavigating(image, win);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
function paintIdle(image: GrayImage): void {
|
||||
image.drawText(mediumFont, 24, 16, "Navigate", 245);
|
||||
const busy = phase !== "idle";
|
||||
const hint = isMapboxConfigured()
|
||||
? "Ask the voice assistant to navigate somewhere, or use Voice input from the long-press menu to say a destination."
|
||||
: "Set a Mapbox token in Settings > API Keys to enable navigation.";
|
||||
image.drawTextWrapped({ font: smallFont, x: 24, y: 64, width: image.width - 48, text: hint, value: 170 });
|
||||
if (statusMessage) {
|
||||
image.drawTextWrapped({
|
||||
font: smallFont,
|
||||
x: 24,
|
||||
y: 130,
|
||||
width: image.width - 48,
|
||||
text: statusMessage,
|
||||
value: busy ? 220 : 190,
|
||||
});
|
||||
}
|
||||
drawFooter(image, `${GESTURE_DOUBLE_CLICK} back`);
|
||||
}
|
||||
|
||||
function paintNavigating(image: GrayImage, win: NavWindow): void {
|
||||
// Map pane (left).
|
||||
if (mapImage) {
|
||||
image.bitBlt(mapImage, 0, 0);
|
||||
if (mapMode === "follow") drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2);
|
||||
} else {
|
||||
image.drawRect(0, 0, MAP_SIZE, MAP_SIZE, 60);
|
||||
const text = mapLastError ? "Map unavailable" : "Loading map...";
|
||||
image.drawText(smallFont, 24, MAP_SIZE / 2 - 8, text, 120);
|
||||
}
|
||||
|
||||
// Guidance panel (right) — its own region so text deltas never overlap the map's.
|
||||
const panelWidth = win.viewportWidth - PANEL_X;
|
||||
if (phase === "arrived") {
|
||||
drawManeuverGlyph(image, PANEL_X + 8, 14, 56, "arrive", "", 245);
|
||||
image.drawText(mediumFont, PANEL_X + 76, 26, "Arrived", 245);
|
||||
image.drawTextWrapped({
|
||||
font: smallFont,
|
||||
x: PANEL_X + 8,
|
||||
y: 84,
|
||||
width: panelWidth - 16,
|
||||
text: destinationName,
|
||||
value: 200,
|
||||
});
|
||||
drawFooter(image, `${GESTURE_CLICK} done ${GESTURE_DOUBLE_CLICK} back`);
|
||||
return;
|
||||
}
|
||||
|
||||
const step = follower && progress ? follower.route.steps[progress.nextStepIndex] : null;
|
||||
if (step && progress) {
|
||||
drawManeuverGlyph(image, PANEL_X + 8, 14, 56, step.maneuverType, step.maneuverModifier, 245);
|
||||
if (step.exit !== null && (step.maneuverType === "roundabout" || step.maneuverType === "rotary")) {
|
||||
image.drawText(smallFont, PANEL_X + 30, 46, String(step.exit), 245);
|
||||
}
|
||||
image.drawText(largeFont, PANEL_X + 76, 24, formatDistanceShort(progress.metersToNextManeuver), 250);
|
||||
image.drawTextWrapped({
|
||||
font: mediumFont,
|
||||
x: PANEL_X + 8,
|
||||
y: 84,
|
||||
width: panelWidth - 16,
|
||||
text: step.instruction || step.name || step.maneuverType,
|
||||
value: 220,
|
||||
});
|
||||
const eta = `${formatDistance(progress.remainingMeters)} · ${formatDurationShort(progress.remainingSec)} · ${formatClock(
|
||||
Date.now() + progress.remainingSec * 1000,
|
||||
)}`;
|
||||
image.drawText(smallFont, PANEL_X + 8, win.viewportHeight - 62, eta, 170);
|
||||
} else {
|
||||
image.drawTextWrapped({
|
||||
font: mediumFont,
|
||||
x: PANEL_X + 8,
|
||||
y: 24,
|
||||
width: panelWidth - 16,
|
||||
text: `Waiting for GPS...`,
|
||||
value: 200,
|
||||
});
|
||||
}
|
||||
if (statusMessage) {
|
||||
image.drawText(smallFont, PANEL_X + 8, win.viewportHeight - 44, statusMessage, 200);
|
||||
}
|
||||
const modeHint = mapMode === "follow" ? "overview" : "follow";
|
||||
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8);
|
||||
}
|
||||
|
||||
/** Position chevron, fixed at the map center (heading-up: it always points up). */
|
||||
function drawChevron(image: GrayImage, cx: number, cy: number): void {
|
||||
// Black halo first so it reads over bright roads.
|
||||
fillTriangle(image, cx, cy - 11, cx - 9, cy + 9, cx + 9, cy + 9, 0);
|
||||
fillTriangle(image, cx, cy - 8, cx - 6, cy + 6, cx + 6, cy + 6, 255);
|
||||
}
|
||||
|
||||
function fillTriangle(image: GrayImage, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, value: number): void {
|
||||
const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2)));
|
||||
const maxY = Math.min(image.height - 1, Math.ceil(Math.max(y0, y1, y2)));
|
||||
for (let y = minY; y <= maxY; y++) {
|
||||
let minX = Number.POSITIVE_INFINITY;
|
||||
let maxX = Number.NEGATIVE_INFINITY;
|
||||
const edges: Array<[[number, number], [number, number]]> = [
|
||||
[[x0, y0], [x1, y1]],
|
||||
[[x1, y1], [x2, y2]],
|
||||
[[x2, y2], [x0, y0]],
|
||||
];
|
||||
for (const [[ax, ay], [bx, by]] of edges) {
|
||||
if ((ay <= y && by >= y) || (by <= y && ay >= y)) {
|
||||
if (Math.abs(by - ay) < 0.0001) {
|
||||
minX = Math.min(minX, ax, bx);
|
||||
maxX = Math.max(maxX, ax, bx);
|
||||
} else {
|
||||
const t = (y - ay) / (by - ay);
|
||||
const x = ax + t * (bx - ax);
|
||||
minX = Math.min(minX, x);
|
||||
maxX = Math.max(maxX, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (minX <= maxX) {
|
||||
image.fillRect(Math.round(minX), y, Math.round(maxX - minX) + 1, 1, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawFooter(image: GrayImage, text: string, x = 16): void {
|
||||
image.drawText(smallFont, x, image.height - 22, text, 115);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Formatting (imperial; matches the rest of the UI)
|
||||
|
||||
function formatDistanceShort(meters: number): string {
|
||||
const feet = meters * 3.28084;
|
||||
if (feet < 900) return `${Math.max(0, Math.round(feet / 50) * 50)} ft`;
|
||||
return `${(feet / 5280).toFixed(1)} mi`;
|
||||
}
|
||||
|
||||
function formatDistance(meters: number): string {
|
||||
const feet = meters * 3.28084;
|
||||
if (feet < 1000) return `${Math.max(0, Math.round(feet / 50) * 50)} ft`;
|
||||
const miles = feet / 5280;
|
||||
return miles >= 10 ? `${Math.round(miles)} mi` : `${miles.toFixed(1)} mi`;
|
||||
}
|
||||
|
||||
function formatDurationShort(seconds: number): string {
|
||||
const minutes = Math.round(seconds / 60);
|
||||
if (minutes < 60) return `${Math.max(1, minutes)} min`;
|
||||
return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function formatDurationLong(seconds: number): string {
|
||||
const minutes = Math.round(seconds / 60);
|
||||
if (minutes < 60) return `${Math.max(1, minutes)} minutes`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
function formatClock(timestampMs: number): string {
|
||||
const date = new Date(timestampMs);
|
||||
let hours = date.getHours();
|
||||
const minutes = String(date.getMinutes()).padStart(2, "0");
|
||||
const meridiem = hours >= 12 ? "PM" : "AM";
|
||||
hours = hours % 12;
|
||||
if (hours === 0) hours = 12;
|
||||
return `${hours}:${minutes} ${meridiem}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Render plumbing
|
||||
|
||||
function render(): void {
|
||||
if (window) renderAndSubmit(window, 0);
|
||||
}
|
||||
|
||||
function renderAndSubmit(win: NavWindow, inputFrameId: number): void {
|
||||
if (!win.foreground && inputFrameId === 0) return;
|
||||
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
|
||||
try {
|
||||
const paintStartedAtMs = Date.now();
|
||||
const image = frameTimings.span(frameId, "paint", () =>
|
||||
frameTimings.runWithFrame(frameId, () => paint(win)),
|
||||
);
|
||||
const paintMs = Date.now() - paintStartedAtMs;
|
||||
const fingerprint = image.fingerprint();
|
||||
if (fingerprint === win.lastSubmittedFingerprint) {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate content unchanged");
|
||||
return;
|
||||
}
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) {
|
||||
frameTimings.finishFrame(frameId, "discarded: no active communicator");
|
||||
return;
|
||||
}
|
||||
const buffer = image.to8bppBuffer();
|
||||
communicator.submitSurfaceFrame(
|
||||
buffer.buffer,
|
||||
win.surfaceId,
|
||||
0,
|
||||
0,
|
||||
image.width,
|
||||
image.height,
|
||||
fingerprint,
|
||||
paintMs,
|
||||
frameId,
|
||||
);
|
||||
win.lastSubmittedFingerprint = fingerprint;
|
||||
} catch (error) {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate render failed");
|
||||
console.error(`navigate worker render failed: ${error}`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user