diff --git a/App_Resources/Android/src/main/AndroidManifest.xml b/App_Resources/Android/src/main/AndroidManifest.xml
index efec7b97..e1d2a210 100644
--- a/App_Resources/Android/src/main/AndroidManifest.xml
+++ b/App_Resources/Android/src/main/AndroidManifest.xml
@@ -25,7 +25,17 @@
-
+
+
+
+
+
+
+
@@ -127,10 +137,40 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CHANGELOG b/CHANGELOG
index 63bf7943..b22efcc3 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,55 @@
# Changelog
+## 0.6.6 - Future
+* Navigate and terminal app: App-specific screen size/position setting
+* Transcribe app: Scrolling; automatic reconnection; insert newlines
+* Notifications: Add notification filters
+* Phone screen preview: Add rotation option; improve landscape layout
+* Add "AI Chat" app (conversational-style use of the voice assistant with hold-to-talk)
+* Add rightness control to the system context menu
+* Messaging in the flasher distinguishes between downgrading from stock firmwares where that's been validated and veresions where it hasn't, and considers 2.2.10 validated
+* Add R1 battery indicator to the top bar
+* Change the styling and add more customization options for battery indicators
+
+## 0.6.5 - 2026-09-04
+* Changed context menu gestures: — for system, ●— for app context menu.
+* System and app context menus show gesture help for switching to the other context menu
+* Move some items from app context menus to the system context menu
+* Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing)
+* Content beneath an open context menu is dimmed
+* Add a keyboard-input button to the phone home screen
+* Add a light sensor demo to the Developer app
+* Move Calculator, Microphones, Nightscout, and Roam apps to Prototypes folder by default
+* Navigate app: Location indicator rotates based on the compass
+* Navigate app: Add saved home/work and recent address settings
+* Navigate app: Darken the map background color
+* EvenHub app: Add New, Search, and Updates tabs
+* Timer app: Fully rewritten, with new better UI
+* Add a teleprompter app
+
+## 0.6.4 - 2026-09-02
+* Context menus are centered and include window title
+* Long-press and short-then-long with a context menu open switches between context menus
+* Developer speed metrics include bytes/frame
+* The custom firmware uninstaller flashes 2.2.9.22, not 2.2.6.10
+* Compass app: Increase sample rate from 1/s to ~3/s
+* Compass app: Handle the distinction between true north and magnetic north
+* EvenHub compass readings now include calibrated magnetic, declination and true headings
+* Files app: Viewing image files gamma-corrects and dithers them
+* Watch app: Uses ambient mode so the watch no longer blurs when idle
+* Watch app: Fix flicker on waking the watch
+* Watch app: Tapping the idle watch to wake it counts as a tap on the pad
+* Watch app: Remove a number of unfinished prototype features
+* Firmware flasher checks for glasses battery>30% before starting
+* Fix a problem in 0.6.3 where it would abort before starting a custom firmware install with a checksum error
+
+## 0.6.3 - 2026-09-01
+* Update custom firmware base version from 2.2.6 to 2.2.9
+* Add support for the short-then-long-press gesture
+* Update EvenHub compatibility layer to include new functions from 0.0.14
+* EvenHub permissions dialog scrolls when it overflows
+* Add "Show BLE bandwidth usage" option to developer settings
+
## 0.6.2 - 2026-08-30
* Preview Only mode works
* Voice input uses phone mic in preview mode
diff --git a/README.md b/README.md
index 75dd4dcd..cb4af4c2 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ User-facing documentation lives at https://faceclaw.org/.



-
+
## Installation
@@ -81,23 +81,14 @@ import it into the new version.
* **Power management**: the glasses go to sleep properly when the screen is
off, and wake when you double-tap the ring or speak the wakeword, allowing
battery life similar to the stock Even app.
- * **Connection management** with auto-reconnect, and autodetection of
- conflict with the official Even Realities app.
- * **A Wear OS watch app** that replaces (and outdoes) the R1 ring: tap,
+ * **A Wear OS watch app** that complements (or replaces) the R1 ring: tap,
swipe, hold and crown gestures, side buttons, app launching and window
switching, voice or keyboard queries to the assistant with the reply on
your wrist, typing into apps, and glasses status/lock/display control.
- * **On-phone screen mirroring with touch control**: tap what you see on the
- mirror (sidebar icons, launcher cells), or use the phone's own touchpad,
- d-pad and Back/Menu buttons — the same spatial scheme as the watch — plus a
- compact ring simulator. A display-mode picker (576×288 band, 576×480 tall,
- or the full 640×480 panel with an auto-hiding sidebar) and a brightness
- slider with an Auto toggle sit beside the mirror.
- * **Bluetooth pairing** that scans for nearby glasses and identifies each
- pair before connecting: model, frame shape, and colour decoded from the
- advertised serial (with product photos), left and right arms matched to
- each other by that serial, an estimated distance so the pair in your hand
- sorts first, and the optional R1 ring.
+ * **On-phone screen mirroring**: Shows the glasses screen contents and
+ provides a phone-screen touch area equivalent to the R1 ring or the Wear OS
+ watch app. This can also be used to try out the app without pairing or
+ flashing a real pair of glasses.
* **Dual-language NativeScript architecture**, with Java for the
multithreaded Android API and bluetooth stack bits, Typescript for the bits
you want to hack on.
diff --git a/app/app.css b/app/app.css
index 72804c5e..faa23972 100644
--- a/app/app.css
+++ b/app/app.css
@@ -98,6 +98,13 @@ Button.-primary {
font-size: 13;
}
+/* Developer BLE-bandwidth totals overlaid on the main page's bottom edge. */
+.ble-bandwidth-indicator {
+ color: #777777;
+ font-size: 12;
+ padding: 2 8;
+}
+
/*
* Stands in for the lens preview when showing it would be misleading (silent
* mode, or a disconnect explained by a flat battery). Sized by the view model
@@ -175,11 +182,12 @@ Button.-primary {
background-color: #424242;
color: #ffffff;
}
-/* The wakeword button at the tab bar's right edge: icon-only, narrower than
- * the tabs, and never in the selected state (it isn't a tab). It is a
- * button-styled GridLayout (Buttons can't hold images), so it borrows the
- * .tab-button look and adds the elevation MaterialButtons get for free. */
-.tab-mic-button {
+/* The wakeword and keyboard buttons at the tab bar's right edge: icon-only,
+ * narrower than the tabs, and never in the selected state (they aren't tabs).
+ * Each is a button-styled GridLayout (Buttons can't hold images), so it
+ * borrows the .tab-button look and adds the elevation MaterialButtons get for
+ * free. */
+.tab-icon-button {
width: 56;
/* The real MaterialButtons render 48dp tall inside a 60dp layout box (6dp
* insets top and bottom); the margins and explicit height reproduce that.
@@ -189,11 +197,32 @@ Button.-primary {
margin: 6 2;
android-elevation: 2;
}
-.tab-mic-icon {
+.tab-icon {
height: 20;
tint-color: #333333;
}
-.ns-dark .tab-mic-icon {
+/* Landscape uses the full page height and a shared left edge for tabs/pad. */
+.landscape-layout .remote-controls {
+ margin: 0;
+}
+.landscape-layout .controls-tab-bar {
+ margin-bottom: 2;
+}
+.landscape-layout .tab-button {
+ margin-left: 1;
+ margin-right: 1;
+ min-width: 0;
+}
+.landscape-layout .tab-button[col="0"] {
+ margin-left: 0;
+}
+.landscape-layout .tab-icon-button {
+ width: 48;
+}
+.landscape-layout .tab-icon-button[col="4"] {
+ margin-right: 0;
+}
+.ns-dark .tab-icon {
tint-color: #cccccc;
}
.ns-dark .tab-button {
diff --git a/app/app.ts b/app/app.ts
index b1f9e59b..7a2f44f9 100644
--- a/app/app.ts
+++ b/app/app.ts
@@ -7,9 +7,11 @@ purpose of the file is to pass control to the app’s first module.
import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents'
import { installNativeUserAgent } from './util/http'
+import { registerPhoneRotation } from './native/phone-rotation'
installNativeUserAgent()
registerShareIntentHandler()
+registerPhoneRotation()
Application.run({ moduleName: 'app-root' })
diff --git a/app/apps/ai-chat/ai-chat-app.ts b/app/apps/ai-chat/ai-chat-app.ts
new file mode 100644
index 00000000..195477a2
--- /dev/null
+++ b/app/apps/ai-chat/ai-chat-app.ts
@@ -0,0 +1,166 @@
+import { GrayImage, type UiFont } from "../../graphics/image";
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { truncateText, wrapText } from "../../graphics/textwrap";
+import { ASSISTANT_MODEL_VALUES, assistantModelLabel, resolveAssistantModel } from "../../assistant/models";
+import type { AssistantTranscriptEntry } from "../../assistant/session";
+import type { AssistantConversations, ReasoningLevel } from "../../assistant/conversations";
+import { anthropicApiKeySetting, assistantBackendSetting, openAiApiKeySetting } from "../../ui/dashboard-settings";
+import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_LONG_PRESS, gestureHints, type InputEvent } from "../../ui/gestures";
+import type { Layer, LayerContext } from "../../ui/layers";
+import type { MenuItem } from "../../ui/menu";
+import { WindowMenuLayer } from "../../ui/window-menu";
+import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
+import { shell } from "../../ui/shell/shell";
+import { VoiceDraft } from "./voice-draft";
+
+class AiChatLayer implements Layer {
+ readonly acceptsDirectional = true;
+ private firstLine: number | null = null; // null follows the streaming tail
+ private maxFirstLine = 0;
+ private selectedId = "";
+ private requestRender = () => {};
+ private readonly wrappedEntries = new WeakMap();
+ readonly draft: VoiceDraft;
+
+ constructor(private readonly conversations: AssistantConversations, options: InProcessAppOptions) {
+ this.draft = new VoiceDraft(options.actions, () => shell.prepareChatVoiceCapture(),
+ () => this.requestRender(), (text) => this.send(text));
+ }
+ start(render: () => void): () => void {
+ this.requestRender = render;
+ return this.conversations.onChanged(() => render());
+ }
+ send(text: string): void {
+ this.firstLine = null;
+ shell.sendToAssistant(text, false);
+ }
+ paint(ctx: LayerContext): GrayImage {
+ const size = ctx.stack.getBaseSize();
+ const image = new GrayImage(size.width, size.height);
+ const font = getDefaultSmallFont();
+ const step = font.lineHeight + 3;
+ const left = 12;
+ const width = size.width - 28;
+ const record = this.conversations.current();
+ if (this.selectedId !== record.id) { this.selectedId = record.id; this.firstLine = null; }
+ const transcript = record.session?.transcript ?? record.history?.transcript ?? [];
+ const title = this.conversations.title();
+ image.drawText(font, left, 6, truncateText(font, title, width), 180);
+ const label = assistantBackendSetting.get() === "external" ? "External agent" :
+ `${assistantModelLabel(record.model)} · ${record.reasoning === "default" ? "default reasoning" : record.reasoning}`;
+ const footer = wrapText(font, `${label} ${gestureHints([
+ [GESTURE_CLICK, "menu"], [GESTURE_DOUBLE_CLICK, "back"], [GESTURE_LONG_PRESS, "hold to talk"],
+ ])}`, width);
+ const footerY = size.height - step * footer.length;
+ const footerTop = footerY - step * 3 - 12;
+ const historyTop = step + 16;
+ const visible = Math.max(1, Math.floor((footerTop - historyTop - 8) / step));
+ const lines: { text: string; color: number }[] = [];
+ for (const entry of transcript) {
+ if (!entry.text) continue;
+ let wrapped = this.wrappedEntries.get(entry);
+ if (!wrapped || wrapped.font !== font || wrapped.width !== width || wrapped.text !== entry.text) {
+ wrapped = { font, width, text: entry.text,
+ lines: wrapText(font, `${entry.role === "user" ? "You" : "AI"}: ${entry.text}`, width - 8) };
+ this.wrappedEntries.set(entry, wrapped);
+ }
+ for (const text of wrapped.lines) {
+ lines.push({ text, color: entry.role === "user" ? 175 : 245 });
+ }
+ lines.push({ text: "", color: 0 });
+ }
+ if (!lines.length) lines.push({ text: "Hold to talk to your assistant.", color: 175 },
+ { text: "Voice and chat share this conversation.", color: 150 });
+ this.maxFirstLine = Math.max(0, lines.length - visible);
+ const first = this.firstLine === null ? this.maxFirstLine : Math.min(this.firstLine, this.maxFirstLine);
+ for (let row = 0; row < visible; row++) {
+ const line = lines[first + row];
+ if (line) image.drawText(font, left, historyTop + row * step, line.text, line.color);
+ }
+ if (this.maxFirstLine > 0) {
+ const track = visible * step;
+ const thumb = Math.max(8, Math.floor(track * visible / lines.length));
+ image.fillRect(size.width - 5, historyTop + Math.floor((track - thumb) * first / this.maxFirstLine), 2, thumb, 110);
+ }
+ image.fillRect(left, footerTop, width, 1, 65);
+ const state = this.draft.active ? this.draft.status : record.session?.status || this.draft.status;
+ if (state) image.drawText(font, left, footerTop + 5, truncateText(font, state, width), 160);
+ const pending = wrapText(font, this.draft.text || (this.draft.active ? "Listening..." : "Hold to speak; release to send"), width);
+ pending.slice(-2).forEach((text, i) => image.drawText(font, left, footerTop + step * (i + 1) + 5, text, 220));
+ footer.forEach((text, i) => image.drawText(font, left + width - font.measureText(text), footerY + i * step, text, 120));
+ return image;
+ }
+ handleInput(event: InputEvent): void {
+ switch (event.type) {
+ case "scroll-up": case "swipe-up":
+ this.firstLine = Math.max(0, (this.firstLine ?? this.maxFirstLine) - 3); return;
+ case "scroll-down": case "swipe-down": {
+ const next = (this.firstLine ?? this.maxFirstLine) + 3;
+ this.firstLine = next >= this.maxFirstLine ? null : next; return;
+ }
+ case "long-press":
+ if (!this.conversations.current().session?.isTurnActive()) {
+ if (!shell.isAssistantAvailable()) { shell.showAlert("Set an API key or download the on-phone model in Settings."); return; }
+ void this.draft.start();
+ }
+ return;
+ case "long-press-release": this.draft.release(); return;
+ case "double-click": this.draft.cancel(); shell.yieldFocusToSidebar(); return;
+ }
+ }
+ menuItems(): MenuItem[] {
+ const record = this.conversations.current();
+ const busy = () => this.draft.active || Boolean(record.session?.isTurnActive());
+ const external = assistantBackendSetting.get() === "external";
+ const submenu = (ctx: LayerContext, title: string, items: MenuItem[]) => ctx.stack.push(new WindowMenuLayer(title, items, true));
+ return [
+ ...(external ? [{ label: "Sessions and model managed by bridge", disabled: true, onSelect: () => {} }] : []),
+ { label: "New session", disabled: () => external || busy(), onSelect: (ctx) => {
+ if (this.conversations.create()) ctx.stack.clearToBase();
+ } },
+ { label: "Switch session", disabled: () => external || busy(), onSelect: (ctx) => submenu(ctx, "Sessions",
+ [...this.conversations.list()].reverse().map((item) => ({
+ label: `${item.id === record.id ? "✓ " : ""}${this.conversations.title(item)}`,
+ onSelect: (ctx) => { if (this.conversations.select(item.id)) ctx.stack.clearToBase(); },
+ }))) },
+ { label: `Model: ${assistantModelLabel(record.model)}`, disabled: () => external || busy(), onSelect: (ctx) => submenu(ctx, "Model",
+ ASSISTANT_MODEL_VALUES.map((model) => ({
+ label: `${model === record.model ? "✓ " : ""}${assistantModelLabel(model)}`,
+ disabled: () => !this.conversations.available(model, record.reasoning),
+ onSelect: (ctx) => { if (this.conversations.configure(model, record.reasoning)) ctx.stack.clearToBase(); },
+ }))) },
+ { label: `Reasoning: ${record.reasoning}`, disabled: () => {
+ const llm = resolveAssistantModel(record.model, { anthropic: anthropicApiKeySetting.get(), openai: openAiApiKeySetting.get() });
+ return external || busy() || !llm?.effort;
+ }, onSelect: (ctx) => submenu(ctx, "Reasoning", (["default", "low", "medium", "high"] as ReasoningLevel[]).map((reasoning) => ({
+ label: `${reasoning === record.reasoning ? "✓ " : ""}${reasoning === "default" ? "Model default" : reasoning}`,
+ onSelect: (ctx) => { if (this.conversations.configure(record.model, reasoning)) ctx.stack.clearToBase(); },
+ }))) },
+ ...(record.session?.isTurnActive() ? [{ label: "Cancel response", onSelect: (ctx: LayerContext) => {
+ record.session?.cancel(); ctx.stack.clearToBase();
+ } }] : []),
+ ];
+ }
+}
+
+export function createAiChatWindow(options: InProcessAppOptions): InProcessWindow {
+ const layer = new AiChatLayer(shell.getAssistantConversations(), options);
+ let unsubscribe = () => {};
+ const app = createInProcessWindow({
+ ...options,
+ appId: "ai-chat", windowId: "ai-chat", title: "AI Chat", iconLetter: "AI", icon: "message-circle", closeable: true,
+ baseLayer: layer, holdToTalk: true,
+ isVoiceCapturing: () => layer.draft.active,
+ onSystemMenuOpened: () => layer.draft.cancel(),
+ onAppMenuOpened: () => layer.draft.cancel(),
+ setScreenOn: (on) => { if (!on) layer.draft.cancel(); },
+ setSurfaceVisible: (visible) => { if (!visible) layer.draft.cancel(); options.setSurfaceVisible(visible); },
+ menuItems: () => layer.menuItems(),
+ receiveTextInput: (text) => { if (!layer.draft.active) layer.send(text); },
+ onClosed: () => { unsubscribe(); layer.draft.cancel(); options.onClosed(); },
+ });
+ unsubscribe = layer.start(app.requestRender);
+ return app;
+}
diff --git a/app/apps/ai-chat/index.ts b/app/apps/ai-chat/index.ts
new file mode 100644
index 00000000..0ac4210a
--- /dev/null
+++ b/app/apps/ai-chat/index.ts
@@ -0,0 +1,10 @@
+import type { AppDefinition } from "../app-definition";
+import { createAiChatWindow } from "./ai-chat-app";
+
+const aiChatApp: AppDefinition = {
+ appId: "ai-chat",
+ title: "AI Chat",
+ icon: "message-circle",
+ launch: (ctx) => ctx.launchInProcessApp("ai-chat", "window:ai-chat", createAiChatWindow),
+};
+export default aiChatApp;
diff --git a/app/apps/ai-chat/voice-draft.ts b/app/apps/ai-chat/voice-draft.ts
new file mode 100644
index 00000000..0cb6854c
--- /dev/null
+++ b/app/apps/ai-chat/voice-draft.ts
@@ -0,0 +1,125 @@
+import { voiceControlBridge } from "../../native/voice-control";
+import { voiceActivity } from "../../ui/shell/voice-activity";
+import type { LayerActions } from "../../ui/layers";
+
+/** One hold/release cycle. Async startup and trailing cloud finals belong to this cycle only. */
+export class VoiceDraft {
+ phase: "idle" | "preparing" | "listening" | "finishing" = "idle";
+ text = "";
+ status = "";
+ private committed = "";
+ private live = "";
+ private generation = 0;
+ private started = false;
+ private ownsVoiceActivity = false;
+ private starting = false;
+ private unsubscribe: (() => void)[] = [];
+ private timer: ReturnType | null = null;
+
+ constructor(
+ private readonly actions: Pick,
+ private readonly prepare: () => Promise,
+ private readonly changed: () => void,
+ private readonly send: (text: string) => void,
+ ) {}
+
+ get active(): boolean { return this.phase !== "idle" || this.starting; }
+
+ async start(): Promise {
+ if (this.active) return;
+ const generation = ++this.generation;
+ this.text = this.committed = this.live = "";
+ this.phase = "preparing";
+ this.status = "Preparing microphone...";
+ this.changed();
+ try {
+ const ready = await this.prepare();
+ if (generation !== this.generation) return;
+ if (!ready) { this.cancel("Microphone unavailable"); return; }
+ this.phase = "listening";
+ this.status = "Listening... release to send";
+ this.ownsVoiceActivity = true;
+ voiceActivity.setActive(true);
+ this.unsubscribe.push(voiceControlBridge.onTranscript((event) => {
+ if (!this.active || generation !== this.generation) return;
+ if (event.isFinal) {
+ const text = event.text.trim();
+ if (text) this.committed = [this.committed, text].filter(Boolean).join(" ");
+ this.live = "";
+ } else this.live = event.text.trim();
+ this.text = [this.committed, this.live].filter(Boolean).join(" ");
+ if (event.isFinal && this.phase === "finishing") this.finish();
+ else this.changed();
+ }));
+ // onStatus immediately replays the previous capture's status.
+ let subscribed = false;
+ this.unsubscribe.push(voiceControlBridge.onStatus(({ status }) => {
+ if (!subscribed) return;
+ if (generation !== this.generation || !this.active) return;
+ if (/ignored|failed|error|denied/i.test(status)) this.cancel(status);
+ }));
+ subscribed = true;
+ if (generation !== this.generation) return;
+ this.starting = true;
+ this.changed();
+ await this.actions.startVoiceCapture();
+ this.starting = false;
+ if (generation !== this.generation) {
+ await this.actions.stopVoiceCapture();
+ this.changed();
+ return;
+ }
+ this.started = true;
+ if (this.isFinishing()) this.stopAndFinalize();
+ } catch (error) {
+ this.starting = false;
+ if (generation === this.generation) this.cancel(`Microphone: ${String(error)}`);
+ }
+ }
+
+ private isFinishing(): boolean { return this.phase === "finishing"; }
+
+ release(): void {
+ if (this.phase === "preparing") { this.cancel(); return; }
+ if (this.phase !== "listening") return;
+ this.phase = "finishing";
+ this.status = "Finishing transcription...";
+ this.changed();
+ if (!this.starting) this.stopAndFinalize();
+ }
+
+ private stopAndFinalize(): void {
+ // Install fallback first: stop may synchronously deliver the final.
+ this.timer = setTimeout(() => this.finish(), 1500);
+ if (this.started) {
+ this.started = false;
+ void Promise.resolve(this.actions.stopVoiceCapture()).catch((error) => this.cancel(String(error)));
+ }
+ }
+
+ private finish(): void {
+ if (this.phase !== "finishing") return;
+ const text = this.text.trim();
+ this.cancel(text ? "" : "No speech detected");
+ if (text) this.send(text);
+ }
+
+ cancel(status = ""): void {
+ ++this.generation;
+ this.phase = "idle";
+ this.status = status;
+ this.text = this.live = this.committed = "";
+ if (this.timer !== null) clearTimeout(this.timer);
+ this.timer = null;
+ for (const unsubscribe of this.unsubscribe.splice(0)) unsubscribe();
+ if (this.started) {
+ this.started = false;
+ void Promise.resolve(this.actions.stopVoiceCapture()).catch(() => {});
+ }
+ if (this.ownsVoiceActivity) {
+ this.ownsVoiceActivity = false;
+ voiceActivity.setActive(false);
+ }
+ this.changed();
+ }
+}
diff --git a/app/apps/all-apps.ts b/app/apps/all-apps.ts
index 96982703..07b6dbb4 100644
--- a/app/apps/all-apps.ts
+++ b/app/apps/all-apps.ts
@@ -1,4 +1,5 @@
import { type AppDefinition } from "./app-definition";
+import aiChatApp from "./ai-chat";
import launcherApp from "./launcher";
import timerApp from "./timer";
import calculatorApp from "./calculator";
@@ -7,6 +8,7 @@ import filesApp from "./files";
import musicApp from "./music";
import nightscoutApp from "./nightscout";
import transcribeApp from "./transcribe";
+import teleprompterApp from "./teleprompter";
import microphonesApp from "./microphones";
import notificationsApp from "./notifications";
import calendarApp from "./calendar";
@@ -29,6 +31,7 @@ import settingsApp from "./settings";
*/
export const ALL_APPS: readonly AppDefinition[] = [
launcherApp,
+ aiChatApp,
timerApp,
calculatorApp,
terminalApp,
@@ -36,6 +39,7 @@ export const ALL_APPS: readonly AppDefinition[] = [
musicApp,
nightscoutApp,
transcribeApp,
+ teleprompterApp,
microphonesApp,
notificationsApp,
calendarApp,
diff --git a/app/apps/blocks/blocks-app.worker.ts b/app/apps/blocks/blocks-app.worker.ts
index 4c9b270e..4a5ec5f1 100644
--- a/app/apps/blocks/blocks-app.worker.ts
+++ b/app/apps/blocks/blocks-app.worker.ts
@@ -6,18 +6,19 @@
* Controls (in play): scroll moves the piece, click rotates, long-press hard
* drops, double-click pauses. Watch swipes are spatial: left/right move,
* up rotates, down hard-drops. Paused: click resumes, double-click yields
- * focus, long-press opens the window menu.
+ * focus, tap-then-hold opens the window menu.
*/
import "@nativescript/core/globals";
import { GrayImage } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
+import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { type MenuItem } from "../../ui/menu";
+import { WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import {
directionalFallback,
@@ -136,12 +137,13 @@ type GamePhase = "playing" | "paused" | "game-over";
type BlocksWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
/** Whether this window is the shell's input target (pushed with each message). */
focused: boolean;
- /** Long-press window menu; created on first open. */
+ /** Tap-then-hold window menu; created on first open. */
menu: WindowMenu | null;
phase: GamePhase;
/** Locked cells; 0 = empty, otherwise the piece's shade byte. */
@@ -181,6 +183,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
const window: BlocksWindow = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -285,9 +288,9 @@ function playSfx(window: BlocksWindow, steps: Step[]): void {
}
}
-/** The window's long-press menu (sound toggle + default entries). */
-function openWindowMenu(window: BlocksWindow): void {
- windowMenu(window).open([
+/** The window's context menu (sound toggle), offered while paused or over; playing keeps long-press for hard drop. */
+function windowMenuItems(window: BlocksWindow): MenuItem[] {
+ return [
{
label: window.soundOn ? "Sound: on" : "Sound: off",
onSelect: (ctx) => {
@@ -296,13 +299,17 @@ function openWindowMenu(window: BlocksWindow): void {
if (window.soundOn) playSfx(window, SFX_RESUME);
},
},
- ...defaultWindowMenuItems(window.windowId, post),
- ]);
+ ];
}
function windowMenu(window: BlocksWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
+ windowId: window.windowId,
+ post,
+ title: () => window.title,
+ items: () => (window.phase === "playing" ? [] : windowMenuItems(window)),
+ claimsLongPress: () => window.phase === "playing",
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
@@ -353,6 +360,10 @@ function handlePlayingInput(window: BlocksWindow, event: InputEvent, frameId: nu
case "long-press":
hardDrop(window);
break;
+ case "short-then-long-press":
+ // No context menu mid-game, so this opens the system menu instead.
+ windowMenu(window).open();
+ break;
case "double-click":
window.phase = "paused";
updateTickTimer(window);
@@ -378,8 +389,8 @@ function handleIdleInput(window: BlocksWindow, event: InputEvent, frameId: numbe
frameTimings.finishFrame(frameId, "discarded: blocks yielded focus");
post({ type: "yield-focus", windowId: window.windowId });
return;
- case "long-press":
- openWindowMenu(window);
+ case "short-then-long-press":
+ windowMenu(window).open();
break;
default:
frameTimings.finishFrame(frameId, "discarded: blocks ignored input");
@@ -554,10 +565,7 @@ function updateTickTimer(window: BlocksWindow): void {
}
function paint(window: BlocksWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- return singlePlane(paintContent(window));
+ return windowMenu(window).paint();
}
function paintContent(window: BlocksWindow): GrayImage {
diff --git a/app/apps/calculator/calculator-app.ts b/app/apps/calculator/calculator-app.ts
index 7aaad25a..53b68053 100644
--- a/app/apps/calculator/calculator-app.ts
+++ b/app/apps/calculator/calculator-app.ts
@@ -1,5 +1,5 @@
/**
- * Calculator window wiring: the in-process window, its long-press menu (mode
+ * Calculator window wiring: the in-process window, its context menu (mode
* follow-ups, clear, settings), the assistant tools, and the voice/text
* plumbing into the layer.
*
diff --git a/app/apps/compass/calibration-layer.ts b/app/apps/compass/calibration-layer.ts
index e75d505a..55acb41d 100644
--- a/app/apps/compass/calibration-layer.ts
+++ b/app/apps/compass/calibration-layer.ts
@@ -1,7 +1,11 @@
/**
* The compass calibration screen: a crosshair the wearer aims at a landmark
- * of known heading, plus raw/offset/calibrated readouts. Swipe adjusts the
- * offset by 1°, double-tap returns to the compass.
+ * of known heading, plus raw/offset/declination/calibrated readouts. Swipe
+ * adjusts the offset by 1°, double-tap returns to the compass.
+ *
+ * The landmark's heading must be in the frame the compass is showing: aiming
+ * at a true heading in true mode leaves the wearer-fit offset free of
+ * declination, which is what lets the calibration survive travel.
*/
import { GrayImage } from "../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
@@ -10,18 +14,16 @@ import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { lineStep } from "../../ui/metrics";
import { screenCenterInViewportX } from "../../ui/shell/geometry";
-import {
- formatOffset,
- getCompassOffset,
- markCompassCalibrated,
- normalizeHeading,
- setCompassOffset,
-} from "./calibration";
+import { formatOffset, getCompassOffset, markCompassCalibrated, setCompassOffset } from "./calibration";
+import { resolveHeading, type NorthReference } from "./heading";
-const INSTRUCTIONS =
+const INSTRUCTIONS_PREAMBLE =
"This compass uses the magnetometer in the right arm of the glasses; depending how it rests on your head, "
- + "it may be slightly off. To calibrate, look at a distant object or down a street where you know the true "
- + "compass heading, then adjust the calibration offset below";
+ + "it may be slightly off. To calibrate, look at a distant object or down a street where you know the ";
+const INSTRUCTIONS_BY_FRAME: Record = {
+ true: "true compass heading (as shown on a map), then adjust the calibration offset below",
+ magnetic: "magnetic compass heading (as read by another compass), then adjust the calibration offset below",
+};
/** Margins around the instruction paragraph. */
const TEXT_PADDING_X = 16;
@@ -40,7 +42,12 @@ export class CompassCalibrationLayer implements Layer {
const medium = getDefaultMediumFont();
const smallStep = lineStep(small);
- const lines = wrapText(small, INSTRUCTIONS, width - TEXT_PADDING_X * 2);
+ const raw = this.getRawHeading();
+ const resolved = raw === null ? null : resolveHeading(raw);
+ // Before the first reading there is no frame to name yet; the true-mode
+ // wording is the default and the readout will correct it once data arrives.
+ const frame = resolved?.frame ?? "true";
+ const lines = wrapText(small, INSTRUCTIONS_PREAMBLE + INSTRUCTIONS_BY_FRAME[frame], width - TEXT_PADDING_X * 2);
for (let i = 0; i < lines.length; i++) {
image.drawText(small, TEXT_PADDING_X, TEXT_PADDING_TOP + i * smallStep, lines[i]!, 190);
}
@@ -49,13 +56,20 @@ export class CompassCalibrationLayer implements Layer {
// Readouts along the bottom: dim label over a bright value, in thirds.
const valueTop = height - medium.lineHeight;
const labelTop = valueTop - small.lineHeight;
- const raw = this.getRawHeading();
- const offset = getCompassOffset();
const columns: Array<[string, string]> = [
["Raw", raw === null ? "--°" : `${Math.round(raw)}°`],
- ["Offset", formatOffset(offset)],
- ["Calibrated", raw === null ? "--°" : `${Math.round(normalizeHeading(raw + offset))}°`],
+ ["Offset", formatOffset(getCompassOffset())],
];
+ // Declination is only part of the sum in true mode, so only show it then;
+ // in magnetic mode it would be a number that changes nothing on screen.
+ if (frame === "true") {
+ const declination = resolved?.declinationDegrees ?? null;
+ columns.push(["Declination", declination === null ? "--°" : formatOffset(Math.round(declination))]);
+ }
+ columns.push([
+ frame === "true" ? "True" : "Magnetic",
+ resolved === null ? "--°" : `${Math.round(resolved.displayDegrees)}°`,
+ ]);
const columnWidth = width / columns.length;
for (let i = 0; i < columns.length; i++) {
const [label, value] = columns[i]!;
diff --git a/app/apps/compass/compass-app.ts b/app/apps/compass/compass-app.ts
index 16bdf099..a0f75e18 100644
--- a/app/apps/compass/compass-app.ts
+++ b/app/apps/compass/compass-app.ts
@@ -7,6 +7,7 @@ import {
addCompassListener,
setCompassEnabled,
type CompassEvent,
+ type CompassDiagnostics,
} from "../../native/compass";
import { wrapText } from "../../graphics/textwrap";
import { type InputEvent } from "../../ui/gestures";
@@ -20,8 +21,12 @@ import {
type InProcessWindow,
} from "../../ui/shell/in-process-window";
import { shell } from "../../ui/shell/shell";
-import { calibrateHeading, isCompassCalibrated, normalizeHeading } from "./calibration";
+import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
+import { isCompassCalibrated, normalizeHeading } from "./calibration";
import { CompassCalibrationLayer } from "./calibration-layer";
+import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination";
+import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading";
+import { compassDebugLines, isCompassDebugEnabled, setCompassDebugEnabled } from "./debug";
export const COMPASS_WINDOW_ID = "compass";
export const COMPASS_SURFACE_ID = "window:compass";
@@ -92,19 +97,56 @@ const WALL_LIT = 62;
class CompassLayer implements Layer {
private rawHeading: number | null = null;
+ private diagnostics: CompassDiagnostics | null = null;
/** A firmware calibration message, shown until the next heading arrives. */
private firmwareStatus: string | null = null;
private enabled = false;
private removed = false;
private timer: ReturnType | null = null;
private unsubscribe: (() => void) | null = null;
+ private unsubscribeDeclination: (() => void) | null = null;
+ private requestingPermission = false;
+ private background: { key: string; image: GrayImage } | null = null;
constructor(private readonly requestRender: () => void) {}
start(): void {
this.unsubscribe = addCompassListener((event) => this.onCompassEvent(event));
+ this.unsubscribeDeclination = onDeclinationChanged(() => this.requestRender());
this.timer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
this.reconcile();
+ this.ensureDeclination();
+ }
+
+ /**
+ * True north needs the phone's location. Ask for it the way Weather does,
+ * on opening, but only while the wearer actually wants true north: a
+ * magnetic-mode compass has no business raising a permission prompt.
+ */
+ private ensureDeclination(): void {
+ if (getNorthReference() !== "true") return;
+ if (hasLocationPermission()) {
+ refreshDeclination();
+ return;
+ }
+ if (this.requestingPermission) return;
+ this.requestingPermission = true;
+ void ensureLocationPermission().then((granted) => {
+ this.requestingPermission = false;
+ if (granted) refreshDeclination();
+ this.requestRender();
+ });
+ }
+
+ toggleNorthReference(): void {
+ setNorthReference(getNorthReference() === "true" ? "magnetic" : "true");
+ this.ensureDeclination();
+ this.requestRender();
+ }
+
+ toggleDebugInfo(): void {
+ setCompassDebugEnabled(!isCompassDebugEnabled());
+ this.requestRender();
}
stop(): void {
@@ -114,6 +156,8 @@ class CompassLayer implements Layer {
this.timer = null;
this.unsubscribe?.();
this.unsubscribe = null;
+ this.unsubscribeDeclination?.();
+ this.unsubscribeDeclination = null;
if (this.enabled) setCompassEnabled(false);
this.enabled = false;
}
@@ -132,8 +176,11 @@ class CompassLayer implements Layer {
const visible = shell.isWindowVisible(COMPASS_WINDOW_ID);
if (visible === this.enabled) return;
this.enabled = visible;
+ this.diagnostics = null;
setCompassEnabled(visible);
this.firmwareStatus = null;
+ // The stored fix may have aged out while the compass was hidden.
+ if (visible && hasLocationPermission()) refreshDeclination();
this.requestRender();
}
@@ -141,6 +188,7 @@ class CompassLayer implements Layer {
if (this.removed) return;
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
this.rawHeading = normalizeHeading(event.headingDegrees);
+ this.diagnostics = event.diagnostics ?? null;
this.firmwareStatus = null;
} else if (event.command === COMPASS_CALIBRATION_STARTED) {
this.firmwareStatus = "Calibrating — move the glasses";
@@ -154,18 +202,29 @@ class CompassLayer implements Layer {
if (this.firmwareStatus !== null) return this.firmwareStatus;
if (!this.enabled) return "Compass paused";
if (this.rawHeading === null) return "Waiting for compass data…";
- return isCompassCalibrated() ? "Magnetic heading" : "Uncalibrated - Tap to calibrate";
+ if (!isCompassCalibrated()) return "Uncalibrated - Tap to calibrate";
+ return frameStatusText();
}
paint(ctx: LayerContext): GrayImage {
const { width, height } = ctx.stack.getBaseSize();
- const image = new GrayImage(width, height, 0);
const small = getDefaultSmallFont();
const large = getDefaultLargeFont();
- const heading = this.rawHeading === null ? null : calibrateHeading(this.rawHeading);
+ const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees;
const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`;
const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2);
const smallStep = lineStep(small);
+ const debugLines = isCompassDebugEnabled() ? compassDebugLines(this.diagnostics) : [];
+ const debugWidth = Math.max(0, ...debugLines.map((line) => small.measureText(line)));
+ const debugGap = debugLines.length ? 12 : 0;
+ // Keep diagnostics beside the heading even in narrow windows. The rose
+ // stays centred on the optical axis; the combined readout fits the viewport.
+ const headingFont = large.measureText(headingText) + debugGap + debugWidth <= width - EDGE_PAD * 2
+ ? large : small;
+ const headingWidth = headingFont.measureText(headingText);
+ const readoutWidth = headingWidth + debugGap + debugWidth;
+ const debugHeight = debugLines.length ? (debugLines.length - 1) * smallStep + small.lineHeight : 0;
+ const readoutHeight = Math.max(headingFont.lineHeight, debugHeight);
// One column centred on the display's true centre, so the rose sits where
// the wearer is looking rather than 32px right of it.
@@ -173,7 +232,7 @@ class CompassLayer implements Layer {
// The rose is sized and placed first — it hangs off the bottom edge — and
// the readout then floats in whatever room is left above it.
- const textHeight = large.lineHeight + 4 + statusLines.length * smallStep;
+ const textHeight = readoutHeight + 4 + statusLines.length * smallStep;
const radius = Math.max(
24,
Math.min(
@@ -191,15 +250,30 @@ class CompassLayer implements Layer {
const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE);
let y = Math.max(TOP_PAD, Math.round((ringTop - TICK_HEIGHT - textHeight) / 2));
- image.drawText(large, Math.round(cx - large.measureText(headingText) / 2), y, headingText, heading === null ? 150 : 255);
- y += large.lineHeight + 4;
+ const fade = heading === null ? 0.45 : 1;
+ const clipY = y + textHeight + 6;
+ const backgroundKey = [width, height, cx, cy, radius, clipY, fade].join(",");
+ if (this.background?.key !== backgroundKey) {
+ this.background = {
+ key: backgroundKey,
+ image: createCompassBackground(width, height, cx, cy, radius, clipY, fade),
+ };
+ }
+ const image = this.background.image.clone();
+ drawCompassRose(image, cx, cy, radius, heading);
+ const readoutX = Math.round(Math.max(EDGE_PAD, Math.min(width - EDGE_PAD - readoutWidth, cx - readoutWidth / 2)));
+ image.drawText(headingFont, readoutX, y + Math.floor((readoutHeight - headingFont.lineHeight) / 2),
+ headingText, heading === null ? 150 : 255);
+ for (let i = 0; i < debugLines.length; i++) {
+ image.drawText(small, readoutX + headingWidth + debugGap,
+ y + Math.floor((readoutHeight - debugHeight) / 2) + i * smallStep, debugLines[i]!, 175);
+ }
+ y += readoutHeight + 4;
for (const line of statusLines) {
image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125);
y += smallStep;
}
- drawPlaneGrid(image, cx, cy, radius, y + 6);
- drawCompassRose(image, cx, cy, radius, heading);
return image;
}
@@ -231,6 +305,22 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
layer.openCalibration(ctx);
},
},
+ {
+ label: `North: ${northReferenceName(getNorthReference())}`,
+ description: "True north is what maps use. Magnetic north matches a handheld compass; it needs no location.",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ layer.toggleNorthReference();
+ },
+ },
+ {
+ label: `Debug information: ${isCompassDebugEnabled() ? "On" : "Off"}`,
+ description: "Show magnetic accuracy (0–3), anomaly flags (0–2), and orientation source beside the heading.",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ layer.toggleDebugInfo();
+ },
+ },
],
baseLayer: new YieldAtRootLayer(layer),
submitFrame: options.submitFrame,
@@ -246,6 +336,27 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
return app;
}
+export function northReferenceName(reference: NorthReference): string {
+ return reference === "true" ? "True" : "Magnetic";
+}
+
+/**
+ * Name the frame the readout is in. When the wearer wants true north but the
+ * phone can't supply declination, say that the reading is magnetic and why,
+ * rather than quietly showing a magnetic heading under a "true" label.
+ */
+function frameStatusText(): string {
+ if (getNorthReference() === "magnetic") return "Magnetic heading";
+ switch (getDeclinationAvailability()) {
+ case "available":
+ return "True heading";
+ case "no-permission":
+ return "Magnetic heading - location permission needed for true north";
+ case "no-fix":
+ return "Magnetic heading - waiting for location";
+ }
+}
+
function cardinalDirection(heading: number): string {
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
return names[Math.round(normalizeHeading(heading) / 45) % names.length]!;
@@ -272,15 +383,66 @@ function projectRose(cx: number, cy: number, scale: number, radius: number, angl
};
}
-/** Draw the tilted rose, with its brightest point aimed at magnetic north. */
+/**
+ * Bounds of every orientation of the rotating points. The longest tip sweeps
+ * a circle in the disc's plane; perspective projects it to an offset ellipse.
+ * Round outward so all rasterized triangle pixels fit inside the rectangle.
+ */
+function rotatingRoseBounds(cx: number, cy: number, radius: number): {
+ x: number; y: number; width: number; height: number;
+} {
+ const perspective = TILT_PERSPECTIVE * CARDINAL_TIP;
+ const halfWidth = radius * CARDINAL_TIP / Math.sqrt(1 - perspective * perspective);
+ const depth = radius * CARDINAL_TIP * TILT_SQUASH;
+ const x = Math.floor(cx - halfWidth);
+ const y = Math.floor(cy - depth / (1 + perspective));
+ return {
+ x,
+ y,
+ width: Math.ceil(cx + halfWidth) - x,
+ height: Math.ceil(cy + depth / (1 - perspective)) - y,
+ };
+}
+
+/**
+ * Keep the fixed pixels inside the rotating rose's dirty rectangle as one
+ * immutable texture. The wire planner can omit them from each raster delta
+ * and restore them with a cached image draw. Outside that rectangle the
+ * background stays raster, since heading updates do not change it.
+ *
+ * The texture uses transparent zero for the empty disc interior, so it can
+ * overlay the rotating points. Its only ink over the points is the fixed
+ * heading tick, which belongs on top of them.
+ */
+function createCompassBackground(
+ width: number, height: number, cx: number, cy: number, radius: number, clipY: number, fade: number,
+): GrayImage {
+ const image = new GrayImage(width, height, 0);
+ drawPlaneGrid(image, cx, cy, radius, clipY);
+ drawDiscWall(image, cx, cy, radius, fade);
+ drawTiltedRing(image, cx, cy, radius, 105 * fade);
+ drawHeadingTick(image, cx, cy, radius, 255 * fade);
+
+ const bounds = rotatingRoseBounds(cx, cy, radius);
+ const left = Math.max(0, bounds.x);
+ const top = Math.max(0, bounds.y);
+ const right = Math.min(width, bounds.x + bounds.width);
+ const bottom = Math.min(height, bounds.y + bounds.height);
+ if (right > left && bottom > top) {
+ const texture = new GrayImage(right - left, bottom - top, 0);
+ texture.bitBlt(image, 0, 0, { sx: left, sy: top, width: texture.width, height: texture.height });
+ image.fillRect(left, top, texture.width, texture.height, 0);
+ image.drawImage(texture, left, top);
+ }
+ return image;
+}
+
+/** Draw only the rotating points, with the brightest one aimed at north. */
function drawCompassRose(image: GrayImage, cx: number, cy: number, radius: number, heading: number | null): void {
// Without a reading there is nothing to aim, so show the rose in its resting
// orientation, dimmed, rather than an empty ring.
const fade = heading === null ? 0.45 : 1;
const bearing = heading ?? 0;
- drawDiscWall(image, cx, cy, radius, fade);
- drawTiltedRing(image, cx, cy, radius, 105 * fade);
- drawHeadingTick(image, cx, cy, radius, 255 * fade);
// Short points first, so the long ones sit on top of them at the waist. Only
// north is drawn at full brightness: the other seven are there to make the
// rose read as a rose, and competing with north would defeat the point.
@@ -411,14 +573,15 @@ function drawTiltedRing(image: GrayImage, cx: number, cy: number, radius: number
}
}
-/** A fixed mark at the top of the ring: the heading the wearer is facing. */
+/** A fixed mark just inside the top rim: the heading the wearer is facing. */
function drawHeadingTick(image: GrayImage, cx: number, cy: number, radius: number, value: number): void {
const top = projectRose(cx, cy, radius, 1, 0);
+ const tickTop = top.y + 1;
fillTriangle(
image,
- { x: cx, y: top.y - 1 },
- { x: cx - TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT },
- { x: cx + TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT },
+ { x: cx, y: tickTop + TICK_HEIGHT - 1 },
+ { x: cx - TICK_HALF_WIDTH, y: tickTop },
+ { x: cx + TICK_HALF_WIDTH, y: tickTop },
value,
);
}
diff --git a/app/apps/compass/debug.ts b/app/apps/compass/debug.ts
new file mode 100644
index 00000000..72cdec70
--- /dev/null
+++ b/app/apps/compass/debug.ts
@@ -0,0 +1,21 @@
+import type { CompassDiagnostics } from "../../native/compass";
+import { getBooleanSetting, setBooleanSetting } from "../../native/settings-store";
+
+const DEBUG_KEY = "compass.debugInfo";
+
+export function isCompassDebugEnabled(): boolean {
+ return getBooleanSetting(DEBUG_KEY, false);
+}
+
+export function setCompassDebugEnabled(enabled: boolean): void {
+ setBooleanSetting(DEBUG_KEY, enabled);
+}
+
+export function compassDebugLines(diagnostics: CompassDiagnostics | null): string[] {
+ if (!diagnostics) return ["Diagnostics", "unavailable"];
+ if (!(diagnostics.flags & 0x80)) return ["Sample data", "unavailable"];
+ const accuracy = diagnostics.magneticAccuracy < 0 ? "--" : `${diagnostics.magneticAccuracy}/3`;
+ const anomalies = diagnostics.magneticAnomalies < 0 ? "--" : String(diagnostics.magneticAnomalies);
+ const source = ["--", "GRV", "GMRV", "RV"][diagnostics.orientationSource] ?? "--";
+ return [`Mag: ${accuracy}`, `Anom: ${anomalies}`, `Src: ${source}`];
+}
diff --git a/app/apps/compass/declination.ts b/app/apps/compass/declination.ts
new file mode 100644
index 00000000..beb9cfe5
--- /dev/null
+++ b/app/apps/compass/declination.ts
@@ -0,0 +1,97 @@
+/**
+ * Local magnetic declination for the compass, so the app can show true north.
+ *
+ * Declination only varies over tens of kilometres, so the location it needs is
+ * whatever the phone can cheaply produce: the same one-shot coarse lookup the
+ * Weather app uses, refreshed no more than daily. The last fix is persisted so
+ * a fresh start has a usable declination before location comes back, and the
+ * model is re-evaluated at the current time when it does.
+ */
+import { hasLocationPermission } from "../../g2/android-permissions";
+import { magneticDeclinationDegrees } from "../../native/geomagnetic";
+import { getCurrentLocation } from "../../native/location";
+import { getStringSetting, setStringSetting } from "../../native/settings-store";
+
+const LATITUDE_KEY = "compass.declination.latitude";
+const LONGITUDE_KEY = "compass.declination.longitude";
+const LOCATED_AT_KEY = "compass.declination.locatedAtMs";
+
+/** A stored fix older than this is refreshed when the compass next runs. */
+const FIX_MAX_AGE_MS = 24 * 60 * 60 * 1000;
+/** Back-off between failed location attempts, so a denied or dark phone isn't polled. */
+const RETRY_INTERVAL_MS = 10 * 60 * 1000;
+
+export type DeclinationAvailability = "available" | "no-permission" | "no-fix";
+
+type StoredFix = { latitude: number; longitude: number; locatedAtMs: number };
+
+let declination: number | null = null;
+let fix: StoredFix | null = null;
+let loaded = false;
+let refreshing = false;
+let lastAttemptMs = 0;
+const listeners = new Set<() => void>();
+
+function loadStoredFix(): void {
+ if (loaded) return;
+ loaded = true;
+ const latitude = parseFloat(getStringSetting(LATITUDE_KEY, ""));
+ const longitude = parseFloat(getStringSetting(LONGITUDE_KEY, ""));
+ const locatedAtMs = parseInt(getStringSetting(LOCATED_AT_KEY, ""), 10);
+ if (Number.isFinite(latitude) && Number.isFinite(longitude) && Number.isFinite(locatedAtMs)) {
+ fix = { latitude, longitude, locatedAtMs };
+ declination = magneticDeclinationDegrees(latitude, longitude);
+ }
+}
+
+/** Declination in degrees (east positive), or null when no location is known. */
+export function getDeclinationDegrees(): number | null {
+ loadStoredFix();
+ return declination;
+}
+
+/** Why declination is or isn't available, for the compass status line. */
+export function getDeclinationAvailability(): DeclinationAvailability {
+ if (getDeclinationDegrees() !== null) return "available";
+ return hasLocationPermission() ? "no-fix" : "no-permission";
+}
+
+export function onDeclinationChanged(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/**
+ * Fetch a location and recompute declination if the stored fix is stale or
+ * missing. Safe to call on every compass start; it is a no-op while a lookup
+ * is in flight, while the fix is fresh, or shortly after a failed attempt.
+ * Never prompts for permission: callers that want to ask do that themselves.
+ */
+export function refreshDeclination(): void {
+ loadStoredFix();
+ if (refreshing || !hasLocationPermission()) return;
+ const now = Date.now();
+ if (fix !== null && now - fix.locatedAtMs < FIX_MAX_AGE_MS) return;
+ if (now - lastAttemptMs < RETRY_INTERVAL_MS) return;
+ lastAttemptMs = now;
+ refreshing = true;
+ getCurrentLocation()
+ .then((location) => {
+ const value = magneticDeclinationDegrees(location.latitude, location.longitude);
+ if (value === null) return;
+ fix = { latitude: location.latitude, longitude: location.longitude, locatedAtMs: now };
+ declination = value;
+ setStringSetting(LATITUDE_KEY, String(location.latitude));
+ setStringSetting(LONGITUDE_KEY, String(location.longitude));
+ setStringSetting(LOCATED_AT_KEY, String(now));
+ for (const listener of listeners) listener();
+ })
+ .catch((error) => {
+ console.warn(`Compass declination location lookup failed: ${error}`);
+ })
+ .finally(() => {
+ refreshing = false;
+ });
+}
diff --git a/app/apps/compass/heading.ts b/app/apps/compass/heading.ts
new file mode 100644
index 00000000..b45fc580
--- /dev/null
+++ b/app/apps/compass/heading.ts
@@ -0,0 +1,54 @@
+/**
+ * The compass heading model: raw magnetometer reading → wearer-calibrated
+ * magnetic heading → true heading, and which of the last two the wearer has
+ * asked to see.
+ *
+ * The wearer-fit offset and declination are kept as separate terms on purpose.
+ * The offset changes when the glasses are re-seated but not when the wearer
+ * travels; declination is the reverse. One combined hand-tuned number would go
+ * quietly wrong after a long trip.
+ */
+import { getStringSetting, setStringSetting } from "../../native/settings-store";
+import { calibrateHeading, normalizeHeading } from "./calibration";
+import { getDeclinationDegrees } from "./declination";
+
+const NORTH_REFERENCE_KEY = "compass.northReference";
+
+/** Which north the compass reads relative to. True is the default: it is what maps use. */
+export type NorthReference = "true" | "magnetic";
+
+export type ResolvedHeading = {
+ /** Raw reading corrected by the wearer-fit offset. */
+ magneticDegrees: number;
+ /** Local declination (east positive), or null when no location is known. */
+ declinationDegrees: number | null;
+ /** Magnetic heading plus declination, or null when declination is unknown. */
+ trueDegrees: number | null;
+ /** The heading to show, in whichever frame `frame` names. */
+ displayDegrees: number;
+ /** The frame actually shown: true if requested and available, else magnetic. */
+ frame: NorthReference;
+};
+
+export function getNorthReference(): NorthReference {
+ return getStringSetting(NORTH_REFERENCE_KEY, "true") === "magnetic" ? "magnetic" : "true";
+}
+
+export function setNorthReference(reference: NorthReference): void {
+ setStringSetting(NORTH_REFERENCE_KEY, reference);
+}
+
+export function resolveHeading(rawDegrees: number): ResolvedHeading {
+ const magneticDegrees = calibrateHeading(rawDegrees);
+ const declinationDegrees = getDeclinationDegrees();
+ const trueDegrees = declinationDegrees === null ? null : normalizeHeading(magneticDegrees + declinationDegrees);
+ const wantTrue = getNorthReference() === "true";
+ const frame: NorthReference = wantTrue && trueDegrees !== null ? "true" : "magnetic";
+ return {
+ magneticDegrees,
+ declinationDegrees,
+ trueDegrees,
+ displayDegrees: frame === "true" ? trueDegrees! : magneticDegrees,
+ frame,
+ };
+}
diff --git a/app/apps/developer/developer-app.ts b/app/apps/developer/developer-app.ts
index 61e40ccf..c81d0945 100644
--- a/app/apps/developer/developer-app.ts
+++ b/app/apps/developer/developer-app.ts
@@ -3,6 +3,7 @@ import { ScreenTestLayer } from "./screen-test";
import { BuzzerDemoLayer } from "./buzzer-demo";
import { AccelerometerDemoLayer } from "./accelerometer-demo";
import { BandwidthBenchmarkLayer } from "./bandwidth-benchmark";
+import { LightSensorDemoLayer } from "./light-sensor-demo";
import { ResourceUsageLayer } from "./resource-usage";
import { LoadAppFromQrLayer, LoadAppFromUrlLayer } from "./load-app";
import { type AppContext } from "../app-definition";
@@ -68,6 +69,12 @@ function debugTestsMenu(): MenuLayer {
ctx.stack.push(new AccelerometerDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
},
},
+ {
+ label: "Light sensor",
+ onSelect: (ctx) => {
+ ctx.stack.push(new LightSensorDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
+ },
+ },
{
label: "BLE bandwidth",
onSelect: (ctx) => {
diff --git a/app/apps/developer/light-sensor-demo.ts b/app/apps/developer/light-sensor-demo.ts
new file mode 100644
index 00000000..4a5a2748
--- /dev/null
+++ b/app/apps/developer/light-sensor-demo.ts
@@ -0,0 +1,199 @@
+import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { GrayImage } from "../../graphics/image";
+import { clamp } from "../../util/numeric-util";
+import {
+ addAmbientLightListener,
+ queryAmbientLight,
+ setAmbientLightPolling,
+ type AmbientLightReport,
+} from "../../native/ambient-light";
+import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
+import { Layer, type LayerContext } from "../../ui/layers";
+import { shell } from "../../ui/shell/shell";
+
+// Passive poll period requested from the firmware (it clamps to 100..5000 ms).
+const POLL_INTERVAL_MS = 250;
+// Report every poll (min delta 0) so the trace shows the raw reading; the
+// heartbeat only matters if the firmware ever starts filtering.
+const POLL_MIN_DELTA = 0;
+const POLL_HEARTBEAT_MS = 1_000;
+// How often to reconcile the polling on/off state with window visibility.
+const RECONCILE_INTERVAL_MS = 400;
+// Length of the on-screen trace.
+const HISTORY_MS = 30_000;
+const MAX_SAMPLES = Math.ceil(HISTORY_MS / 100) + 2;
+
+type Sample = { atMs: number; value: number; peak: number };
+
+/**
+ * Light sensor demo: turns CFW passive light-sensor polling (mode 16) on while
+ * this page is visible and off otherwise, and shows the latest OPT3001
+ * reading, the stock driver's peak/target, and a 30 s trace.
+ *
+ * While passive polling is on the stock auto-brightness adjuster does not step
+ * the panel, so the level shown here stays wherever it was set. Leaving the
+ * page hands the sensor back to the stock firmware.
+ */
+export class LightSensorDemoLayer implements Layer {
+ private report: AmbientLightReport | null = null;
+ private readonly samples: Sample[] = [];
+ private reportCount = 0;
+ private enabled = false;
+ private removed = false;
+ private reconcileTimer: ReturnType | null = null;
+ private unsubscribe: (() => void) | null = null;
+
+ constructor(
+ private readonly windowId: string,
+ private readonly requestRender: () => void,
+ ) {
+ this.start();
+ }
+
+ private start(): void {
+ this.unsubscribe = addAmbientLightListener((report) => {
+ if (this.removed) return;
+ this.report = report;
+ this.reportCount++;
+ const atMs = Date.now();
+ if (report.readOk || !report.passive) {
+ this.samples.push({ atMs, value: report.alsValue, peak: report.peak });
+ const cutoff = atMs - HISTORY_MS;
+ while (this.samples.length > 1 && this.samples[0]!.atMs < cutoff) this.samples.shift();
+ while (this.samples.length > MAX_SAMPLES) this.samples.shift();
+ }
+ this.requestRender();
+ });
+ // Show whatever the driver currently holds before polling has started.
+ queryAmbientLight();
+ this.reconcileTimer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
+ this.reconcile();
+ }
+
+ /** Match the polling on/off state to whether this page is currently visible. */
+ private reconcile(): void {
+ if (this.removed) return;
+ const visible = shell.isWindowVisible(this.windowId);
+ if (visible === this.enabled) return;
+ this.enabled = visible;
+ setAmbientLightPolling(visible, {
+ intervalMs: POLL_INTERVAL_MS,
+ minDelta: POLL_MIN_DELTA,
+ heartbeatMs: POLL_HEARTBEAT_MS,
+ bindToLease: true,
+ });
+ this.requestRender();
+ }
+
+ onRemoved(): void {
+ this.removed = true;
+ if (this.reconcileTimer !== null) {
+ clearInterval(this.reconcileTimer);
+ this.reconcileTimer = null;
+ }
+ this.unsubscribe?.();
+ this.unsubscribe = null;
+ if (this.enabled) {
+ setAmbientLightPolling(false);
+ this.enabled = false;
+ }
+ }
+
+ paint(ctx: LayerContext): GrayImage {
+ const small = getDefaultSmallFont();
+ const medium = getDefaultMediumFont();
+ const { width, height } = ctx.stack.getBaseSize();
+ const image = new GrayImage(width, height, 0);
+
+ image.drawText(small, 20, 8, "Light sensor", 220);
+ const status = this.enabled ? "polling" : "paused";
+ image.drawText(small, width - 20 - small.measureText(status), 8, status, 150);
+
+ const report = this.report;
+ if (!report) {
+ const message = this.enabled ? "Waiting for a report…" : "Paused (page not visible).";
+ image.drawText(small, 22, 44, message, 190);
+ image.drawText(small, 22, 66, "Needs custom firmware with the als16", 120);
+ image.drawText(small, 22, 82, "extension (EVENCFW/18 or newer).", 120);
+ image.drawText(small, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
+ return image;
+ }
+
+ // Headline reading. The stock driver's unit is roughly a tenth of a lux.
+ const lux = (report.alsValue / 10).toFixed(1);
+ image.drawText(medium, 22, 30, `${lux} lux`, 245);
+ const peakText = `peak ${(report.peak / 10).toFixed(1)}`;
+ image.drawText(small, 22 + medium.measureText(`${lux} lux`) + 14, 36, peakText, 170);
+
+ const flags: string[] = [];
+ if (!report.opened) flags.push("sensor closed");
+ if (report.passive) flags.push("passive");
+ if (report.autoBrightness) flags.push("auto on");
+ if (report.passive && !report.readOk) flags.push("read failed");
+ image.drawText(small, 22, 58, flags.join(" ") || "stock polling", 150);
+
+ image.drawText(
+ small,
+ 22,
+ 76,
+ `brightness ${report.brightness} stock target ${report.stockTarget} gear ${report.gear} scale ${(report.scaleQ10 / 1024).toFixed(2)}`,
+ 170,
+ );
+
+ // 30 s trace of the reading (bright) and the driver's 5-sample peak (dim).
+ // The axis label sits between the stats line and the chart, so the chart
+ // starts a full text line lower than the stats.
+ const chartTop = 76 + small.lineHeight * 2 + 4;
+ const bounds = { x: 20, y: chartTop, width: width - 40, height: height - chartTop - 34 };
+ const maxValue = Math.max(...this.samples.map((sample) => Math.max(sample.value, sample.peak)), 10);
+ const scale = roundUpScale(maxValue * 1.08);
+ image.drawText(small, bounds.x, bounds.y - small.lineHeight - 2, `0–${(scale / 10).toFixed(0)} lux, last 30 s`, 120);
+ drawTrace(image, this.samples, Date.now(), bounds, scale);
+
+ image.drawText(small, 20, height - 16, `reports: ${this.reportCount}`, 110);
+ const back = `${GESTURE_DOUBLE_CLICK} back`;
+ image.drawText(small, width - 20 - small.measureText(back), height - 16, back, 110);
+ return image;
+ }
+
+ async handleInput(event: InputEvent, ctx: LayerContext): Promise {
+ if (event.type === "double-click") {
+ ctx.stack.pop();
+ }
+ }
+}
+
+/** Round a trace ceiling up to 1/2/5 × 10^n so the axis label stays tidy. */
+function roundUpScale(value: number): number {
+ const magnitude = 10 ** Math.floor(Math.log10(Math.max(value, 1)));
+ for (const step of [1, 2, 5, 10]) {
+ if (value <= step * magnitude) return step * magnitude;
+ }
+ return 10 * magnitude;
+}
+
+function drawTrace(
+ image: GrayImage,
+ samples: readonly Sample[],
+ nowMs: number,
+ bounds: { x: number; y: number; width: number; height: number },
+ scale: number,
+): void {
+ image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 45);
+ const startMs = nowMs - HISTORY_MS;
+ const series: Array<[(sample: Sample) => number, number]> = [
+ [(sample) => sample.peak, 90],
+ [(sample) => sample.value, 235],
+ ];
+ for (const [value, shade] of series) {
+ let previous: { x: number; y: number } | null = null;
+ for (const sample of samples) {
+ if (sample.atMs < startMs) continue;
+ const x = bounds.x + Math.round(clamp((sample.atMs - startMs) / HISTORY_MS, 0, 1) * (bounds.width - 1));
+ const y = bounds.y + bounds.height - 1 - Math.round(clamp(value(sample) / scale, 0, 1) * (bounds.height - 1));
+ if (previous) image.drawLine(previous.x, previous.y, x, y, shade);
+ else image.setPixel(x, y, shade);
+ previous = { x, y };
+ }
+ }
+}
diff --git a/app/apps/evenhub/compass-router.ts b/app/apps/evenhub/compass-router.ts
index 854e67a6..0d8e7910 100644
--- a/app/apps/evenhub/compass-router.ts
+++ b/app/apps/evenhub/compass-router.ts
@@ -3,18 +3,46 @@
* running EvenHub apps, mirroring the IMU router. Only the foreground app
* receives headings, so a backgrounded app can't keep the sensor running.
*
- * The compass is NOT pre-calibrated — the magnetometer is in the right arm,
- * which rests on the head with a wearer-dependent curl (see compass-app memory);
- * headings are relative, not true north.
+ * The raw reading is NOT pre-calibrated — the magnetometer is in the right
+ * arm, which rests on the head with a wearer-dependent curl (see compass-app
+ * memory). Each delivery also carries the Compass app's wearer-calibrated
+ * magnetic heading and, when the phone has a location, declination and the
+ * true heading, so apps needn't redo that work.
*/
import { addCompassListener, setCompassEnabled, COMPASS_CHANGED, type CompassEvent } from "../../native/compass";
+import { isCompassCalibrated } from "../compass/calibration";
+import { refreshDeclination } from "../compass/declination";
+import { resolveHeading } from "../compass/heading";
+
+/** Wire shape of the `compass` extension event (faceclaw-extensions `CompassReading`). */
+export type EvenHubCompassReading = {
+ headingDegrees: number;
+ magneticHeadingDegrees: number;
+ wearerCalibrated: boolean;
+ declinationDegrees?: number;
+ trueHeadingDegrees?: number;
+};
export type EvenHubCompassClient = {
readonly windowId: string;
isForeground(): boolean;
- deliverCompass(headingDegrees: number): void;
+ deliverCompass(reading: EvenHubCompassReading): void;
};
+export function buildCompassReading(rawDegrees: number): EvenHubCompassReading {
+ const resolved = resolveHeading(rawDegrees);
+ const reading: EvenHubCompassReading = {
+ headingDegrees: rawDegrees,
+ magneticHeadingDegrees: resolved.magneticDegrees,
+ wearerCalibrated: isCompassCalibrated(),
+ };
+ if (resolved.declinationDegrees !== null && resolved.trueDegrees !== null) {
+ reading.declinationDegrees = resolved.declinationDegrees;
+ reading.trueHeadingDegrees = resolved.trueDegrees;
+ }
+ return reading;
+}
+
class EvenHubCompassRouter {
private readonly requesting = new Set();
private active: EvenHubCompassClient | null = null;
@@ -47,13 +75,16 @@ class EvenHubCompassRouter {
this.unsubscribe = addCompassListener((event: CompassEvent) => {
// Only heading updates carry a real heading; calibration events use -1.
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
- this.active?.deliverCompass(event.headingDegrees);
+ this.active?.deliverCompass(buildCompassReading(event.headingDegrees));
}
});
}
if (!this.enabled) {
setCompassEnabled(true);
this.enabled = true;
+ // Uses location only if the wearer already granted it; an app turning
+ // on the compass is not a reason to raise a system permission prompt.
+ refreshDeclination();
}
} else {
if (this.enabled) {
diff --git a/app/apps/evenhub/compositor.ts b/app/apps/evenhub/compositor.ts
index 60d2c706..56ab1d5e 100644
--- a/app/apps/evenhub/compositor.ts
+++ b/app/apps/evenhub/compositor.ts
@@ -26,9 +26,23 @@ export const EVENHUB_SCREEN_HEIGHT = 288;
const TEXT_WHITE = 255;
const LIST_ROW_PADDING = 4;
+/**
+ * SDK 0.0.14 textColor levels 0..4 as grey values. Level 4 is the default and
+ * the only one apps got before 0.0.14, so it must stay exactly TEXT_WHITE.
+ * Level 0 is the firmware's "fully dim" step, which over the black page
+ * background means the text is effectively not shown.
+ */
+const TEXT_BRIGHTNESS_GREYS = [0, 64, 128, 191, 255];
+
+function textGrey(level: number | undefined): number {
+ return level === undefined ? TEXT_WHITE : (TEXT_BRIGHTNESS_GREYS[level] ?? TEXT_WHITE);
+}
+
/** Chars the font lacks are skipped silently on stock (no tofu); EvenHubFont
* skips unknown glyphs, matching that. */
function paintTextContainer(image: GrayImage, container: EvenHubTextContainer): void {
+ // Only the text dims: textColor is a text-brightness level, and stock draws
+ // the container's border at full brightness regardless.
paintBorder(image, container);
const inset = container.borderWidth + container.paddingLength;
EvenHubFont.get().drawTextWrapped(
@@ -37,7 +51,7 @@ function paintTextContainer(image: GrayImage, container: EvenHubTextContainer):
container.y + inset,
Math.max(1, container.width - 2 * inset),
container.content,
- TEXT_WHITE,
+ textGrey(container.textColor),
);
}
diff --git a/app/apps/evenhub/containers.ts b/app/apps/evenhub/containers.ts
index 95954fa6..c529290e 100644
--- a/app/apps/evenhub/containers.ts
+++ b/app/apps/evenhub/containers.ts
@@ -22,6 +22,8 @@ export type EvenHubTextContainer = {
/** Extended-layout: inherit content from a same-named container on replace. */
preserve: boolean;
content: string;
+ /** SDK 0.0.14 textColor: brightness level 0..4; undefined means the device default (4). */
+ textColor: number | undefined;
};
export type EvenHubImageContainer = {
@@ -63,11 +65,31 @@ export type EvenHubListContainer = {
export type EvenHubContainer = EvenHubTextContainer | EvenHubImageContainer | EvenHubListContainer;
+/** One entry of the OS contextual menu an app registers via `menuObject`. */
+export type EvenHubMenuItem = {
+ itemName: string;
+ /** Non-zero uint32, unique within the menu; echoed back in menuItemClickEvent. */
+ itemID: number;
+};
+
export type EvenHubPage = {
/** In declaration order (lists, images, texts); z-sorted at paint time. */
containers: EvenHubContainer[];
+ /**
+ * The page's contextual-menu entries (SDK 0.0.14 `menuObject`). Empty when
+ * the app declared none, which on rebuild is how a menu is cleared.
+ */
+ menuItems: EvenHubMenuItem[];
};
+/** Firmware brightness levels for text; 4 is the device default. */
+const MIN_TEXT_BRIGHTNESS = 0;
+const MAX_TEXT_BRIGHTNESS = 4;
+
+/** Firmware limits on a contextual menu, enforced app-side by the SDK too. */
+const MENU_MAX_ITEMS = 10;
+const MENU_NAME_MAX_BYTES = 32;
+
function normalizeKey(key: string): string {
return key.replace(/_/g, "").toLowerCase();
}
@@ -123,9 +145,62 @@ function parseTextContainer(json: Record): EvenHubTextContainer
zOrderIndex: readOptionalNumber(json, "zOrderIndex"),
preserve: readNumber(json, "preserve", 0) !== 0,
content: readString(json, "content", ""),
+ textColor: readTextBrightness(json),
};
}
+/**
+ * A text container's brightness level, or undefined for the device default.
+ * Out-of-range values are dropped rather than clamped: the SDK rejects the
+ * whole call for them, so an app that sends one is already misbehaving and
+ * the default level is the least surprising thing to draw.
+ */
+export function readTextBrightness(json: Record): number | undefined {
+ const value = readOptionalNumber(json, "textColor");
+ if (value === undefined || !Number.isInteger(value)) return undefined;
+ if (value < MIN_TEXT_BRIGHTNESS || value > MAX_TEXT_BRIGHTNESS) return undefined;
+ return value;
+}
+
+/** The raw `menuObject.menuItems` array as sent, before any rule is applied. */
+export function declaredMenuItems(data: Record): unknown[] {
+ const raw = pickLoose(asRecord(pickLoose(data, "menuObject")), "menuItems");
+ return Array.isArray(raw) ? raw : [];
+}
+
+function utf8ByteLength(value: string): number {
+ let bytes = 0;
+ for (const char of value) {
+ const code = char.codePointAt(0) ?? 0;
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
+ }
+ return bytes;
+}
+
+/**
+ * Parse `menuObject.menuItems`. The SDK validates these app-side and refuses
+ * to call the host at all on a violation, so anything invalid arriving here
+ * came from an app bypassing the SDK; drop the offending entries (and any
+ * past the tenth) rather than rejecting the whole page, which would leave the
+ * app with no UI at all.
+ */
+export function parseMenuItems(data: Record): EvenHubMenuItem[] {
+ const items: EvenHubMenuItem[] = [];
+ const seen = new Set();
+ for (const entry of declaredMenuItems(data)) {
+ if (items.length >= MENU_MAX_ITEMS) break;
+ const json = asRecord(entry);
+ const itemID = readNumber(json, "itemID", 0);
+ if (!Number.isInteger(itemID) || itemID <= 0 || itemID > 0xffffffff) continue;
+ if (seen.has(itemID)) continue;
+ const itemName = readString(json, "itemName", "");
+ if (utf8ByteLength(itemName) > MENU_NAME_MAX_BYTES) continue;
+ seen.add(itemID);
+ items.push({ itemName, itemID });
+ }
+ return items;
+}
+
function parseImageContainer(json: Record): EvenHubImageContainer {
return {
kind: "image",
@@ -173,6 +248,9 @@ function parseListContainer(json: Record): EvenHubListContainer
* page. Containers keep declaration order within and across the three arrays
* (lists, then images, then texts — texts last so info panels and capture
* containers sit above image tiles when no zOrderIndex is given).
+ *
+ * The whole page is replaced on rebuild, which is also what gives an omitted
+ * menuObject its documented meaning: the previous contextual menu goes away.
*/
export function parsePage(data: Record): EvenHubPage {
const containers: EvenHubContainer[] = [];
@@ -188,7 +266,7 @@ export function parsePage(data: Record): EvenHubPage {
if (Array.isArray(texts)) {
for (const item of texts) containers.push(parseTextContainer(asRecord(item)));
}
- return { containers };
+ return { containers, menuItems: parseMenuItems(data) };
}
/** The container that owns gesture events (exactly one per valid page). */
diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts
index ea8a5ba6..971a10ec 100644
--- a/app/apps/evenhub/even-api.ts
+++ b/app/apps/evenhub/even-api.ts
@@ -20,6 +20,7 @@ const API_HOST = "https://api.evenrealities.com";
const PUBLIC_CDN_HOST = "https://cdn-pub.evenhub.evenrealities.com";
const SIGN_KEY = "a7964f42c39200cfa25c258b7a311b106e20232173667e543c34ced91d63b404";
const REQUEST_TIMEOUT_MS = 30_000;
+const PAGE_SIZE = 40;
export type EvenHubStoreApp = {
id: number;
@@ -80,17 +81,31 @@ export class EvenHubApiClient {
private loginPromise: Promise | null = null;
async listApps(page = 1, category = ""): Promise {
- const query: Record = { page, page_size: 40 };
+ const query: Record = { page, page_size: PAGE_SIZE };
if (category) query.category = category;
const data = await this.authenticatedRequest("GET", "/v2/evenhub/leaderboard", { query });
- const root = asRecord(data);
- const list = Array.isArray(root.list) ? root.list : [];
- return {
- apps: list.map(parseStoreApp).filter((app): app is EvenHubStoreApp => app !== null),
- total: finiteNumber(root.total),
- page: finiteNumber(root.page) || page,
- pageSize: finiteNumber(root.page_size) || 40,
- };
+ return parseStorePage(data, page);
+ }
+
+ /**
+ * Public apps ordered by first publication, newest first. The official app
+ * requests `/ranking?sort_by=first_published_at`; whether the endpoint pages
+ * is unverified, so callers must tolerate a repeated (or complete) list and
+ * a missing total.
+ */
+ async listNewApps(page = 1): Promise {
+ const data = await this.authenticatedRequest("GET", "/v2/evenhub/ranking", {
+ query: { sort_by: "first_published_at", page, page_size: PAGE_SIZE },
+ });
+ return parseStorePage(data, page);
+ }
+
+ /** Full-text storefront search (`/search?q=`), with the same paging caveats as listNewApps. */
+ async searchApps(queryText: string, page = 1): Promise {
+ const data = await this.authenticatedRequest("GET", "/v2/evenhub/search", {
+ query: { q: queryText, page, page_size: PAGE_SIZE },
+ });
+ return parseStorePage(data, page);
}
async getAppDetail(packageId: string): Promise> {
@@ -254,8 +269,15 @@ function buildCommon(version: 1 | 3): string {
const fields: Record = {
platform: "16",
package: "com.even.sg",
- versionName: "2.2.6",
- build: "114",
+ // versionName/build must be a real shipped pair of the official Android
+ // app (versionName/versionCode from its manifest): 2.2.8 = versionCode 122
+ // (captures/even-2.2.8-base.apk). Earlier this said 2.2.6 with build 114,
+ // but 114 was actually 2.2.4's versionCode (see notes/firmware-download.md).
+ // buildTime is not a literal in the app binary (computed at runtime), so
+ // it still carries the value from the 2.2.4 capture; the API has accepted
+ // the mismatch so far.
+ versionName: "2.2.8",
+ build: "122",
brand: "Google",
model: "Pixel 7a",
osVersion: "16",
@@ -357,6 +379,25 @@ export function getPhoneOpenUdid(): string {
return openUdid;
}
+/**
+ * Parse a list response. The leaderboard returns `{list, total, page,
+ * page_size}`; the ranking/search endpoints were only recovered from the
+ * client's request paths, so accept a bare array or the other common
+ * wrapper keys too. A missing total comes back as 0 ("unknown").
+ */
+function parseStorePage(data: unknown, requestedPage: number): EvenHubStorePage {
+ const root = asRecord(data);
+ const list = Array.isArray(data)
+ ? data
+ : [root.list, root.apps, root.items, root.data, root.results].find(Array.isArray) ?? [];
+ return {
+ apps: list.map(parseStoreApp).filter((app): app is EvenHubStoreApp => app !== null),
+ total: finiteNumber(root.total),
+ page: finiteNumber(root.page) || requestedPage,
+ pageSize: finiteNumber(root.page_size) || PAGE_SIZE,
+ };
+}
+
function parseStoreApp(value: unknown): EvenHubStoreApp | null {
const item = asRecord(value);
const version = asRecord(item.version);
diff --git a/app/apps/evenhub/evenhub-window.ts b/app/apps/evenhub/evenhub-window.ts
index 8ca31823..09d399d1 100644
--- a/app/apps/evenhub/evenhub-window.ts
+++ b/app/apps/evenhub/evenhub-window.ts
@@ -35,9 +35,11 @@ class EvenHubAppLayer implements Layer {
}
handleInput(event: InputEvent): void {
- // Everything goes to the app; long-press never reaches here (the window
- // menu intercepts it), which is the guaranteed way out since EvenHub
- // apps own double-click.
+ // Everything goes to the app; the menu gestures never reach here (the
+ // shell keeps long-press for its system menu and the window's context
+ // menu intercepts tap-then-hold), which is the guaranteed way out since
+ // EvenHub apps own double-click. Tap-then-hold is still reported to the
+ // app as LONG_PRESS_EVENT — see the handleInput wrapper below.
this.session.handleGesture(event);
}
}
@@ -61,9 +63,22 @@ export function createEvenHubWindow(
fallbackIcon,
),
heightMode: "medium",
- // Glasses-first: the app runs without the phone showing it; this reveals
- // its phone UI (config pages, etc.) over the dashboard on demand.
- menuItems: () => [{ label: "Show phone UI", onSelect: (ctx) => { ctx.stack.pop(); onShowPhone(); } }],
+ // The window's context menu doubles as the OS contextual menu EvenHub
+ // apps register with `menuObject` (SDK 0.0.14): the app's own entries come
+ // first, then the host entries. Evaluated at open time, so a rebuild that
+ // changes or clears the menu is reflected on the next press.
+ menuItems: () => [
+ ...session.contextMenuItems().map((item) => ({
+ label: item.itemName,
+ onSelect: (ctx: LayerContext) => {
+ ctx.stack.pop();
+ session.selectContextMenuItem(item.itemID);
+ },
+ })),
+ // Glasses-first: the app runs without the phone showing it; this reveals
+ // its phone UI (config pages, etc.) over the dashboard on demand.
+ { label: "Show phone UI", onSelect: (ctx: LayerContext) => { ctx.stack.pop(); onShowPhone(); } },
+ ],
actions: options.actions,
baseLayer: new EvenHubAppLayer(session),
submitFrame: options.submitFrame,
@@ -87,6 +102,20 @@ export function createEvenHubWindow(
windowId,
});
+ // LONG_PRESS_EVENT / LONG_PRESS_RELEASE_EVENT (SDK 0.0.14): the app hears
+ // the context-menu gesture (tap-then-hold; a plain long-press is the
+ // shell's and never arrives) as its long-press. Wrapped at the window
+ // rather than handled in the base layer because the press opens the window
+ // menu and so never reaches a layer, and because the release lands on that
+ // menu once it is up.
+ const baseHandleInput = created.window.handleInput;
+ created.window.handleInput = async (event, frameId) => {
+ if (event.type === "short-then-long-press" || event.type === "long-press-release") {
+ session.handleGesture(event);
+ }
+ await baseHandleInput(event, frameId);
+ };
+
// FOREGROUND_ENTER/EXIT for the app on shell focus changes.
const baseSetForeground = created.window.setForeground;
created.window.setForeground = (foreground) => {
diff --git a/app/apps/evenhub/index.ts b/app/apps/evenhub/index.ts
index d938c123..f7968676 100644
--- a/app/apps/evenhub/index.ts
+++ b/app/apps/evenhub/index.ts
@@ -14,6 +14,7 @@ import { launchPackage, launchUrl, normalizeAppUrl } from "./manager";
import { createInProcessWindow, type InProcessWindow } from "../../ui/shell/in-process-window";
import { renderEvenRealitiesLogo } from "../../graphics/even-realities-logo";
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
+import { type InstalledEvenHubApp } from "./installed-apps";
const EVENHUB_STORE_WINDOW_ID = "evenhub:store";
const EVENHUB_STORE_SURFACE_ID = "window:evenhub:store";
@@ -40,45 +41,71 @@ export function isLoadableAppUrl(url: string): boolean {
return normalizeAppUrl(url) !== null;
}
+/** The open store window, so a second launch focuses it and deep links can reach its layer. */
+let storeWindow: { window: InProcessWindow; store: EvenHubStoreLayer } | null = null;
+
+/** Open the store window, or focus the one already open. */
+async function ensureStoreWindow(ctx: AppContext): Promise<{ window: InProcessWindow; store: EvenHubStoreLayer }> {
+ if (storeWindow && shell.getWindows().some((window) => window.windowId === EVENHUB_STORE_WINDOW_ID)) {
+ shell.focusWindow(EVENHUB_STORE_WINDOW_ID);
+ ctx.requestShellRender();
+ return storeWindow;
+ }
+ let created: InProcessWindow | null = null;
+ const store = new EvenHubStoreLayer({
+ launchApp: (appId) => ctx.launchApp(appId),
+ appendLog: ctx.appendLog,
+ });
+ await ctx.launchInProcessApp(EVENHUB_STORE_WINDOW_ID, EVENHUB_STORE_SURFACE_ID, (options) => {
+ created = createInProcessWindow({
+ appId: "evenhub",
+ windowId: EVENHUB_STORE_WINDOW_ID,
+ title: "EvenHub",
+ iconLetter: "EH",
+ icon: "package",
+ drawIcon: makeImageWindowIcon(renderEvenRealitiesLogo, windowIcon("package", "EH")),
+ closeable: true,
+ menuItems: () => (created?.stack.isAtBase() ? store.buildMenuItems() : []),
+ actions: options.actions,
+ // Dictated text runs a store search (when the store page itself is on top).
+ receiveTextInput: (text) => {
+ if (created?.stack.receiveTextInput(text)) created.requestRender();
+ },
+ baseLayer: store,
+ submitFrame: options.submitFrame,
+ setSurfaceVisible: options.setSurfaceVisible,
+ removeSurface: options.removeSurface,
+ onClosed: () => {
+ store.onWindowClosed(options.actions);
+ if (storeWindow?.store === store) storeWindow = null;
+ options.onClosed();
+ },
+ });
+ return created;
+ });
+ if (!created) throw new Error("EvenHub store window was not created.");
+ storeWindow = { window: created, store };
+ return storeWindow;
+}
+
+/**
+ * Open the store on an installed app's page. The launcher uses it when the
+ * registry lists a package whose EHPK is gone (a settings import after a
+ * reinstall), so the tap lands on a Reinstall button instead of failing.
+ */
+export async function openEvenHubStoreForPackage(ctx: AppContext, installed: InstalledEvenHubApp): Promise {
+ const { window, store } = await ensureStoreWindow(ctx);
+ store.showInstalledPackage(window.stack, installed);
+ window.requestRender();
+}
+
const evenhubApp: AppDefinition = {
appId: "evenhub",
title: "EvenHub",
icon: "package",
renderIcon: renderEvenRealitiesLogo,
launch: async (ctx) => {
- const existing = shell.getWindows().find((window) => window.windowId === EVENHUB_STORE_WINDOW_ID);
- if (existing) {
- shell.focusWindow(existing.windowId);
- ctx.requestShellRender();
- return;
- }
- let created: InProcessWindow | null = null;
- const store = new EvenHubStoreLayer({
- launchApp: (appId) => ctx.launchApp(appId),
- appendLog: ctx.appendLog,
- });
- await ctx.launchInProcessApp(EVENHUB_STORE_WINDOW_ID, EVENHUB_STORE_SURFACE_ID, (options) => {
- created = createInProcessWindow({
- appId: "evenhub",
- windowId: EVENHUB_STORE_WINDOW_ID,
- title: "EvenHub",
- iconLetter: "EH",
- icon: "package",
- drawIcon: makeImageWindowIcon(renderEvenRealitiesLogo, windowIcon("package", "EH")),
- closeable: true,
- menuItems: () => (created?.stack.isAtBase() ? store.buildMenuItems() : []),
- actions: options.actions,
- baseLayer: store,
- submitFrame: options.submitFrame,
- setSurfaceVisible: options.setSurfaceVisible,
- removeSurface: options.removeSurface,
- onClosed: () => {
- store.onWindowClosed(options.actions);
- options.onClosed();
- },
- });
- return created;
- });
+ await ensureStoreWindow(ctx);
},
};
diff --git a/app/apps/evenhub/permission-dialog.ts b/app/apps/evenhub/permission-dialog.ts
index ec187add..07977024 100644
--- a/app/apps/evenhub/permission-dialog.ts
+++ b/app/apps/evenhub/permission-dialog.ts
@@ -3,7 +3,7 @@ import { GrayImage } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap";
import { type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
-import { drawSelectionHighlight } from "../../ui/menu";
+import { drawListScrollbar, drawSelectionHighlight } from "../../ui/menu";
import { permissionDetail, permissionLabel, type EvenHubPermission } from "./permissions";
import { openPrivacyPolicyOnPhone } from "./privacy-policy";
import { lineStep, listRowHeight } from "../../ui/metrics";
@@ -19,10 +19,20 @@ const PERM_GAP = 4;
* before installing it or running an uninstalled package. Allow proceeds;
* Cancel (or double-click) backs out. A privacy-policy-only app still reaches
* this dialog so the user can review the policy before allowing first run.
+ *
+ * When the list overflows the viewport the dialog scrolls: scroll events move
+ * through the content row by row, and only once the bottom is fully visible do
+ * further scrolls move the action selection. The actions are inert until then
+ * (a click just scrolls), so the user can't Allow without having had the whole
+ * list on screen.
*/
export class EvenHubPermissionDialogLayer implements Layer {
/** Starts on Allow; the optional privacy-policy action is inserted after it. */
private selectedIndex = 0;
+ /** First content row drawn; rows above it are scrolled off. */
+ private firstRow = 0;
+ /** Scroll position at which the last row is fully visible; set by paint. */
+ private maxFirstRow = 0;
private resolved = false;
constructor(
@@ -33,6 +43,11 @@ export class EvenHubPermissionDialogLayer implements Layer {
private readonly onCancel: () => void,
) {}
+ /** Whether the dialog is scrolled to the bottom, making the actions live. */
+ private atBottom(): boolean {
+ return this.firstRow >= this.maxFirstRow;
+ }
+
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const font = getDefaultSmallFont();
const { height: viewportHeight } = ctx.stack.getBaseSize();
@@ -44,48 +59,88 @@ export class EvenHubPermissionDialogLayer implements Layer {
const permLabelStep = lineStep(font) + 1;
const permDetailStep = lineStep(font) - 1;
const actionRowH = listRowHeight(font);
- const permsHeight = this.permissions.reduce(
- (sum, permission) => sum + permLabelStep + (permissionDetail(permission) ? permDetailStep : 0) + PERM_GAP,
- 0,
- );
- const emptyPermissionsHeight = this.permissions.length === 0 ? permLabelStep + PERM_GAP : 0;
- const bodyTop = PADDING + headerStep + 6 + permsHeight + emptyPermissionsHeight + 6;
- const height = Math.min(bodyTop + this.actions().length * actionRowH + PADDING, viewportHeight - 2 * DIALOG_Y);
+ const actions = this.actions();
+ const focused = ctx.stack.isFocused();
+
+ // The dialog body as scrollable rows; each row's height includes the gap
+ // below it, so scrolling and visibility checks work on whole rows.
+ type Row = { height: number; draw: (top: number) => void };
+ const rows: Row[] = [];
+ const heading = this.permissions.length ? `${this.appName} needs:` : `${this.appName} is ready to run`;
+ rows.push({
+ height: headerStep + 6,
+ draw: (top) => image.drawText(font, left, top, truncateText(font, heading, textWidth), 235),
+ });
+ if (this.permissions.length === 0) {
+ rows.push({
+ height: permLabelStep + PERM_GAP + 2,
+ draw: (top) => image.drawText(font, left, top, "No special permissions requested.", 140),
+ });
+ }
+ for (let index = 0; index < this.permissions.length; index++) {
+ const permission = this.permissions[index]!;
+ const detail = permissionDetail(permission);
+ const gapBelow = PERM_GAP + (index === this.permissions.length - 1 ? 2 : 0);
+ rows.push({
+ height: permLabelStep + (detail ? 0 : gapBelow),
+ draw: (top) => image.drawText(font, left, top, truncateText(font, permissionLabel(permission.name), textWidth), 220),
+ });
+ if (detail) {
+ rows.push({
+ height: permDetailStep + gapBelow,
+ draw: (top) => image.drawText(font, left + 8, top, truncateText(font, detail, textWidth - 8), 140),
+ });
+ }
+ }
+ for (let index = 0; index < actions.length; index++) {
+ rows.push({
+ height: actionRowH,
+ draw: (top) => {
+ const selected = this.atBottom() && index === this.selectedIndex;
+ if (selected) {
+ drawSelectionHighlight(image, DIALOG_X + 12, top, DIALOG_WIDTH - 24, actionRowH - 1, focused, 8);
+ }
+ image.drawText(font, DIALOG_X + 22, top + 3, actions[index]!, selected ? 255 : 200);
+ },
+ });
+ }
+
+ const contentHeight = rows.reduce((sum, row) => sum + row.height, 0);
+ const height = Math.min(contentHeight + 2 * PADDING, viewportHeight - 2 * DIALOG_Y);
+ const visibleHeight = height - 2 * PADDING;
+
+ // The bottommost scroll position: the largest suffix of rows that fits.
+ let maxFirstRow = rows.length;
+ for (let suffixHeight = 0; maxFirstRow > 0; maxFirstRow--) {
+ const rowHeight = rows[maxFirstRow - 1]!.height;
+ if (suffixHeight + rowHeight > visibleHeight) break;
+ suffixHeight += rowHeight;
+ }
+ this.maxFirstRow = maxFirstRow;
+ this.firstRow = Math.max(0, Math.min(this.firstRow, maxFirstRow));
// Fill 1 (transparent color key is 0), outline for the dialog edge.
image.fillRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 1);
image.drawRoundedRect(DIALOG_X, DIALOG_Y, DIALOG_WIDTH, height, 72);
let y = DIALOG_Y + PADDING;
- const heading = this.permissions.length ? `${this.appName} needs:` : `${this.appName} is ready to run`;
- image.drawText(font, left, y, truncateText(font, heading, textWidth), 235);
- y += headerStep + 6;
-
- if (this.permissions.length === 0) {
- image.drawText(font, left, y, "No special permissions requested.", 140);
- y += emptyPermissionsHeight;
+ for (let index = this.firstRow; index < rows.length; index++) {
+ const row = rows[index]!;
+ if (y + row.height > DIALOG_Y + PADDING + visibleHeight) break;
+ row.draw(y);
+ y += row.height;
}
- for (const permission of this.permissions) {
- image.drawText(font, left, y, truncateText(font, permissionLabel(permission.name), textWidth), 220);
- y += permLabelStep;
- const detail = permissionDetail(permission);
- if (detail) {
- image.drawText(font, left + 8, y, truncateText(font, detail, textWidth - 8), 140);
- y += permDetailStep;
- }
- y += PERM_GAP;
- }
- y += 2;
- const focused = ctx.stack.isFocused();
- const actions = this.actions();
- for (let index = 0; index < actions.length; index++) {
- const rowY = y + index * actionRowH;
- const selected = index === this.selectedIndex;
- if (selected) {
- drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, actionRowH - 1, focused, 8);
- }
- image.drawText(font, DIALOG_X + 22, rowY + 3, actions[index]!, selected ? 255 : 200);
+ if (maxFirstRow > 0) {
+ drawListScrollbar(
+ image,
+ DIALOG_X + DIALOG_WIDTH - 7,
+ DIALOG_Y + PADDING,
+ visibleHeight,
+ this.firstRow,
+ rows.length - maxFirstRow,
+ rows.length,
+ );
}
return image;
}
@@ -94,12 +149,24 @@ export class EvenHubPermissionDialogLayer implements Layer {
const actions = this.actions();
switch (event.type) {
case "scroll-up":
- this.selectedIndex = (this.selectedIndex + actions.length - 1) % actions.length;
+ if (this.atBottom() && this.selectedIndex > 0) {
+ this.selectedIndex -= 1;
+ } else if (this.firstRow > 0) {
+ this.firstRow -= 1;
+ }
return;
case "scroll-down":
- this.selectedIndex = (this.selectedIndex + 1) % actions.length;
+ if (!this.atBottom()) {
+ this.firstRow += 1;
+ } else {
+ this.selectedIndex = Math.min(actions.length - 1, this.selectedIndex + 1);
+ }
return;
case "click":
+ if (!this.atBottom()) {
+ this.firstRow += 1;
+ return;
+ }
if (actions[this.selectedIndex] === "Privacy policy") {
openPrivacyPolicyOnPhone(this.privacyPolicyUrl, this.appName);
} else {
diff --git a/app/apps/evenhub/session.ts b/app/apps/evenhub/session.ts
index 739a920f..c9341c8c 100644
--- a/app/apps/evenhub/session.ts
+++ b/app/apps/evenhub/session.ts
@@ -38,14 +38,17 @@ import {
import { EvenHubApiKeyDialogLayer } from "./api-key-dialog";
import {
asRecord,
+ declaredMenuItems,
eventCaptureContainer,
parsePage,
readNumber,
readOptionalNumber,
readString,
+ readTextBrightness,
type EvenHubImageContainer,
type EvenHubListContainer,
type EvenHubContainer,
+ type EvenHubMenuItem,
type EvenHubPage,
} from "./containers";
import { compositePage } from "./compositor";
@@ -53,7 +56,7 @@ import { type EvenHubManifest } from "./ehpk";
import { permissionsIncludeMicrophone, permissionsInclude } from "./permissions";
import { evenHubMicRouter, type EvenHubMicClient } from "./mic-router";
import { evenHubImuRouter, type EvenHubImuClient } from "./imu-router";
-import { evenHubCompassRouter, type EvenHubCompassClient } from "./compass-router";
+import { evenHubCompassRouter, type EvenHubCompassClient, type EvenHubCompassReading } from "./compass-router";
import { type ImuReading } from "../../native/imu";
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
import { getCurrentLocation } from "../../native/location";
@@ -73,6 +76,9 @@ const FOREGROUND_ENTER_EVENT = 4;
const FOREGROUND_EXIT_EVENT = 5;
const SYSTEM_EXIT_EVENT = 7;
const IMU_DATA_REPORT_EVENT = 8;
+/** SDK 0.0.14: the press gesture, delivered like any other list/text/sys event. */
+const LONG_PRESS_EVENT = 9;
+const LONG_PRESS_RELEASE_EVENT = 10;
/**
* Injected into every served HTML document at document start (before any app
@@ -440,6 +446,24 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
case "double-click":
this.emitSysEvent(DOUBLE_CLICK_EVENT, gestureSource(event.source));
break;
+ case "long-press":
+ case "short-then-long-press":
+ case "long-press-release": {
+ // SDK 0.0.14 exposes press and release as ordinary events. The app's
+ // press is the context-menu gesture (tap-then-hold; the shell keeps
+ // the plain long-press for its system menu): the window still opens
+ // its menu on it (that menu is where the app's contextual-menu items
+ // live, and it is the way out of an app that owns double-click), so
+ // an app hears the press as well as seeing the menu — it cannot be
+ // given exclusive use of the gesture.
+ const eventType = event.type === "long-press-release" ? LONG_PRESS_RELEASE_EVENT : LONG_PRESS_EVENT;
+ if (capture?.kind === "list") {
+ this.emitListEvent(capture, eventType);
+ } else {
+ this.emitSysEvent(eventType, gestureSource(event.source));
+ }
+ break;
+ }
case "scroll-up":
case "scroll-down": {
const eventType = event.type === "scroll-up" ? SCROLL_TOP_EVENT : SCROLL_BOTTOM_EVENT;
@@ -455,6 +479,20 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
}
}
+ /**
+ * The contextual-menu entries the running page registered (SDK 0.0.14
+ * `menuObject`), for the window to merge into its own menu. Empty when the
+ * app declared none.
+ */
+ contextMenuItems(): EvenHubMenuItem[] {
+ return this.page?.menuItems ?? [];
+ }
+
+ /** The user picked one of the app's contextual-menu entries. */
+ selectContextMenuItem(itemID: number): void {
+ this.pushMessage("evenHubEvent", { type: "menuItemClickEvent", jsonData: { itemID } });
+ }
+
private scrollList(list: EvenHubListContainer, eventType: number): void {
// Swipe up selects the previous item, swipe down the next (stock direction).
const delta = eventType === SCROLL_TOP_EVENT ? -1 : 1;
@@ -542,10 +580,21 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
return this.screenOn;
}
- /** A decoded mic frame from the router: hand it to the app as an audioEvent. */
+ /**
+ * A decoded mic frame from the router: hand it to the app as an audioEvent.
+ *
+ * SDK 0.0.14 added per-frame `direction` and `speakerRole`. Neither is
+ * available here — the router hands over plain PCM with no beamforming tag,
+ * and speakerRole is an app-level diarization result the stock host computes
+ * — so both are sent as the fallbacks the SDK documents for a phone mic and
+ * for older hosts.
+ */
deliverAudioPcm(pcm: Uint8Array): void {
const audioPcm = Array.from(pcm);
- this.pushMessage("evenHubEvent", { type: "audioEvent", jsonData: { audioPcm } });
+ this.pushMessage("evenHubEvent", {
+ type: "audioEvent",
+ jsonData: { audioPcm, direction: null, speakerRole: "unknown" },
+ });
}
/**
@@ -757,7 +806,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
return 1;
}
const page = parsePage(data);
- this.warnOnInvalidPage(page);
+ this.warnOnInvalidPage(page, data);
this.page = page;
this.pageCreated = true;
// The launch focus arrived before the page existed; deliver the ENTER now.
@@ -772,14 +821,21 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
private rebuildPage(data: Record): boolean {
// Also serves as create for apps that fall back to rebuild-on-error.
const page = parsePage(data);
- this.warnOnInvalidPage(page);
+ this.warnOnInvalidPage(page, data);
this.page = page;
this.pageCreated = true;
this.windowHooks?.requestRender();
return true;
}
- private warnOnInvalidPage(page: EvenHubPage): void {
+ private warnOnInvalidPage(page: EvenHubPage, data: Record): void {
+ const declaredMenuCount = declaredMenuItems(data).length;
+ if (declaredMenuCount > page.menuItems.length) {
+ this.log(
+ `evenhub: dropped ${declaredMenuCount - page.menuItems.length} of ${declaredMenuCount} contextual menu ` +
+ "items (max 10, itemID must be non-zero and unique, itemName at most 32 UTF-8 bytes)",
+ );
+ }
// Stock rejects these outright; we accept-and-log until rejection is
// proven necessary for compatibility.
const captures = page.containers.filter((c) => c.kind !== "image" && c.isEventCapture).length;
@@ -813,6 +869,10 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
} else {
container.content = content;
}
+ // SDK 0.0.14: textColor on an incremental update sets the container's
+ // brightness; omitting it keeps whatever level the container has.
+ const brightness = readTextBrightness(data);
+ if (brightness !== undefined) container.textColor = brightness;
this.windowHooks?.requestRender();
return true;
}
@@ -953,8 +1013,8 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
// ----- compass (EvenHubCompassClient) -----
- deliverCompass(headingDegrees: number): void {
- this.pushExtEvent("compass", { headingDegrees });
+ deliverCompass(reading: EvenHubCompassReading): void {
+ this.pushExtEvent("compass", reading);
}
private setCompass(enable: boolean): void {
diff --git a/app/apps/evenhub/store-detail-layer.ts b/app/apps/evenhub/store-detail-layer.ts
index 9eeffad6..ab179023 100644
--- a/app/apps/evenhub/store-detail-layer.ts
+++ b/app/apps/evenhub/store-detail-layer.ts
@@ -8,13 +8,12 @@ import { TextViewerLayer } from "../files/text-viewer";
import { evenHubApi, type EvenHubStoreApp } from "./even-api";
import {
getInstalledEvenHubApp,
- installEvenHubPackageBytes,
installedEvenHubAppId,
- readEvenHubPackageManifestBytes,
setInstalledEvenHubIcon,
- type EvenHubInstallIcon,
+ type InstalledEvenHubApp,
} from "./installed-apps";
-import { EvenHubPermissionDialogLayer } from "./permission-dialog";
+import { cleanError, installStoreApp } from "./store-install";
+import { describeUpdate } from "./updates";
import { lineStep, listRowHeight } from "../../ui/metrics";
const X = 18;
@@ -22,6 +21,8 @@ const X = 18;
export type EvenHubStoreDetailOptions = {
launchApp: (appId: string) => Promise | void;
appendLog: (message: string) => void;
+ /** A package was installed, updated, or reinstalled from this page. */
+ onInstalled?: (app: InstalledEvenHubApp) => void;
};
/** Storefront metadata and the Install/Launch action for one public app. */
@@ -46,7 +47,7 @@ export class EvenHubStoreDetailLayer implements Layer {
const actionRowH = listRowHeight(font) + 4;
const installed = getInstalledEvenHubApp(this.app.packageId);
- const actions = ["About", "What's New", this.working ? "Installing..." : installed ? "Launch" : "Install"];
+ const actions = ["About", "What's New", this.working ? "Installing..." : this.primaryActionLabel(installed)];
// Detail lines as (text, shade, extra gap below); built per candidate
// width so the layout choice below can measure before drawing.
@@ -70,7 +71,13 @@ export class EvenHubStoreDetailLayer implements Layer {
lines.push({ text: truncateText(font, line, textWidth), value: 125, gapAfter: 0 });
}
if (installed && !this.status) {
- lines.push({ text: `Installed version ${installed.version}`, value: 155, gapAfter: 0 });
+ const standing = describeUpdate(installed, this.app);
+ const note = standing.packageMissing
+ ? " · package missing, reinstall"
+ : standing.updateAvailable
+ ? " · update available"
+ : "";
+ lines.push({ text: truncateText(font, `Installed version ${installed.version}${note}`, textWidth), value: 155, gapAfter: 0 });
}
if (this.status) {
lines.push({ text: truncateText(font, this.status, textWidth), value: 180, gapAfter: 0 });
@@ -138,77 +145,39 @@ export class EvenHubStoreDetailLayer implements Layer {
}
const installed = getInstalledEvenHubApp(this.app.packageId);
- if (installed) {
+ if (installed && this.primaryActionLabel(installed) === "Launch") {
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
return;
}
- await this.prepareInstall(ctx);
+ await this.install(ctx);
}
- private async prepareInstall(ctx: LayerContext): Promise {
+ /** Install for a new app; Update / Reinstall when the installed copy is stale or gone. */
+ private primaryActionLabel(installed: InstalledEvenHubApp | null): string {
+ if (!installed) return "Install";
+ const standing = describeUpdate(installed, this.app);
+ if (standing.packageMissing) return "Reinstall";
+ return standing.updateAvailable ? "Update" : "Launch";
+ }
+
+ private async install(ctx: LayerContext): Promise {
this.working = true;
- this.status = `Downloading ${this.app.name}...`;
ctx.actions.requestRender();
try {
- const [download, icon] = await Promise.all([
- evenHubApi.downloadApp(this.app.packageId),
- this.app.iconPath
- ? evenHubApi.downloadPublicAsset(this.app.iconPath).catch((error) => {
- this.options.appendLog(`evenhub store: icon unavailable for ${this.app.packageId}: ${cleanError(error)}`);
- return undefined;
- })
- : Promise.resolve(undefined),
- ]);
- const manifest = readEvenHubPackageManifestBytes(download.bytes);
- if (!manifest) throw new Error("The downloaded EHPK manifest could not be read.");
- const privacyPolicyUrl = download.privacyPolicyUrl || manifest.privacyPolicyUrl;
- this.working = false;
- this.status = "";
- ctx.actions.requestRender();
- if (manifest.permissions.length > 0 || privacyPolicyUrl) {
- ctx.stack.push(
- new EvenHubPermissionDialogLayer(
- manifest.name,
- manifest.permissions,
- privacyPolicyUrl,
- () => {
- void this.installAndLaunch(ctx, download.bytes, icon);
- },
- () => {
- this.status = "Installation canceled.";
- ctx.actions.requestRender();
- },
- ),
- );
+ const result = await installStoreApp(ctx, this.app, {
+ appendLog: this.options.appendLog,
+ onStatus: (status) => {
+ this.status = status;
+ ctx.actions.requestRender();
+ },
+ });
+ if (!result) {
+ this.status = "Installation canceled.";
return;
}
- await this.installAndLaunch(ctx, download.bytes, icon);
- } catch (error) {
- this.working = false;
- this.status = cleanError(error);
- this.options.appendLog(`evenhub store: ${this.status}`);
- ctx.actions.requestRender();
- }
- }
-
- private async installAndLaunch(
- ctx: LayerContext,
- bytes: Uint8Array,
- icon: EvenHubInstallIcon | undefined,
- ): Promise {
- this.working = true;
- this.status = "Installing...";
- ctx.actions.requestRender();
- try {
- const result = installEvenHubPackageBytes(bytes, {
- expectedPackageId: this.app.packageId,
- icon,
- });
- this.options.appendLog(
- `evenhub store: installed ${result.packageId} ${result.version} (${bytes.length} bytes)`,
- );
this.status = "Installed";
+ this.options.onInstalled?.(result);
ctx.actions.requestRender();
await this.options.launchApp(installedEvenHubAppId(result.packageId));
} catch (error) {
@@ -258,7 +227,3 @@ function formatBytes(value: number): string {
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
return `${(value / (1024 * 1024)).toFixed(1)} MB`;
}
-
-function cleanError(error: unknown): string {
- return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
-}
diff --git a/app/apps/evenhub/store-install.ts b/app/apps/evenhub/store-install.ts
new file mode 100644
index 00000000..5c63e1a9
--- /dev/null
+++ b/app/apps/evenhub/store-install.ts
@@ -0,0 +1,97 @@
+/**
+ * The storefront install pipeline shared by the app detail page and the
+ * Updates tab: download the package and its icon, confirm permissions when
+ * that is warranted, close running instances, and store the package.
+ */
+import { type LayerContext } from "../../ui/layers";
+import { evenHubApi, type EvenHubStoreApp } from "./even-api";
+import { type EvenHubManifest } from "./ehpk";
+import {
+ installEvenHubPackageBytes,
+ installedEvenHubPackagePath,
+ readEvenHubPackageManifest,
+ readEvenHubPackageManifestBytes,
+ type InstalledEvenHubApp,
+} from "./installed-apps";
+import { closeRunningPackage } from "./manager";
+import { EvenHubPermissionDialogLayer } from "./permission-dialog";
+
+export type StoreInstallOptions = {
+ appendLog: (message: string) => void;
+ /** Progress text for the caller's status line ("Downloading X...", "Installing..."). */
+ onStatus: (status: string) => void;
+};
+
+/**
+ * Install (or update/reinstall) one storefront app. Resolves to the new
+ * registry entry, or null when the user declined the permission dialog.
+ * Failures throw with a user-presentable message.
+ *
+ * The permission dialog is shown for a first install, and for an update
+ * whose manifest declares permissions the currently installed package did
+ * not (or a privacy policy it did not); an update that asks for nothing new
+ * goes straight through.
+ */
+export async function installStoreApp(
+ ctx: LayerContext,
+ app: EvenHubStoreApp,
+ options: StoreInstallOptions,
+): Promise {
+ options.onStatus(`Downloading ${app.name}...`);
+ const [download, icon] = await Promise.all([
+ evenHubApi.downloadApp(app.packageId),
+ app.iconPath
+ ? evenHubApi.downloadPublicAsset(app.iconPath).catch((error) => {
+ options.appendLog(`evenhub store: icon unavailable for ${app.packageId}: ${cleanError(error)}`);
+ return undefined;
+ })
+ : Promise.resolve(undefined),
+ ]);
+ const manifest = readEvenHubPackageManifestBytes(download.bytes);
+ if (!manifest) throw new Error("The downloaded EHPK manifest could not be read.");
+ const privacyPolicyUrl = download.privacyPolicyUrl || manifest.privacyPolicyUrl;
+ const needsPrompt = (manifest.permissions.length > 0 || privacyPolicyUrl)
+ && !alreadyGranted(app.packageId, manifest);
+ if (needsPrompt) {
+ options.onStatus("");
+ ctx.actions.requestRender();
+ const accepted = await new Promise((resolve) => {
+ ctx.stack.push(
+ new EvenHubPermissionDialogLayer(
+ manifest.name,
+ manifest.permissions,
+ privacyPolicyUrl,
+ () => resolve(true),
+ () => resolve(false),
+ ),
+ );
+ });
+ if (!accepted) return null;
+ }
+
+ options.onStatus("Installing...");
+ ctx.actions.requestRender();
+ // A running instance would keep serving the old unpacked runtime; every
+ // launch re-unpacks from the stored EHPK, so closing it is enough.
+ closeRunningPackage(app.packageId);
+ const result = installEvenHubPackageBytes(download.bytes, { expectedPackageId: app.packageId, icon });
+ options.appendLog(`evenhub store: installed ${result.packageId} ${result.version} (${download.bytes.length} bytes)`);
+ return result;
+}
+
+/**
+ * Whether the installed package already declares every permission the new
+ * manifest asks for. (The store's privacy-policy link is not compared: the
+ * download metadata carries it as a CDN path while the installed app.json
+ * usually has none, so comparing would re-prompt on every update.)
+ */
+function alreadyGranted(packageId: string, manifest: EvenHubManifest): boolean {
+ const current = readEvenHubPackageManifest(installedEvenHubPackagePath(packageId));
+ if (!current) return false;
+ const granted = new Set(current.permissions);
+ return manifest.permissions.every((permission) => granted.has(permission));
+}
+
+export function cleanError(error: unknown): string {
+ return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
+}
diff --git a/app/apps/evenhub/store-layer.ts b/app/apps/evenhub/store-layer.ts
index 55a7f49c..82df0fee 100644
--- a/app/apps/evenhub/store-layer.ts
+++ b/app/apps/evenhub/store-layer.ts
@@ -3,39 +3,119 @@ import { GrayImage, type UiFont } from "../../graphics/image";
import { truncateText, wrapText } from "../../graphics/textwrap";
import { clamp } from "../../util/numeric-util";
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
-import { type Layer, type LayerActions, type LayerContext } from "../../ui/layers";
+import { type Layer, type LayerActions, type LayerContext, type LayerStack } from "../../ui/layers";
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
import { shell } from "../../ui/shell/shell";
-import { evenHubApi, EvenHubAuthenticationError, isEvenHubStoreConfigured, type EvenHubStoreApp } from "./even-api";
+import { ConfigSettingString } from "../../ui/dashboard-settings";
+import { evenHubApi, EvenHubAuthenticationError, isEvenHubStoreConfigured, type EvenHubStoreApp, type EvenHubStorePage } from "./even-api";
import { clearEvenHubLoginForm, clearEvenHubSession, clearTransientEvenHubSession, evenHubLoginEmailSetting, evenHubLoginPasswordSetting, evenHubRememberMeSetting, resetEvenHubLoginForm } from "./credentials";
+import { getInstalledEvenHubApps, uninstallEvenHubPackage, type InstalledEvenHubApp } from "./installed-apps";
import { EvenHubStoreDetailLayer } from "./store-detail-layer";
+import { cleanError, installStoreApp } from "./store-install";
+import { checkForEvenHubUpdates, describeUpdate, type EvenHubAppUpdate } from "./updates";
import { lineStep } from "../../ui/metrics";
const LIST_X = 18;
+/** Horizontal gap between tab labels. */
+const TAB_GAP = 18;
-/** Header: title line, then the status/subtitle line, then a small gap. */
+/** Header: title + tabs line, then the status/subtitle line, then a small gap. */
function headerHeight(font: UiFont): number {
return 8 + lineStep(font) + font.lineHeight + 6;
}
+/** Last search typed on the phone; kept so reopening the store shows it again. */
+export const evenHubSearchQuerySetting = new ConfigSettingString({
+ id: "evenhub-search-query",
+ label: "Search",
+ storageKey: "evenhub.store.searchQuery",
+ defaultValue: "",
+ editorTitle: "Search EvenHub",
+ glassesEditTitle: "Search EvenHub",
+ normalize: (value) => (value ?? "").replace(/\s+/g, " ").trim(),
+});
+
+type StoreTab = "top" | "new" | "search" | "updates";
+
+const TABS: { id: StoreTab; label: string }[] = [
+ { id: "top", label: "Top" },
+ { id: "new", label: "New" },
+ { id: "search", label: "Search" },
+ { id: "updates", label: "Updates" },
+];
+
+type StoreRow =
+ /** A storefront app; `update` is set on the Updates tab. */
+ | { kind: "app"; app: EvenHubStoreApp; update?: EvenHubAppUpdate }
+ /** The Search tab's first row: shows the query and opens the phone editor. */
+ | { kind: "search-query" }
+ /** A registry entry whose package is gone and which the store no longer lists. */
+ | { kind: "orphan"; update: EvenHubAppUpdate };
+
+type TabState = {
+ rows: StoreRow[];
+ /** Server-reported total, or 0 when unknown. */
+ total: number;
+ nextPage: number;
+ /** No further pages: the total was reached, or a page added nothing new. */
+ exhausted: boolean;
+ /** A load has completed (or failed) at least once. */
+ loaded: boolean;
+ loading: boolean;
+ /** Progress or error text for the subtitle line. */
+ status: string;
+ selectedIndex: number;
+ scrollRow: number;
+ /** Search only: the query the rows belong to. */
+ query: string;
+};
+
+function emptyTab(): TabState {
+ return {
+ rows: [],
+ total: 0,
+ nextPage: 1,
+ exhausted: false,
+ loaded: false,
+ loading: false,
+ status: "",
+ selectedIndex: 0,
+ scrollRow: 0,
+ query: "",
+ };
+}
+
export type EvenHubStoreLayerOptions = {
launchApp: (appId: string) => Promise | void;
appendLog: (message: string) => void;
};
-/** Browse the public EvenHub leaderboard and download one package to run. */
+/**
+ * The EvenHub storefront: Top (leaderboard), New (by first publication),
+ * Search, and Updates (installed apps that are stale or whose package is
+ * missing). The tab row is its own focus level above the list: double-click
+ * in the list focuses the tabs, scrolling there switches tabs, and a click
+ * returns to the list.
+ */
export class EvenHubStoreLayer implements Layer {
- private apps: EvenHubStoreApp[] = [];
- private selectedIndex = 0;
- private scrollRow = 0;
- private total = 0;
- private nextPage = 1;
+ private readonly tabs: Record = {
+ top: emptyTab(),
+ new: emptyTab(),
+ search: emptyTab(),
+ updates: emptyTab(),
+ };
+ private activeTab: StoreTab = "top";
+ private focus: "list" | "tabs" = "list";
private started = false;
- private loading = false;
private showingLogin = !isEvenHubStoreConfigured();
- private status = this.showingLogin ? "Sign in to browse public apps." : "";
- private credentialEditorOpen = false;
+ private loginStatus = this.showingLogin ? "Sign in to browse public apps." : "";
+ private loginBusy = false;
+ private phoneEditor: "none" | "credentials" | "search" = "none";
private closed = false;
+ /** Serializes the Update All action; also blocks per-row installs meanwhile. */
+ private updatingAll = false;
+ /** An app page requested while the login form was up; opened once signed in. */
+ private pendingPackage: InstalledEvenHubApp | null = null;
constructor(private readonly options: EvenHubStoreLayerOptions) {
if (this.showingLogin) resetEvenHubLoginForm();
@@ -47,7 +127,7 @@ export class EvenHubStoreLayer implements Layer {
if (this.showingLogin) {
this.openCredentialEditor(ctx);
} else {
- void this.reload(ctx);
+ void this.ensureTabLoaded(ctx, this.activeTab);
}
}
@@ -57,11 +137,9 @@ export class EvenHubStoreLayer implements Layer {
const headerH = headerHeight(font);
image.drawText(font, LIST_X, 8, "EvenHub", 220);
- const subtitle = this.status || (this.total ? `${this.apps.length} of ${this.total} public apps` : "Public apps");
- image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, subtitle, width - LIST_X * 2), 125);
-
if (this.showingLogin) {
- const message = this.loading
+ image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, this.loginStatus, width - LIST_X * 2), 125);
+ const message = this.loginBusy
? "Signing in..."
: "Enter your Even account email and password in the phone app.";
for (const [index, line] of wrapText(font, message, width - LIST_X * 2).entries()) {
@@ -71,69 +149,181 @@ export class EvenHubStoreLayer implements Layer {
return image;
}
- if (this.apps.length === 0) {
- const message = this.loading ? "Loading apps..." : this.status || "No apps returned.";
- image.drawText(font, LIST_X, headerH + 22, truncateText(font, message, width - LIST_X * 2), 190);
- } else {
- this.selectedIndex = clamp(this.selectedIndex, 0, this.apps.length - 1);
- const rowH = Math.max(30, 2 * lineStep(font) + 4);
- const visibleRows = Math.max(1, Math.floor((height - headerH - 4) / rowH));
- this.scrollRow = scrollToKeepSelectionVisible(
- this.scrollRow,
- this.selectedIndex,
- visibleRows,
- this.apps.length,
- );
- const last = Math.min(this.apps.length, this.scrollRow + visibleRows);
- for (let index = this.scrollRow; index < last; index++) {
- const app = this.apps[index]!;
- const y = headerH + (index - this.scrollRow) * rowH;
- const selected = index === this.selectedIndex;
- if (selected) {
- drawSelectionHighlight(image, LIST_X - 6, y, width - LIST_X * 2 + 12, rowH - 2, ctx.stack.isFocused(), 5);
- }
- image.drawText(font, LIST_X, y + 2, truncateText(font, app.name, width - LIST_X * 2), 215);
- const detail = app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`;
- image.drawText(font, LIST_X, y + 2 + lineStep(font), truncateText(font, detail, width - LIST_X * 2), 115);
- }
- if (this.apps.length > visibleRows) {
- drawListScrollbar(image, width - 5, headerH, visibleRows * rowH - 3, this.scrollRow, visibleRows, this.apps.length);
+ this.paintTabs(image, font, ctx);
+
+ const tab = this.tabs[this.activeTab];
+ const subtitle = tab.status || this.subtitle(this.activeTab, tab);
+ image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, subtitle, width - LIST_X * 2), 125);
+
+ if (tab.rows.length === 0) {
+ const message = tab.loading ? "Loading..." : this.emptyMessage(this.activeTab, tab);
+ for (const [index, line] of wrapText(font, message, width - LIST_X * 2).slice(0, 3).entries()) {
+ image.drawText(font, LIST_X, headerH + 22 + index * lineStep(font), line, 190);
}
+ return image;
}
+ tab.selectedIndex = clamp(tab.selectedIndex, 0, tab.rows.length - 1);
+ const rowH = Math.max(30, 2 * lineStep(font) + 4);
+ const visibleRows = Math.max(1, Math.floor((height - headerH - 4) / rowH));
+ tab.scrollRow = scrollToKeepSelectionVisible(tab.scrollRow, tab.selectedIndex, visibleRows, tab.rows.length);
+ const last = Math.min(tab.rows.length, tab.scrollRow + visibleRows);
+ const listFocused = ctx.stack.isFocused() && this.focus === "list";
+ for (let index = tab.scrollRow; index < last; index++) {
+ const row = tab.rows[index]!;
+ const y = headerH + (index - tab.scrollRow) * rowH;
+ if (index === tab.selectedIndex) {
+ drawSelectionHighlight(image, LIST_X - 6, y, width - LIST_X * 2 + 12, rowH - 2, listFocused, 5);
+ }
+ const { title, detail, titleValue } = this.rowText(row);
+ image.drawText(font, LIST_X, y + 2, truncateText(font, title, width - LIST_X * 2), titleValue);
+ image.drawText(font, LIST_X, y + 2 + lineStep(font), truncateText(font, detail, width - LIST_X * 2), 115);
+ }
+ if (tab.rows.length > visibleRows) {
+ drawListScrollbar(image, width - 5, headerH, visibleRows * rowH - 3, tab.scrollRow, visibleRows, tab.rows.length);
+ }
return image;
}
+ /** Tab labels to the right of the title; the active one is bright and underlined. */
+ private paintTabs(image: GrayImage, font: UiFont, ctx: LayerContext): void {
+ const tabsFocused = ctx.stack.isFocused() && this.focus === "tabs";
+ let x = LIST_X + font.measureText("EvenHub") + 28;
+ for (const tab of TABS) {
+ const label = this.tabLabel(tab.id);
+ const w = font.measureText(label);
+ const active = tab.id === this.activeTab;
+ if (active) {
+ if (tabsFocused) {
+ drawSelectionHighlight(image, x - 6, 5, w + 12, font.lineHeight + 6, true, 4);
+ } else {
+ image.fillRect(x, 8 + font.lineHeight + 1, w, 1, 150);
+ }
+ }
+ image.drawText(font, x, 8, label, active ? 235 : 120);
+ x += w + TAB_GAP;
+ }
+ }
+
+ private tabLabel(tab: StoreTab): string {
+ const label = TABS.find((entry) => entry.id === tab)!.label;
+ if (tab !== "updates") return label;
+ const updates = this.tabs.updates;
+ const count = updates.rows.filter((row) => row.kind !== "search-query").length;
+ return updates.loaded && count > 0 ? `${label} (${count})` : label;
+ }
+
+ private subtitle(tab: StoreTab, state: TabState): string {
+ const count = state.rows.length;
+ switch (tab) {
+ case "top":
+ return state.total ? `${count} of ${state.total} public apps` : count ? `${count} public apps` : "Public apps by popularity";
+ case "new":
+ return count ? `${count} newest apps` : "Recently published apps";
+ case "search": {
+ const results = count - 1;
+ if (!state.query) return "Search public apps";
+ return results === 1 ? `1 result for "${state.query}"` : `${results} results for "${state.query}"`;
+ }
+ case "updates":
+ if (!state.loaded) return "Installed apps with newer versions";
+ return count === 0 ? "All installed apps are up to date" : count === 1 ? "1 app needs attention" : `${count} apps need attention`;
+ }
+ }
+
+ private emptyMessage(tab: StoreTab, state: TabState): string {
+ if (state.status) return state.status;
+ switch (tab) {
+ case "updates":
+ return getInstalledEvenHubApps().length === 0
+ ? "No apps are installed from EvenHub."
+ : "Every installed app is at its latest version.";
+ default:
+ return "No apps returned.";
+ }
+ }
+
+ private rowText(row: StoreRow): { title: string; detail: string; titleValue: number } {
+ switch (row.kind) {
+ case "search-query": {
+ const query = evenHubSearchQuerySetting.get();
+ return {
+ title: query ? `Search: ${query}` : "Search: (enter a query)",
+ detail: "Click to type on the phone, or use voice input.",
+ titleValue: 200,
+ };
+ }
+ case "orphan":
+ return {
+ title: row.update.installed.name,
+ detail: row.update.error
+ ? `Package missing · store lookup failed: ${row.update.error}`
+ : "Package missing · not in the store · click to forget",
+ titleValue: 170,
+ };
+ case "app": {
+ const { app, update } = row;
+ if (!update) {
+ return {
+ title: app.name,
+ detail: app.tagline || `${app.creatorName} · ${formatCount(app.installCount)} installs`,
+ titleValue: 215,
+ };
+ }
+ const detail = update.packageMissing
+ ? `Package missing · reinstall ${app.version ? `version ${app.version}` : ""}`.trim()
+ : `Version ${update.installed.version} installed · ${app.version} available`;
+ return { title: app.name, detail, titleValue: 215 };
+ }
+ }
+ }
+
async handleInput(event: InputEvent, ctx: LayerContext): Promise {
if (this.showingLogin) {
- if (event.type === "click" && !this.loading) {
+ if (event.type === "click" && !this.loginBusy) {
this.openCredentialEditor(ctx);
} else if (event.type === "double-click") {
shell.yieldFocusToSidebar();
}
return;
}
+ if (this.focus === "tabs") {
+ await this.handleTabInput(event, ctx);
+ return;
+ }
+ const tab = this.tabs[this.activeTab];
switch (event.type) {
case "scroll-up":
- this.selectedIndex = Math.max(0, this.selectedIndex - 1);
+ tab.selectedIndex = Math.max(0, tab.selectedIndex - 1);
return;
case "scroll-down":
- this.selectedIndex = Math.min(Math.max(0, this.apps.length - 1), this.selectedIndex + 1);
- if (this.selectedIndex >= this.apps.length - 4 && this.apps.length < this.total) {
- void this.loadNextPage(ctx);
- }
+ tab.selectedIndex = Math.min(Math.max(0, tab.rows.length - 1), tab.selectedIndex + 1);
+ if (tab.selectedIndex >= tab.rows.length - 4) void this.loadNextPage(ctx, this.activeTab);
return;
case "click":
- if (!this.loading) {
- const app = this.apps[this.selectedIndex];
- if (app) {
- ctx.stack.push(
- new EvenHubStoreDetailLayer(app, {
- launchApp: this.options.launchApp,
- appendLog: this.options.appendLog,
- }),
- );
- }
+ await this.activateRow(ctx, tab.rows[tab.selectedIndex]);
+ return;
+ case "double-click":
+ this.focus = "tabs";
+ return;
+ default:
+ return;
+ }
+ }
+
+ private async handleTabInput(event: InputEvent, ctx: LayerContext): Promise {
+ const index = TABS.findIndex((tab) => tab.id === this.activeTab);
+ switch (event.type) {
+ case "scroll-up":
+ this.switchTab(ctx, TABS[Math.max(0, index - 1)]!.id);
+ return;
+ case "scroll-down":
+ this.switchTab(ctx, TABS[Math.min(TABS.length - 1, index + 1)]!.id);
+ return;
+ case "click":
+ this.focus = "list";
+ if (this.activeTab === "search" && !evenHubSearchQuerySetting.get()) {
+ this.openSearchEditor(ctx);
}
return;
case "double-click":
@@ -144,107 +334,366 @@ export class EvenHubStoreLayer implements Layer {
}
}
- buildMenuItems(): MenuItem[] {
- if (this.showingLogin) return [];
- return [
- {
- label: "Refresh",
- onSelect: (ctx) => {
- ctx.stack.pop();
- void this.reload(ctx);
- },
- },
- {
- label: "Log Out",
- onSelect: (ctx) => {
- ctx.stack.pop();
- clearEvenHubSession();
- this.enterLogin(ctx, "Signed out.");
- },
- },
- ];
+ private switchTab(ctx: LayerContext, tab: StoreTab): void {
+ if (tab === this.activeTab) return;
+ if (this.activeTab === "search") this.closePhoneEditor(ctx.actions, "search");
+ this.activeTab = tab;
+ void this.ensureTabLoaded(ctx, tab);
}
- closeCredentialEditor(actions: Pick): void {
- if (!this.credentialEditorOpen) return;
- this.credentialEditorOpen = false;
- void actions.endTextSettingEdit();
+ private async activateRow(ctx: LayerContext, row: StoreRow | undefined): Promise {
+ if (!row) return;
+ switch (row.kind) {
+ case "search-query":
+ this.openSearchEditor(ctx);
+ return;
+ case "orphan": {
+ // Nothing can be reinstalled; the only useful action is to drop the
+ // dead registry entry so the launcher stops offering it.
+ const { packageId, name } = row.update.installed;
+ if (uninstallEvenHubPackage(packageId)) {
+ this.options.appendLog(`evenhub store: forgot missing package ${packageId}`);
+ this.removeUpdateRow(packageId);
+ this.tabs.updates.status = `Forgot ${name}.`;
+ }
+ return;
+ }
+ case "app":
+ if (this.updatingAll) return;
+ ctx.stack.push(
+ new EvenHubStoreDetailLayer(row.app, {
+ launchApp: this.options.launchApp,
+ appendLog: this.options.appendLog,
+ onInstalled: (installed) => this.onInstalled(installed),
+ }),
+ );
+ return;
+ }
+ }
+
+ /**
+ * Jump to an installed app's store page (the launcher's route for a package
+ * whose file is missing). Any page already open above the list is replaced.
+ * Store metadata is filled in by the detail page itself; until then a
+ * placeholder built from the registry entry stands in.
+ */
+ showInstalledPackage(stack: LayerStack, installed: InstalledEvenHubApp): void {
+ if (this.showingLogin) {
+ this.pendingPackage = installed;
+ return;
+ }
+ this.pendingPackage = null;
+ stack.clearToBase();
+ stack.push(
+ new EvenHubStoreDetailLayer(placeholderStoreApp(installed), {
+ launchApp: this.options.launchApp,
+ appendLog: this.options.appendLog,
+ onInstalled: (result) => this.onInstalled(result),
+ }),
+ );
+ }
+
+ /** Dictated text becomes a search (the shell's "Type Into App" / voice input). */
+ receiveTextInput(text: string, ctx: LayerContext): void {
+ if (this.showingLogin) return;
+ const query = evenHubSearchQuerySetting.set(text);
+ if (!query) return;
+ this.closePhoneEditor(ctx.actions, "search");
+ this.activeTab = "search";
+ this.focus = "list";
+ void this.runSearch(ctx, query);
+ }
+
+ buildMenuItems(): MenuItem[] {
+ if (this.showingLogin) return [];
+ const items: MenuItem[] = [];
+ if (this.activeTab === "search") {
+ items.push({
+ label: "Search...",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.focus = "list";
+ this.openSearchEditor(ctx);
+ },
+ });
+ }
+ if (this.activeTab === "updates" && this.updatableRows().length > 0) {
+ items.push({
+ label: this.updatingAll ? "Updating..." : "Update All",
+ disabled: () => this.updatingAll,
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ void this.updateAll(ctx);
+ },
+ });
+ }
+ items.push({
+ label: this.activeTab === "updates" ? "Check Again" : "Refresh",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ void this.reload(ctx, this.activeTab);
+ },
+ });
+ items.push({
+ label: "Log Out",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ clearEvenHubSession();
+ this.enterLogin(ctx, "Signed out.");
+ },
+ });
+ return items;
}
onWindowClosed(actions: Pick): void {
this.closed = true;
- this.closeCredentialEditor(actions);
+ this.closePhoneEditor(actions);
clearTransientEvenHubSession();
}
- private async reload(ctx: LayerContext): Promise {
- if (this.loading) return;
- this.apps = [];
- this.total = 0;
- this.nextPage = 1;
- this.selectedIndex = 0;
- this.scrollRow = 0;
- this.status = "";
+ // ---- loading -----------------------------------------------------------
+
+ private ensureTabLoaded(ctx: LayerContext, tab: StoreTab): Promise {
+ const state = this.tabs[tab];
+ if (state.loaded || state.loading) return Promise.resolve();
+ return this.reload(ctx, tab);
+ }
+
+ private async reload(ctx: LayerContext, tab: StoreTab): Promise {
if (!isEvenHubStoreConfigured()) {
this.enterLogin(ctx);
return;
}
- await this.loadNextPage(ctx);
+ if (this.tabs[tab].loading) return;
+ switch (tab) {
+ case "top":
+ case "new":
+ this.tabs[tab] = emptyTab();
+ await this.loadNextPage(ctx, tab);
+ return;
+ case "search":
+ await this.runSearch(ctx, evenHubSearchQuerySetting.get());
+ return;
+ case "updates":
+ await this.checkUpdates(ctx);
+ return;
+ }
}
- private async loadNextPage(ctx: LayerContext): Promise {
- if (this.loading || (this.total > 0 && this.apps.length >= this.total)) return;
- this.loading = true;
- this.status = this.apps.length ? "Loading more apps..." : "Loading apps...";
+ private async loadNextPage(ctx: LayerContext, tab: StoreTab): Promise {
+ const state = this.tabs[tab];
+ if (state.loading || state.exhausted) return;
+ if (tab === "search" && !state.query) return;
+ if (tab === "updates") return;
+ state.loading = true;
+ state.status = state.rows.length ? "Loading more apps..." : "Loading apps...";
ctx.actions.requestRender();
try {
- const page = await evenHubApi.listApps(this.nextPage);
- const seen = new Set(this.apps.map((app) => app.packageId));
- this.apps.push(...page.apps.filter((app) => !seen.has(app.packageId)));
- this.total = page.total;
- this.nextPage = page.page + 1;
- this.status = "";
- } catch (error) {
- const message = cleanError(error);
- if (error instanceof EvenHubAuthenticationError) {
- this.options.appendLog(`evenhub store login failed: ${message}`);
- this.enterLogin(ctx, `Login failed: ${message}`);
- return;
+ const page = await this.fetchPage(tab, state.nextPage, state.query);
+ const seen = new Set(state.rows.map((row) => (row.kind === "app" ? row.app.packageId : "")));
+ const fresh = page.apps.filter((app) => !seen.has(app.packageId));
+ state.rows.push(...fresh.map((app): StoreRow => ({ kind: "app", app })));
+ state.total = page.total;
+ state.nextPage = page.page + 1;
+ // A page that adds nothing (or a short page with no known total) means
+ // the endpoint has no more to give — or ignores paging altogether.
+ state.exhausted = (state.total > 0 && state.rows.length >= state.total)
+ || fresh.length === 0
+ || (state.total === 0 && page.apps.length < page.pageSize);
+ state.status = "";
+ if (tab === "top" && state.nextPage === 2 && !this.tabs.updates.loaded && !this.tabs.updates.loading) {
+ // Quietly find out whether the Updates tab deserves a count.
+ void this.checkUpdates(ctx, true);
}
- this.status = message;
- this.options.appendLog(`evenhub store: ${this.status}`);
+ } catch (error) {
+ if (this.handleAuthError(ctx, error)) return;
+ state.status = cleanError(error);
+ this.options.appendLog(`evenhub store: ${state.status}`);
} finally {
- this.loading = false;
+ state.loaded = true;
+ state.loading = false;
+ if (!this.closed) ctx.actions.requestRender();
+ }
+ }
+
+ private fetchPage(tab: StoreTab, page: number, query: string): Promise {
+ switch (tab) {
+ case "new":
+ return evenHubApi.listNewApps(page);
+ case "search":
+ return evenHubApi.searchApps(query, page);
+ default:
+ return evenHubApi.listApps(page);
+ }
+ }
+
+ private async runSearch(ctx: LayerContext, query: string): Promise {
+ const state = emptyTab();
+ state.query = query;
+ state.rows = [{ kind: "search-query" }];
+ state.loaded = !query;
+ // Keep the cursor on the first result once there are some.
+ state.selectedIndex = query ? 1 : 0;
+ this.tabs.search = state;
+ ctx.actions.requestRender();
+ if (query) await this.loadNextPage(ctx, "search");
+ }
+
+ private async checkUpdates(ctx: LayerContext, quiet = false): Promise {
+ const state = this.tabs.updates;
+ if (state.loading) return;
+ state.loading = true;
+ state.status = "";
+ const installedCount = getInstalledEvenHubApps().length;
+ if (!quiet) {
+ state.status = installedCount ? `Checking ${installedCount} installed apps...` : "";
ctx.actions.requestRender();
}
+ try {
+ const updates = await checkForEvenHubUpdates((done, total) => {
+ if (quiet) return;
+ state.status = `Checking installed apps (${done}/${total})...`;
+ ctx.actions.requestRender();
+ });
+ const rows: StoreRow[] = updates.map((update) =>
+ update.latest ? { kind: "app", app: update.latest, update } : { kind: "orphan", update },
+ );
+ state.rows = rows;
+ state.selectedIndex = 0;
+ state.scrollRow = 0;
+ state.status = "";
+ state.exhausted = true;
+ } catch (error) {
+ if (this.handleAuthError(ctx, error)) return;
+ state.status = cleanError(error);
+ this.options.appendLog(`evenhub store: update check failed: ${state.status}`);
+ } finally {
+ state.loaded = true;
+ state.loading = false;
+ if (!this.closed) ctx.actions.requestRender();
+ }
+ }
+
+ private updatableRows(): Extract[] {
+ return this.tabs.updates.rows.filter(
+ (row): row is Extract => row.kind === "app" && row.update !== undefined,
+ );
+ }
+
+ /** Install every pending update in turn; a declined permission dialog skips that app. */
+ private async updateAll(ctx: LayerContext): Promise {
+ if (this.updatingAll) return;
+ this.updatingAll = true;
+ const state = this.tabs.updates;
+ const pending = this.updatableRows();
+ let installed = 0;
+ const failures: string[] = [];
+ try {
+ for (const [index, row] of pending.entries()) {
+ if (this.closed) return;
+ const prefix = `${index + 1}/${pending.length} ${row.app.name}: `;
+ try {
+ const result = await installStoreApp(ctx, row.app, {
+ appendLog: this.options.appendLog,
+ onStatus: (status) => {
+ state.status = prefix + (status || "Confirm permissions on the glasses...");
+ ctx.actions.requestRender();
+ },
+ });
+ if (result) {
+ installed++;
+ this.onInstalled(result);
+ } else {
+ failures.push(`${row.app.name} (declined)`);
+ }
+ } catch (error) {
+ const message = cleanError(error);
+ this.options.appendLog(`evenhub store: update of ${row.app.packageId} failed: ${message}`);
+ failures.push(row.app.name);
+ }
+ }
+ state.status = failures.length
+ ? `Updated ${installed}; skipped ${failures.join(", ")}`
+ : installed === 1 ? "Updated 1 app." : `Updated ${installed} apps.`;
+ } finally {
+ this.updatingAll = false;
+ if (!this.closed) ctx.actions.requestRender();
+ }
+ }
+
+ /** After any install, drop the Updates row it satisfied (from the detail page or Update All). */
+ private onInstalled(installed: InstalledEvenHubApp): void {
+ const row = this.tabs.updates.rows.find(
+ (entry) => entry.kind === "app" && entry.app.packageId === installed.packageId,
+ );
+ if (row?.kind !== "app" || !row.update) return;
+ const standing = describeUpdate(installed, row.app);
+ if (!standing.updateAvailable && !standing.packageMissing) this.removeUpdateRow(installed.packageId);
+ }
+
+ private removeUpdateRow(packageId: string): void {
+ const state = this.tabs.updates;
+ state.rows = state.rows.filter((row) =>
+ row.kind === "search-query" ? true : row.kind === "app" ? row.app.packageId !== packageId : row.update.installed.packageId !== packageId,
+ );
+ state.selectedIndex = clamp(state.selectedIndex, 0, Math.max(0, state.rows.length - 1));
+ }
+
+ // ---- login and phone editors --------------------------------------------
+
+ /** Route a rejected session back to the login form; true if it was one. */
+ private handleAuthError(ctx: LayerContext, error: unknown): boolean {
+ if (!(error instanceof EvenHubAuthenticationError)) return false;
+ const message = cleanError(error);
+ this.options.appendLog(`evenhub store login failed: ${message}`);
+ this.enterLogin(ctx, `Login failed: ${message}`);
+ return true;
}
private enterLogin(ctx: LayerContext, status = "Sign in to browse public apps."): void {
const wasShowingLogin = this.showingLogin;
+ this.closePhoneEditor(ctx.actions, "search");
this.showingLogin = true;
- this.loading = false;
- this.apps = [];
- this.total = 0;
- this.status = status;
+ this.loginBusy = false;
+ this.loginStatus = status;
+ for (const tab of TABS) this.tabs[tab.id] = emptyTab();
+ this.focus = "list";
if (!wasShowingLogin) resetEvenHubLoginForm();
this.openCredentialEditor(ctx);
ctx.actions.requestRender();
}
private openCredentialEditor(ctx: LayerContext): void {
- if (this.credentialEditorOpen) return;
- this.credentialEditorOpen = true;
+ if (this.phoneEditor !== "none") return;
+ this.phoneEditor = "credentials";
void ctx.actions.startTextSettingsEdit(
[evenHubLoginEmailSetting, evenHubLoginPasswordSetting],
"Sign in to EvenHub",
() => {
- this.credentialEditorOpen = false;
+ this.phoneEditor = "none";
void this.submitCredentials(ctx);
},
{ setting: evenHubRememberMeSetting, label: "Remember me" },
);
}
+ private openSearchEditor(ctx: LayerContext): void {
+ if (this.phoneEditor !== "none") return;
+ this.phoneEditor = "search";
+ void ctx.actions.startTextSettingsEdit([evenHubSearchQuerySetting], "Search EvenHub", () => {
+ this.phoneEditor = "none";
+ if (this.closed) return;
+ void this.runSearch(ctx, evenHubSearchQuerySetting.get());
+ });
+ }
+
+ /** Close the phone editor if one is open (optionally only a given kind). */
+ private closePhoneEditor(actions: Pick, kind?: "credentials" | "search"): void {
+ if (this.phoneEditor === "none" || (kind && this.phoneEditor !== kind)) return;
+ this.phoneEditor = "none";
+ void actions.endTextSettingEdit();
+ }
+
private async submitCredentials(ctx: LayerContext): Promise {
const email = evenHubLoginEmailSetting.get();
const password = evenHubLoginPasswordSetting.get();
@@ -252,8 +701,8 @@ export class EvenHubStoreLayer implements Layer {
this.enterLogin(ctx, "Email and password are required.");
return;
}
- this.loading = true;
- this.status = "Signing in...";
+ this.loginBusy = true;
+ this.loginStatus = "Signing in...";
ctx.actions.requestRender();
try {
await evenHubApi.signIn(email, password, evenHubRememberMeSetting.get());
@@ -263,26 +712,43 @@ export class EvenHubStoreLayer implements Layer {
}
this.showingLogin = false;
clearEvenHubLoginForm();
- this.loading = false;
- await this.reload(ctx);
+ this.loginBusy = false;
+ const pending = this.pendingPackage;
+ if (pending) this.showInstalledPackage(ctx.stack, pending);
+ await this.reload(ctx, this.activeTab);
} catch (error) {
if (this.closed) return;
const message = cleanError(error);
this.options.appendLog(`evenhub store login failed: ${message}`);
- this.status = `Login failed: ${message}`;
+ this.loginStatus = `Login failed: ${message}`;
evenHubLoginPasswordSetting.set("");
this.openCredentialEditor(ctx);
} finally {
evenHubLoginPasswordSetting.set("");
- this.loading = false;
+ this.loginBusy = false;
if (!this.closed) ctx.actions.requestRender();
}
}
-
}
-function cleanError(error: unknown): string {
- return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
+/** A registry entry dressed as a store record, for pages opened before the store record arrives. */
+function placeholderStoreApp(installed: InstalledEvenHubApp): EvenHubStoreApp {
+ return {
+ id: 0,
+ packageId: installed.packageId,
+ name: installed.name,
+ creatorName: "",
+ tagline: "",
+ description: "",
+ categories: [],
+ installCount: 0,
+ likeCount: 0,
+ firstPublishedAt: "",
+ iconPath: "",
+ version: "",
+ changelog: "",
+ fileSize: 0,
+ };
}
function formatCount(value: number): string {
diff --git a/app/apps/evenhub/updates.ts b/app/apps/evenhub/updates.ts
new file mode 100644
index 00000000..05139c4c
--- /dev/null
+++ b/app/apps/evenhub/updates.ts
@@ -0,0 +1,100 @@
+/**
+ * Update detection for installed EvenHub apps.
+ *
+ * Two situations need the user's attention: the store has a newer version
+ * than the one installed, and the registry lists a package whose EHPK is no
+ * longer on disk (a settings export imported after a reinstall carries the
+ * registry but not the files).
+ */
+import { statPath } from "../../native/file-access";
+import { evenHubApi, EvenHubAuthenticationError, type EvenHubStoreApp } from "./even-api";
+import {
+ getInstalledEvenHubApps,
+ installedEvenHubPackagePath,
+ type InstalledEvenHubApp,
+} from "./installed-apps";
+
+export type EvenHubAppUpdate = {
+ installed: InstalledEvenHubApp;
+ /** Storefront record, or null when the store no longer lists the package. */
+ latest: EvenHubStoreApp | null;
+ /** The registry entry has no package file behind it. */
+ packageMissing: boolean;
+ /** The store's version is newer than the installed one. */
+ updateAvailable: boolean;
+ /** Why the store lookup failed, when it did. */
+ error?: string;
+};
+
+/** Whether an installed package's EHPK is actually present on disk. */
+export function isInstalledPackagePresent(packageId: string): boolean {
+ const entry = statPath(installedEvenHubPackagePath(packageId));
+ return entry !== null && !entry.isDirectory && entry.sizeBytes > 0;
+}
+
+/**
+ * Whether `candidate` is a newer version than `current`. Dotted numeric
+ * components compare numerically; non-numeric versions (or ones that agree
+ * numerically but differ textually, e.g. "1.0.0-beta" vs "1.0.0") are not
+ * treated as newer, so a stray tag never nags forever.
+ */
+export function isNewerVersion(candidate: string, current: string): boolean {
+ const a = versionComponents(candidate);
+ const b = versionComponents(current);
+ if (a.length === 0 || b.length === 0) return false;
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const delta = (a[i] ?? 0) - (b[i] ?? 0);
+ if (delta !== 0) return delta > 0;
+ }
+ return false;
+}
+
+function versionComponents(version: string): number[] {
+ const match = version.trim().match(/^v?(\d+(?:\.\d+)*)/i);
+ return match ? match[1]!.split(".").map(Number) : [];
+}
+
+/** Describe an installed app's standing against the store record it was fetched with. */
+export function describeUpdate(installed: InstalledEvenHubApp, latest: EvenHubStoreApp | null): EvenHubAppUpdate {
+ return {
+ installed,
+ latest,
+ packageMissing: !isInstalledPackagePresent(installed.packageId),
+ updateAvailable: latest !== null && isNewerVersion(latest.version, installed.version),
+ };
+}
+
+/**
+ * Look up every installed app in the store and return the ones needing
+ * action (a newer version, or a missing package). Lookups run a few at a
+ * time; `onProgress` reports how many have completed so far.
+ */
+export async function checkForEvenHubUpdates(
+ onProgress?: (done: number, total: number) => void,
+): Promise {
+ const installed = getInstalledEvenHubApps();
+ const results: EvenHubAppUpdate[] = new Array(installed.length);
+ let next = 0;
+ let done = 0;
+ const worker = async () => {
+ while (next < installed.length) {
+ const index = next++;
+ const app = installed[index]!;
+ try {
+ results[index] = describeUpdate(app, await evenHubApi.getStoreAppDetail(app.packageId));
+ } catch (error) {
+ // A rejected session affects every lookup: let the caller re-login.
+ if (error instanceof EvenHubAuthenticationError) throw error;
+ results[index] = { ...describeUpdate(app, null), error: cleanError(error) };
+ }
+ done++;
+ onProgress?.(done, installed.length);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(4, installed.length) }, worker));
+ return results.filter((update) => update.updateAvailable || update.packageMissing);
+}
+
+function cleanError(error: unknown): string {
+ return String((error as Error)?.message ?? error).replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
+}
diff --git a/app/apps/files/image-viewer.ts b/app/apps/files/image-viewer.ts
index 52d9072d..974dae06 100644
--- a/app/apps/files/image-viewer.ts
+++ b/app/apps/files/image-viewer.ts
@@ -2,7 +2,7 @@ import { type BdfFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { truncateText } from "../../graphics/textwrap";
import { GrayImage } from "../../graphics/image";
-import { loadImageFileAsGray } from "../../native/image-files";
+import { loadImageFileAsGray, PHOTO_TONE } from "../../native/image-files";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext } from "../../ui/layers";
@@ -13,8 +13,9 @@ const BODY_MARGIN = 2;
/**
* Image viewer for a file on disk: title line, then the image decoded to
- * grayscale and downscaled to fit the remaining area (never upscaled).
- * Double-click closes it. Sized to its hosting stack (a Files document
+ * grayscale with the shared photo tone (sRGB gamma, dithered onto the 16
+ * display levels) and downscaled to fit the remaining area (never
+ * upscaled). Double-click closes it. Sized to its hosting stack (a Files document
* window, or pushed over the file browser for view-in-place).
*/
export class ImageViewerLayer implements Layer {
@@ -35,7 +36,7 @@ export class ImageViewerLayer implements Layer {
const bodyHeight = height - BODY_TOP - BODY_MARGIN;
if (!this.loadAttempted) {
this.loadAttempted = true;
- this.image = loadImageFileAsGray(this.path, width - 2 * BODY_MARGIN, bodyHeight);
+ this.image = loadImageFileAsGray(this.path, width - 2 * BODY_MARGIN, bodyHeight, PHOTO_TONE);
}
if (!this.image) {
out.drawText(font, MARGIN_X, BODY_TOP + 16, "(could not load image)", 160);
diff --git a/app/apps/freecell/freecell-app.worker.ts b/app/apps/freecell/freecell-app.worker.ts
index 2529c48d..27132a55 100644
--- a/app/apps/freecell/freecell-app.worker.ts
+++ b/app/apps/freecell/freecell-app.worker.ts
@@ -8,7 +8,7 @@
* on a destination moves there; cascade-to-cascade moves take the longest
* legal run that fits (supermoves via empty cells/columns). Double-click
* sends the card at the cursor to its foundation, or cancels a pending
- * selection. Long-press opens the window menu (undo, new game, restart).
+ * selection. Tap-then-hold opens the window menu (undo, new game, restart).
* Watch swipes move the cursor spatially: left/right within the row, up/down
* between the top row (cells + foundations) and the cascades.
* Safe cards auto-play to the foundations after every move.
@@ -22,7 +22,7 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { WindowMenu } from "../../ui/window-menu";
import type { MenuItem } from "../../ui/menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import { directionalFallback, GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_LONG_PRESS, type InputEvent } from "../../ui/gestures";
@@ -100,12 +100,13 @@ type Snapshot = {
type FreecellWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
/** Whether this window is the shell's input target (pushed with each message). */
focused: boolean;
- /** Long-press window menu; created on first open. */
+ /** Tap-then-hold window menu; created on first open. */
menu: WindowMenu | null;
phase: "playing" | "won";
cascades: number[][];
@@ -142,6 +143,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
const window: FreecellWindow = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -212,8 +214,8 @@ function playSfx(window: FreecellWindow, steps: Step[]): void {
}
}
-/** The window's long-press menu (game actions + default entries). */
-function openWindowMenu(window: FreecellWindow): void {
+/** The window's context menu (game actions). */
+function windowMenuItems(window: FreecellWindow): MenuItem[] {
const items: MenuItem[] = [];
if (window.undoStack.length > 0 && window.phase === "playing") {
items.push({
@@ -250,12 +252,16 @@ function openWindowMenu(window: FreecellWindow): void {
},
},
);
- windowMenu(window).open([...items, ...defaultWindowMenuItems(window.windowId, post)]);
+ return items;
}
function windowMenu(window: FreecellWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
+ windowId: window.windowId,
+ post,
+ title: () => window.title,
+ items: () => windowMenuItems(window),
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
@@ -326,8 +332,8 @@ function handlePlayingInput(window: FreecellWindow, event: InputEvent, frameId:
sendToFoundation(window, window.cursor);
}
break;
- case "long-press":
- openWindowMenu(window);
+ case "short-then-long-press":
+ windowMenu(window).open();
break;
default:
frameTimings.finishFrame(frameId, "discarded: freecell ignored input");
@@ -346,8 +352,8 @@ function handleWonInput(window: FreecellWindow, event: InputEvent, frameId: numb
frameTimings.finishFrame(frameId, "discarded: freecell yielded focus");
post({ type: "yield-focus", windowId: window.windowId });
return;
- case "long-press":
- openWindowMenu(window);
+ case "short-then-long-press":
+ windowMenu(window).open();
break;
default:
frameTimings.finishFrame(frameId, "discarded: freecell ignored input");
@@ -629,19 +635,18 @@ function layoutFor(window: FreecellWindow): Layout {
}
function paint(window: FreecellWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- const planes = singlePlane(paintContent(window));
- if (window.phase === "won") {
- // The win box goes on its own plane: card labels are deferred glyphs that
- // render above their own image's raster, so an overlay drawn into the
- // board image could not cover them.
- const overlay = new GrayImage(window.viewportWidth, window.viewportHeight, 0);
- paintWinOverlay(overlay, window);
- planes.push({ image: overlay, x: 0, y: 0 });
- }
- return planes;
+ return windowMenu(window).paint(() => {
+ const planes = singlePlane(paintContent(window));
+ if (window.phase === "won") {
+ // The win box goes on its own plane: card labels are deferred glyphs
+ // that render above their own image's raster, so an overlay drawn into
+ // the board image could not cover them.
+ const overlay = new GrayImage(window.viewportWidth, window.viewportHeight, 0);
+ paintWinOverlay(overlay, window);
+ planes.push({ image: overlay, x: 0, y: 0 });
+ }
+ return planes;
+ });
}
function paintContent(window: FreecellWindow): GrayImage {
diff --git a/app/apps/launcher/launcher-app.ts b/app/apps/launcher/launcher-app.ts
index 099a1b1a..28a137c5 100644
--- a/app/apps/launcher/launcher-app.ts
+++ b/app/apps/launcher/launcher-app.ts
@@ -169,7 +169,7 @@ class LauncherGridLayer implements Layer {
}
/**
- * App-specific entries for the window's long-press menu. Only item mode
+ * App-specific entries for the window's context menu. Only item mode
* pins the selection to a single cell, and only apps can move to folders,
* so anywhere else the menu falls back to just the defaults.
*/
diff --git a/app/apps/launcher/launcher-folders.ts b/app/apps/launcher/launcher-folders.ts
index 53398d46..69eb486c 100644
--- a/app/apps/launcher/launcher-folders.ts
+++ b/app/apps/launcher/launcher-folders.ts
@@ -16,6 +16,10 @@ const DEFAULT_ASSIGNMENTS: Record = {
freecell: "Games",
minesweeper: "Games",
pinball: "Games",
+ calculator: "Prototypes",
+ microphones: "Prototypes",
+ nightscout: "Prototypes",
+ roam: "Prototypes",
};
export const FOLDER_NAME_MAX_LENGTH = 24;
diff --git a/app/apps/minesweeper/minesweeper-app.worker.ts b/app/apps/minesweeper/minesweeper-app.worker.ts
index edc91513..1f1b958a 100644
--- a/app/apps/minesweeper/minesweeper-app.worker.ts
+++ b/app/apps/minesweeper/minesweeper-app.worker.ts
@@ -15,14 +15,15 @@
*/
import "@nativescript/core/globals";
import { GrayImage } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
+import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { type MenuItem } from "../../ui/menu";
+import { WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import {
directionalFallback,
@@ -94,12 +95,13 @@ type GamePhase = "playing" | "paused" | "won" | "lost";
type MinesweeperWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
/** Whether this window is the shell's input target (pushed with each message). */
focused: boolean;
- /** Long-press window menu; created on first open. */
+ /** Tap-then-hold window menu; created on first open. */
menu: WindowMenu | null;
phase: GamePhase;
difficultyIndex: number;
@@ -146,6 +148,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
const window: MinesweeperWindow = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -249,10 +252,10 @@ function playSfx(window: MinesweeperWindow, steps: Step[]): void {
}
}
-/** The window's long-press menu (game actions + default entries). */
-function openWindowMenu(window: MinesweeperWindow): void {
+/** The window's context menu (game actions), offered while paused or over; playing keeps long-press for flagging. */
+function windowMenuItems(window: MinesweeperWindow): MenuItem[] {
const nextDifficulty = DIFFICULTIES[(window.difficultyIndex + 1) % DIFFICULTIES.length]!;
- windowMenu(window).open([
+ return [
{
label: "New game",
onSelect: (ctx) => {
@@ -278,13 +281,17 @@ function openWindowMenu(window: MinesweeperWindow): void {
if (window.soundOn) playSfx(window, SFX_RESUME);
},
},
- ...defaultWindowMenuItems(window.windowId, post),
- ]);
+ ];
}
function windowMenu(window: MinesweeperWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
+ windowId: window.windowId,
+ post,
+ title: () => window.title,
+ items: () => (window.phase === "playing" ? [] : windowMenuItems(window)),
+ claimsLongPress: () => window.phase === "playing",
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
@@ -359,6 +366,10 @@ function handlePlayingInput(window: MinesweeperWindow, event: InputEvent, frameI
}
toggleFlag(window);
break;
+ case "short-then-long-press":
+ // No context menu mid-game, so this opens the system menu instead.
+ windowMenu(window).open();
+ break;
case "double-click":
if (rowMode || watch) {
window.phase = "paused";
@@ -391,8 +402,8 @@ function handleIdleInput(window: MinesweeperWindow, event: InputEvent, frameId:
frameTimings.finishFrame(frameId, "discarded: minesweeper yielded focus");
post({ type: "yield-focus", windowId: window.windowId });
return;
- case "long-press":
- openWindowMenu(window);
+ case "short-then-long-press":
+ windowMenu(window).open();
break;
default:
frameTimings.finishFrame(frameId, "discarded: minesweeper ignored input");
@@ -588,10 +599,7 @@ function elapsedMs(window: MinesweeperWindow): number {
}
function paint(window: MinesweeperWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- return singlePlane(paintContent(window));
+ return windowMenu(window).paint();
}
function paintContent(window: MinesweeperWindow): GrayImage {
diff --git a/app/apps/music/music-app.ts b/app/apps/music/music-app.ts
index 13cb7b5e..c1895007 100644
--- a/app/apps/music/music-app.ts
+++ b/app/apps/music/music-app.ts
@@ -8,6 +8,7 @@ import { lineStep, tightRowHeight } from "../../ui/metrics";
import { mediaControllerBridge, type MediaControllerState, type MediaQueueItem } from "../../native/media-controller";
import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser";
import { MediaBrowseLayer } from "./media-browse";
+import { MusicSettingsLayer } from "./music-settings";
import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
@@ -480,6 +481,13 @@ export function createMusicAppWindow(options: InProcessAppOptions): InProcessWin
iconLetter: "M",
icon: "music",
closeable: true,
+ menuItems: () => [{
+ label: "Music settings",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ ctx.stack.push(new MusicSettingsLayer());
+ },
+ }],
actions: options.actions,
baseLayer: new MusicRootLayer(musicLayer),
submitFrame: options.submitFrame,
diff --git a/app/apps/music/music-settings.ts b/app/apps/music/music-settings.ts
new file mode 100644
index 00000000..52dac95d
--- /dev/null
+++ b/app/apps/music/music-settings.ts
@@ -0,0 +1,57 @@
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { GrayImage } from "../../graphics/image";
+import { truncateText } from "../../graphics/textwrap";
+import { mediaBrowserBridge } from "../../native/media-browser";
+import { isMediaAppEnabled, readMediaApps, setMediaAppEnabled } from "../../native/media-apps";
+import { type InputEvent } from "../../ui/gestures";
+import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
+import { drawToggleMenuItem, MenuLayer, type MenuItem } from "../../ui/menu";
+
+/** Discovered apps stay visible even when ignored or no longer publishing a session. */
+export class MusicSettingsLayer implements Layer {
+ private menu: MenuLayer | null = null;
+ private signature = "";
+ private selectedPackage = "";
+
+ constructor() {
+ // Refresh installed browser services, remembering ignored services too.
+ mediaBrowserBridge.listBrowsableApps(true);
+ }
+
+ private currentMenu(ctx: LayerContext): MenuLayer {
+ const apps = readMediaApps().sort((a, b) =>
+ a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
+ const width = ctx.stack.getBaseSize().width;
+ const signature = JSON.stringify([width, apps.map((app) => [app.packageName, app.appName])]);
+ if (!this.menu || signature !== this.signature) {
+ this.signature = signature;
+ const items: MenuItem[] = apps.map((app) => ({
+ label: app.appName,
+ onSelect: () => setMediaAppEnabled(app, !isMediaAppEnabled(app.packageName)),
+ render: ({ image, x, y, width, selected }) => {
+ if (selected) this.selectedPackage = app.packageName;
+ const font = getDefaultSmallFont();
+ const duplicateName = apps.some((other) => other !== app && other.appName === app.appName);
+ const label = duplicateName ? `${app.appName} (${app.packageName})` : app.appName;
+ drawToggleMenuItem(image, font, x, y, width, truncateText(font, label, width - 48),
+ isMediaAppEnabled(app.packageName), selected);
+ },
+ }));
+ if (!items.length) items.push({ label: "No media apps discovered yet.", disabled: true, onSelect: () => {} });
+ this.menu = new MenuLayer("Music settings", items, {
+ x: 8, y: 8, width: width - 16,
+ opaque: true, showBorder: false,
+ footer: "On = enabled Off = ignored",
+ }).selectItem(Math.max(0, apps.findIndex((app) => app.packageName === this.selectedPackage)));
+ }
+ return this.menu;
+ }
+
+ paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
+ return this.currentMenu(ctx).paint(ctx, paintBelow);
+ }
+
+ async handleInput(event: InputEvent, ctx: LayerContext): Promise {
+ await this.currentMenu(ctx).handleInput(event, ctx);
+ }
+}
diff --git a/app/apps/navigate/destinations.ts b/app/apps/navigate/destinations.ts
new file mode 100644
index 00000000..03849521
--- /dev/null
+++ b/app/apps/navigate/destinations.ts
@@ -0,0 +1,167 @@
+/**
+ * Saved and recent destinations for the Navigate app: Home and Work (plain
+ * address settings, also editable in the Settings app), custom named
+ * destinations, and a recency list of resolved places. Pure settings-store
+ * accessors, usable from the worker and the main thread alike.
+ */
+import {
+ navigateHomeAddressSetting,
+ navigateRecentDestinationsSetting,
+ navigateRememberRecentSetting,
+ navigateSavedDestinationsSetting,
+ navigateWorkAddressSetting,
+} from "../../ui/dashboard-settings";
+
+export const HOME_DESTINATION_ID = "home";
+export const WORK_DESTINATION_ID = "work";
+
+/** A named place the user set up; the address is resolved when navigating. */
+export type SavedDestination = {
+ id: string;
+ name: string;
+ address: string;
+ /** Home and Work are fixed slots (renaming/removal disabled); others are custom. */
+ builtin: boolean;
+};
+
+/** A place the user actually navigated to, already geocoded. */
+export type RecentDestination = {
+ name: string;
+ place: string;
+ longitude: number;
+ latitude: number;
+ atMs: number;
+};
+
+const MAX_RECENT = 8;
+const MAX_CUSTOM = 20;
+
+/** Every saved destination in display order: Home, Work (when set), then custom ones. */
+export function loadSavedDestinations(): SavedDestination[] {
+ const out: SavedDestination[] = [];
+ const home = navigateHomeAddressSetting.get();
+ if (home) out.push({ id: HOME_DESTINATION_ID, name: "Home", address: home, builtin: true });
+ const work = navigateWorkAddressSetting.get();
+ if (work) out.push({ id: WORK_DESTINATION_ID, name: "Work", address: work, builtin: true });
+ out.push(...loadCustomDestinations());
+ return out;
+}
+
+export function loadCustomDestinations(): SavedDestination[] {
+ const parsed = parseJsonArray(navigateSavedDestinationsSetting.get());
+ const out: SavedDestination[] = [];
+ for (const entry of parsed) {
+ if (!entry || typeof entry !== "object") continue;
+ const record = entry as Record;
+ const id = typeof record.id === "string" ? record.id : "";
+ const name = typeof record.name === "string" ? record.name.trim() : "";
+ const address = typeof record.address === "string" ? record.address.trim() : "";
+ if (!id || !name) continue;
+ out.push({ id, name, address, builtin: false });
+ }
+ return out;
+}
+
+function saveCustomDestinations(destinations: SavedDestination[]): void {
+ navigateSavedDestinationsSetting.set(
+ JSON.stringify(destinations.slice(0, MAX_CUSTOM).map(({ id, name, address }) => ({ id, name, address }))),
+ );
+}
+
+/** Add a custom destination; returns its id. */
+export function addCustomDestination(name: string, address: string): string {
+ const id = `d${Date.now().toString(36)}`;
+ saveCustomDestinations([...loadCustomDestinations(), { id, name, address, builtin: false }]);
+ return id;
+}
+
+export function updateCustomDestination(id: string, patch: { name?: string; address?: string }): void {
+ saveCustomDestinations(
+ loadCustomDestinations().map((destination) =>
+ destination.id === id
+ ? { ...destination, name: patch.name ?? destination.name, address: patch.address ?? destination.address }
+ : destination,
+ ),
+ );
+}
+
+export function removeCustomDestination(id: string): void {
+ saveCustomDestinations(loadCustomDestinations().filter((destination) => destination.id !== id));
+}
+
+/** Set a destination's address; Home/Work go to their own settings. */
+export function setDestinationAddress(id: string, address: string): void {
+ if (id === HOME_DESTINATION_ID) navigateHomeAddressSetting.set(address);
+ else if (id === WORK_DESTINATION_ID) navigateWorkAddressSetting.set(address);
+ else updateCustomDestination(id, { address });
+}
+
+/**
+ * Find a saved destination by name ("home", "work", or a custom name),
+ * case-insensitively, for voice/assistant queries such as "navigate home".
+ */
+export function findSavedDestinationByName(query: string): SavedDestination | null {
+ const wanted = query.trim().toLowerCase();
+ if (!wanted) return null;
+ return loadSavedDestinations().find((destination) => destination.name.toLowerCase() === wanted) ?? null;
+}
+
+export function loadRecentDestinations(): RecentDestination[] {
+ if (!navigateRememberRecentSetting.get()) return [];
+ const parsed = parseJsonArray(navigateRecentDestinationsSetting.get());
+ const out: RecentDestination[] = [];
+ for (const entry of parsed) {
+ if (!entry || typeof entry !== "object") continue;
+ const record = entry as Record;
+ const name = typeof record.name === "string" ? record.name : "";
+ const longitude = Number(record.longitude);
+ const latitude = Number(record.latitude);
+ if (!name || !Number.isFinite(longitude) || !Number.isFinite(latitude)) continue;
+ out.push({
+ name,
+ place: typeof record.place === "string" ? record.place : "",
+ longitude,
+ latitude,
+ atMs: Number(record.atMs) || 0,
+ });
+ }
+ return out;
+}
+
+/** Record a navigated-to place at the head of the recent list (no-op when the setting is off). */
+export function rememberRecentDestination(destination: Omit): void {
+ if (!navigateRememberRecentSetting.get()) return;
+ const others = loadRecentDestinations().filter((recent) => !isSamePlace(recent, destination));
+ const next = [{ ...destination, atMs: Date.now() }, ...others].slice(0, MAX_RECENT);
+ navigateRecentDestinationsSetting.set(JSON.stringify(next));
+}
+
+export function removeRecentDestination(destination: RecentDestination): void {
+ const remaining = loadRecentDestinations().filter((recent) => !isSamePlace(recent, destination));
+ navigateRecentDestinationsSetting.set(JSON.stringify(remaining));
+}
+
+export function clearRecentDestinations(): void {
+ navigateRecentDestinationsSetting.set("[]");
+}
+
+function isSamePlace(
+ a: { name: string; place: string; longitude: number; latitude: number },
+ b: { name: string; place: string; longitude: number; latitude: number },
+): boolean {
+ // Within ~10 m, or the same name at the same formatted place: a repeat
+ // visit, not a new entry. (Two branches of one chain stay distinct.)
+ return (
+ (a.name === b.name && a.place === b.place) ||
+ (Math.abs(a.longitude - b.longitude) < 0.0001 && Math.abs(a.latitude - b.latitude) < 0.0001)
+ );
+}
+
+function parseJsonArray(text: string): unknown[] {
+ try {
+ const parsed = JSON.parse(text);
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
diff --git a/app/apps/navigate/navigate-app.worker.ts b/app/apps/navigate/navigate-app.worker.ts
index 96404d6b..e8855384 100644
--- a/app/apps/navigate/navigate-app.worker.ts
+++ b/app/apps/navigate/navigate-app.worker.ts
@@ -8,16 +8,60 @@
*/
import "@nativescript/core/globals";
import { GrayImage } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
+import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import {
+ drawListScrollbar,
+ drawRightValueMenuItem,
+ drawSelectionHighlight,
+ drawSubmenuIndicator,
+ drawToggleMenuItem,
+ scrollToKeepSelectionVisible,
+ type MenuItem,
+} from "../../ui/menu";
+import { LIST_ROW_TEXT_INSET, listRowHeight } from "../../ui/metrics";
+import { WindowMenu, WindowMenuLayer } from "../../ui/window-menu";
+import type { LayerContext } from "../../ui/layers";
+import { truncateText, wrapText } from "../../graphics/textwrap";
+import { onSettingsStoreChanged } from "../../native/settings-store";
+import {
+ navigateDestinationAddressDraftSetting,
+ navigateDestinationNameDraftSetting,
+ navigateRememberRecentSetting,
+ navigateDisplayModeSetting,
+ navigateVerticalPositionSetting,
+ enumSettingMenuItem,
+ type ConfigSettingString,
+} from "../../ui/dashboard-settings";
+import {
+ addCustomDestination,
+ clearRecentDestinations,
+ findSavedDestinationByName,
+ HOME_DESTINATION_ID,
+ loadRecentDestinations,
+ loadSavedDestinations,
+ removeCustomDestination,
+ rememberRecentDestination,
+ removeRecentDestination,
+ setDestinationAddress,
+ updateCustomDestination,
+ WORK_DESTINATION_ID,
+ type RecentDestination,
+ type SavedDestination,
+} from "./destinations";
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, type InputEvent } from "../../ui/gestures";
+import {
+ GESTURE_CLICK,
+ GESTURE_DOUBLE_CLICK,
+ GESTURE_SCROLL,
+ GESTURE_SHORT_THEN_LONG_PRESS,
+ type InputEvent,
+} from "../../ui/gestures";
import { LocationTracker, type TrackedLocation } from "../../native/location-tracker";
import {
fetchRoute,
@@ -29,6 +73,9 @@ import {
type RouteProfile,
type StaticMapCamera,
} from "../../native/mapbox";
+import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "../../native/compass";
+import { magneticDeclinationDegrees } from "../../native/geomagnetic";
+import { calibrateHeading, normalizeHeading } from "../compass/calibration";
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower";
import { drawManeuverGlyph } from "./maneuver-icons";
@@ -46,8 +93,19 @@ 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;
+/**
+ * A fix older than this is not where the user is now. The tracker seeds each
+ * start with the platform's cached fix, and after a previous trip that can be
+ * the old destination: routing from it, or feeding it to the follower, ends a
+ * fresh navigation with "Arrived" before a live fix ever comes in.
+ */
+const FIX_MAX_AGE_MS = 60_000;
/** Above this speed a GPS bearing is trustworthy for heading-up. */
const BEARING_MIN_SPEED_MPS = 2.5;
+/** The head-direction chevron only redraws once the wearer has turned this far. */
+const HEADING_STEP_DEG = 4;
+/** Our claim on the shared glasses magnetometer (see setCompassEnabled). */
+const COMPASS_OWNER = "navigate";
const largeFont = getFont("terminus32");
const mediumFont = getFont("terminus24");
@@ -59,6 +117,7 @@ type MapMode = "follow" | "overview";
type NavWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
@@ -71,7 +130,7 @@ 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.",
+ "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. The name of one of the user's saved destinations (e.g. 'home', 'work') is used directly. 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: {
@@ -123,6 +182,35 @@ let rerouteInFlight = false;
/** Bumped on every new route/mode so stale map fetches can be discarded. */
let routeGeneration = 0;
+/**
+ * Where to go: free text to geocode (optionally shown under a saved
+ * destination's label), or an already-resolved place (a recent destination).
+ */
+type NavTarget =
+ | { kind: "query"; query: string; label?: string }
+ | { kind: "place"; name: string; place: string; longitude: number; latitude: number };
+
+/** An entry on the idle page's destination list. */
+type IdleEntry =
+ | { kind: "saved"; destination: SavedDestination }
+ | { kind: "recent"; destination: RecentDestination };
+
+/** Idle-page list selection (index into idleEntries()). */
+let idleSelection = 0;
+let idleScrollRow = 0;
+
+/**
+ * In-progress destination edit: the phone text editor is open on `setting`
+ * (a staging draft); click confirms with the typed value, double-click
+ * cancels. `onDone` may start another edit (name, then address).
+ */
+type DestinationEdit = {
+ setting: ConfigSettingString;
+ title: string;
+ onDone: (value: string) => void;
+};
+let editing: DestinationEdit | null = null;
+
let mapMode: MapMode = "follow";
let zoomOffset = 0;
let mapImage: GrayImage | null = null;
@@ -132,6 +220,17 @@ let mapLastFetchAtMs = 0;
let mapLastFetchCenter: [number, number] | null = null;
let mapNextRetryAtMs = 0;
let mapLastError = "";
+/** Bearing the current map image was rendered with (its "up"), for follow mode. */
+let mapFetchedBearingDeg = 0;
+
+// Glasses compass: the same firmware feed and wearer calibration as the
+// Compass app, so the position chevron shows where the wearer is looking
+// relative to the map rather than always pointing up the direction of travel.
+let compassActive = false;
+let unsubscribeCompass: (() => void) | null = null;
+/** Wearer's true heading (degrees clockwise from north) as last drawn, or null before compass data arrives. */
+let headHeadingDeg: number | null = null;
+let declinationCache: { latitude: number; longitude: number; degrees: number | null } | null = null;
let tickTimer: ReturnType | null = null;
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
@@ -149,6 +248,12 @@ function post(message: WorkerAppReply): void {
global.postMessage(message);
}
+// Destinations edited on the phone (the text editor, or the Settings app's
+// Home/Work rows) repaint the idle list / the edit screen live.
+onSettingsStoreChanged((key) => {
+ if (key.startsWith("navigate.")) render();
+});
+
// The host queues messages until this arrives: posts to a worker whose bundle
// is still evaluating can be silently dropped (see WorkerAppHost). Top-level
// evaluation is synchronous, so the handler below is installed before any
@@ -162,6 +267,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
window = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -171,9 +277,24 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
};
post({ type: "set-tools", windowId: message.windowId, tools: NAVIGATE_TOOLS });
break;
+ case "resize-window":
+ if (!window || window.windowId !== message.windowId) break;
+ if (window.viewportWidth === message.viewport.width && window.viewportHeight === message.viewport.height) break;
+ window.viewportWidth = message.viewport.width;
+ window.viewportHeight = message.viewport.height;
+ window.menu?.resize(message.viewport);
+ window.lastSubmittedFingerprint = "";
+ render();
+ break;
case "close-window":
+ if (editing) {
+ // Window closed mid-edit: shut the phone editor down.
+ editing = null;
+ post({ type: "end-text-setting-edit" });
+ }
stopNavigation("");
window = null;
+ reconcileCompass();
break;
case "input":
if (!window || window.windowId !== message.windowId) {
@@ -187,8 +308,12 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
handleInput(window, message.event as InputEvent, message.frameId);
break;
case "text-input":
- // Voice input / typed text sets a destination directly.
- if (message.text.trim()) {
+ if (editing) {
+ // Voice input as an alternative to the phone keyboard.
+ editing.setting.set(message.text.trim());
+ render();
+ } else if (message.text.trim()) {
+ // Voice input / typed text sets a destination directly.
void startNavigation(message.text.trim(), profile).catch(() => {});
}
break;
@@ -201,6 +326,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
if (!window) break;
window.foreground = message.foreground;
window.focused = message.focused;
+ reconcileCompass();
if (window.foreground) {
maybeRefreshMap();
render();
@@ -208,6 +334,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
break;
case "screen":
screenOn = message.on;
+ reconcileCompass();
if (screenOn && window?.foreground) {
maybeRefreshMap();
render();
@@ -232,7 +359,20 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
// ---------------------------------------------------------------------------
// Navigation state machine
-async function startNavigation(query: string, requestedProfile: RouteProfile): Promise {
+/**
+ * Navigate to free text: a saved destination's name ("home") routes to its
+ * address under that label; anything else is geocoded as typed.
+ */
+function startNavigation(query: string, requestedProfile: RouteProfile): Promise {
+ const saved = findSavedDestinationByName(query);
+ return startNavigationTo(
+ saved ? { kind: "query", query: saved.address, label: saved.name } : { kind: "query", query },
+ requestedProfile,
+ );
+}
+
+async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfile): Promise {
+ const query = target.kind === "query" ? target.query : target.name;
if (!isMapboxConfigured()) {
statusMessage = "Set a Mapbox token in Settings > API Keys.";
phase = "idle";
@@ -255,21 +395,44 @@ async function startNavigation(query: string, requestedProfile: RouteProfile): P
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}".`);
+ let picked: GeocodeCandidate;
+ let candidates: GeocodeCandidate[] = [];
+ if (target.kind === "place") {
+ picked = {
+ name: target.name,
+ placeFormatted: target.place,
+ longitude: target.longitude,
+ latitude: target.latitude,
+ distanceMeters: null,
+ };
+ } else {
+ statusMessage = `Finding ${query}...`;
+ render();
+ candidates = await geocodeForward(query, fix, 5);
+ if (!candidates.length) {
+ throw new Error(`No places found matching "${query}".`);
+ }
+ picked = candidates[0]!;
}
- const picked = candidates[0]!;
destination = { longitude: picked.longitude, latitude: picked.latitude };
- destinationName = picked.name;
+ destinationName = target.kind === "query" && target.label ? target.label : picked.name;
destinationPlace = picked.placeFormatted;
- statusMessage = `Routing to ${picked.name}...`;
+ statusMessage = `Routing to ${destinationName}...`;
render();
const route = await fetchRoute(fix, destination, profile);
adoptRoute(route);
+ // Saved destinations already have a row of their own on the idle page;
+ // everything else (voice, assistant, a re-picked recent) goes on the
+ // recent list, most recent first.
+ if (!(target.kind === "query" && target.label)) {
+ rememberRecentDestination({
+ name: picked.name,
+ place: picked.placeFormatted,
+ longitude: picked.longitude,
+ latitude: picked.latitude,
+ });
+ }
if (window) post({ type: "focus-window", windowId: window.windowId });
return startSummary(picked, candidates, route);
} catch (error) {
@@ -323,8 +486,16 @@ function stopNavigation(finalStatus: string): void {
ensureTickTimer();
}
+function isFreshFix(fix: TrackedLocation): boolean {
+ return Date.now() - fix.timestampMs < FIX_MAX_AGE_MS;
+}
+
function handleFix(fix: TrackedLocation): void {
- lastFix = fix;
+ if (!lastFix || fix.timestampMs >= lastFix.timestampMs) lastFix = fix;
+ // A stale fix (a cached seed from a previous outing) may position the map
+ // until something better arrives, but it must not stand in for the user's
+ // current location: it neither starts a route nor advances guidance.
+ if (!isFreshFix(fix)) return;
if (fix.bearingDeg !== null && (fix.speedMps ?? 0) >= BEARING_MIN_SPEED_MPS) {
lastBearingDeg = fix.bearingDeg;
}
@@ -378,7 +549,7 @@ function stopTrackingIfIdle(): void {
}
function waitForFix(): Promise {
- if (lastFix && Date.now() - lastFix.timestampMs < 60_000) {
+ if (lastFix && isFreshFix(lastFix)) {
return Promise.resolve(lastFix);
}
return new Promise((resolve, reject) => {
@@ -394,6 +565,59 @@ function waitForFix(): Promise {
});
}
+// ---------------------------------------------------------------------------
+// Head heading (glasses compass)
+
+/** Hold the magnetometer only while its reading is actually on screen. */
+function reconcileCompass(): void {
+ const wanted =
+ window !== null && window.foreground && screenOn && phase === "navigating" && mapMode === "follow";
+ if (wanted === compassActive) return;
+ compassActive = wanted;
+ if (wanted) {
+ unsubscribeCompass = addCompassListener(handleCompassEvent);
+ setCompassEnabled(true, COMPASS_OWNER);
+ } else {
+ setCompassEnabled(false, COMPASS_OWNER);
+ unsubscribeCompass?.();
+ unsubscribeCompass = null;
+ headHeadingDeg = null;
+ }
+}
+
+function handleCompassEvent(event: CompassEvent): void {
+ if (!compassActive || event.command !== COMPASS_CHANGED || event.headingDegrees < 0) return;
+ // Wearer-fit offset from the Compass app's calibration, then declination
+ // from our own GPS fix: the map is always true-north referenced.
+ const magnetic = calibrateHeading(event.headingDegrees);
+ const heading = normalizeHeading(magnetic + (currentDeclination() ?? 0));
+ if (headHeadingDeg !== null && angularDistance(heading, headHeadingDeg) < HEADING_STEP_DEG) return;
+ headHeadingDeg = heading;
+ render();
+}
+
+/** Declination at the last fix; it only varies over tens of kilometres, so cache per coarse position. */
+function currentDeclination(): number | null {
+ if (!lastFix) return null;
+ if (
+ !declinationCache ||
+ Math.abs(declinationCache.latitude - lastFix.latitude) > 0.5 ||
+ Math.abs(declinationCache.longitude - lastFix.longitude) > 0.5
+ ) {
+ declinationCache = {
+ latitude: lastFix.latitude,
+ longitude: lastFix.longitude,
+ degrees: magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude),
+ };
+ }
+ return declinationCache.degrees;
+}
+
+function angularDistance(a: number, b: number): number {
+ const delta = Math.abs(normalizeHeading(a) - normalizeHeading(b));
+ return Math.min(delta, 360 - delta);
+}
+
function ensureTickTimer(): void {
const shouldRun = phase === "navigating";
if (shouldRun && tickTimer === null) {
@@ -512,9 +736,10 @@ function maybeRefreshMap(): void {
.then((image) => {
mapInFlight = false;
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
- boostContrast(image);
+ levelMap(image);
mapImage = image;
mapFetchedKey = view.key;
+ mapFetchedBearingDeg = view.camera.kind === "center" ? view.camera.bearingDeg : 0;
mapLastFetchAtMs = Date.now();
mapLastFetchCenter = view.camera.kind === "center" ? [view.camera.longitude, view.camera.latitude] : null;
mapLastError = "";
@@ -539,11 +764,25 @@ function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[
return out;
}
-/** Stretch the dark-style render so roads survive 4bpp quantization. */
-function boostContrast(image: GrayImage): void {
+/**
+ * Level the render for the lens. The dominant tone is the land fill: black
+ * when the style override took, dark gray otherwise. Either way it becomes
+ * the black point, and everything above it is stretched so roads survive
+ * 4bpp quantization.
+ */
+function levelMap(image: GrayImage): void {
+ const histogram = new Uint32Array(256);
+ for (let i = 0; i < image.pixels.length; i++) histogram[image.pixels[i]!]++;
+ let black = 0;
+ for (let value = 1; value < 256; value++) {
+ if (histogram[value]! > histogram[black]!) black = value;
+ }
+ // A bright dominant tone isn't a floor (a large plaza, a fetch that came
+ // back mostly label); flattening it would eat the roads.
+ if (black > 64) black = 0;
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)));
+ image.pixels[i] = value <= black ? 0 : Math.min(255, Math.round((value - black) * 1.7));
}
}
@@ -609,9 +848,272 @@ function describeRouteStatus(): string {
// ---------------------------------------------------------------------------
// Input
+/**
+ * The window's context menu: Stop navigation while a route is up, then the
+ * display and saved-destination settings (Home, Work, custom named places), and the
+ * recent-destinations preference.
+ */
+function windowMenuItems(win: NavWindow): MenuItem[] {
+ const items: MenuItem[] = [];
+ if (phase === "navigating" || phase === "arrived") {
+ items.push({
+ label: "Stop navigation",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ stopNavigation("Navigation stopped.");
+ render();
+ },
+ });
+ }
+ items.push(
+ enumSettingMenuItem(navigateDisplayModeSetting),
+ enumSettingMenuItem(navigateVerticalPositionSetting),
+ );
+ items.push({
+ label: "Saved destinations",
+ onSelect: (ctx) => {
+ ctx.stack.push(new WindowMenuLayer("Saved destinations", savedDestinationMenuItems()));
+ },
+ render: ({ image, x, y, width, height, text }) => {
+ image.drawText(smallFont, x, y + LIST_ROW_TEXT_INSET, text, 200);
+ drawSubmenuIndicator(image, smallFont, x - 10, y, width + 20, height, 150);
+ },
+ });
+ items.push({
+ label: navigateRememberRecentSetting.label,
+ onSelect: () => {
+ const enabled = navigateRememberRecentSetting.toggle();
+ if (!enabled) clearRecentDestinations();
+ clampIdleSelection();
+ },
+ render: ({ image, x, y, width, selected }) => {
+ drawToggleMenuItem(
+ image,
+ smallFont,
+ x,
+ y,
+ width,
+ navigateRememberRecentSetting.label,
+ navigateRememberRecentSetting.get(),
+ selected,
+ );
+ },
+ });
+ const selectedEntry = phase === "idle" ? idleEntries()[idleSelection] : undefined;
+ if (selectedEntry?.kind === "recent") {
+ const recent = selectedEntry.destination;
+ items.push({
+ label: `Forget ${truncateText(smallFont, recent.name, 160)}`,
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ removeRecentDestination(recent);
+ clampIdleSelection();
+ },
+ });
+ }
+ if (loadRecentDestinations().length) {
+ items.push({
+ label: "Clear recent destinations",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ clearRecentDestinations();
+ clampIdleSelection();
+ },
+ });
+ }
+ return items;
+}
+
+/** Home, Work, each custom destination (its own action submenu), and Add. */
+function savedDestinationMenuItems(): MenuItem[] {
+ const items: MenuItem[] = [];
+ const saved = loadSavedDestinations();
+ const home = saved.find((d) => d.id === HOME_DESTINATION_ID);
+ const work = saved.find((d) => d.id === WORK_DESTINATION_ID);
+ items.push(addressMenuItem("Home", HOME_DESTINATION_ID, home?.address ?? ""));
+ items.push(addressMenuItem("Work", WORK_DESTINATION_ID, work?.address ?? ""));
+ for (const destination of saved) {
+ if (destination.builtin) continue;
+ items.push({
+ label: destination.name,
+ onSelect: (ctx) => {
+ ctx.stack.push(new WindowMenuLayer(destination.name, customDestinationMenuItems(destination)));
+ },
+ render: ({ image, x, y, width, height }) => {
+ drawAddressRow(image, x, y, width, destination.name, destination.address, true);
+ drawSubmenuIndicator(image, smallFont, x - 10, y, width + 20, height, 150);
+ },
+ });
+ }
+ items.push({
+ label: "Add destination...",
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => beginAddDestination());
+ },
+ });
+ return items;
+}
+
+/** A Home/Work row: shows the address, opens the address editor. */
+function addressMenuItem(label: string, id: string, address: string): MenuItem {
+ return {
+ label,
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => beginAddressEdit(id, label, address));
+ },
+ render: ({ image, x, y, width }) => {
+ drawAddressRow(image, x, y, width, label, address, false);
+ },
+ };
+}
+
+function customDestinationMenuItems(destination: SavedDestination): MenuItem[] {
+ return [
+ {
+ label: "Navigate there",
+ disabled: !destination.address,
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => {
+ void startNavigationTo({ kind: "query", query: destination.address, label: destination.name }, profile).catch(
+ () => {},
+ );
+ });
+ },
+ },
+ {
+ label: "Set address",
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => beginAddressEdit(destination.id, destination.name, destination.address));
+ },
+ },
+ {
+ label: "Rename",
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => {
+ navigateDestinationNameDraftSetting.set(destination.name);
+ beginEdit(navigateDestinationNameDraftSetting, `Rename ${destination.name}`, (name) => {
+ if (name) updateCustomDestination(destination.id, { name });
+ });
+ });
+ },
+ },
+ {
+ label: "Remove",
+ onSelect: (ctx) => {
+ closeMenusAnd(ctx, () => {
+ removeCustomDestination(destination.id);
+ clampIdleSelection();
+ });
+ },
+ },
+ ];
+}
+
+function drawAddressRow(
+ image: GrayImage,
+ x: number,
+ y: number,
+ width: number,
+ label: string,
+ address: string,
+ hasSubmenu: boolean,
+): void {
+ const valueWidth = Math.max(40, width - smallFont.measureText(label) - (hasSubmenu ? 28 : 12));
+ const value = truncateText(smallFont, address || "(not set)", valueWidth);
+ drawRightValueMenuItem(image, smallFont, x, y, width - (hasSubmenu ? 16 : 0), label, value);
+}
+
+/** Close the whole menu stack, then run an action that takes over the window. */
+function closeMenusAnd(ctx: LayerContext, action: () => void): void {
+ ctx.stack.clearToBase();
+ action();
+}
+
+// ---------------------------------------------------------------------------
+// Destination editing (phone text editor + voice input)
+
+/**
+ * Open the phone text editor on a staging setting. The editor writes the
+ * draft live (repainted via the settings listener); click here confirms.
+ */
+function beginEdit(setting: ConfigSettingString, title: string, onDone: (value: string) => void): void {
+ editing = { setting, title, onDone };
+ post({ type: "start-text-setting-edit", settingId: setting.id });
+ render();
+}
+
+function finishEdit(confirmed: boolean): void {
+ const current = editing;
+ editing = null;
+ post({ type: "end-text-setting-edit" });
+ if (current && confirmed) current.onDone(current.setting.get());
+ // onDone may have started the next step; only fully leave when it didn't.
+ if (!editing) {
+ navigateDestinationNameDraftSetting.set("");
+ navigateDestinationAddressDraftSetting.set("");
+ clampIdleSelection();
+ render();
+ }
+}
+
+function beginAddressEdit(id: string, name: string, current: string): void {
+ navigateDestinationAddressDraftSetting.set(current);
+ beginEdit(navigateDestinationAddressDraftSetting, `${name} address`, (address) => {
+ if (address) setDestinationAddress(id, address);
+ });
+}
+
+/** Two-step add: a name, then its address. An empty answer cancels. */
+function beginAddDestination(): void {
+ navigateDestinationNameDraftSetting.set("");
+ beginEdit(navigateDestinationNameDraftSetting, "New destination name", (name) => {
+ if (!name) return;
+ navigateDestinationAddressDraftSetting.set("");
+ beginEdit(navigateDestinationAddressDraftSetting, `${name} address`, (address) => {
+ if (address) addCustomDestination(name, address);
+ });
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Idle page destination list
+
+function idleEntries(): IdleEntry[] {
+ const entries: IdleEntry[] = loadSavedDestinations()
+ .filter((destination) => destination.address)
+ .map((destination): IdleEntry => ({ kind: "saved", destination }));
+ for (const destination of loadRecentDestinations()) {
+ entries.push({ kind: "recent", destination });
+ }
+ return entries;
+}
+
+function clampIdleSelection(): void {
+ const count = idleEntries().length;
+ idleSelection = Math.max(0, Math.min(idleSelection, count - 1));
+}
+
+function navigateToIdleEntry(entry: IdleEntry): void {
+ const target: NavTarget =
+ entry.kind === "saved"
+ ? { kind: "query", query: entry.destination.address, label: entry.destination.name }
+ : {
+ kind: "place",
+ name: entry.destination.name,
+ place: entry.destination.place,
+ longitude: entry.destination.longitude,
+ latitude: entry.destination.latitude,
+ };
+ void startNavigationTo(target, profile).catch(() => {});
+}
+
function windowMenu(win: NavWindow): WindowMenu {
if (!win.menu) {
win.menu = new WindowMenu({
+ windowId: win.windowId,
+ post,
+ title: () => win.title,
+ items: () => windowMenuItems(win),
size: { width: win.viewportWidth, height: win.viewportHeight },
paintBase: () => paintContent(win),
isFocused: () => win.focused,
@@ -628,19 +1130,20 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
.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();
- },
- });
+ if (editing) {
+ if (event.type === "click") {
+ finishEdit(true);
+ } else if (event.type === "double-click") {
+ finishEdit(false);
+ } else {
+ frameTimings.finishFrame(frameId, "discarded: navigate edit ignored input");
+ return;
}
- windowMenu(win).open(items);
+ renderAndSubmit(win, frameId);
+ return;
+ }
+ if (event.type === "short-then-long-press") {
+ windowMenu(win).open();
renderAndSubmit(win, frameId);
return;
}
@@ -656,6 +1159,13 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
maybeRefreshMap();
} else if (phase === "arrived") {
stopNavigation("");
+ } else if (phase === "idle") {
+ const entry = idleEntries()[idleSelection];
+ if (!entry) {
+ frameTimings.finishFrame(frameId, "discarded: navigate ignored click");
+ return;
+ }
+ navigateToIdleEntry(entry);
} else {
frameTimings.finishFrame(frameId, "discarded: navigate ignored click");
return;
@@ -668,6 +1178,10 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
zoomOffset = Math.max(-3, Math.min(2, zoomOffset + (event.type === "scroll-up" ? 0.5 : -0.5)));
maybeRefreshMap();
renderAndSubmit(win, frameId);
+ } else if (phase === "idle" && idleEntries().length > 1) {
+ const count = idleEntries().length;
+ idleSelection = Math.max(0, Math.min(count - 1, idleSelection + (event.type === "scroll-down" ? 1 : -1)));
+ renderAndSubmit(win, frameId);
} else {
frameTimings.finishFrame(frameId, "discarded: navigate ignored scroll");
}
@@ -680,45 +1194,133 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
// Painting
function paint(win: NavWindow): Plane[] {
- if (win.menu?.isOpen()) return win.menu.paint();
- return singlePlane(paintContent(win));
+ return windowMenu(win).paint();
}
function paintContent(win: NavWindow): GrayImage {
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
- if (phase === "idle" || phase === "acquiring" || phase === "routing") {
- paintIdle(image);
+ if (editing) {
+ paintEdit(image, editing);
+ } else if (phase === "idle" || phase === "acquiring" || phase === "routing") {
+ paintIdle(image, win);
} else {
paintNavigating(image, win);
}
return image;
}
-function paintIdle(image: GrayImage): void {
+/** The "type on the phone" screen for a destination name/address edit. */
+function paintEdit(image: GrayImage, edit: DestinationEdit): void {
+ const step = smallFont.lineHeight + 2;
+ image.drawText(mediumFont, 24, 16, edit.title, 245);
+ const messageY = 64;
+ const lines = wrapText(smallFont, "Type the value in the phone app, or use voice input.", image.width - 48);
+ for (let index = 0; index < lines.length; index++) {
+ image.drawText(smallFont, 24, messageY + index * step, lines[index]!, 190);
+ }
+ const value = edit.setting.get();
+ image.drawText(
+ smallFont,
+ 24,
+ messageY + (lines.length + 1) * step,
+ truncateText(smallFont, value || "(empty)", image.width - 48),
+ value ? 225 : 130,
+ );
+ drawFooter(image, `${GESTURE_CLICK} done ${GESTURE_DOUBLE_CLICK} cancel`);
+}
+
+function paintIdle(image: GrayImage, win: NavWindow): 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 });
+ const entries = busy ? [] : idleEntries();
+ const hint = !isMapboxConfigured()
+ ? "Set a Mapbox token in Settings > API Keys to enable navigation."
+ : entries.length
+ ? "Pick a destination below, or say one via Voice input (system menu, long-press)."
+ : "Ask the voice assistant to navigate somewhere, or pick Voice input from the system menu (long-press) to say a destination. Save Home, Work and other places from the app menu.";
+ const hintLines = wrapText(smallFont, hint, image.width - 48);
+ const hintStep = smallFont.lineHeight + 2;
+ for (let index = 0; index < hintLines.length; index++) {
+ image.drawText(smallFont, 24, 52 + index * hintStep, hintLines[index]!, 170);
+ }
+ let y = 52 + hintLines.length * hintStep + 6;
if (statusMessage) {
- image.drawTextWrapped({
- font: smallFont,
- x: 24,
- y: 130,
- width: image.width - 48,
- text: statusMessage,
- value: busy ? 220 : 190,
- });
+ const statusLines = wrapText(smallFont, statusMessage, image.width - 48);
+ for (let index = 0; index < statusLines.length; index++) {
+ image.drawText(smallFont, 24, y + index * hintStep, statusLines[index]!, busy ? 220 : 190);
+ }
+ y += statusLines.length * hintStep + 6;
+ }
+ if (entries.length) {
+ paintIdleList(image, win, entries, y);
+ drawFooter(
+ image,
+ `${GESTURE_SCROLL} select ${GESTURE_CLICK} go ${GESTURE_SHORT_THEN_LONG_PRESS} app menu ${GESTURE_DOUBLE_CLICK} back`,
+ );
+ } else {
+ drawFooter(image, `${GESTURE_SHORT_THEN_LONG_PRESS} app menu ${GESTURE_DOUBLE_CLICK} back`);
+ }
+}
+
+/** Saved destinations (name + address) then recent places, one selectable row each. */
+function paintIdleList(image: GrayImage, win: NavWindow, entries: IdleEntry[], top: number): void {
+ const rowHeight = listRowHeight(smallFont);
+ const listBottom = image.height - 30;
+ const visibleRows = Math.max(1, Math.floor((listBottom - top) / rowHeight));
+ idleSelection = Math.max(0, Math.min(idleSelection, entries.length - 1));
+ idleScrollRow = scrollToKeepSelectionVisible(idleScrollRow, idleSelection, visibleRows, entries.length);
+ const rowX = 20;
+ const rowWidth = image.width - 40 - (entries.length > visibleRows ? 10 : 0);
+ const labelWidth = Math.floor(rowWidth * 0.4);
+ for (let row = 0; row < visibleRows; row++) {
+ const index = idleScrollRow + row;
+ const entry = entries[index];
+ if (!entry) break;
+ const y = top + row * rowHeight;
+ const selected = index === idleSelection;
+ if (selected) drawSelectionHighlight(image, rowX, y, rowWidth, rowHeight - 2, win.focused);
+ const textX = rowX + 6;
+ const textY = y + LIST_ROW_TEXT_INSET;
+ if (entry.kind === "saved") {
+ const label = truncateText(smallFont, entry.destination.name, labelWidth);
+ image.drawText(smallFont, textX, textY, label, selected ? 245 : 210);
+ const detailX = textX + labelWidth + 8;
+ image.drawText(
+ smallFont,
+ detailX,
+ textY,
+ truncateText(smallFont, entry.destination.address, rowX + rowWidth - 6 - detailX),
+ selected ? 170 : 130,
+ );
+ } else {
+ const label = truncateText(smallFont, entry.destination.name, labelWidth);
+ image.drawText(smallFont, textX, textY, label, selected ? 245 : 210);
+ const detailX = textX + labelWidth + 8;
+ const detail = entry.destination.place ? `${entry.destination.place} (recent)` : "(recent)";
+ image.drawText(
+ smallFont,
+ detailX,
+ textY,
+ truncateText(smallFont, detail, rowX + rowWidth - 6 - detailX),
+ selected ? 170 : 130,
+ );
+ }
+ }
+ if (entries.length > visibleRows) {
+ drawListScrollbar(image, rowX + rowWidth + 4, top, visibleRows * rowHeight - 2, idleScrollRow, visibleRows, entries.length);
}
- 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);
+ if (mapMode === "follow") {
+ // Head heading relative to the map's up (its render bearing); no
+ // compass reading yet means "up", i.e. the direction of travel.
+ const angle = headHeadingDeg === null ? 0 : headHeadingDeg - mapFetchedBearingDeg;
+ drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2, angle);
+ }
} else {
image.drawRect(0, 0, MAP_SIZE, MAP_SIZE, 60);
const text = mapLastError ? "Map unavailable" : "Loading map...";
@@ -778,11 +1380,21 @@ function paintNavigating(image: GrayImage, win: NavWindow): void {
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 {
+/**
+ * Position chevron, fixed at the map center and rotated `angleDeg` clockwise
+ * from straight up (the map's render bearing) to the wearer's head heading.
+ */
+function drawChevron(image: GrayImage, cx: number, cy: number, angleDeg: number): void {
+ const radians = (angleDeg * Math.PI) / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const triangle = (points: Array<[number, number]>, value: number): void => {
+ const [a, b, c] = points.map(([x, y]): [number, number] => [cx + x * cos - y * sin, cy + x * sin + y * cos]);
+ fillTriangle(image, a![0], a![1], b![0], b![1], c![0], c![1], value);
+ };
// 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);
+ triangle([[0, -11], [-9, 9], [9, 9]], 0);
+ triangle([[0, -8], [-6, 6], [6, 6]], 255);
}
function fillTriangle(image: GrayImage, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, value: number): void {
@@ -866,6 +1478,9 @@ function render(): void {
}
function renderAndSubmit(win: NavWindow, inputFrameId: number): void {
+ // Every state change funnels through here, so it doubles as the point where
+ // the compass claim tracks foreground/phase/mode.
+ reconcileCompass();
if (!win.foreground && inputFrameId === 0) return;
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
try {
diff --git a/app/apps/nightscout/index.ts b/app/apps/nightscout/index.ts
index 078af81c..6f5f59ad 100644
--- a/app/apps/nightscout/index.ts
+++ b/app/apps/nightscout/index.ts
@@ -1,10 +1,11 @@
import { type AppDefinition } from "../app-definition";
-import { createNightscoutAppWindow, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
+import { createNightscoutAppWindow, startNightscoutTrayIcon, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
const nightscoutApp: AppDefinition = {
appId: "nightscout",
title: "Nightscout",
icon: "nightscout",
+ boot: () => startNightscoutTrayIcon(),
launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
};
diff --git a/app/apps/nightscout/nightscout-alerts.ts b/app/apps/nightscout/nightscout-alerts.ts
new file mode 100644
index 00000000..9c87accd
--- /dev/null
+++ b/app/apps/nightscout/nightscout-alerts.ts
@@ -0,0 +1,33 @@
+export type NightscoutAlertValues = {
+ cageTimestampMs: number | null;
+ reservoirUnits: number | null;
+ batteryVoltage: number | null;
+ loopTimestampMs: number | null;
+};
+
+export type NightscoutThresholds = {
+ maxCannulaAgeHours: number;
+ cartridgeLowUnits: number;
+ batteryLowVoltage: number;
+ maxLoopAgeMinutes: number;
+};
+
+/** Zero disables a threshold. Missing measurements do not imply a breach. */
+export function evaluateNightscoutAlerts(values: NightscoutAlertValues, limits: NightscoutThresholds, nowMs: number) {
+ const known = (value: number | null): value is number => value !== null && Number.isFinite(value) && value >= 0;
+ const enabled = (value: number): boolean => Number.isFinite(value) && value > 0;
+ const tooOld = (timestamp: number | null, limit: number, unitMs: number): boolean =>
+ enabled(limit) && known(timestamp) && timestamp > 0 && nowMs - timestamp > limit * unitMs;
+ const tooLow = (value: number | null, limit: number): boolean => enabled(limit) && known(value) && value < limit;
+ const cannula = tooOld(values.cageTimestampMs, limits.maxCannulaAgeHours, 3_600_000);
+ const cartridge = tooLow(values.reservoirUnits, limits.cartridgeLowUnits);
+ const battery = tooLow(values.batteryVoltage, limits.batteryLowVoltage);
+ const loop = tooOld(values.loopTimestampMs, limits.maxLoopAgeMinutes, 60_000);
+ return { cannula, cartridge, battery, loop, any: cannula || cartridge || battery || loop };
+}
+
+export function normalizeNightscoutThreshold(value: string | null | undefined): string {
+ const text = (value ?? "").trim();
+ const number = Number(text);
+ return /^(\d+(\.\d*)?|\.\d+)$/.test(text) && Number.isFinite(number) && number >= 0 ? String(number) : "0";
+}
diff --git a/app/apps/nightscout/nightscout-app.ts b/app/apps/nightscout/nightscout-app.ts
index c2e479ba..b2fbdb00 100644
--- a/app/apps/nightscout/nightscout-app.ts
+++ b/app/apps/nightscout/nightscout-app.ts
@@ -8,6 +8,8 @@ import {
type InProcessAppOptions,
type InProcessWindow,
} from "../../ui/shell/in-process-window";
+import { evaluateNightscoutAlerts } from "./nightscout-alerts";
+import { loadNightscoutThresholds, nightscoutAlwaysShowInTopBarSetting, onAnySettingChanged } from "../../ui/dashboard-settings";
import { shell } from "../../ui/shell/shell";
export const NIGHTSCOUT_WINDOW_ID = "nightscout";
@@ -19,14 +21,34 @@ const TRAY_GRAPH_WIDTH = 48;
const TRAY_STALE_MS = 15 * 60 * 1000;
const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
-/**
- * The Nightscout app: the full-screen glucose view (previously reached via
- * the dashboard card) in its own in-process window. While the app is running
- * it also publishes a top-bar tray icon: the latest blood-glucose value
- * (struck through when stale) plus a minimal 48px history graph.
- */
+const windowRenders = new Set<() => void>();
+let trayStarted = false;
+let trayTick: ReturnType | null = null;
+
+function syncNightscout(): void {
+ const visible = windowRenders.size > 0 || nightscoutAlwaysShowInTopBarSetting.get();
+ shell.setTrayIcon(TRAY_ICON_ID, visible ? buildNightscoutTrayIcon(nightscoutBridge.snapshot()) : null);
+ for (const render of windowRenders) render();
+ // Age warnings and stale glucose must advance even during a stalled fetch.
+ if (visible && trayTick === null) trayTick = setInterval(syncNightscout, 60_000);
+ if (!visible && trayTick !== null) {
+ clearInterval(trayTick);
+ trayTick = null;
+ }
+}
+
+/** Shell-lifetime subscription so the tray can be enabled before any window opens. */
+export function startNightscoutTrayIcon(): void {
+ if (trayStarted) return;
+ trayStarted = true;
+ nightscoutBridge.onStateChange(syncNightscout);
+ onAnySettingChanged(syncNightscout);
+}
+
+/** Full-screen glucose view with a shared, optionally persistent tray readout. */
export function createNightscoutAppWindow(options: InProcessAppOptions): InProcessWindow {
- let unsubscribe: (() => void) | null = null;
+ startNightscoutTrayIcon();
+ const render = () => app.requestRender();
const app = createInProcessWindow({
appId: "nightscout",
windowId: NIGHTSCOUT_WINDOW_ID,
@@ -41,28 +63,25 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
- unsubscribe?.();
- unsubscribe = null;
- shell.setTrayIcon(TRAY_ICON_ID, null);
+ windowRenders.delete(render);
+ syncNightscout();
options.onClosed();
},
});
- // onStateChange fires immediately with the current snapshot, so this also
- // publishes the initial tray icon.
- unsubscribe = nightscoutBridge.onStateChange((state) => {
- shell.setTrayIcon(TRAY_ICON_ID, buildNightscoutTrayIcon(state));
- app.requestRender();
- });
+ windowRenders.add(render);
+ syncNightscout();
return app;
}
-/** BG value (struck through when stale) + minimal 2-hour line graph. */
+/** BG value, 2-hour graph, then a warning triangle when any threshold is breached. */
function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
const font = getDefaultSmallFont();
const nowMs = Date.now();
const label = state.latest ? `${state.latest.sgv}` : "--";
const labelWidth = font.measureText(label);
- const image = new GrayImage(labelWidth + 4 + TRAY_GRAPH_WIDTH, TRAY_HEIGHT, 0);
+ const warning = evaluateNightscoutAlerts(state, loadNightscoutThresholds(), nowMs).any;
+ const graphEnd = labelWidth + 4 + TRAY_GRAPH_WIDTH;
+ const image = new GrayImage(graphEnd + (warning ? 24 : 0), TRAY_HEIGHT, 0);
const textY = Math.max(0, ((TRAY_HEIGHT - font.lineHeight) / 2) | 0);
image.drawText(font, 0, textY, label, 220);
@@ -72,6 +91,14 @@ function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
}
drawTrayGraph(image, labelWidth + 4, state, nowMs);
+ if (warning) {
+ const x = graphEnd + 4;
+ image.drawLine(x + 9, 3, x, 20, 255);
+ image.drawLine(x, 20, x + 18, 20, 255);
+ image.drawLine(x + 18, 20, x + 9, 3, 255);
+ image.fillRect(x + 8, 9, 2, 6, 255);
+ image.fillRect(x + 8, 17, 2, 2, 255);
+ }
return image;
}
diff --git a/app/apps/nightscout/nightscout.ts b/app/apps/nightscout/nightscout.ts
index 82cab700..380f0595 100644
--- a/app/apps/nightscout/nightscout.ts
+++ b/app/apps/nightscout/nightscout.ts
@@ -1,3 +1,4 @@
+import { evaluateNightscoutAlerts } from "./nightscout-alerts";
import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage, type UiFont } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap";
@@ -6,6 +7,13 @@ import { Layer, LayerContext } from "../../ui/layers";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import {
isNightscoutSettingsConfigured,
+ loadNightscoutThresholds,
+ nightscoutMaxCannulaAgeSetting,
+ nightscoutCartridgeLowSetting,
+ nightscoutBatteryLowSetting,
+ nightscoutMaxLoopAgeSetting,
+ nightscoutAlwaysShowInTopBarSetting,
+ toggleSettingMenuItem,
nightscoutApiTokenSetting,
nightscoutSiteUrlSetting,
textSettingMenuItem,
@@ -332,21 +340,43 @@ export class NightscoutLayer implements Layer {
const statusX = 170;
const statusWidth = width - 22 - statusX;
- const statusLines: { text: string; shade: number; direction?: string }[] = [
+ const alerts = evaluateNightscoutAlerts(nightscout, loadNightscoutThresholds(), nowMs);
+ const statusLines: { text: string; shade: number; direction?: string; fields?: { text: string; warning?: boolean }[] }[] = [
{ text: `Delta ${formatDelta(nightscout.delta)} Trend `, shade: 180, direction: nightscout.direction },
{
text: `IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
shade: 160,
},
{
- text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
- shade: 160,
+ text: "", shade: 160,
+ fields: [
+ { text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)}`, warning: alerts.cannula },
+ { text: `Loop ${formatAgeShortFromTimestamp(nightscout.loopTimestampMs, nowMs)}`, warning: alerts.loop },
+ ],
+ },
+ {
+ text: "", shade: 150,
+ fields: [
+ { text: "Pump" },
+ { text: nightscout.reservoirUnits === null ? "--U" : `${Math.round(nightscout.reservoirUnits)}U`, warning: alerts.cartridge },
+ { text: nightscout.batteryVoltage === null ? "--V" : `${nightscout.batteryVoltage.toFixed(2)}V`, warning: alerts.battery },
+ { text: nightscout.pumpStatus || "--" },
+ ],
},
- { text: `Pump ${nightscout.pumpStatus || "--"}`, shade: 150 },
];
let statusY = graphTop - 8 - statusLines.length * step;
for (const line of statusLines) {
- if (line.direction !== undefined) {
+ if (line.fields) {
+ let x = statusX;
+ for (const field of line.fields) {
+ const text = truncateText(font, field.text, Math.max(0, statusX + statusWidth - x));
+ const textWidth = font.measureText(text);
+ if (field.warning && textWidth > 0) image.fillRect(x - 2, statusY - 1, textWidth + 4, font.lineHeight + 2, 230);
+ image.drawText(font, x, statusY, text, field.warning ? 0 : line.shade);
+ x += textWidth + font.measureText(" ");
+ if (x >= statusX + statusWidth) break;
+ }
+ } else if (line.direction !== undefined) {
image.drawText(font, statusX, statusY, line.text, line.shade);
drawDirectionIndicator(image, font, statusX + font.measureText(line.text), statusY, line.direction, line.shade);
} else {
@@ -390,6 +420,11 @@ export function nightscoutMenuItems(): MenuItem[] {
openSettingsSubMenu(ctx, "Nightscout settings", [
textSettingMenuItem(nightscoutSiteUrlSetting),
textSettingMenuItem(nightscoutApiTokenSetting),
+ textSettingMenuItem(nightscoutMaxCannulaAgeSetting),
+ textSettingMenuItem(nightscoutCartridgeLowSetting),
+ textSettingMenuItem(nightscoutBatteryLowSetting),
+ textSettingMenuItem(nightscoutMaxLoopAgeSetting),
+ toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting),
]);
},
},
diff --git a/app/apps/notifications/notifications-app.ts b/app/apps/notifications/notifications-app.ts
index 168de962..a7f0bf75 100644
--- a/app/apps/notifications/notifications-app.ts
+++ b/app/apps/notifications/notifications-app.ts
@@ -1,4 +1,5 @@
import { NotificationsListLayer } from "../../ui/notifications";
+import { NotificationFilterLayer } from "../../ui/notification-filter";
import { onAndroidNotificationPosted } from "../../native/notification-icons";
import {
createInProcessWindow,
@@ -25,6 +26,13 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr
iconLetter: "N",
icon: "bell",
closeable: true,
+ menuItems: () => [{
+ label: "Notification filter",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ ctx.stack.push(new NotificationFilterLayer());
+ },
+ }],
actions: options.actions,
baseLayer: new YieldAtRootLayer(new NotificationsListLayer()),
submitFrame: options.submitFrame,
diff --git a/app/apps/pinball/pinball-app.worker.ts b/app/apps/pinball/pinball-app.worker.ts
index 65bf6348..b38b40ea 100644
--- a/app/apps/pinball/pinball-app.worker.ts
+++ b/app/apps/pinball/pinball-app.worker.ts
@@ -21,7 +21,7 @@
*/
import "@nativescript/core/globals";
import { GrayImage } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
+import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
@@ -29,7 +29,8 @@ import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { type MenuItem } from "../../ui/menu";
+import { WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import {
directionalFallback,
@@ -71,7 +72,7 @@ const GRAVITY = 240;
const DRAG_PER_S = 0.12;
const MAX_SPEED = 600;
const PHYSICS_DT = 1 / 120;
-const RENDER_TICK_MS = 110;
+const RENDER_TICK_MS = 50;
/** Launch speed by power setting (index = power - 1). */
const LAUNCH_SPEEDS = [320, 380, 440, 500, 560] as const;
const BUMPER_KICK = 340;
@@ -242,12 +243,13 @@ type Flipper = {
type PinballWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
/** Whether this window is the shell's input target (pushed with each message). */
focused: boolean;
- /** Long-press window menu; created on first open. */
+ /** Tap-then-hold window menu; created on first open. */
menu: WindowMenu | null;
phase: GamePhase;
/** "ready" = parked on the plunger awaiting launch; "live" = in play. */
@@ -301,6 +303,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
const window: PinballWindow = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -443,9 +446,9 @@ function playSfx(window: PinballWindow, steps: Step[], minor = false): void {
}
}
-/** The window's long-press menu (game actions + default entries). */
-function openWindowMenu(window: PinballWindow): void {
- windowMenu(window).open([
+/** The window's context menu (game actions), offered while paused or over; playing keeps long-press for the nudge. */
+function windowMenuItems(window: PinballWindow): MenuItem[] {
+ return [
{
label: "New game",
onSelect: (ctx) => {
@@ -462,13 +465,17 @@ function openWindowMenu(window: PinballWindow): void {
if (window.soundOn) playSfx(window, SFX_RESUME);
},
},
- ...defaultWindowMenuItems(window.windowId, post),
- ]);
+ ];
}
function windowMenu(window: PinballWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
+ windowId: window.windowId,
+ post,
+ title: () => window.title,
+ items: () => (window.phase === "playing" ? [] : windowMenuItems(window)),
+ claimsLongPress: () => window.phase === "playing",
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
@@ -547,6 +554,10 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n
}
nudge(window);
break;
+ case "short-then-long-press":
+ // No context menu mid-game, so this opens the system menu instead.
+ windowMenu(window).open();
+ break;
case "double-click":
window.phase = "paused";
syncTickTimer(window);
@@ -573,8 +584,8 @@ function handleIdleInput(window: PinballWindow, event: InputEvent, frameId: numb
frameTimings.finishFrame(frameId, "discarded: pinball yielded focus");
post({ type: "yield-focus", windowId: window.windowId });
return;
- case "long-press":
- openWindowMenu(window);
+ case "short-then-long-press":
+ windowMenu(window).open();
break;
default:
frameTimings.finishFrame(frameId, "discarded: pinball ignored input");
@@ -945,10 +956,7 @@ function drawFlipper(image: GrayImage, flipper: Flipper): void {
}
function paint(window: PinballWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- return singlePlane(paintContent(window));
+ return windowMenu(window).paint();
}
function paintContent(window: PinballWindow): GrayImage {
diff --git a/app/apps/roam/roam-api.ts b/app/apps/roam/roam-api.ts
index 8e8136bf..a42782d5 100644
--- a/app/apps/roam/roam-api.ts
+++ b/app/apps/roam/roam-api.ts
@@ -104,7 +104,7 @@ async function roamPost(endpoint: "q" | "pull" | "write", body: object): Promise
const graph = roamGraphNameSetting.get();
const token = roamApiTokenSetting.get();
if (!graph || !token) {
- throw new Error("Set the Roam graph name and API token from the Roam app's long-press menu.");
+ throw new Error("Set the Roam graph name and API token from the Roam app's context menu (tap, then hold).");
}
const path = `/api/graph/${encodeURIComponent(graph)}/${endpoint}`;
const payload = JSON.stringify(body);
diff --git a/app/apps/roam/roam-app.worker.ts b/app/apps/roam/roam-app.worker.ts
index d78ea93a..f35d09b3 100644
--- a/app/apps/roam/roam-app.worker.ts
+++ b/app/apps/roam/roam-app.worker.ts
@@ -4,7 +4,7 @@
* todo or follows a [[page]] link, double-click walks back through visited
* pages then yields focus. Edits (check/uncheck, add todo, edit block) go
* through the Roam backend API and are also exposed as assistant tools.
- * The graph name and API token are configured here too, from the long-press
+ * The graph name and API token are configured here too, from the context
* menu, via the phone app's text editor.
*/
import "@nativescript/core/globals";
@@ -17,7 +17,7 @@ import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { onSettingsStoreChanged } from "../../native/settings-store";
import type { MenuItem } from "../../ui/menu";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
@@ -64,6 +64,7 @@ const smallFont = getDefaultSmallFont();
type RoamWindow = {
windowId: string;
surfaceId: string;
+ title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
@@ -168,6 +169,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
window = {
windowId: message.windowId,
surfaceId: message.surfaceId,
+ title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
@@ -327,6 +329,10 @@ function maybeRefreshStalePage(): void {
function windowMenu(win: RoamWindow): WindowMenu {
if (!win.menu) {
win.menu = new WindowMenu({
+ windowId: win.windowId,
+ post,
+ title: () => win.title,
+ items: () => menuItems(win),
size: { width: win.viewportWidth, height: win.viewportHeight },
paintBase: () => paintContent(win),
isFocused: () => win.focused,
@@ -377,7 +383,7 @@ function menuItems(win: RoamWindow): MenuItem[] {
beginSettingEdit(roamApiTokenSetting);
},
});
- return [...items, ...defaultWindowMenuItems(win.windowId, post)];
+ return items;
}
/**
@@ -417,8 +423,8 @@ function handleInput(win: RoamWindow, event: InputEvent, frameId: number): void
}
return;
}
- if (event.type === "long-press") {
- windowMenu(win).open(menuItems(win));
+ if (event.type === "short-then-long-press") {
+ windowMenu(win).open();
renderAndSubmit(win, frameId);
return;
}
@@ -519,7 +525,7 @@ async function addTodoFromText(text: string): Promise {
async function handleRoamTool(name: string, args: any): Promise {
if (!isRoamConfigured()) {
- return { ok: false, error: "Roam is not configured; set the graph name and API token from the Roam app's long-press menu." };
+ return { ok: false, error: "Roam is not configured; set the graph name and API token from the Roam app's context menu (tap, then hold)." };
}
switch (name) {
case "read_page": {
@@ -580,9 +586,9 @@ async function handleRoamTool(name: string, args: any): Promise {
// Painting
function paint(win: RoamWindow): Plane[] {
- if (win.menu?.isOpen()) return win.menu.paint();
- if (editingSetting) return singlePlane(paintSettingEdit(win, editingSetting));
- return singlePlane(paintContent(win));
+ return windowMenu(win).paint(() =>
+ singlePlane(editingSetting ? paintSettingEdit(win, editingSetting) : paintContent(win)),
+ );
}
/** The "type on the phone" screen shown while a Roam setting is being edited. */
@@ -628,7 +634,7 @@ function paintContent(win: RoamWindow): GrayImage {
image.drawLine(DOC_MARGIN, HEADER_HEIGHT - 4, win.viewportWidth - DOC_MARGIN, HEADER_HEIGHT - 4, 40);
if (!isRoamConfigured()) {
- drawBodyMessage(image, win, "Set the Roam graph name and API token: long-press for the menu, then pick Set graph name and Set API token.");
+ drawBodyMessage(image, win, "Set the Roam graph name and API token: tap, then hold, for the menu; pick Set graph name and Set API token.");
} else if (errorMessage) {
drawBodyMessage(image, win, `${errorMessage}\n\n${GESTURE_CLICK} retry`);
} else if (currentPage && currentPage.children.length === 0 && !loading) {
diff --git a/app/apps/teleprompter/index.ts b/app/apps/teleprompter/index.ts
new file mode 100644
index 00000000..f2abbcf1
--- /dev/null
+++ b/app/apps/teleprompter/index.ts
@@ -0,0 +1,19 @@
+import { type AppDefinition } from "../app-definition";
+import { createTeleprompterAppWindow, TELEPROMPTER_SURFACE_ID, TELEPROMPTER_WINDOW_ID } from "./teleprompter-app";
+
+const teleprompterApp: AppDefinition = {
+ appId: "teleprompter",
+ title: "Teleprompter",
+ icon: "scroll-text",
+ launch: (ctx) =>
+ ctx.launchInProcessApp(TELEPROMPTER_WINDOW_ID, TELEPROMPTER_SURFACE_ID, (options) =>
+ createTeleprompterAppWindow({
+ ...options,
+ startContinuousVoiceCapture: () => void options.actions.startContinuousVoiceCapture(),
+ stopContinuousVoiceCapture: () => void options.actions.stopContinuousVoiceCapture(),
+ appendLog: (message) => ctx.appendLog(message),
+ }),
+ ),
+};
+
+export default teleprompterApp;
diff --git a/app/apps/teleprompter/reader.ts b/app/apps/teleprompter/reader.ts
new file mode 100644
index 00000000..a3c39205
--- /dev/null
+++ b/app/apps/teleprompter/reader.ts
@@ -0,0 +1,300 @@
+import { GrayImage, type UiFont } from "../../graphics/image";
+import { truncateText } from "../../graphics/textwrap";
+import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { voiceControlBridge, type VoiceTranscriptEvent } from "../../native/voice-control";
+import { type InputEvent } from "../../ui/gestures";
+import { Layer, type LayerContext } from "../../ui/layers";
+import { type MenuItem } from "../../ui/menu";
+import { lineStep } from "../../ui/metrics";
+import { clamp } from "../../util/numeric-util";
+import { ScriptTracker, tokenizeScript, type TokenizedScript } from "./script-tracker";
+
+const MARGIN_X = 18;
+const BODY_TOP = 6;
+/** Gap between the last body line and the footer. */
+const FOOTER_GAP = 4;
+/** Lines per ring scroll tick. */
+const SCROLL_STEP_LINES = 2;
+
+/** Brightness of words already spoken, still to come, and the next one. */
+const PAST_VALUE = 90;
+const UPCOMING_VALUE = 200;
+const NEXT_VALUE = 255;
+
+type LayoutSpan = { tokenIndex: number; x: number; width: number; text: string };
+type LayoutLine = { spans: LayoutSpan[] };
+
+export type ReaderHooks = {
+ requestRender: () => void;
+ /** Hold continuous mic capture while tracking is on. */
+ startCapture: () => void;
+ stopCapture: () => void;
+ /** The reader closed (or paused) at this word position. */
+ savePosition: (position: number) => void;
+};
+
+/**
+ * The teleprompter's reading view. Lays the script out word by word in the
+ * medium UI font, follows the speaker through it from the live transcript
+ * (see ScriptTracker), auto-scrolls to keep the next word about a third of
+ * the way down, and highlights that word. Ring scrolls move the view by hand
+ * and re-anchor the tracker to what is now at the anchor row, so scrolling
+ * doubles as "I'm here now". Click pauses/resumes tracking; double-click
+ * goes back to the file list.
+ */
+export class TeleprompterReaderLayer implements Layer {
+ private readonly script: TokenizedScript;
+ private readonly tracker: ScriptTracker;
+ private lines: LayoutLine[] | null = null;
+ /** Line index of each word (parallel to script.words). */
+ private wordLines: number[] = [];
+ private layoutKey = "";
+ private firstLine = 0;
+ /** True after the tracker moved: the next paint re-centers on the position. */
+ private autoScrollPending = true;
+ private tracking = true;
+ private status = "";
+ private unsubscribeTranscript: (() => void) | null = null;
+ private unsubscribeStatus: (() => void) | null = null;
+ // Geometry from the last paint, for the input handlers.
+ private visibleRows = 10;
+ private anchorRow = 3;
+
+ constructor(
+ text: string,
+ private readonly title: string,
+ private readonly hooks: ReaderHooks,
+ initialPosition = 0,
+ ) {
+ this.script = tokenizeScript(text);
+ this.tracker = new ScriptTracker(this.script.words);
+ this.tracker.anchor(initialPosition);
+ }
+
+ /** Start listening. Called once the layer is on its stack. */
+ attach(): void {
+ this.unsubscribeStatus = voiceControlBridge.onStatus((state) => {
+ this.status = state.status;
+ this.hooks.requestRender();
+ });
+ this.startTracking();
+ }
+
+ onRemoved(): void {
+ this.hooks.savePosition(this.resumePosition());
+ this.stopTracking();
+ this.unsubscribeStatus?.();
+ this.unsubscribeStatus = null;
+ }
+
+ get position(): number {
+ return this.tracker.position;
+ }
+
+ buildMenuItems(): MenuItem[] {
+ return [
+ {
+ label: this.tracking ? "Pause voice tracking" : "Resume voice tracking",
+ onSelect: (ctx) => {
+ this.toggleTracking();
+ ctx.stack.pop();
+ },
+ },
+ {
+ label: "Restart from the top",
+ onSelect: (ctx) => {
+ this.tracker.anchor(0);
+ this.firstLine = 0;
+ this.autoScrollPending = true;
+ ctx.stack.pop();
+ },
+ },
+ ];
+ }
+
+ paint(ctx: LayerContext): GrayImage {
+ const font = getDefaultMediumFont();
+ const smallFont = getDefaultSmallFont();
+ const step = lineStep(font);
+ const { width, height } = ctx.stack.getBaseSize();
+ const image = new GrayImage(width, height, 0);
+
+ const footerY = height - smallFont.lineHeight - 4;
+ this.visibleRows = Math.max(1, Math.floor((footerY - FOOTER_GAP - BODY_TOP) / step));
+ this.anchorRow = Math.floor(this.visibleRows / 3);
+ const lines = this.layout(font, width - 2 * MARGIN_X);
+
+ if (this.autoScrollPending) {
+ this.autoScrollPending = false;
+ this.firstLine = this.clampFirstLine(this.lineOfPosition() - this.anchorRow);
+ } else {
+ this.firstLine = this.clampFirstLine(this.firstLine);
+ }
+
+ const position = this.tracker.position;
+ const nextToken = position < this.script.words.length ? this.script.wordTokens[position]! : this.script.tokens.length;
+ const lastLine = Math.min(lines.length, this.firstLine + this.visibleRows);
+ for (let lineIndex = this.firstLine; lineIndex < lastLine; lineIndex++) {
+ const y = BODY_TOP + (lineIndex - this.firstLine) * step;
+ for (const span of lines[lineIndex]!.spans) {
+ const isNext = span.tokenIndex === nextToken;
+ const value = isNext ? NEXT_VALUE : span.tokenIndex < nextToken ? PAST_VALUE : UPCOMING_VALUE;
+ image.drawText(font, MARGIN_X + span.x, y, span.text, value);
+ if (isNext) {
+ image.fillRect(MARGIN_X + span.x, y + font.lineHeight - 2, span.width, 2, NEXT_VALUE);
+ }
+ }
+ }
+
+ this.paintFooter(image, smallFont, width, footerY);
+ return image;
+ }
+
+ handleInput(event: InputEvent, ctx: LayerContext): void {
+ switch (event.type) {
+ case "scroll-down":
+ this.scrollBy(SCROLL_STEP_LINES);
+ return;
+ case "scroll-up":
+ this.scrollBy(-SCROLL_STEP_LINES);
+ return;
+ case "click":
+ this.toggleTracking();
+ return;
+ case "double-click":
+ ctx.stack.pop();
+ return;
+ default:
+ return;
+ }
+ }
+
+ private paintFooter(image: GrayImage, font: UiFont, width: number, y: number): void {
+ const total = this.script.words.length;
+ const percent = total === 0 ? 0 : Math.round((100 * this.tracker.position) / total);
+ const right = `${this.tracking ? this.status || "Listening" : "Paused"} ${percent}%`;
+ const rightWidth = font.measureText(right);
+ image.drawText(font, width - MARGIN_X - rightWidth, y, right, 110);
+ const titleMax = width - 2 * MARGIN_X - rightWidth - 12;
+ if (titleMax > 20) {
+ image.drawText(font, MARGIN_X, y, truncateText(font, this.title, titleMax), 110);
+ }
+ }
+
+ /**
+ * Hand-scroll by whole lines. The tracker is re-anchored to the first word
+ * at (or after) the anchor row, so the highlight follows the view and
+ * speech matching resumes from there.
+ */
+ private scrollBy(deltaLines: number): void {
+ const lines = this.lines;
+ if (!lines) return;
+ this.autoScrollPending = false;
+ this.firstLine = this.clampFirstLine(this.firstLine + deltaLines);
+ const anchorLine = this.firstLine + this.anchorRow;
+ const word = this.firstWordAtOrAfterLine(anchorLine);
+ this.tracker.anchor(word);
+ }
+
+ private clampFirstLine(value: number): number {
+ const lineCount = this.lines?.length ?? 0;
+ // Scroll far enough that the last line can reach the anchor row.
+ return clamp(value, 0, Math.max(0, lineCount - this.anchorRow - 1));
+ }
+
+ private lineOfPosition(): number {
+ const position = this.tracker.position;
+ if (this.wordLines.length === 0) return 0;
+ if (position >= this.wordLines.length) return this.wordLines[this.wordLines.length - 1]!;
+ return this.wordLines[position]!;
+ }
+
+ private firstWordAtOrAfterLine(line: number): number {
+ for (let word = 0; word < this.wordLines.length; word++) {
+ if (this.wordLines[word]! >= line) return word;
+ }
+ return this.wordLines.length;
+ }
+
+ /** Where to resume next time: a script read to the end restarts from the top. */
+ private resumePosition(): number {
+ return this.tracker.position >= this.script.words.length ? 0 : this.tracker.position;
+ }
+
+ private toggleTracking(): void {
+ if (this.tracking) {
+ this.stopTracking();
+ this.hooks.savePosition(this.resumePosition());
+ } else {
+ this.startTracking();
+ }
+ }
+
+ private startTracking(): void {
+ this.tracking = true;
+ if (!this.unsubscribeTranscript) {
+ this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => this.onTranscript(event));
+ }
+ this.hooks.startCapture();
+ }
+
+ private stopTracking(): void {
+ this.tracking = false;
+ this.unsubscribeTranscript?.();
+ this.unsubscribeTranscript = null;
+ this.hooks.stopCapture();
+ }
+
+ private onTranscript(event: VoiceTranscriptEvent): void {
+ if (!this.tracking) return;
+ if (this.tracker.feed(event.text)) {
+ this.autoScrollPending = true;
+ this.hooks.requestRender();
+ }
+ }
+
+ /** Word-by-word greedy line layout; cached per font and width. */
+ private layout(font: UiFont, maxWidth: number): LayoutLine[] {
+ const key = `${font.fingerprintId}:${maxWidth}`;
+ if (this.lines && this.layoutKey === key) return this.lines;
+ const spaceWidth = font.measureText(" ");
+ const lines: LayoutLine[] = [];
+ const wordLines: number[] = [];
+ let current: LayoutLine = { spans: [] };
+ let currentWidth = 0;
+ let paragraph = -1;
+ const flush = () => {
+ lines.push(current);
+ current = { spans: [] };
+ currentWidth = 0;
+ };
+ for (let tokenIndex = 0; tokenIndex < this.script.tokens.length; tokenIndex++) {
+ const token = this.script.tokens[tokenIndex]!;
+ if (token.paragraph !== paragraph) {
+ // New paragraph: end the current line, and leave one empty line per
+ // blank source line (paragraph numbers count every newline).
+ if (paragraph >= 0) {
+ flush();
+ for (let blank = paragraph + 1; blank < token.paragraph; blank++) flush();
+ }
+ paragraph = token.paragraph;
+ }
+ const wordWidth = font.measureText(token.text);
+ const x = current.spans.length === 0 ? 0 : currentWidth + spaceWidth;
+ if (current.spans.length > 0 && x + wordWidth > maxWidth) {
+ flush();
+ }
+ const spanX = current.spans.length === 0 ? 0 : currentWidth + spaceWidth;
+ current.spans.push({ tokenIndex, x: spanX, width: wordWidth, text: token.text });
+ currentWidth = spanX + wordWidth;
+ if (token.wordIndex >= 0) {
+ wordLines[token.wordIndex] = lines.length;
+ }
+ }
+ if (current.spans.length > 0 || lines.length === 0) flush();
+ this.lines = lines;
+ this.wordLines = wordLines;
+ this.layoutKey = key;
+ return lines;
+ }
+}
diff --git a/app/apps/teleprompter/recent-files.ts b/app/apps/teleprompter/recent-files.ts
new file mode 100644
index 00000000..61b1d809
--- /dev/null
+++ b/app/apps/teleprompter/recent-files.ts
@@ -0,0 +1,80 @@
+import { getStringSetting, setStringSetting } from "../../native/settings-store";
+
+/**
+ * The Teleprompter's recently opened scripts, most recent first, with the
+ * word position the reader was at when it closed (so reopening resumes
+ * there). Stored as a JSON array in the settings store.
+ */
+export type RecentScript = {
+ path: string;
+ name: string;
+ /** Word index the reader was at when last closed; 0 = start. */
+ position: number;
+ openedMs: number;
+};
+
+const RECENTS_KEY = "teleprompter.recents";
+const MAX_RECENTS = 12;
+
+export function getRecentScripts(): RecentScript[] {
+ try {
+ const parsed: unknown = JSON.parse(getStringSetting(RECENTS_KEY, "[]"));
+ if (!Array.isArray(parsed)) return [];
+ return parsed
+ .filter((entry): entry is RecentScript => !!entry && typeof entry === "object" && typeof entry.path === "string")
+ .map((entry) => ({
+ path: entry.path,
+ name: typeof entry.name === "string" && entry.name ? entry.name : baseName(entry.path),
+ position: typeof entry.position === "number" && entry.position >= 0 ? entry.position : 0,
+ openedMs: typeof entry.openedMs === "number" ? entry.openedMs : 0,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+function saveRecentScripts(recents: RecentScript[]): void {
+ setStringSetting(RECENTS_KEY, JSON.stringify(recents.slice(0, MAX_RECENTS)));
+}
+
+/** Move (or add) a script to the top of the list, keeping its saved position. */
+export function touchRecentScript(path: string, name: string): RecentScript {
+ const recents = getRecentScripts();
+ const existing = recents.find((entry) => entry.path === path);
+ const entry: RecentScript = {
+ path,
+ name,
+ position: existing?.position ?? 0,
+ openedMs: Date.now(),
+ };
+ saveRecentScripts([entry, ...recents.filter((other) => other.path !== path)]);
+ return entry;
+}
+
+export function saveRecentScriptPosition(path: string, position: number): void {
+ const recents = getRecentScripts();
+ const entry = recents.find((other) => other.path === path);
+ if (!entry) return;
+ entry.position = Math.max(0, position);
+ saveRecentScripts(recents);
+}
+
+export function removeRecentScript(path: string): void {
+ saveRecentScripts(getRecentScripts().filter((entry) => entry.path !== path));
+}
+
+export function clearRecentScripts(): void {
+ saveRecentScripts([]);
+}
+
+export function baseName(path: string): string {
+ const slash = path.lastIndexOf("/");
+ return slash >= 0 ? path.slice(slash + 1) : path;
+}
+
+/** The last directory segment of a file path, for a dim "where it lives" hint. */
+export function parentDirName(path: string): string {
+ const slash = path.lastIndexOf("/");
+ if (slash <= 0) return "";
+ return baseName(path.slice(0, slash));
+}
diff --git a/app/apps/teleprompter/script-tracker.ts b/app/apps/teleprompter/script-tracker.ts
new file mode 100644
index 00000000..8cdb4e41
--- /dev/null
+++ b/app/apps/teleprompter/script-tracker.ts
@@ -0,0 +1,260 @@
+/**
+ * Follows a speaker through a script from live speech-to-text. Pure logic
+ * (no NativeScript imports) so it runs under plain node for the tests.
+ *
+ * The script is tokenized once into display tokens; the subset with a
+ * non-empty normalized key are the "words" the tracker aligns against. The
+ * tracker keeps `position`: the index (in word space) of the next word the
+ * speaker is expected to say. Each transcript update (replace semantics: the
+ * whole current utterance, partial or final) re-aligns the tail of the
+ * transcript against a window of script words around the current position,
+ * with a local alignment that tolerates misrecognized, skipped and ad-libbed
+ * words, and moves the position to just after the last aligned script word.
+ */
+
+export type ScriptToken = {
+ /** The token as written, for display. */
+ text: string;
+ /** Paragraph number (newline-separated), for layout. */
+ paragraph: number;
+ /** Lowercased alphanumeric key, or "" for punctuation-only tokens. */
+ key: string;
+ /** Index into the tracker's word list, or -1 when key is empty. */
+ wordIndex: number;
+};
+
+export type TokenizedScript = {
+ tokens: ScriptToken[];
+ /** Normalized keys of the trackable tokens, in order. */
+ words: string[];
+ /** Token index of each word. */
+ wordTokens: number[];
+};
+
+/** Lowercase, strip everything but letters/digits, fold common apostrophes. */
+export function normalizeWord(raw: string): string {
+ return raw
+ .normalize("NFKD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "");
+}
+
+export function tokenizeScript(text: string): TokenizedScript {
+ const tokens: ScriptToken[] = [];
+ const words: string[] = [];
+ const wordTokens: number[] = [];
+ const paragraphs = text.replace(/\r/g, "").split("\n");
+ for (let paragraph = 0; paragraph < paragraphs.length; paragraph++) {
+ for (const raw of paragraphs[paragraph]!.split(/\s+/)) {
+ if (!raw) continue;
+ const key = normalizeWord(raw);
+ const wordIndex = key ? words.length : -1;
+ if (key) {
+ words.push(key);
+ wordTokens.push(tokens.length);
+ }
+ tokens.push({ text: raw, paragraph, key, wordIndex });
+ }
+ }
+ return { tokens, words, wordTokens };
+}
+
+/** Split a transcript into normalized keys, dropping empties. */
+export function transcriptKeys(text: string): string[] {
+ return text
+ .split(/\s+/)
+ .map(normalizeWord)
+ .filter((key) => key.length > 0);
+}
+
+// Function words match so often that on their own they say little about
+// where the speaker is; they count for less than content words.
+const STOP_WORDS = new Set([
+ "a", "an", "the", "and", "or", "but", "of", "to", "in", "on", "at", "for", "is", "it", "its",
+ "i", "we", "you", "he", "she", "they", "that", "this", "as", "be", "are", "was", "were",
+ "with", "by", "so", "if", "not", "no", "do", "have", "has", "had", "will", "can",
+]);
+
+const MATCH_SCORE = 3;
+const STOP_WORD_MATCH_SCORE = 1.5;
+/** A fuzzy (edit-distance 1) or prefix match: real evidence, but weaker. */
+const FUZZY_MATCH_SCORE = 2;
+const MISMATCH_SCORE = -2;
+const GAP_SCORE = -1.5;
+/** The alignment must be worth at least this to move the position at all. */
+const MIN_ALIGNMENT_SCORE = 4.5;
+const MIN_MATCHED_WORDS = 2;
+/** Per-word cost of ending an alignment away from the expected position (a tie-breaker). */
+const FORWARD_DISTANCE_COST = 0.02;
+const BACKWARD_DISTANCE_COST = 0.1;
+
+export type TrackerOptions = {
+ /** Script words before the current position that stay in play (repeats, backtracking). */
+ back?: number;
+ /** Script words after the current position that stay in play (skipping ahead). */
+ ahead?: number;
+ /** Only the last this-many transcript words are aligned. */
+ tailWords?: number;
+};
+
+const DEFAULT_OPTIONS: Required = { back: 30, ahead: 160, tailWords: 20 };
+
+/**
+ * Edit distance capped at 1 (true when the strings are within one edit),
+ * which covers the typical STT slip: a dropped/extra letter or a substitution.
+ */
+export function withinOneEdit(a: string, b: string): boolean {
+ if (a === b) return true;
+ const lengthDelta = a.length - b.length;
+ if (lengthDelta > 1 || lengthDelta < -1) return false;
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
+ let i = 0;
+ let j = 0;
+ let edits = 0;
+ while (i < short.length && j < long.length) {
+ if (short[i] === long[j]) {
+ i++;
+ j++;
+ continue;
+ }
+ if (++edits > 1) return false;
+ if (short.length === long.length) {
+ i++;
+ }
+ j++;
+ }
+ return edits + (long.length - j) <= 1;
+}
+
+/** Score of aligning transcript key `spoken` with script key `expected`. */
+function matchScore(spoken: string, expected: string, isLastSpoken: boolean): number {
+ if (spoken === expected) {
+ return STOP_WORDS.has(expected) ? STOP_WORD_MATCH_SCORE : MATCH_SCORE;
+ }
+ // The final transcript word is often still being recognized: a prefix of
+ // the script word counts, once it is long enough not to be noise.
+ if (isLastSpoken && spoken.length >= 2 && expected.length > spoken.length && expected.startsWith(spoken)) {
+ return FUZZY_MATCH_SCORE;
+ }
+ if (spoken.length >= 5 && expected.length >= 5 && withinOneEdit(spoken, expected)) {
+ return FUZZY_MATCH_SCORE;
+ }
+ return MISMATCH_SCORE;
+}
+
+export type AlignmentResult = {
+ /** Index (in the script word list) of the word after the last aligned one; the new position. */
+ position: number;
+ score: number;
+ matchedWords: number;
+};
+
+/**
+ * Align the transcript tail against script words [windowStart, windowEnd).
+ * Local alignment (free start on both sides) that must consume the last
+ * transcript word and may end anywhere in the window. Returns null when the
+ * best alignment is too weak to trust.
+ */
+export function alignTail(
+ words: readonly string[],
+ spoken: readonly string[],
+ windowStart: number,
+ windowEnd: number,
+ expectedPosition: number,
+): AlignmentResult | null {
+ const m = spoken.length;
+ const n = windowEnd - windowStart;
+ if (m === 0 || n <= 0) return null;
+
+ // H[i][j]: best score of an alignment ending with spoken[i-1] / window[j-1]
+ // (or a gap), clamped at 0 (free start). Matches counts how many spoken
+ // words matched along the path that produced H[i][j].
+ const width = n + 1;
+ const score = new Float64Array((m + 1) * width);
+ const matches = new Uint16Array((m + 1) * width);
+ for (let i = 1; i <= m; i++) {
+ const spokenWord = spoken[i - 1]!;
+ const isLast = i === m;
+ for (let j = 1; j <= n; j++) {
+ const here = i * width + j;
+ const s = matchScore(spokenWord, words[windowStart + j - 1]!, isLast);
+ const diagonal = score[here - width - 1]! + s;
+ const skipScript = score[here - 1]! + GAP_SCORE;
+ const skipSpoken = score[here - width]! + GAP_SCORE;
+ let best = 0;
+ let bestMatches = 0;
+ if (diagonal > best) {
+ best = diagonal;
+ bestMatches = matches[here - width - 1]! + (s > 0 ? 1 : 0);
+ }
+ if (skipScript > best) {
+ best = skipScript;
+ bestMatches = matches[here - 1]!;
+ }
+ if (skipSpoken > best) {
+ best = skipSpoken;
+ bestMatches = matches[here - width]!;
+ }
+ score[here] = best;
+ matches[here] = bestMatches;
+ }
+ }
+
+ let bestColumn = -1;
+ let bestAdjusted = -Infinity;
+ for (let j = 1; j <= n; j++) {
+ const raw = score[m * width + j]!;
+ if (raw <= 0) continue;
+ const position = windowStart + j;
+ const distance = position - expectedPosition;
+ const adjusted = raw - (distance >= 0 ? distance * FORWARD_DISTANCE_COST : -distance * BACKWARD_DISTANCE_COST);
+ if (adjusted > bestAdjusted) {
+ bestAdjusted = adjusted;
+ bestColumn = j;
+ }
+ }
+ if (bestColumn < 0) return null;
+ const rawScore = score[m * width + bestColumn]!;
+ const matchedWords = matches[m * width + bestColumn]!;
+ if (rawScore < MIN_ALIGNMENT_SCORE || matchedWords < MIN_MATCHED_WORDS) return null;
+ return { position: windowStart + bestColumn, score: rawScore, matchedWords };
+}
+
+export class ScriptTracker {
+ private readonly options: Required;
+ /** Index of the next word the speaker is expected to say (0..words.length). */
+ position = 0;
+
+ constructor(
+ private readonly words: readonly string[],
+ options: TrackerOptions = {},
+ ) {
+ this.options = { ...DEFAULT_OPTIONS, ...options };
+ }
+
+ get wordCount(): number {
+ return this.words.length;
+ }
+
+ /** Jump the expected position (manual scroll, restart). */
+ anchor(position: number): void {
+ this.position = Math.max(0, Math.min(this.words.length, position));
+ }
+
+ /**
+ * Apply a transcript update (the whole current utterance, partial or
+ * final). Returns true when the position moved.
+ */
+ feed(text: string): boolean {
+ const keys = transcriptKeys(text);
+ if (keys.length === 0) return false;
+ const tail = keys.length > this.options.tailWords ? keys.slice(-this.options.tailWords) : keys;
+ const windowStart = Math.max(0, this.position - this.options.back);
+ const windowEnd = Math.min(this.words.length, this.position + this.options.ahead);
+ const result = alignTail(this.words, tail, windowStart, windowEnd, this.position);
+ if (!result || result.position === this.position) return false;
+ this.position = result.position;
+ return true;
+ }
+}
diff --git a/app/apps/teleprompter/teleprompter-app.ts b/app/apps/teleprompter/teleprompter-app.ts
new file mode 100644
index 00000000..bbd3be46
--- /dev/null
+++ b/app/apps/teleprompter/teleprompter-app.ts
@@ -0,0 +1,188 @@
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { truncateText } from "../../graphics/textwrap";
+import { readTextFile, type DirectoryEntry } from "../../native/file-access";
+import { LIST_ROW_TEXT_INSET } from "../../ui/metrics";
+import { MenuLayer, type MenuItem } from "../../ui/menu";
+import { type Layer, type LayerContext } from "../../ui/layers";
+import { appViewportSize } from "../../ui/shell/geometry";
+import {
+ createInProcessWindow,
+ YieldAtRootLayer,
+ type InProcessAppOptions,
+ type InProcessWindow,
+} from "../../ui/shell/in-process-window";
+import { FileBrowserLayer } from "../files/file-browser";
+import { TeleprompterReaderLayer } from "./reader";
+import {
+ baseName,
+ clearRecentScripts,
+ getRecentScripts,
+ parentDirName,
+ removeRecentScript,
+ saveRecentScriptPosition,
+ touchRecentScript,
+} from "./recent-files";
+
+export const TELEPROMPTER_WINDOW_ID = "teleprompter";
+export const TELEPROMPTER_SURFACE_ID = "window:teleprompter";
+
+const SCRIPT_FILE = /\.(txt|md|markdown|text|log)$/i;
+
+const HOME_LAYOUT = {
+ x: 8,
+ y: 8,
+ width: 272,
+ showBorder: false,
+ minHeight: 0,
+ maxHeight: appViewportSize("min").height - 16,
+ opaque: true,
+};
+
+export type TeleprompterAppOptions = InProcessAppOptions & {
+ /** Hold continuous mic capture while a script is being tracked. */
+ startContinuousVoiceCapture: () => void;
+ stopContinuousVoiceCapture: () => void;
+ appendLog: (message: string) => void;
+};
+
+/**
+ * The Teleprompter app window. The home page is a Browse entry plus the
+ * recently opened scripts; Browse pushes the Files app's browser to pick a
+ * text file, and either path pushes the reader (see TeleprompterReaderLayer)
+ * over the home page.
+ */
+export function createTeleprompterAppWindow(options: TeleprompterAppOptions): InProcessWindow {
+ // The home menu's items are rebuilt in place whenever the recents change
+ // (MenuLayer reads the array each paint).
+ const homeItems: MenuItem[] = [];
+ const home = new MenuLayer("Teleprompter", homeItems, HOME_LAYOUT);
+ let created: InProcessWindow | null = null;
+ let notice = "";
+
+ const requestRender = () => created?.requestRender();
+
+ /** The layer currently on top of the window's stack (the home menu at base). */
+ const topLayer = (): Layer => {
+ let top: Layer = home;
+ created?.stack.topMatches((layer) => {
+ top = layer;
+ return true;
+ });
+ return top;
+ };
+
+ const openScript = (ctx: LayerContext, path: string, name: string) => {
+ const text = readTextFile(path);
+ if (text === null) {
+ removeRecentScript(path);
+ notice = `Could not read ${name}`;
+ options.appendLog(`teleprompter: could not read ${path}`);
+ refreshHome();
+ return;
+ }
+ const recent = touchRecentScript(path, name);
+ notice = "";
+ refreshHome();
+ const layer = new TeleprompterReaderLayer(
+ text,
+ name,
+ {
+ requestRender,
+ startCapture: () => options.startContinuousVoiceCapture(),
+ stopCapture: () => options.stopContinuousVoiceCapture(),
+ savePosition: (position) => saveRecentScriptPosition(path, position),
+ },
+ recent.position,
+ );
+ ctx.stack.push(layer);
+ layer.attach();
+ };
+
+ const openBrowser = (ctx: LayerContext) => {
+ const stack = ctx.stack;
+ const picker = new FileBrowserLayer({
+ isSupportedFile: (name) => SCRIPT_FILE.test(name),
+ onLeave: () => stack.pop(),
+ onFilePicked: (entry: DirectoryEntry, pickCtx) => {
+ if (!SCRIPT_FILE.test(entry.name)) {
+ notice = "Pick a text file (.txt, .md)";
+ return;
+ }
+ pickCtx.stack.pop();
+ openScript(pickCtx, entry.path, entry.name);
+ },
+ });
+ stack.push(picker);
+ };
+
+ function refreshHome(): void {
+ const font = getDefaultSmallFont();
+ const items: MenuItem[] = [
+ {
+ label: "Browse for a script...",
+ onSelect: (ctx) => openBrowser(ctx),
+ },
+ ];
+ for (const recent of getRecentScripts()) {
+ const folder = parentDirName(recent.path);
+ items.push({
+ label: recent.name || baseName(recent.path),
+ onSelect: (ctx) => openScript(ctx, recent.path, recent.name),
+ render: ({ image, x, y, width, selected, text }) => {
+ const value = selected ? 255 : 200;
+ const folderWidth = folder ? font.measureText(folder) : 0;
+ const nameMax = folder ? width - folderWidth - 12 : width;
+ image.drawText(font, x, y + LIST_ROW_TEXT_INSET, truncateText(font, text, Math.max(40, nameMax)), value);
+ if (folder && nameMax >= 40) {
+ image.drawText(font, x + width - folderWidth, y + LIST_ROW_TEXT_INSET, folder, 90);
+ }
+ },
+ });
+ }
+ if (notice) {
+ items.push({ label: notice, disabled: true, onSelect: () => {} });
+ }
+ homeItems.length = 0;
+ homeItems.push(...items);
+ // Land on the most recent script (one click resumes it), else on Browse.
+ home.selectItem(getRecentScripts().length > 0 ? 1 : 0);
+ }
+
+ refreshHome();
+
+ created = createInProcessWindow({
+ appId: "teleprompter",
+ windowId: TELEPROMPTER_WINDOW_ID,
+ title: "Teleprompter",
+ iconLetter: "Tp",
+ icon: "scroll-text",
+ closeable: true,
+ actions: options.actions,
+ menuItems: () => {
+ const top = topLayer();
+ if (top instanceof TeleprompterReaderLayer) return top.buildMenuItems();
+ if (top instanceof FileBrowserLayer) return top.buildMenuItems();
+ if (top !== home) return [];
+ return [
+ {
+ label: "Clear recent scripts",
+ onSelect: (ctx) => {
+ clearRecentScripts();
+ refreshHome();
+ ctx.stack.pop();
+ },
+ },
+ ];
+ },
+ onFocus: (lastInput) => {
+ const top = topLayer();
+ if (top instanceof FileBrowserLayer) top.onFocus(lastInput);
+ },
+ baseLayer: new YieldAtRootLayer(home),
+ submitFrame: options.submitFrame,
+ setSurfaceVisible: options.setSurfaceVisible,
+ removeSurface: options.removeSurface,
+ onClosed: options.onClosed,
+ });
+ return created;
+}
diff --git a/app/apps/terminal/terminal-app.worker.ts b/app/apps/terminal/terminal-app.worker.ts
index 17cf623d..3f315a0b 100644
--- a/app/apps/terminal/terminal-app.worker.ts
+++ b/app/apps/terminal/terminal-app.worker.ts
@@ -32,11 +32,11 @@
*/
import "@nativescript/core/globals";
import { GrayImage, type UiFont } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
+import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts";
import { truncateText } from "../../graphics/textwrap";
-import { TERMINAL_ICON_GLYPHS } from "../../graphics/icons";
+import { TERMINAL_ICON_GLYPHS, type IconActivity } from "../../graphics/icons";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
@@ -48,7 +48,7 @@ import { connectionDisplayName, loadConnections, parseConnectionString, saveConn
import { TerminalEmulator } from "./terminal-emulator";
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
import { lineStep, listRowHeight } from "../../ui/metrics";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
+import { WindowMenu } from "../../ui/window-menu";
import { appViewportSize } from "../../ui/shell/geometry";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
@@ -88,6 +88,8 @@ const NEW_CONNECTION_DRAFT_KEY = "terminal.newConnectionDraft";
type BaseWindow = {
windowId: string;
surfaceId: string;
+ /** Shell-side window title, echoed back in the open-window message. */
+ title: string;
/** Content viewport from the shell's open-window message; grid = viewport / cell. */
viewportWidth: number;
viewportHeight: number;
@@ -283,7 +285,7 @@ const sessionRecency = new Map();
// continues, so 5s of slack keeps the indicator lit through the gaps.
const sessionActivity = new Map();
const ACTIVITY_ACTIVE_MS = 5_000;
-// Alternation period of the hub's activity indicator.
+// Alternation period shared by hub rows and sidebar cursors.
const HUB_ANIMATION_STEP_MS = 800;
function recencyKey(connectionId: string, socket: string): string {
@@ -304,8 +306,32 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
const message = event.data;
switch (message.type) {
case "open-window":
- openWindow(message.windowId, message.surfaceId, message.viewport);
+ openWindow(message.windowId, message.surfaceId, message.title, message.viewport);
break;
+ case "resize-window": {
+ const window = windows.get(message.windowId);
+ if (!window || (window.viewportWidth === message.viewport.width && window.viewportHeight === message.viewport.height)) break;
+ window.viewportWidth = message.viewport.width;
+ window.viewportHeight = message.viewport.height;
+ window.menu?.resize(message.viewport);
+ window.lastSubmittedFingerprint = "";
+ if (window.kind === "view") {
+ window.gridCols = Math.floor(window.viewportWidth / window.cellWidth);
+ window.gridRows = Math.floor(window.viewportHeight / window.cellHeight);
+ if (window.reconnectTimer) clearTimeout(window.reconnectTimer);
+ window.reconnectTimer = null;
+ window.client.stop();
+ window.client.setViewport(window.gridCols, window.gridRows);
+ window.emulator.dispose();
+ window.emulator = new TerminalEmulator(window.gridCols, window.gridRows);
+ window.receivedData = false;
+ window.archive = [];
+ window.scrollTop = null;
+ reconnectView(window);
+ }
+ scheduleRender(window);
+ break;
+ }
case "close-window":
closeWindow(message.windowId);
break;
@@ -430,11 +456,12 @@ function cancelPendingReconnects(): void {
}
}
-function openWindow(windowId: string, surfaceId: string, viewport: { width: number; height: number }): void {
+function openWindow(windowId: string, surfaceId: string, title: string, viewport: { width: number; height: number }): void {
const pendingView = pendingViews.get(windowId);
if (pendingView) {
pendingViews.delete(windowId);
- windows.set(windowId, createViewWindow(windowId, surfaceId, viewport, pendingView));
+ windows.set(windowId, createViewWindow(windowId, surfaceId, title, viewport, pendingView));
+ updateHubAnimation();
renderHubWindows();
return;
}
@@ -443,6 +470,7 @@ function openWindow(windowId: string, surfaceId: string, viewport: { width: numb
kind: "hub",
windowId,
surfaceId,
+ title,
viewportWidth: viewport.width,
viewportHeight: viewport.height,
gridCols: Math.floor(viewport.width / hubCell.cellWidth),
@@ -463,6 +491,7 @@ function openWindow(windowId: string, surfaceId: string, viewport: { width: numb
if (!controlsInitialized) {
syncControlsFromSettings();
}
+ updateHubAnimation();
}
function closeWindow(windowId: string): void {
@@ -483,6 +512,8 @@ function closeWindow(windowId: string): void {
endAddConnection(window);
}
windows.delete(windowId);
+ windowIconActivity.delete(windowId);
+ updateHubAnimation();
// Auto-reconnect only runs while at least one terminal window is open.
if (windows.size === 0) {
for (const control of controls.values()) {
@@ -693,42 +724,47 @@ function renderHubWindows(): void {
}
}
-// Hub activity animation: while a foregrounded hub lists at least one active
-// session, a timer re-renders it so the per-row indicator alternates. The
-// timer stops itself once every session's activity ages out (its final tick
-// renders the rows indicator-free) or the hub leaves the foreground.
+// One animation clock for foreground hub rows and every terminal sidebar icon.
+// Keep ticking while the sidebar can show activity, even with the hub closed.
let hubAnimationPhase = 0;
let hubAnimationTimer: ReturnType | null = null;
+const windowIconActivity = new Map();
function isSessionActive(connectionId: string, socket: string): boolean {
const at = sessionActivity.get(recencyKey(connectionId, socket));
return at !== undefined && Date.now() - at < ACTIVITY_ACTIVE_MS;
}
-function hubAnimationShouldRun(): boolean {
- if (!screenOn) return false;
- let hubVisible = false;
- for (const window of windows.values()) {
- if (window.kind === "hub" && window.foreground) hubVisible = true;
- }
- if (!hubVisible) return false;
+function isWindowSessionActive(window: TerminalWindow): boolean {
+ if (window.kind === "view") return isSessionActive(window.connectionId, window.socket);
const now = Date.now();
- for (const at of sessionActivity.values()) {
- if (now - at < ACTIVITY_ACTIVE_MS) return true;
- }
- return false;
+ return [...sessionActivity.values()].some((at) => now - at < ACTIVITY_ACTIVE_MS);
}
-/** Start or stop the animation timer to match the current state. */
+function hubAnimationShouldRun(): boolean {
+ return screenOn && [...windows.values()].some(isWindowSessionActive);
+}
+
+function syncWindowIconActivity(): void {
+ for (const window of windows.values()) {
+ const activity: IconActivity = screenOn && isWindowSessionActive(window)
+ ? (hubAnimationPhase === 0 ? "on" : "off") : "idle";
+ if ((windowIconActivity.get(window.windowId) ?? "idle") === activity) continue;
+ windowIconActivity.set(window.windowId, activity);
+ post({ type: "set-icon-activity", windowId: window.windowId, activity });
+ }
+}
+
+/** Start or stop animation and publish changed icons, including expiry/wake. */
function updateHubAnimation(): void {
- if (hubAnimationShouldRun()) {
+ const shouldRun = hubAnimationShouldRun();
+ if (shouldRun && !hubAnimationTimer) hubAnimationPhase = 0;
+ syncWindowIconActivity();
+ if (shouldRun) {
if (hubAnimationTimer) return;
hubAnimationTimer = setInterval(() => {
hubAnimationPhase = (hubAnimationPhase + 1) % 2;
- if (!hubAnimationShouldRun() && hubAnimationTimer) {
- clearInterval(hubAnimationTimer);
- hubAnimationTimer = null;
- }
+ updateHubAnimation();
// Render even on the stopping tick, to clear expired indicators.
renderHubWindows();
}, HUB_ANIMATION_STEP_MS);
@@ -753,6 +789,7 @@ function noteSessionActivity(connectionId: string, socket: string): void {
function createViewWindow(
windowId: string,
surfaceId: string,
+ title: string,
viewport: { width: number; height: number },
view: PendingView,
): ViewWindow {
@@ -768,6 +805,7 @@ function createViewWindow(
kind: "view",
windowId,
surfaceId,
+ title,
viewportWidth: viewport.width,
viewportHeight: viewport.height,
gridCols,
@@ -896,10 +934,14 @@ function reconnectView(window: ViewWindow): void {
scheduleRender(window);
}
-/** The window's long-press menu, created lazily so window literals stay simple. */
+/** The window's context menu, created lazily so window literals stay simple. */
function windowMenu(window: TerminalWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
+ windowId: window.windowId,
+ post,
+ title: () => window.title,
+ items: () => windowMenuItems(window),
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
@@ -978,7 +1020,6 @@ function windowMenuItems(window: TerminalWindow): MenuItem[] {
},
);
}
- items.push(...defaultWindowMenuItems(window.windowId, post));
return items;
}
@@ -992,8 +1033,8 @@ function handleInput(window: TerminalWindow, event: InputEvent, frameId: number)
.then(() => renderAndSubmit(window, frameId));
return;
}
- if (event.type === "long-press") {
- windowMenu(window).open(windowMenuItems(window));
+ if (event.type === "short-then-long-press") {
+ windowMenu(window).open();
renderAndSubmit(window, frameId);
return;
}
@@ -1426,8 +1467,7 @@ function openViewWindow(control: ControlConnection, socket: string, label: strin
icon: "terminal",
iconGlyph: glyph || undefined,
focus: true,
- // Terminal views are the one full-height window kind: more rows matter
- // more than a small on-screen footprint.
+ // Default to tall sessions; the app display setting can override this.
heightMode: "max",
});
}
@@ -1451,10 +1491,7 @@ async function launchAndOpenView(control: ControlConnection, preset: string): Pr
}
function paint(window: TerminalWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- return singlePlane(paintContent(window));
+ return windowMenu(window).paint();
}
function paintContent(window: TerminalWindow): GrayImage {
diff --git a/app/apps/terminal/terminal-emulator.ts b/app/apps/terminal/terminal-emulator.ts
index c4610b96..914ff50f 100644
--- a/app/apps/terminal/terminal-emulator.ts
+++ b/app/apps/terminal/terminal-emulator.ts
@@ -53,6 +53,10 @@ export class TerminalEmulator {
this.term.write(data, onProcessed);
}
+ dispose(): void {
+ this.term.dispose();
+ }
+
/** Full reset; snapshots are defined as repainting from a cleared screen. */
reset(): void {
this.term.reset();
diff --git a/app/apps/timer/index.ts b/app/apps/timer/index.ts
index a2cf51b8..a2073eb6 100644
--- a/app/apps/timer/index.ts
+++ b/app/apps/timer/index.ts
@@ -1,17 +1,42 @@
-import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
+import { type AppDefinition } from "../app-definition";
+import { shell } from "../../ui/shell/shell";
+import { registerTimerTools } from "../../assistant/timer-tools";
+import { timerEngine, timersWakeSetting } from "./timer-engine";
+import { createTimerAppWindow, startTimersTrayIcon, TIMER_SURFACE_ID, TIMER_WINDOW_ID } from "./timer-app";
+/**
+ * Timers, stopwatch and alarms. The clock engine boots with the shell so
+ * timers and alarms fire (and the assistant's timer.* / alarm.* tools work)
+ * with no window open; launching only opens the view on it.
+ */
const timerApp: AppDefinition = {
appId: "timer",
- title: "Timer",
+ title: "Timers",
icon: "timer",
- launch: (ctx) =>
- launchWorkerAppWindow(ctx, {
- createWorker: () => new Worker("./timer-app.worker"),
- windowId: "timer:main",
- title: "Timer",
- iconLetter: "T",
- icon: "timer",
- }),
+ boot: (ctx) => {
+ timerEngine.boot({
+ playBuzzer: (payload) => ctx.actions.playBuzzerSequence(payload),
+ onRing: (item) => {
+ // Bring the ringing item on screen: focus the Timers window, then
+ // wake the display if it is off (a setting, since a wearer may
+ // prefer the phone alone while the glasses sleep). Only once it is
+ // actually showing does the phone start its acknowledgement clock;
+ // otherwise the phone adds its own sound within seconds.
+ void ctx
+ .launchApp("timer")
+ .then(() => {
+ if (timersWakeSetting.get() && !shell.isScreenOn()) shell.wake("window");
+ if (shell.isScreenOn() && shell.foregroundWindow()?.windowId === TIMER_WINDOW_ID) {
+ timerEngine.markDeliveredToGlasses(item);
+ }
+ })
+ .catch((error) => console.error(`timers ring launch failed: ${error}`));
+ },
+ });
+ startTimersTrayIcon();
+ registerTimerTools((appId) => ctx.launchApp(appId));
+ },
+ launch: (ctx) => ctx.launchInProcessApp(TIMER_WINDOW_ID, TIMER_SURFACE_ID, createTimerAppWindow),
};
export default timerApp;
diff --git a/app/apps/timer/timer-app.ts b/app/apps/timer/timer-app.ts
new file mode 100644
index 00000000..0555aecf
--- /dev/null
+++ b/app/apps/timer/timer-app.ts
@@ -0,0 +1,1370 @@
+/**
+ * The Timers app window: one screen for countdown timers, the stopwatch and
+ * alarms. See notes/timers-app-design.md for the design.
+ *
+ * Layout is stage + list. The right ~40% is a list of rows under three
+ * section headers (TIMERS / STOPWATCH / ALARMS); the selected row is shown
+ * large on the left stage. Scroll moves the selection, click does the
+ * obvious thing for the selected row (pause, resume, start, stop, toggle,
+ * dismiss), tap-then-hold opens the row's context menu, double-click leaves
+ * the app. Pickers (the duration dial, the fine-tune fields, the alarm time
+ * fields) and a ringing item's buttons are transient states of the same
+ * screen and double-click cancels them.
+ *
+ * All state lives in the engine (timer-engine.ts); this file only paints it
+ * and turns gestures into engine calls.
+ */
+import { GrayImage, type UiFont } from "../../graphics/image";
+import { getFont } from "../../graphics/bdffont";
+import { ensurePreinstalledFonts, installedFontPath } from "../../graphics/installed-fonts";
+import { truncateText } from "../../graphics/textwrap";
+import { TtfFont } from "../../graphics/ttf-font";
+import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { timeFormatSetting } from "../../ui/dashboard-settings";
+import {
+ GESTURE_CLICK,
+ GESTURE_DOUBLE_CLICK,
+ GESTURE_SCROLL,
+ GESTURE_SHORT_THEN_LONG_PRESS,
+ gestureHints,
+ type InputEvent,
+} from "../../ui/gestures";
+import { type Layer, type LayerContext } from "../../ui/layers";
+import {
+ drawListScrollbar,
+ drawRightValueMenuItem,
+ drawSelectionHighlight,
+ drawToggleMenuItem,
+ scrollToKeepSelectionVisible,
+ TextPageLayer,
+ type MenuItem,
+} from "../../ui/menu";
+import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
+import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
+import { shell } from "../../ui/shell/shell";
+import { WindowMenuLayer } from "../../ui/window-menu";
+import { clamp } from "../../util/numeric-util";
+import {
+ soonestRunningTimerRemainingMs,
+ timerEngine,
+ timersSnoozeSetting,
+ timersSoundSetting,
+ timersWakeSetting,
+ type RingingItem,
+ type SnoozeMinutes,
+} from "./timer-engine";
+import {
+ alarmNextRingMs,
+ DAY_BITS,
+ DAY_FULL_NAMES,
+ DAY_LETTERS,
+ DEFAULT_TIMER_DURATION_MS,
+ DURATION_LADDER_MS,
+ EVERY_DAY_MASK,
+ formatClockAt,
+ formatCountdown,
+ formatDays,
+ formatDurationWords,
+ formatElapsed,
+ formatSpanWords,
+ formatTimeOfDay,
+ nearestLadderIndex,
+ sortAlarms,
+ sortTimers,
+ stopwatchElapsedMs,
+ stopwatchIsRunning,
+ timerDisplayName,
+ timerPhase,
+ timerRemainingMs,
+ timerProgress,
+ WEEKDAYS_MASK,
+ WEEKEND_MASK,
+ type Alarm,
+ type CountdownTimer,
+} from "./timer-model";
+
+export const TIMER_WINDOW_ID = "timer";
+export const TIMER_SURFACE_ID = "window:timer";
+
+/** Width of the list column, as a share of the viewport, and its bounds. */
+const LIST_SHARE = 0.4;
+const LIST_MIN_WIDTH = 190;
+const LIST_MAX_WIDTH = 240;
+const LIST_TOP = 6;
+const STAGE_X = 10;
+/** Gap between the stage's right edge and the list's divider. */
+const STAGE_LIST_GAP = 14;
+/** Brightness factor for the list while a picker owns the stage. */
+const LIST_DIM = 0.4;
+/** Big-digit sizes tried largest first until the text fits the stage. */
+const DIGIT_SIZES = [96, 80, 64, 52, 40];
+/** Field digits in the pickers. */
+const FIELD_DIGIT_SIZE = 56;
+const MINUTE_MS = 60_000;
+
+type RowKind = "header" | "timer" | "new-timer" | "stopwatch" | "alarm" | "new-alarm";
+
+type Row = {
+ key: string;
+ kind: RowKind;
+ title?: string;
+ timer?: CountdownTimer;
+ alarm?: Alarm;
+};
+
+/**
+ * Screen state beyond the selection. "list" is the resting state; the rest
+ * are pickers that own the stage and the scroll wheel until they finish or
+ * a double-click cancels them.
+ */
+type Mode =
+ | { kind: "list" }
+ | { kind: "dial"; index: number; label: string }
+ | { kind: "fine"; hours: number; minutes: number; seconds: number; field: number; label: string }
+ | { kind: "alarm-time"; alarmId: number | null; hour: number; minute: number; field: number };
+
+type LabelTarget = { kind: "timer" | "alarm"; id: number } | { kind: "new-timer" };
+
+function timerKey(timer: CountdownTimer): string {
+ return `timer:${timer.id}`;
+}
+
+function alarmKey(alarm: Alarm): string {
+ return `alarm:${alarm.id}`;
+}
+
+function ringingKey(item: RingingItem): string {
+ return item.kind === "timer" ? timerKey(item.timer) : alarmKey(item.alarm);
+}
+
+function twelveHour(): boolean {
+ return timeFormatSetting.get() === "12h";
+}
+
+function smallFont(): UiFont {
+ return getDefaultSmallFont();
+}
+
+function mediumFont(): UiFont {
+ return getDefaultMediumFont();
+}
+
+// ---------------------------------------------------------------------------
+// Big digits
+
+let digitFontsEnsured = false;
+
+/** The bundled Roboto Bold at a pixel size, or the largest bitmap face off-Android. */
+function digitFont(sizePx: number): UiFont {
+ if (!digitFontsEnsured) {
+ digitFontsEnsured = true;
+ try {
+ ensurePreinstalledFonts();
+ } catch (error) {
+ console.warn(`timers digit font preinstall failed: ${error}`);
+ }
+ }
+ return TtfFont.load(installedFontPath("Roboto-Bold.ttf"), sizePx) ?? getFont("terminus32");
+}
+
+/** The biggest digit font whose rendering of `text` fits `maxWidth`. */
+function fittingDigitFont(text: string, maxWidth: number, sizes: readonly number[] = DIGIT_SIZES): UiFont {
+ let font = digitFont(sizes[0]!);
+ for (const size of sizes) {
+ font = digitFont(size);
+ if (font.measureText(text) <= maxWidth) return font;
+ }
+ return font;
+}
+
+// ---------------------------------------------------------------------------
+// The layer
+
+export class TimersLayer implements Layer {
+ readonly acceptsDirectional = true;
+
+ private selectionKey = "";
+ private scrollRow = 0;
+ private mode: Mode = { kind: "list" };
+ /** Which of the ringing stage's two buttons is highlighted. */
+ private ringButton = 0;
+ /** Where the next text input (a label) goes; null means the selected item. */
+ private labelTarget: LabelTarget | null = null;
+ /** Ringing items already jumped to, so a second ring doesn't re-pin. */
+ private seenRinging = new Set();
+ /** Set the first time this layer paints, to land the selection sensibly. */
+ private initialised = false;
+ /** Feedback shown on the stage after a picker refuses (e.g. zero duration). */
+ private notice = "";
+
+ // -------------------------------------------------------------------------
+ // Rows
+
+ private buildRows(now: number): Row[] {
+ const state = timerEngine.state;
+ const rows: Row[] = [{ key: "h:timers", kind: "header", title: "TIMERS" }];
+ for (const timer of sortTimers(state.timers, now)) rows.push({ key: timerKey(timer), kind: "timer", timer });
+ rows.push({ key: "new-timer", kind: "new-timer" });
+ rows.push({ key: "h:stopwatch", kind: "header", title: "STOPWATCH" }, { key: "stopwatch", kind: "stopwatch" });
+ rows.push({ key: "h:alarms", kind: "header", title: "ALARMS" });
+ for (const alarm of sortAlarms(state.alarms)) rows.push({ key: alarmKey(alarm), kind: "alarm", alarm });
+ rows.push({ key: "new-alarm", kind: "new-alarm" });
+ return rows;
+ }
+
+ /** The most urgent row: ringing, then a running timer, a running stopwatch, else New timer. */
+ private defaultSelection(rows: Row[]): string {
+ const ringing = timerEngine.ringingItems()[0];
+ if (ringing) return ringingKey(ringing);
+ const running = rows.find((row) => row.timer && timerPhase(row.timer) === "running");
+ if (running) return running.key;
+ if (stopwatchIsRunning(timerEngine.state.stopwatch)) return "stopwatch";
+ return "new-timer";
+ }
+
+ /** Keep the selection on a real, selectable row after the rows change. */
+ private reconcileSelection(rows: Row[]): number {
+ if (!this.initialised) {
+ this.initialised = true;
+ this.selectionKey = this.defaultSelection(rows);
+ for (const item of timerEngine.ringingItems()) this.seenRinging.add(ringingKey(item));
+ }
+ let index = rows.findIndex((row) => row.key === this.selectionKey);
+ if (index < 0) {
+ // The row went away (a dismissed timer, a deleted alarm): stay in place.
+ index = clamp(this.scrollRow, 0, rows.length - 1);
+ while (index < rows.length && rows[index]!.kind === "header") index++;
+ if (index >= rows.length) index = rows.findIndex((row) => row.kind !== "header");
+ this.selectionKey = rows[index]!.key;
+ }
+ return index;
+ }
+
+ private selectedRow(rows: Row[]): Row {
+ return rows[this.reconcileSelection(rows)]!;
+ }
+
+ private moveSelection(rows: Row[], delta: number): void {
+ const count = rows.length;
+ let index = this.reconcileSelection(rows);
+ for (let step = 0; step < count; step++) {
+ index = (index + delta + count) % count;
+ if (rows[index]!.kind !== "header") break;
+ }
+ this.selectionKey = rows[index]!.key;
+ }
+
+ /** Called on every engine change: jump to a newly ringing item. */
+ onEngineChanged(): void {
+ const ringing = timerEngine.ringingItems();
+ const keys = new Set(ringing.map(ringingKey));
+ for (const key of Array.from(this.seenRinging)) {
+ if (!keys.has(key)) this.seenRinging.delete(key);
+ }
+ for (const item of ringing) {
+ const key = ringingKey(item);
+ if (this.seenRinging.has(key)) continue;
+ this.seenRinging.add(key);
+ this.selectionKey = key;
+ this.ringButton = 0;
+ this.mode = { kind: "list" };
+ this.notice = "";
+ }
+ }
+
+ private ringingOf(row: Row): RingingItem | null {
+ if (row.timer && row.timer.rungAtMs !== null) return { kind: "timer", timer: row.timer };
+ if (row.alarm && row.alarm.ringingSinceMs !== null) return { kind: "alarm", alarm: row.alarm };
+ return null;
+ }
+
+ // -------------------------------------------------------------------------
+ // Input
+
+ async handleInput(event: InputEvent, _ctx: LayerContext): Promise {
+ timerEngine.check();
+ const now = Date.now();
+ const rows = this.buildRows(now);
+ switch (this.mode.kind) {
+ case "dial":
+ this.handleDialInput(event, this.mode);
+ return;
+ case "fine":
+ this.handleFineInput(event, this.mode);
+ return;
+ case "alarm-time":
+ this.handleAlarmTimeInput(event, this.mode);
+ return;
+ default:
+ this.handleListInput(event, rows);
+ }
+ }
+
+ private handleListInput(event: InputEvent, rows: Row[]): void {
+ const row = this.selectedRow(rows);
+ const ringing = this.ringingOf(row);
+ switch (event.type) {
+ case "scroll-up":
+ case "swipe-up":
+ if (ringing) this.ringButton = 0;
+ else this.moveSelection(rows, -1);
+ return;
+ case "scroll-down":
+ case "swipe-down":
+ if (ringing) this.ringButton = 1;
+ else this.moveSelection(rows, 1);
+ return;
+ case "swipe-left":
+ if (ringing) this.ringButton = 0;
+ else shell.yieldFocusToSidebar();
+ return;
+ case "swipe-right":
+ if (ringing) this.ringButton = 1;
+ else this.activateRow(row);
+ return;
+ case "click":
+ this.activateRow(row);
+ return;
+ case "double-click":
+ shell.yieldFocusToSidebar();
+ return;
+ default:
+ return;
+ }
+ }
+
+ /** Click on a row: its primary action. */
+ private activateRow(row: Row): void {
+ this.notice = "";
+ switch (row.kind) {
+ case "timer": {
+ const timer = row.timer!;
+ switch (timerPhase(timer)) {
+ case "running":
+ timerEngine.pauseTimer(timer.id);
+ return;
+ case "paused":
+ timerEngine.resumeTimer(timer.id);
+ return;
+ case "rung":
+ if (this.ringButton === 0) timerEngine.removeTimer(timer.id);
+ else timerEngine.restartTimer(timer.id);
+ return;
+ }
+ }
+ case "new-timer":
+ this.openDial("");
+ return;
+ case "stopwatch":
+ timerEngine.stopwatchToggle();
+ return;
+ case "alarm": {
+ const alarm = row.alarm!;
+ if (alarm.ringingSinceMs !== null) {
+ if (this.ringButton === 0) timerEngine.dismissAlarm(alarm.id);
+ else timerEngine.snoozeAlarm(alarm.id);
+ return;
+ }
+ timerEngine.setAlarmEnabled(alarm.id, !alarm.enabled);
+ return;
+ }
+ case "new-alarm":
+ this.openAlarmTime(null);
+ return;
+ default:
+ return;
+ }
+ }
+
+ private openDial(label: string): void {
+ const last = timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS;
+ this.mode = { kind: "dial", index: nearestLadderIndex(last), label };
+ }
+
+ private openFine(label: string, durationMs: number): void {
+ const totalSeconds = Math.round(durationMs / 1000);
+ this.mode = {
+ kind: "fine",
+ hours: Math.min(23, Math.floor(totalSeconds / 3600)),
+ minutes: Math.floor(totalSeconds / 60) % 60,
+ seconds: totalSeconds % 60,
+ field: 0,
+ label,
+ };
+ }
+
+ private openAlarmTime(alarm: Alarm | null): void {
+ this.mode = {
+ kind: "alarm-time",
+ alarmId: alarm?.id ?? null,
+ hour: alarm?.hour ?? 7,
+ minute: alarm?.minute ?? 0,
+ field: 0,
+ };
+ }
+
+ private startTimer(durationMs: number, label: string): void {
+ const timer = timerEngine.startTimer(durationMs, label);
+ this.selectionKey = timerKey(timer);
+ this.mode = { kind: "list" };
+ this.notice = "";
+ }
+
+ private handleDialInput(event: InputEvent, mode: Extract): void {
+ switch (event.type) {
+ case "scroll-up":
+ case "swipe-up":
+ mode.index = Math.min(DURATION_LADDER_MS.length - 1, mode.index + 1);
+ return;
+ case "scroll-down":
+ case "swipe-down":
+ mode.index = Math.max(0, mode.index - 1);
+ return;
+ case "click":
+ case "swipe-right":
+ this.startTimer(DURATION_LADDER_MS[mode.index]!, mode.label);
+ return;
+ case "double-click":
+ case "swipe-left":
+ this.mode = { kind: "list" };
+ return;
+ default:
+ return;
+ }
+ }
+
+ private handleFineInput(event: InputEvent, mode: Extract): void {
+ const adjust = (delta: number) => {
+ if (mode.field === 0) mode.hours = (mode.hours + delta + 24) % 24;
+ else if (mode.field === 1) mode.minutes = (mode.minutes + delta + 60) % 60;
+ else mode.seconds = (mode.seconds + delta + 60) % 60;
+ this.notice = "";
+ };
+ switch (event.type) {
+ case "scroll-up":
+ case "swipe-up":
+ adjust(1);
+ return;
+ case "scroll-down":
+ case "swipe-down":
+ adjust(-1);
+ return;
+ case "swipe-right":
+ mode.field = Math.min(2, mode.field + 1);
+ return;
+ case "swipe-left":
+ mode.field = Math.max(0, mode.field - 1);
+ return;
+ case "click": {
+ if (mode.field < 2) {
+ mode.field++;
+ return;
+ }
+ const durationMs = ((mode.hours * 60 + mode.minutes) * 60 + mode.seconds) * 1000;
+ if (durationMs <= 0) {
+ this.notice = "Choose a duration longer than zero";
+ mode.field = 0;
+ return;
+ }
+ this.startTimer(durationMs, mode.label);
+ return;
+ }
+ case "double-click":
+ if (mode.field > 0) mode.field--;
+ else this.mode = { kind: "list" };
+ return;
+ default:
+ return;
+ }
+ }
+
+ /** Field count of the alarm time picker: hour, minute tens, minute ones, and AM/PM in 12-hour mode. */
+ private alarmFieldCount(): number {
+ return twelveHour() ? 4 : 3;
+ }
+
+ private handleAlarmTimeInput(event: InputEvent, mode: Extract): void {
+ const fields = this.alarmFieldCount();
+ const adjust = (delta: number) => {
+ const tens = Math.floor(mode.minute / 10);
+ const ones = mode.minute % 10;
+ if (mode.field === 0) {
+ if (twelveHour()) {
+ // Step within the current half of the day (1..12 wraps without flipping AM/PM).
+ const pm = mode.hour >= 12;
+ const hour12 = ((mode.hour + 11) % 12) + 1;
+ const next = ((hour12 - 1 + delta + 12) % 12) + 1;
+ mode.hour = (next % 12) + (pm ? 12 : 0);
+ } else {
+ mode.hour = (mode.hour + delta + 24) % 24;
+ }
+ } else if (mode.field === 1) {
+ mode.minute = ((tens + delta + 6) % 6) * 10 + ones;
+ } else if (mode.field === 2) {
+ mode.minute = tens * 10 + ((ones + delta + 10) % 10);
+ } else {
+ mode.hour = (mode.hour + 12) % 24;
+ }
+ };
+ switch (event.type) {
+ case "scroll-up":
+ case "swipe-up":
+ adjust(1);
+ return;
+ case "scroll-down":
+ case "swipe-down":
+ adjust(-1);
+ return;
+ case "swipe-right":
+ mode.field = Math.min(fields - 1, mode.field + 1);
+ return;
+ case "swipe-left":
+ mode.field = Math.max(0, mode.field - 1);
+ return;
+ case "click": {
+ if (mode.field < fields - 1) {
+ mode.field++;
+ return;
+ }
+ if (mode.alarmId === null) {
+ const alarm = timerEngine.addAlarm(mode.hour, mode.minute, 0, "");
+ this.selectionKey = alarmKey(alarm);
+ } else {
+ timerEngine.setAlarmTime(mode.alarmId, mode.hour, mode.minute);
+ }
+ this.mode = { kind: "list" };
+ return;
+ }
+ case "double-click":
+ if (mode.field > 0) mode.field--;
+ else this.mode = { kind: "list" };
+ return;
+ default:
+ return;
+ }
+ }
+
+ /** A mirror touch: on the list, select the row under it. */
+ hitTest(x: number, y: number, ctx: LayerContext): boolean {
+ if (this.mode.kind !== "list") return false;
+ const { width, height } = ctx.stack.getBaseSize();
+ const listX = width - listWidthFor(width);
+ if (x < listX) return false;
+ const rows = this.buildRows(Date.now());
+ this.reconcileSelection(rows);
+ const rowHeight = listRowHeight(smallFont());
+ const index = this.scrollRow + Math.floor((y - LIST_TOP) / rowHeight);
+ const row = rows[index];
+ if (!row || row.kind === "header" || y < LIST_TOP || y > height) return true;
+ if (this.selectionKey === row.key) {
+ this.activateRow(row);
+ } else {
+ this.selectionKey = row.key;
+ this.ringButton = 0;
+ }
+ return true;
+ }
+
+ // -------------------------------------------------------------------------
+ // Text input (labels)
+
+ receiveTextInput(text: string): void {
+ const label = text.trim();
+ const target = this.labelTarget;
+ this.labelTarget = null;
+ if (target?.kind === "new-timer" || (!target && (this.mode.kind === "dial" || this.mode.kind === "fine"))) {
+ if (this.mode.kind === "dial" || this.mode.kind === "fine") this.mode.label = label;
+ return;
+ }
+ if (target?.kind === "timer") {
+ timerEngine.setTimerLabel(target.id, label);
+ return;
+ }
+ if (target?.kind === "alarm") {
+ timerEngine.setAlarmLabel(target.id, label);
+ return;
+ }
+ const row = this.selectedRow(this.buildRows(Date.now()));
+ if (row.timer) timerEngine.setTimerLabel(row.timer.id, label);
+ else if (row.alarm) timerEngine.setAlarmLabel(row.alarm.id, label);
+ }
+
+ /** Aim the shell's text-entry dialog at a label, then open it. */
+ private askForLabel(target: LabelTarget): void {
+ this.labelTarget = target;
+ shell.startVoiceInput();
+ }
+
+ // -------------------------------------------------------------------------
+ // Context menus
+
+ menuItems(): MenuItem[] {
+ if (this.mode.kind === "alarm-time") return [];
+ if (this.mode.kind === "dial" || this.mode.kind === "fine") return this.pickerMenuItems(this.mode);
+ const now = Date.now();
+ const row = this.selectedRow(this.buildRows(now));
+ const items: MenuItem[] = [];
+ switch (row.kind) {
+ case "timer":
+ items.push(...this.timerMenuItems(row.timer!));
+ break;
+ case "new-timer":
+ for (const durationMs of timerEngine.state.recentDurationsMs) {
+ items.push({
+ label: `Start ${formatDurationWords(durationMs)}`,
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.startTimer(durationMs, "");
+ },
+ });
+ }
+ items.push({
+ label: "Fine-tune a duration",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.openFine("", timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS);
+ },
+ });
+ break;
+ case "stopwatch":
+ items.push(...this.stopwatchMenuItems());
+ break;
+ case "alarm":
+ items.push(...this.alarmMenuItems(row.alarm!));
+ break;
+ default:
+ break;
+ }
+ items.push({
+ label: "Settings",
+ onSelect: (ctx) => ctx.stack.push(new WindowMenuLayer("Timers settings", this.settingsMenuItems())),
+ });
+ return items;
+ }
+
+ private pickerMenuItems(mode: Extract): MenuItem[] {
+ const items: MenuItem[] = [];
+ if (mode.kind === "dial") {
+ items.push({
+ label: "Fine-tune (h:mm:ss)",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.openFine(mode.label, DURATION_LADDER_MS[mode.index]!);
+ },
+ });
+ }
+ items.push({
+ label: mode.label ? `Label: ${mode.label}` : "Set a label",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.askForLabel({ kind: "new-timer" });
+ },
+ });
+ items.push({
+ label: "Cancel",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.mode = { kind: "list" };
+ },
+ });
+ return items;
+ }
+
+ private timerMenuItems(timer: CountdownTimer): MenuItem[] {
+ const phase = timerPhase(timer);
+ const items: MenuItem[] = [];
+ if (phase === "rung") {
+ items.push(
+ { label: "Dismiss", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.removeTimer(timer.id); } },
+ { label: "Again", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.restartTimer(timer.id); } },
+ );
+ }
+ items.push({
+ label: "+1 minute",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ timerEngine.addTimerTime(timer.id, MINUTE_MS);
+ },
+ });
+ if (phase === "running") {
+ items.push({ label: "Pause", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.pauseTimer(timer.id); } });
+ } else if (phase === "paused") {
+ items.push({ label: "Resume", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.resumeTimer(timer.id); } });
+ }
+ if (phase !== "rung") {
+ items.push({ label: "Restart", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.restartTimer(timer.id); } });
+ }
+ items.push({
+ label: timer.label ? `Label: ${timer.label}` : "Set a label",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.askForLabel({ kind: "timer", id: timer.id });
+ },
+ });
+ if (phase !== "rung") {
+ items.push({ label: "Delete", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.removeTimer(timer.id); } });
+ }
+ return items;
+ }
+
+ private stopwatchMenuItems(): MenuItem[] {
+ const stopwatch = timerEngine.state.stopwatch;
+ const running = stopwatchIsRunning(stopwatch);
+ const items: MenuItem[] = [];
+ if (running) {
+ items.push({ label: "Lap", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.stopwatchLap(); } });
+ }
+ items.push({
+ label: running ? "Stop" : "Start",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ timerEngine.stopwatchToggle();
+ },
+ });
+ items.push({
+ label: "Reset",
+ disabled: () => stopwatchElapsedMs(timerEngine.state.stopwatch, Date.now()) === 0,
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ timerEngine.stopwatchReset();
+ },
+ });
+ return items;
+ }
+
+ private alarmMenuItems(alarm: Alarm): MenuItem[] {
+ const items: MenuItem[] = [];
+ if (alarm.ringingSinceMs !== null) {
+ items.push(
+ { label: "Dismiss", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.dismissAlarm(alarm.id); } },
+ {
+ label: `Snooze ${timersSnoozeSetting.get()} min`,
+ onSelect: (ctx) => { ctx.stack.pop(); timerEngine.snoozeAlarm(alarm.id); },
+ },
+ );
+ } else {
+ items.push({
+ label: alarm.enabled ? "Turn off" : "Turn on",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ timerEngine.setAlarmEnabled(alarm.id, !alarm.enabled);
+ },
+ });
+ }
+ items.push({
+ label: "Change time",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.openAlarmTime(alarm);
+ },
+ });
+ items.push({
+ label: `Repeat: ${formatDays(alarm.days)}`,
+ onSelect: (ctx) => ctx.stack.push(new WindowMenuLayer("Repeat", this.repeatMenuItems(alarm.id))),
+ });
+ items.push({
+ label: alarm.label ? `Label: ${alarm.label}` : "Set a label",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ this.askForLabel({ kind: "alarm", id: alarm.id });
+ },
+ });
+ items.push({ label: "Delete", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.deleteAlarm(alarm.id); } });
+ return items;
+ }
+
+ /** Repeat presets, then one toggle per weekday; the menu stays open while toggling. */
+ private repeatMenuItems(alarmId: number): MenuItem[] {
+ const days = () => timerEngine.findAlarm(alarmId)?.days ?? 0;
+ const preset = (label: string, mask: number): MenuItem => ({
+ label,
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ timerEngine.setAlarmDays(alarmId, mask);
+ },
+ });
+ const items: MenuItem[] = [
+ preset("Once", 0),
+ preset("Weekdays", WEEKDAYS_MASK),
+ preset("Weekends", WEEKEND_MASK),
+ preset("Every day", EVERY_DAY_MASK),
+ ];
+ for (let index = 0; index < 7; index++) {
+ const bit = DAY_BITS[index]!;
+ items.push({
+ label: DAY_FULL_NAMES[index]!,
+ onSelect: () => timerEngine.setAlarmDays(alarmId, days() ^ bit),
+ render: (args) =>
+ drawToggleMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, (days() & bit) !== 0, args.selected),
+ });
+ }
+ return items;
+ }
+
+ private settingsMenuItems(): MenuItem[] {
+ const toggle = (label: string, get: () => boolean, set: (value: boolean) => void): MenuItem => ({
+ label,
+ onSelect: () => set(!get()),
+ render: (args) => drawToggleMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, get(), args.selected),
+ });
+ return [
+ toggle(timersSoundSetting.label, () => timersSoundSetting.get(), (value) => timersSoundSetting.set(value)),
+ toggle(timersWakeSetting.label, () => timersWakeSetting.get(), (value) => timersWakeSetting.set(value)),
+ {
+ label: timersSnoozeSetting.label,
+ onSelect: () => {
+ const values = timersSnoozeSetting.values;
+ const next = values[(values.indexOf(timersSnoozeSetting.get()) + 1) % values.length] as SnoozeMinutes;
+ timersSnoozeSetting.set(next);
+ },
+ render: (args) =>
+ drawRightValueMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, timersSnoozeSetting.displayValue()),
+ },
+ toggle("12-hour clock", () => twelveHour(), (value) => timeFormatSetting.set(value ? "12h" : "24h")),
+ {
+ label: "Phone alarm check",
+ onSelect: (ctx) => {
+ timerEngine.refreshReliability(true);
+ const issues = timerEngine.phoneReliabilityIssues();
+ const body =
+ issues.length === 0
+ ? "No problems found: the phone can ring for alarms when the glasses cannot."
+ : issues.map((issue) => `- ${issue.message}`).join("\n") +
+ "\n\nFix these from the warning triangle on the phone's home screen.";
+ ctx.stack.push(new TextPageLayer("Phone alarm check", body));
+ },
+ },
+ ];
+ }
+
+ // -------------------------------------------------------------------------
+ // Painting
+
+ paint(ctx: LayerContext): GrayImage {
+ timerEngine.check();
+ const now = Date.now();
+ const { width, height } = ctx.stack.getBaseSize();
+ const image = new GrayImage(width, height, 0);
+ const rows = this.buildRows(now);
+ const selectedIndex = this.reconcileSelection(rows);
+ const listWidth = listWidthFor(width);
+ const listX = width - listWidth;
+ const picking = this.mode.kind !== "list";
+
+ this.paintList(image, rows, selectedIndex, listX, listWidth, height, ctx.stack.isFocused(), picking ? LIST_DIM : 1, now);
+ image.drawLine(listX - 7, 8, listX - 7, height - 8, picking ? 20 : 40);
+
+ const stage = { x: STAGE_X, y: 0, width: listX - 7 - STAGE_LIST_GAP - STAGE_X, height };
+ switch (this.mode.kind) {
+ case "dial":
+ this.paintDial(image, stage, this.mode, now);
+ break;
+ case "fine":
+ this.paintFine(image, stage, this.mode);
+ break;
+ case "alarm-time":
+ this.paintAlarmTime(image, stage, this.mode, now);
+ break;
+ default:
+ this.paintStage(image, stage, rows[selectedIndex]!, now, ctx.stack.isFocused());
+ }
+ return image;
+ }
+
+ private paintList(
+ image: GrayImage,
+ rows: Row[],
+ selectedIndex: number,
+ listX: number,
+ listWidth: number,
+ height: number,
+ focused: boolean,
+ dim: number,
+ now: number,
+ ): void {
+ const font = smallFont();
+ const rowHeight = listRowHeight(font);
+ const visible = Math.max(1, Math.floor((height - 2 * LIST_TOP) / rowHeight));
+ this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, selectedIndex, visible, rows.length);
+ const shade = (value: number) => Math.round(value * dim);
+ const textX = listX + 8;
+ const textWidth = listWidth - 24;
+ const last = Math.min(rows.length, this.scrollRow + visible);
+ for (let index = this.scrollRow; index < last; index++) {
+ const row = rows[index]!;
+ const y = LIST_TOP + (index - this.scrollRow) * rowHeight;
+ const textY = y + LIST_ROW_TEXT_INSET;
+ if (row.kind === "header") {
+ image.drawText(font, textX, textY, row.title!, shade(90));
+ continue;
+ }
+ const selected = index === selectedIndex;
+ if (selected && dim === 1) {
+ drawSelectionHighlight(image, listX, y, listWidth - 12, rowHeight - 1, focused, 6);
+ }
+ const bright = shade(selected ? 250 : 210);
+ const soft = shade(selected ? 170 : 130);
+ switch (row.kind) {
+ case "timer": {
+ const timer = row.timer!;
+ const phase = timerPhase(timer);
+ const digits = phase === "rung" ? "0:00" : formatCountdown(timerRemainingMs(timer, now));
+ const digitsValue = phase === "rung" ? (Math.floor(now / 1000) % 2 ? bright : soft) : phase === "paused" ? soft : bright;
+ image.drawText(font, textX, textY, digits, digitsValue);
+ const digitsWidth = font.measureText(digits) + 8;
+ const nameWidth = textWidth - digitsWidth - (phase === "paused" ? 12 : 0);
+ if (nameWidth > 12) {
+ image.drawText(font, textX + digitsWidth, textY, truncateText(font, timerDisplayName(timer), nameWidth), soft);
+ }
+ if (phase === "paused") drawPauseMark(image, listX + listWidth - 22, y + Math.floor(rowHeight / 2) - 5, soft);
+ break;
+ }
+ case "new-timer":
+ image.drawText(font, textX, textY, "+ New timer", shade(selected ? 220 : 150));
+ break;
+ case "stopwatch": {
+ const stopwatch = timerEngine.state.stopwatch;
+ const running = stopwatchIsRunning(stopwatch);
+ const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, now), false);
+ image.drawText(font, textX, textY, "Stopwatch", running ? bright : soft);
+ image.drawText(font, listX + listWidth - 16 - font.measureText(elapsed), textY, elapsed, running ? bright : soft);
+ break;
+ }
+ case "alarm": {
+ const alarm = row.alarm!;
+ const on = alarm.enabled;
+ const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour());
+ image.drawText(font, textX, textY, time, on ? bright : soft);
+ const timeWidth = font.measureText(time) + 8;
+ const daysWidth = textWidth - timeWidth - 14;
+ if (daysWidth > 12) {
+ image.drawText(font, textX + timeWidth, textY, truncateText(font, alarm.label || formatDays(alarm.days), daysWidth), on ? soft : shade(80));
+ }
+ const dotX = listX + listWidth - 22;
+ const dotY = y + Math.floor(rowHeight / 2) - 4;
+ if (alarm.ringingSinceMs !== null || on) image.fillRoundedRect(dotX, dotY, 8, 8, on ? shade(220) : shade(90), 4);
+ else image.drawRoundedRect(dotX, dotY, 8, 8, shade(90), 4);
+ break;
+ }
+ case "new-alarm":
+ image.drawText(font, textX, textY, "+ New alarm", shade(selected ? 220 : 150));
+ break;
+ default:
+ break;
+ }
+ }
+ if (rows.length > visible) {
+ drawListScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4, this.scrollRow, visible, rows.length);
+ }
+ }
+
+ private paintStage(image: GrayImage, stage: StageRect, row: Row, now: number, focused: boolean): void {
+ switch (row.kind) {
+ case "timer":
+ this.paintTimerStage(image, stage, row.timer!, now, focused);
+ return;
+ case "new-timer": {
+ const last = timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS;
+ const block = new StageBlock(stage);
+ block.title(image, "New timer", 200);
+ block.digits(image, formatCountdown(last), 110);
+ block.line(image, `${formatDurationWords(last)} last time`, 120);
+ block.hints(image, [[GESTURE_CLICK, "choose duration"], [GESTURE_SHORT_THEN_LONG_PRESS, "recent"]]);
+ return;
+ }
+ case "stopwatch":
+ this.paintStopwatchStage(image, stage, now);
+ return;
+ case "alarm":
+ this.paintAlarmStage(image, stage, row.alarm!, now, focused);
+ return;
+ case "new-alarm": {
+ const block = new StageBlock(stage);
+ block.title(image, "New alarm", 200);
+ block.digits(image, twelveHour() ? "7:00" : "07:00", 110);
+ block.line(image, "Rings once unless you set a repeat", 120);
+ block.hints(image, [[GESTURE_CLICK, "set time"]]);
+ return;
+ }
+ default:
+ return;
+ }
+ }
+
+ private paintTimerStage(image: GrayImage, stage: StageRect, timer: CountdownTimer, now: number, focused: boolean): void {
+ const block = new StageBlock(stage);
+ const phase = timerPhase(timer);
+ if (phase === "rung") {
+ const flash = Math.floor(now / 1000) % 2 === 0;
+ block.title(image, "Time's up", flash ? 255 : 170);
+ block.digits(image, `+${formatCountdown(now - timer.rungAtMs!)}`, 200);
+ block.line(image, `${timerDisplayName(timer)} · rang at ${formatClockAt(timer.rungAtMs!, twelveHour())}`, 150);
+ block.buttons(image, ["Dismiss", "Again"], this.ringButton, focused);
+ block.hints(image, [[GESTURE_SCROLL, "choose"], [GESTURE_CLICK, "select"]]);
+ return;
+ }
+ const remaining = timerRemainingMs(timer, now);
+ block.title(image, phase === "paused" ? `${timerDisplayName(timer)} · Paused` : timerDisplayName(timer), 200);
+ block.digits(image, formatCountdown(remaining), phase === "paused" ? 150 : 250);
+ block.progress(image, timerProgress(timer, now), phase === "paused" ? 120 : 200);
+ const info =
+ phase === "paused"
+ ? `${formatDurationWords(timer.durationMs)} timer · ${formatCountdown(remaining)} left`
+ : `${formatDurationWords(timer.durationMs)} timer · ends ${formatClockAt(timer.endsAtMs!, twelveHour())}`;
+ block.line(image, info, 150);
+ block.hints(image, [[GESTURE_CLICK, phase === "paused" ? "resume" : "pause"], [GESTURE_SHORT_THEN_LONG_PRESS, "options"]]);
+ }
+
+ private paintStopwatchStage(image: GrayImage, stage: StageRect, now: number): void {
+ const stopwatch = timerEngine.state.stopwatch;
+ const running = stopwatchIsRunning(stopwatch);
+ const elapsed = stopwatchElapsedMs(stopwatch, now);
+ const block = new StageBlock(stage);
+ block.title(image, running ? "Stopwatch · Running" : elapsed > 0 ? "Stopwatch · Stopped" : "Stopwatch", 200);
+ // Tenths only while stopped: the display updates once a second while running.
+ block.digits(image, formatElapsed(elapsed, !running), running ? 250 : elapsed > 0 ? 200 : 130);
+ const laps = stopwatch.lapsMs;
+ if (laps.length > 0) {
+ const font = smallFont();
+ const shown = laps.slice(-Math.max(1, Math.min(4, block.linesLeft())));
+ for (let index = 0; index < shown.length; index++) {
+ const lapIndex = laps.length - shown.length + index;
+ const total = shown[index]!;
+ const split = total - (lapIndex > 0 ? laps[lapIndex - 1]! : 0);
+ block.columns(image, font, [`Lap ${lapIndex + 1}`, formatElapsed(split, true), formatElapsed(total, true)], index === shown.length - 1 ? 190 : 130);
+ }
+ } else {
+ block.line(image, running ? "" : "Laps appear here", 110);
+ }
+ block.hints(image, [[GESTURE_CLICK, running ? "stop" : "start"], [GESTURE_SHORT_THEN_LONG_PRESS, running ? "lap" : "reset"]]);
+ }
+
+ private paintAlarmStage(image: GrayImage, stage: StageRect, alarm: Alarm, now: number, focused: boolean): void {
+ const block = new StageBlock(stage);
+ const ringing = alarm.ringingSinceMs !== null;
+ const flash = Math.floor(now / 1000) % 2 === 0;
+ block.title(image, ringing ? (alarm.label ? `Alarm · ${alarm.label}` : "Alarm") : alarm.label || "Alarm", ringing ? (flash ? 255 : 170) : 200);
+ const time = formatTimeOfDay(alarm.hour, alarm.minute, false);
+ const suffix = twelveHour() ? (alarm.hour < 12 ? "AM" : "PM") : "";
+ block.digits(image, twelveHour() ? formatTimeOfDay(alarm.hour, alarm.minute, true).replace(/ [AP]M$/, "") : time, alarm.enabled ? 250 : 130, suffix);
+ block.days(image, alarm.days, alarm.enabled ? 230 : 110);
+ if (ringing) {
+ block.buttons(image, ["Dismiss", `Snooze ${timersSnoozeSetting.get()}m`], this.ringButton, focused);
+ block.hints(image, [[GESTURE_SCROLL, "choose"], [GESTURE_CLICK, "select"]]);
+ return;
+ }
+ let status: string;
+ if (!alarm.enabled) status = "Off";
+ else if (alarm.snoozedUntilMs !== null) status = `Snoozed until ${formatClockAt(alarm.snoozedUntilMs, twelveHour())}`;
+ else {
+ const next = alarmNextRingMs(alarm, now);
+ status = next === null ? "Off" : `Rings in ${formatSpanWords(next - now)}`;
+ }
+ block.line(image, status, 150);
+ const warning = timerEngine.phoneReliabilityIssues()[0];
+ if (alarm.enabled && warning) block.line(image, `Phone: ${warning.message}`, 120);
+ block.hints(image, [[GESTURE_CLICK, alarm.enabled ? "turn off" : "turn on"], [GESTURE_SHORT_THEN_LONG_PRESS, "edit"]]);
+ }
+
+ private paintDial(image: GrayImage, stage: StageRect, mode: Extract, now: number): void {
+ const durationMs = DURATION_LADDER_MS[mode.index]!;
+ const block = new StageBlock(stage);
+ block.title(image, mode.label ? `New timer · ${mode.label}` : "New timer", 200);
+ block.digits(image, formatCountdown(durationMs), 250);
+ block.line(image, `${formatDurationWords(durationMs)} · ends ${formatClockAt(now + durationMs, twelveHour())}`, 150);
+ block.hints(image, [[GESTURE_SCROLL, "duration"], [GESTURE_CLICK, "start"], [GESTURE_DOUBLE_CLICK, "cancel"]]);
+ }
+
+ private paintFine(image: GrayImage, stage: StageRect, mode: Extract): void {
+ const block = new StageBlock(stage);
+ block.title(image, mode.label ? `New timer · ${mode.label}` : "New timer", 200);
+ block.fields(image, [pad2(mode.hours), pad2(mode.minutes), pad2(mode.seconds)], [":", ":"], mode.field, ["hours", "min", "sec"]);
+ block.line(image, this.notice, 190);
+ block.hints(image, [[GESTURE_SCROLL, "adjust"], [GESTURE_CLICK, mode.field < 2 ? "next" : "start"], [GESTURE_DOUBLE_CLICK, "back"]]);
+ }
+
+ private paintAlarmTime(image: GrayImage, stage: StageRect, mode: Extract, now: number): void {
+ const block = new StageBlock(stage);
+ block.title(image, mode.alarmId === null ? "New alarm" : "Alarm time", 200);
+ const tens = String(Math.floor(mode.minute / 10));
+ const ones = String(mode.minute % 10);
+ if (twelveHour()) {
+ const hour12 = ((mode.hour + 11) % 12) + 1;
+ block.fields(image, [String(hour12), tens, ones, mode.hour < 12 ? "AM" : "PM"], [":", "", " "], mode.field, ["hour", "", "min", ""]);
+ } else {
+ block.fields(image, [pad2(mode.hour), tens, ones], [":", ""], mode.field, ["hour", "", "min"]);
+ }
+ const preview = alarmNextRingMs(
+ { id: 0, hour: mode.hour, minute: mode.minute, days: 0, label: "", enabled: true, snoozedUntilMs: null, ringingSinceMs: null, lastFiredAtMs: null },
+ now,
+ );
+ block.line(image, preview === null ? "" : `Rings in ${formatSpanWords(preview - now)}`, 150);
+ const last = this.alarmFieldCount() - 1;
+ block.hints(image, [[GESTURE_SCROLL, "adjust"], [GESTURE_CLICK, mode.field < last ? "next" : "save"], [GESTURE_DOUBLE_CLICK, "back"]]);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Stage layout helpers
+
+type StageRect = { x: number; y: number; width: number; height: number };
+
+/**
+ * Lays the stage out top to bottom: a title line, the big digits, then
+ * whatever lines follow, with the gesture hints pinned to the bottom. Keeps
+ * a cursor so each element stacks under the previous one.
+ */
+class StageBlock {
+ private cursorY: number;
+ private readonly hintsTop: number;
+
+ constructor(private readonly rect: StageRect) {
+ this.cursorY = rect.y + 12;
+ this.hintsTop = rect.y + rect.height - 10 - lineStep(smallFont());
+ }
+
+ title(image: GrayImage, text: string, value: number): void {
+ const font = mediumFont();
+ image.drawText(font, this.rect.x + 4, this.cursorY, truncateText(font, text, this.rect.width - 8), value);
+ this.cursorY += font.lineHeight + 10;
+ }
+
+ /** The big number, centred; `suffix` (AM/PM) sits beside it in the medium font. */
+ digits(image: GrayImage, text: string, value: number, suffix = ""): void {
+ const suffixFont = mediumFont();
+ const suffixWidth = suffix ? suffixFont.measureText(suffix) + 10 : 0;
+ const font = fittingDigitFont(text, this.rect.width - 8 - suffixWidth);
+ const textWidth = font.measureText(text);
+ const x = this.rect.x + Math.max(0, Math.floor((this.rect.width - textWidth - suffixWidth) / 2));
+ image.drawText(font, x, this.cursorY, text, value);
+ if (suffix) {
+ image.drawText(suffixFont, x + textWidth + 10, this.cursorY + font.ascent - suffixFont.ascent, suffix, Math.round(value * 0.8));
+ }
+ this.cursorY += font.lineHeight + 8;
+ }
+
+ progress(image: GrayImage, fraction: number, value: number): void {
+ const x = this.rect.x + 6;
+ const width = this.rect.width - 12;
+ image.fillRoundedRect(x, this.cursorY, width, 6, 40, 3);
+ const filled = Math.round(width * clamp(fraction, 0, 1));
+ if (filled > 0) image.fillRoundedRect(x, this.cursorY, Math.max(6, filled), 6, value, 3);
+ this.cursorY += 14;
+ }
+
+ line(image: GrayImage, text: string, value: number): void {
+ if (!text) return;
+ const font = smallFont();
+ image.drawText(font, this.rect.x + 6, this.cursorY, truncateText(font, text, this.rect.width - 12), value);
+ this.cursorY += lineStep(font);
+ }
+
+ /** How many small-font lines fit between the cursor and the hints. */
+ linesLeft(): number {
+ return Math.floor((this.hintsTop - 6 - this.cursorY) / lineStep(smallFont()));
+ }
+
+ /** A three-column row (lap table). */
+ columns(image: GrayImage, font: UiFont, cells: string[], value: number): void {
+ if (this.cursorY + font.lineHeight > this.hintsTop - 4) return;
+ const x = this.rect.x + 6;
+ const width = this.rect.width - 12;
+ const columnWidth = Math.floor(width / cells.length);
+ for (let index = 0; index < cells.length; index++) {
+ const text = cells[index]!;
+ const cellX = index === 0 ? x : x + index * columnWidth + columnWidth - font.measureText(text);
+ image.drawText(font, cellX, this.cursorY, text, value);
+ }
+ this.cursorY += lineStep(font);
+ }
+
+ /** The seven weekday letters, lit for the days in `mask`; "Once" for none. */
+ days(image: GrayImage, mask: number, value: number): void {
+ const font = smallFont();
+ if (mask === 0) {
+ this.line(image, "Once", Math.round(value * 0.7));
+ return;
+ }
+ const step = Math.min(26, Math.floor((this.rect.width - 12) / 7));
+ const x = this.rect.x + 6;
+ for (let index = 0; index < 7; index++) {
+ const on = (mask & DAY_BITS[index]!) !== 0;
+ const letter = DAY_LETTERS[index]!;
+ const letterX = x + index * step + Math.floor((step - font.measureText(letter)) / 2);
+ if (on) image.fillRoundedRect(x + index * step + 1, this.cursorY - 2, step - 4, font.lineHeight + 4, 40, 4);
+ image.drawText(font, letterX, this.cursorY, letter, on ? value : Math.round(value * 0.35));
+ }
+ this.cursorY += lineStep(font) + 4;
+ }
+
+ /** Picker fields: boxed values with separators between and captions beneath. */
+ fields(image: GrayImage, values: string[], separators: string[], activeField: number, captions: string[]): void {
+ const font = digitFont(FIELD_DIGIT_SIZE);
+ const sepFont = mediumFont();
+ const small = smallFont();
+ const padX = 8;
+ const widths = values.map((value) => font.measureText(value) + 2 * padX);
+ const sepWidths = separators.map((separator) => (separator ? sepFont.measureText(separator) + 8 : 6));
+ const total = widths.reduce((sum, width) => sum + width, 0) + sepWidths.reduce((sum, width) => sum + width, 0);
+ let x = this.rect.x + Math.max(0, Math.floor((this.rect.width - total) / 2));
+ const boxHeight = font.lineHeight + 4;
+ for (let index = 0; index < values.length; index++) {
+ const width = widths[index]!;
+ const active = index === activeField;
+ if (active) {
+ image.fillRoundedRect(x, this.cursorY - 2, width, boxHeight, 35, 6);
+ image.drawRoundedRect(x, this.cursorY - 2, width, boxHeight, 130, 6);
+ }
+ image.drawText(font, x + padX, this.cursorY, values[index]!, active ? 250 : 170);
+ const caption = captions[index] ?? "";
+ if (caption) {
+ image.drawText(small, x + Math.floor((width - small.measureText(caption)) / 2), this.cursorY + boxHeight + 2, caption, 110);
+ }
+ x += width;
+ if (index < separators.length) {
+ const separator = separators[index]!;
+ if (separator.trim()) {
+ image.drawText(sepFont, x + 4, this.cursorY + font.ascent - sepFont.ascent, separator, 130);
+ }
+ x += sepWidths[index]!;
+ }
+ }
+ this.cursorY += boxHeight + 2 + small.lineHeight + 10;
+ }
+
+ /** A row of buttons; the highlighted one is filled, the rest outlined. */
+ buttons(image: GrayImage, labels: string[], selected: number, focused: boolean): void {
+ const font = smallFont();
+ const gap = 12;
+ const height = font.lineHeight + 14;
+ const width = Math.floor((this.rect.width - 12 - gap * (labels.length - 1)) / labels.length);
+ const y = Math.max(this.cursorY + 4, this.hintsTop - 10 - height);
+ for (let index = 0; index < labels.length; index++) {
+ const x = this.rect.x + 6 + index * (width + gap);
+ const active = index === selected;
+ if (active) {
+ image.fillRoundedRect(x, y, width, height, focused ? 40 : 15, 8);
+ image.drawRoundedRect(x, y, width, height, 150, 8);
+ } else {
+ image.drawRoundedRect(x, y, width, height, 70, 8);
+ }
+ const label = labels[index]!;
+ image.drawText(font, x + Math.floor((width - font.measureText(label)) / 2), y + 7, label, active ? 250 : 170);
+ }
+ this.cursorY = y + height + 6;
+ }
+
+ hints(image: GrayImage, pairs: Array<[string, string]>): void {
+ image.drawText(smallFont(), this.rect.x + 6, this.hintsTop, gestureHints(pairs), 110);
+ }
+}
+
+function listWidthFor(viewportWidth: number): number {
+ return clamp(Math.round(viewportWidth * LIST_SHARE), LIST_MIN_WIDTH, LIST_MAX_WIDTH);
+}
+
+function drawPauseMark(image: GrayImage, x: number, y: number, value: number): void {
+ image.fillRect(x, y, 3, 10, value);
+ image.fillRect(x + 5, y, 3, 10, value);
+}
+
+function pad2(value: number): string {
+ return String(value).padStart(2, "0");
+}
+
+// ---------------------------------------------------------------------------
+// Window
+
+export function createTimerAppWindow(options: InProcessAppOptions): InProcessWindow {
+ const layer = new TimersLayer();
+ let tick: ReturnType | null = null;
+ let unsubscribe: (() => void) | null = null;
+ const stopTick = () => {
+ if (tick !== null) {
+ clearInterval(tick);
+ tick = null;
+ }
+ };
+ const visible = () => shell.isScreenOn() && shell.foregroundWindow()?.windowId === TIMER_WINDOW_ID;
+ const app = createInProcessWindow({
+ appId: "timer",
+ windowId: TIMER_WINDOW_ID,
+ title: "Timers",
+ iconLetter: "T",
+ icon: "timer",
+ closeable: true,
+ actions: options.actions,
+ baseLayer: layer,
+ menuItems: () => layer.menuItems(),
+ receiveTextInput: (text) => {
+ layer.receiveTextInput(text);
+ app.requestRender();
+ },
+ submitFrame: options.submitFrame,
+ setSurfaceVisible: options.setSurfaceVisible,
+ removeSurface: options.removeSurface,
+ reconfigureSurface: options.reconfigureSurface,
+ onClosed: () => {
+ stopTick();
+ unsubscribe?.();
+ unsubscribe = null;
+ options.onClosed();
+ },
+ });
+ // Once a second while something on screen moves by itself and the window
+ // is actually visible; the shell's wake path repaints on its own.
+ tick = setInterval(() => {
+ if (visible() && timerEngine.isDynamic()) app.requestRender();
+ }, 1000);
+ unsubscribe = timerEngine.onChange(() => {
+ layer.onEngineChanged();
+ if (visible()) app.requestRender();
+ });
+ return app;
+}
+
+// ---------------------------------------------------------------------------
+// Tray icon
+
+let trayText: string | null = null;
+let trayTick: ReturnType | null = null;
+
+/**
+ * Keep a small "soonest timer" readout in the top bar while a timer runs,
+ * so any app can glance at it. Minute granularity until the last minute,
+ * so the shell isn't repainted every second for an hour.
+ */
+export function startTimersTrayIcon(): void {
+ const sync = () => {
+ const remaining = soonestRunningTimerRemainingMs(timerEngine);
+ let text: string | null = null;
+ if (remaining !== null) {
+ text = remaining >= MINUTE_MS ? `${Math.ceil(remaining / MINUTE_MS)}m` : `${Math.max(0, Math.ceil(remaining / 1000))}s`;
+ }
+ if (text === trayText) return;
+ trayText = text;
+ shell.setTrayIcon("timer", text === null ? null : renderTrayIcon(text));
+ if (text !== null && trayTick === null) {
+ trayTick = setInterval(sync, 1000);
+ } else if (text === null && trayTick !== null) {
+ clearInterval(trayTick);
+ trayTick = null;
+ }
+ };
+ timerEngine.onChange(sync);
+ sync();
+}
+
+function renderTrayIcon(text: string): GrayImage {
+ const font = getFont("terminus12");
+ const dial = 12;
+ const gap = 4;
+ const width = dial + gap + font.measureText(text);
+ const icon = new GrayImage(width, 16, 0);
+ // A little dial: a ring with a hand pointing up-right.
+ icon.drawRoundedRect(0, 2, dial, dial, 200, 6);
+ icon.drawLine(6, 8, 6, 5, 200);
+ icon.drawLine(6, 8, 8, 8, 200);
+ icon.drawText(font, dial + gap, 2, text, 220);
+ return icon;
+}
diff --git a/app/apps/timer/timer-app.worker.ts b/app/apps/timer/timer-app.worker.ts
deleted file mode 100644
index 1fdd1a92..00000000
--- a/app/apps/timer/timer-app.worker.ts
+++ /dev/null
@@ -1,745 +0,0 @@
-/**
- * Timer app worker. The singleton window contains a stopwatch plus a list of
- * independently scheduled countdown timers. Android AlarmManager owns the
- * durable expiry path; worker timeouts keep the live UI prompt.
- */
-import "@nativescript/core/globals";
-import { type UiFont, GrayImage } from "../../graphics/image";
-import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
-import { prepareFrameDraws } from "../../graphics/glyph-wire";
-import { getFont } from "../../graphics/bdffont";
-import { getDefaultSmallFont } from "../../graphics/ui-fonts";
-import * as frameTimings from "../../native/frame-timings";
-import { getActiveDisplay } from "../../native/active-display";
-import {
- cancelTimerNotification,
- fireTimerNotification,
- scheduleTimerNotification,
-} from "../../native/timer-notifications";
-import { defaultWindowMenuItems, WindowMenu } from "../../ui/window-menu";
-import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
-import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
-import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures";
-import { clamp } from "../../util/numeric-util";
-
-declare const global: any;
-declare const com: any;
-
-const RENDER_INTERVAL_MS = 100;
-const TIMER_ROW_HEIGHT = 34;
-const TIMER_LIST_TOP = 52;
-const FOOTER_HEIGHT = 34;
-
-const largeFont = getFont("terminus32");
-const mediumFont = getFont("terminus24");
-// Resolved per use so a font-setting change applies without a worker restart.
-function smallFont(): UiFont {
- return getDefaultSmallFont();
-}
-
-type TimerView = "stopwatch" | "timers" | "editor";
-
-type TimerWindow = {
- windowId: string;
- surfaceId: string;
- viewportWidth: number;
- viewportHeight: number;
- foreground: boolean;
- /** Whether this window is the shell's input target (pushed with each message). */
- focused: boolean;
- /** Long-press window menu; created on first open. */
- menu: WindowMenu | null;
- view: TimerView;
- stopwatchAction: number;
- timerSelection: number;
- editorField: number;
- editorHours: number;
- editorMinutes: number;
- editorSeconds: number;
- editorMessage: string;
- renderTimer: ReturnType | null;
- lastSubmittedFingerprint: string;
-};
-
-type CountdownTimer = {
- id: number;
- durationMs: number;
- endAtMs: number;
- expired: boolean;
- expiryTimeout: ReturnType | null;
-};
-
-const TIMER_TOOLS: ToolSpec[] = [
- {
- name: "set_timer",
- description:
- "Start a new countdown timer. Give the duration as hours/minutes/seconds; at least one must be nonzero. Returns the timer's number and when it will finish.",
- inputSchema: {
- type: "object",
- properties: {
- hours: { type: "number", description: "Hours component of the duration (default 0)." },
- minutes: { type: "number", description: "Minutes component of the duration (default 0)." },
- seconds: { type: "number", description: "Seconds component of the duration (default 0)." },
- },
- additionalProperties: false,
- },
- availability: "open",
- },
- {
- name: "list_timers",
- description:
- "List the countdown timers: each timer's number, its original duration, and the time remaining (or that it has finished).",
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
- availability: "open",
- },
- {
- name: "cancel_timer",
- description:
- "Cancel a running countdown timer, or dismiss a finished one. Give the timer number from list_timers; it may be omitted when only one timer exists. Pass all=true to clear every timer.",
- inputSchema: {
- type: "object",
- properties: {
- timer: { type: "number", description: "1-based timer number, as shown in the timer list." },
- all: { type: "boolean", description: "Clear all timers instead of a single one." },
- },
- additionalProperties: false,
- },
- availability: "open",
- },
-];
-
-const windows = new Map();
-const timers: CountdownTimer[] = [];
-let screenOn = true;
-let stopwatchAccumulatedMs = 0;
-let stopwatchRunningSinceMs: number | null = null;
-let nextTimerSerial = 1;
-
-function post(message: WorkerAppReply): void {
- global.postMessage(message);
-}
-
-// The host queues messages until this arrives: posts to a worker whose bundle
-// is still evaluating can be silently dropped (see WorkerAppHost). Top-level
-// evaluation is synchronous, so the handler below is installed before any
-// queued message can be delivered.
-post({ type: "worker-ready" });
-
-global.onmessage = (event: { data: WorkerAppMessage }) => {
- const message = event.data;
- switch (message.type) {
- case "open-window":
- windows.set(message.windowId, {
- windowId: message.windowId,
- surfaceId: message.surfaceId,
- viewportWidth: message.viewport.width,
- viewportHeight: message.viewport.height,
- foreground: false,
- focused: false,
- menu: null,
- view: "stopwatch",
- stopwatchAction: 0,
- timerSelection: 0,
- editorField: 0,
- editorHours: 0,
- editorMinutes: 5,
- editorSeconds: 0,
- editorMessage: "",
- renderTimer: null,
- lastSubmittedFingerprint: "",
- });
- post({ type: "set-tools", windowId: message.windowId, tools: TIMER_TOOLS });
- syncExpiredTimers();
- break;
- case "close-window": {
- const window = windows.get(message.windowId);
- if (window?.renderTimer) clearInterval(window.renderTimer);
- windows.delete(message.windowId);
- break;
- }
- case "input": {
- const window = windows.get(message.windowId);
- if (!window) {
- frameTimings.finishFrame(message.frameId, "discarded: unknown timer window");
- break;
- }
- window.focused = message.focused;
- // Marks the main-thread -> worker hop, which is otherwise an
- // unexplained gap inside the shell's handle-input span.
- frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
- handleInput(window, message.event as InputEvent, message.frameId);
- break;
- }
- case "render": {
- const window = windows.get(message.windowId);
- if (!window) break;
- window.focused = message.focused;
- renderAndSubmit(window, 0);
- break;
- }
- case "foreground": {
- const window = windows.get(message.windowId);
- if (!window) break;
- window.foreground = message.foreground;
- window.focused = message.focused;
- updateRenderTimer(window);
- if (window.foreground) renderAndSubmit(window, 0);
- break;
- }
- case "screen":
- screenOn = message.on;
- for (const window of windows.values()) updateRenderTimer(window);
- break;
- case "tool-call": {
- let result: ToolResult;
- try {
- result = handleTimerTool(message.name, message.args);
- } catch (error) {
- result = { ok: false, error: String((error as Error)?.message ?? error) };
- }
- post({ type: "tool-result", callId: message.callId, result });
- break;
- }
- }
-};
-
-// ---------------------------------------------------------------------------
-// Tools
-
-function handleTimerTool(name: string, args: any): ToolResult {
- syncExpiredTimers();
- switch (name) {
- case "set_timer": {
- const hours = toolDurationField(args?.hours, "hours");
- const minutes = toolDurationField(args?.minutes, "minutes");
- const seconds = toolDurationField(args?.seconds, "seconds");
- const durationMs = Math.round(((hours * 60 + minutes) * 60 + seconds) * 1000);
- if (durationMs <= 0) return { ok: false, error: "set_timer requires a duration longer than zero" };
- addTimer(durationMs);
- const timer = timers[timers.length - 1]!;
- refreshWindowsAfterToolChange();
- return {
- ok: true,
- content:
- `Started a ${formatDuration(durationMs)} timer (timer ${timers.length}), ` +
- `finishing at ${formatClock(timer.endAtMs)}.`,
- };
- }
- case "list_timers": {
- if (timers.length === 0) return { ok: true, content: "No timers are set." };
- return { ok: true, content: timers.map(describeTimer).join("\n") };
- }
- case "cancel_timer": {
- if (args?.all === true) {
- if (timers.length === 0) return { ok: true, content: "No timers are set." };
- const count = timers.length;
- for (const timer of [...timers]) removeTimer(timer);
- refreshWindowsAfterToolChange();
- return { ok: true, content: count === 1 ? "Cleared the timer." : `Cleared ${count} timers.` };
- }
- if (timers.length === 0) return { ok: true, content: "No timers are set." };
- let timer: CountdownTimer;
- if (args?.timer === undefined || args?.timer === null) {
- if (timers.length > 1) {
- return {
- ok: false,
- error: `There are ${timers.length} timers; give the timer number.\n${timers.map(describeTimer).join("\n")}`,
- };
- }
- timer = timers[0]!;
- } else {
- const index = Math.floor(Number(args.timer));
- if (!Number.isFinite(index) || index < 1 || index > timers.length) {
- return { ok: false, error: `No timer ${args.timer}; there are ${timers.length} timers.` };
- }
- timer = timers[index - 1]!;
- }
- const description = describeTimer(timer);
- removeTimer(timer);
- refreshWindowsAfterToolChange();
- return { ok: true, content: `${timer.expired ? "Dismissed" : "Canceled"}: ${description}` };
- }
- default:
- return { ok: false, error: `Unknown timer tool: ${name}` };
- }
-}
-
-function toolDurationField(value: unknown, label: string): number {
- if (value === undefined || value === null) return 0;
- const parsed = Number(value);
- if (!Number.isFinite(parsed) || parsed < 0) {
- throw new Error(`Invalid ${label} value: ${value}`);
- }
- return parsed;
-}
-
-function describeTimer(timer: CountdownTimer): string {
- const number = timers.indexOf(timer) + 1;
- const duration = formatDuration(timer.durationMs);
- if (timer.expired) return `Timer ${number}: ${duration} timer, finished.`;
- return (
- `Timer ${number}: ${duration} timer, ${formatCountdown(timer.endAtMs - Date.now())} remaining ` +
- `(finishes at ${formatClock(timer.endAtMs)}).`
- );
-}
-
-/** Repaint and re-gate every window after a tool call changed the timer list. */
-function refreshWindowsAfterToolChange(): void {
- for (const window of windows.values()) {
- window.timerSelection = clamp(window.timerSelection, 0, timers.length + 1);
- updateRenderTimer(window);
- if (window.foreground && screenOn) renderAndSubmit(window, 0);
- }
-}
-
-/** The window's long-press menu (default entries only), created lazily. */
-function windowMenu(window: TimerWindow): WindowMenu {
- if (!window.menu) {
- window.menu = new WindowMenu({
- size: { width: window.viewportWidth, height: window.viewportHeight },
- paintBase: () => paintContent(window),
- isFocused: () => window.focused,
- });
- }
- return window.menu;
-}
-
-function handleInput(window: TimerWindow, event: InputEvent, frameId: number): void {
- // An open window menu owns all input (it closes itself via pop).
- if (window.menu?.isOpen()) {
- window.menu
- .handleInput(event)
- .catch((error) => console.error(`timer menu input failed: ${error}`))
- .then(() => renderAndSubmit(window, frameId));
- return;
- }
- if (event.type === "long-press") {
- windowMenu(window).open(defaultWindowMenuItems(window.windowId, post));
- renderAndSubmit(window, frameId);
- return;
- }
- if (event.type === "double-click") {
- if (window.view === "editor") {
- window.view = "timers";
- window.editorMessage = "";
- updateRenderTimer(window);
- renderAndSubmit(window, frameId);
- } else {
- frameTimings.finishFrame(frameId, "discarded: timer yielded focus");
- post({ type: "yield-focus", windowId: window.windowId });
- }
- return;
- }
-
- if (window.view === "stopwatch") {
- handleStopwatchInput(window, event, frameId);
- } else if (window.view === "timers") {
- handleTimersInput(window, event, frameId);
- } else {
- handleEditorInput(window, event, frameId);
- }
-}
-
-function handleStopwatchInput(window: TimerWindow, event: InputEvent, frameId: number): void {
- if (event.type === "scroll-up" || event.type === "scroll-down") {
- const delta = event.type === "scroll-down" ? 1 : -1;
- window.stopwatchAction = clamp(window.stopwatchAction + delta, 0, 2);
- renderAndSubmit(window, frameId);
- return;
- }
- if (event.type !== "click") {
- frameTimings.finishFrame(frameId, "discarded: timer stopwatch ignored input");
- return;
- }
-
- if (window.stopwatchAction === 0) {
- if (stopwatchRunningSinceMs === null) {
- stopwatchRunningSinceMs = Date.now();
- } else {
- stopwatchAccumulatedMs += Date.now() - stopwatchRunningSinceMs;
- stopwatchRunningSinceMs = null;
- }
- } else if (window.stopwatchAction === 1) {
- stopwatchAccumulatedMs = 0;
- stopwatchRunningSinceMs = null;
- } else {
- window.view = "timers";
- window.timerSelection = 0;
- }
- updateRenderTimer(window);
- renderAndSubmit(window, frameId);
-}
-
-function handleTimersInput(window: TimerWindow, event: InputEvent, frameId: number): void {
- syncExpiredTimers();
- const itemCount = timers.length + 2; // Stopwatch navigation + New timer + timers.
- if (event.type === "scroll-up" || event.type === "scroll-down") {
- const delta = event.type === "scroll-down" ? 1 : -1;
- window.timerSelection = clamp(window.timerSelection + delta, 0, itemCount - 1);
- renderAndSubmit(window, frameId);
- return;
- }
- if (event.type !== "click") {
- frameTimings.finishFrame(frameId, "discarded: timer list ignored input");
- return;
- }
-
- if (window.timerSelection === 0) {
- window.view = "stopwatch";
- } else if (window.timerSelection === 1) {
- openEditor(window);
- } else {
- const timer = timers[window.timerSelection - 2];
- if (timer) removeTimer(timer);
- window.timerSelection = clamp(window.timerSelection, 0, Math.max(0, timers.length + 1));
- }
- updateRenderTimer(window);
- renderAndSubmit(window, frameId);
-}
-
-function handleEditorInput(window: TimerWindow, event: InputEvent, frameId: number): void {
- if (event.type === "scroll-up" || event.type === "scroll-down") {
- const delta = event.type === "scroll-up" ? 1 : -1;
- if (window.editorField === 0) {
- window.editorHours = clamp(window.editorHours + delta, 0, 23);
- } else if (window.editorField === 1) {
- window.editorMinutes = clamp(window.editorMinutes + delta, 0, 59);
- } else if (window.editorField === 2) {
- window.editorSeconds = clamp(window.editorSeconds + delta, 0, 59);
- } else {
- window.editorField = delta > 0 ? 2 : 3;
- }
- window.editorMessage = "";
- renderAndSubmit(window, frameId);
- return;
- }
- if (event.type !== "click") {
- frameTimings.finishFrame(frameId, "discarded: timer editor ignored input");
- return;
- }
-
- if (window.editorField < 3) {
- window.editorField += 1;
- } else {
- const durationMs =
- ((window.editorHours * 60 + window.editorMinutes) * 60 + window.editorSeconds) * 1000;
- if (durationMs <= 0) {
- window.editorMessage = "Choose a duration";
- window.editorField = 0;
- } else {
- addTimer(durationMs);
- window.view = "timers";
- window.timerSelection = timers.length + 1;
- window.editorMessage = "";
- }
- }
- updateRenderTimer(window);
- renderAndSubmit(window, frameId);
-}
-
-function openEditor(window: TimerWindow): void {
- window.view = "editor";
- window.editorField = 0;
- window.editorHours = 0;
- window.editorMinutes = 5;
- window.editorSeconds = 0;
- window.editorMessage = "";
-}
-
-function addTimer(durationMs: number): void {
- // Millisecond epoch plus a small serial is unique across worker restarts and
- // still safely representable as a JavaScript/Java long bridge value.
- const id = Date.now() * 100 + (nextTimerSerial++ % 100);
- const endAtMs = Date.now() + durationMs;
- const timer: CountdownTimer = {
- id,
- durationMs,
- endAtMs,
- expired: false,
- expiryTimeout: null,
- };
- timers.push(timer);
- const durationLabel = formatDuration(durationMs);
- scheduleTimerNotification(id, endAtMs, durationLabel);
- timer.expiryTimeout = setTimeout(() => expireTimer(timer), Math.max(0, endAtMs - Date.now()));
-}
-
-function expireTimer(timer: CountdownTimer, renderWindows = true): void {
- if (timer.expired) return;
- timer.expired = true;
- timer.expiryTimeout = null;
- fireTimerNotification(timer.id, formatDuration(timer.durationMs));
- for (const window of windows.values()) {
- post({ type: "set-attention", windowId: window.windowId, attention: true });
- updateRenderTimer(window);
- if (renderWindows && window.foreground && screenOn) renderAndSubmit(window, 0);
- }
-}
-
-function removeTimer(timer: CountdownTimer): void {
- if (timer.expiryTimeout) clearTimeout(timer.expiryTimeout);
- cancelTimerNotification(timer.id);
- const index = timers.indexOf(timer);
- if (index >= 0) timers.splice(index, 1);
-}
-
-function syncExpiredTimers(): void {
- const now = Date.now();
- for (const timer of timers) {
- // The caller is already about to paint, so avoid a nested render when a
- // sleeping/backgrounded timer is first observed as finished.
- if (!timer.expired && timer.endAtMs <= now) expireTimer(timer, false);
- }
-}
-
-function updateRenderTimer(window: TimerWindow): void {
- const activeCountdowns = timers.some((timer) => !timer.expired);
- const dynamic =
- (window.view === "stopwatch" && stopwatchRunningSinceMs !== null) ||
- (window.view === "timers" && activeCountdowns);
- const shouldRun = dynamic && window.foreground && screenOn;
- if (shouldRun && window.renderTimer === null) {
- window.renderTimer = setInterval(() => {
- syncExpiredTimers();
- renderAndSubmit(window, 0);
- }, RENDER_INTERVAL_MS);
- } else if (!shouldRun && window.renderTimer !== null) {
- clearInterval(window.renderTimer);
- window.renderTimer = null;
- }
-}
-
-function paint(window: TimerWindow): Plane[] {
- if (window.menu?.isOpen()) {
- return window.menu.paint();
- }
- return singlePlane(paintContent(window));
-}
-
-function paintContent(window: TimerWindow): GrayImage {
- syncExpiredTimers();
- const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0);
- if (window.view === "stopwatch") {
- paintStopwatch(image, window);
- } else if (window.view === "timers") {
- paintTimers(image, window);
- } else {
- paintEditor(image, window);
- }
- return image;
-}
-
-function paintStopwatch(image: GrayImage, window: TimerWindow): void {
- drawTabs(image, "stopwatch");
- const elapsed = stopwatchElapsedMs();
- const timeLabel = formatStopwatchElapsed(elapsed);
- const timeX = Math.max(0, Math.round((window.viewportWidth - largeFont.measureText(timeLabel)) / 2));
- image.drawText(largeFont, timeX, 66, timeLabel, 245);
-
- const state = stopwatchRunningSinceMs === null ? (elapsed > 0 ? "Paused" : "Ready") : "Running";
- drawCenteredText(image, smallFont(), 112, state, 145);
-
- const labels = [stopwatchRunningSinceMs === null ? "Start" : "Pause", "Reset", `Timers (${timers.length})`];
- drawButtonRow(image, labels, window.stopwatchAction, 154);
- drawFooter(image, `${GESTURE_SCROLL} action ${GESTURE_CLICK} select ${GESTURE_DOUBLE_CLICK} back`);
-}
-
-function paintTimers(image: GrayImage, window: TimerWindow): void {
- drawTabs(image, "timers");
- const items = ["< Stopwatch", "+ New timer", ...timers.map(timerRowLabel)];
- const listBottom = image.height - FOOTER_HEIGHT;
- const visibleRows = Math.max(1, Math.floor((listBottom - TIMER_LIST_TOP) / TIMER_ROW_HEIGHT));
- const first = clamp(window.timerSelection - visibleRows + 1, 0, Math.max(0, items.length - visibleRows));
-
- for (let row = 0; row < visibleRows; row++) {
- const index = first + row;
- if (index >= items.length) break;
- const y = TIMER_LIST_TOP + row * TIMER_ROW_HEIGHT;
- const selected = index === window.timerSelection;
- if (selected) {
- image.fillRoundedRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 34, 5);
- image.drawRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 105);
- }
- image.drawText(index >= 2 ? mediumFont : smallFont(), 32, y + (index >= 2 ? 2 : 7), items[index]!, selected ? 245 : 180);
- }
-
- const selectedTimer = window.timerSelection >= 2 ? timers[window.timerSelection - 2] : null;
- const action = selectedTimer ? (selectedTimer.expired ? "dismiss" : "cancel") : "select";
- drawFooter(image, `${GESTURE_SCROLL} timer ${GESTURE_CLICK} ${action} ${GESTURE_DOUBLE_CLICK} back`);
-}
-
-function paintEditor(image: GrayImage, window: TimerWindow): void {
- image.drawText(smallFont(), 24, 14, "New timer", 190);
- const fields = [pad2(window.editorHours), pad2(window.editorMinutes), pad2(window.editorSeconds)];
- const labels = ["hours", "minutes", "seconds"];
- const fieldWidth = 118;
- const gap = 22;
- const totalWidth = fieldWidth * 3 + gap * 2;
- const startX = Math.round((image.width - totalWidth) / 2);
-
- for (let index = 0; index < 3; index++) {
- const x = startX + index * (fieldWidth + gap);
- if (window.editorField === index) {
- image.fillRoundedRect(x, 57, fieldWidth, 68, 35, 6);
- image.drawRect(x, 57, fieldWidth, 68, 120);
- }
- drawCenteredIn(image, largeFont, x, fieldWidth, 65, fields[index]!, window.editorField === index ? 250 : 180);
- drawCenteredIn(image, smallFont(), x, fieldWidth, 105, labels[index]!, 125);
- if (index < 2) image.drawText(mediumFont, x + fieldWidth + 5, 71, ":", 130);
- }
-
- const startSelected = window.editorField === 3;
- const buttonWidth = 160;
- const buttonX = Math.round((image.width - buttonWidth) / 2);
- if (startSelected) {
- image.fillRoundedRect(buttonX, 151, buttonWidth, 38, 40, 6);
- image.drawRect(buttonX, 151, buttonWidth, 38, 120);
- }
- drawCenteredIn(image, smallFont(), buttonX, buttonWidth, 162, "Start timer", startSelected ? 250 : 175);
- if (window.editorMessage) drawCenteredText(image, smallFont(), 202, window.editorMessage, 190);
- drawFooter(image, `${GESTURE_SCROLL} adjust ${GESTURE_CLICK} next ${GESTURE_DOUBLE_CLICK} cancel`);
-}
-
-function drawTabs(image: GrayImage, active: "stopwatch" | "timers"): void {
- const stopwatch = "Stopwatch";
- const timerLabel = `Timers (${timers.length})`;
- const left = 24;
- const dividerX = left + smallFont().measureText(stopwatch) + 18;
- image.drawText(smallFont(), left, 15, stopwatch, active === "stopwatch" ? 245 : 105);
- image.drawLine(left, 35, dividerX - 12, 35, active === "stopwatch" ? 200 : 30);
- image.drawText(smallFont(), dividerX, 15, timerLabel, active === "timers" ? 245 : 105);
- image.drawLine(dividerX, 35, dividerX + smallFont().measureText(timerLabel), 35, active === "timers" ? 200 : 30);
-}
-
-function drawButtonRow(image: GrayImage, labels: string[], selected: number, y: number): void {
- const gap = 12;
- const margin = 24;
- const width = Math.floor((image.width - margin * 2 - gap * (labels.length - 1)) / labels.length);
- for (let index = 0; index < labels.length; index++) {
- const x = margin + index * (width + gap);
- if (index === selected) {
- image.fillRoundedRect(x, y, width, 40, 38, 6);
- image.drawRect(x, y, width, 40, 115);
- }
- drawCenteredIn(image, smallFont(), x, width, y + 12, labels[index]!, index === selected ? 245 : 155);
- }
-}
-
-function drawFooter(image: GrayImage, text: string): void {
- image.drawLine(16, image.height - FOOTER_HEIGHT, image.width - 16, image.height - FOOTER_HEIGHT, 35);
- drawCenteredText(image, smallFont(), image.height - 22, text, 115);
-}
-
-function drawCenteredText(image: GrayImage, font: UiFont, y: number, text: string, value: number): void {
- image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, value);
-}
-
-function drawCenteredIn(
- image: GrayImage,
- font: UiFont,
- x: number,
- width: number,
- y: number,
- text: string,
- value: number,
-): void {
- image.drawText(font, Math.round(x + (width - font.measureText(text)) / 2), y, text, value);
-}
-
-function timerRowLabel(timer: CountdownTimer): string {
- const number = timers.indexOf(timer) + 1;
- if (timer.expired) return `${number}. 00:00 Finished`;
- return `${number}. ${formatCountdown(timer.endAtMs - Date.now())} Running`;
-}
-
-function renderAndSubmit(window: TimerWindow, inputFrameId: number): void {
- const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${window.windowId}`);
- try {
- const paintStartedAtMs = Date.now();
- const planes = frameTimings.span(frameId, "paint", () =>
- frameTimings.runWithFrame(frameId, () => paint(window)),
- );
- const paintMs = Date.now() - paintStartedAtMs;
- const fingerprint = planesFingerprint(planes);
- if (fingerprint === window.lastSubmittedFingerprint) {
- frameTimings.finishFrame(frameId, "discarded: timer content unchanged");
- return;
- }
- const communicator = getActiveDisplay();
- if (!communicator) {
- frameTimings.finishFrame(frameId, "discarded: no active display");
- return;
- }
- const { image, draws } = frameTimings.span(frameId, "flatten", () => flattenPlanesWithDraws(planes));
- const buffer = frameTimings.span(frameId, "to8bpp", () => image.to8bppBuffer());
- communicator.submitSurfaceFrame(
- buffer.buffer,
- window.surfaceId,
- 0,
- 0,
- image.width,
- image.height,
- fingerprint,
- paintMs,
- frameId,
- frameTimings.span(frameId, "prepareFrameDraws", () => prepareFrameDraws(draws)),
- );
- window.lastSubmittedFingerprint = fingerprint;
- } catch (error) {
- frameTimings.finishFrame(frameId, "discarded: timer render failed");
- console.error(`timer worker render failed: ${error}`);
- }
-}
-
-function stopwatchElapsedMs(): number {
- const runningMs = stopwatchRunningSinceMs === null ? 0 : Date.now() - stopwatchRunningSinceMs;
- return stopwatchAccumulatedMs + runningMs;
-}
-
-function pad2(value: number): string {
- return String(value).padStart(2, "0");
-}
-
-function formatStopwatchElapsed(totalMs: number): string {
- const totalTenths = Math.floor(totalMs / 100);
- const tenths = totalTenths % 10;
- const totalSeconds = Math.floor(totalTenths / 10);
- const seconds = totalSeconds % 60;
- const totalMinutes = Math.floor(totalSeconds / 60);
- const minutes = totalMinutes % 60;
- const hours = Math.floor(totalMinutes / 60);
- return hours > 0
- ? `${hours}:${pad2(minutes)}:${pad2(seconds)}.${tenths}`
- : `${pad2(minutes)}:${pad2(seconds)}.${tenths}`;
-}
-
-function formatCountdown(remainingMs: number): string {
- const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
- const seconds = totalSeconds % 60;
- const totalMinutes = Math.floor(totalSeconds / 60);
- const minutes = totalMinutes % 60;
- const hours = Math.floor(totalMinutes / 60);
- return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${pad2(minutes)}:${pad2(seconds)}`;
-}
-
-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}`;
-}
-
-function formatDuration(durationMs: number): string {
- const totalSeconds = Math.round(durationMs / 1000);
- const seconds = totalSeconds % 60;
- const totalMinutes = Math.floor(totalSeconds / 60);
- const minutes = totalMinutes % 60;
- const hours = Math.floor(totalMinutes / 60);
- if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
- if (minutes > 0) return `${minutes}m ${seconds}s`;
- return `${seconds}s`;
-}
-
diff --git a/app/apps/timer/timer-engine.ts b/app/apps/timer/timer-engine.ts
new file mode 100644
index 00000000..61efa9c7
--- /dev/null
+++ b/app/apps/timer/timer-engine.ts
@@ -0,0 +1,692 @@
+/**
+ * The Timers app's clock engine: a main-thread singleton that owns the
+ * timers / stopwatch / alarms state, persists it, schedules the durable
+ * phone alarms behind every expiry, rings the glasses buzzer, and tells
+ * listeners (the window, the tray icon, the assistant tools) when anything
+ * changes. It is booted at shell start, so everything here works with the
+ * window closed; the window is only a view on it.
+ *
+ * Two expiry paths run side by side: a JS deadline for prompt on-glasses
+ * ringing while the process is awake, and an AlarmManager alarm-clock alarm
+ * (FaceclawAlarms.java) that rings on the phone at the right moment even if
+ * the process is asleep or dead. The phone shows the item silently first
+ * and adds its own sound when the glasses cannot carry it (not connected,
+ * not worn, charging, not shown within seconds, or not acknowledged within
+ * 30 s); this engine keeps the phone told about the glasses, reports
+ * delivery and acknowledgement, and replays what the wearer did on the
+ * phone (dismiss / snooze) into its own state.
+ */
+import { ConfigSettingBoolean, ConfigSettingEnum, timeFormatSetting } from "../../ui/dashboard-settings";
+import { getStringSetting, setStringSetting } from "../../native/settings-store";
+import {
+ acknowledgePhoneAlarm,
+ cancelPhoneAlarm,
+ checkPhoneAlarmReliability,
+ drainPhoneAlarmJournal,
+ onPhoneAlarmAction,
+ openPhoneAlarmReliabilityFix,
+ phoneAlarmDeliveredToGlasses,
+ ringPhoneAlarm,
+ schedulePhoneAlarm,
+ setPhoneAlarmGlassesStatus,
+ type AlarmReliabilityIssue,
+ type PhoneAlarmAction,
+} from "../../native/alarms";
+import { getGlassesPresence, glassesCanCarryAlert, onGlassesPresenceChanged } from "../../g2/glasses-presence";
+import { buildSoundSequencePayload, findSoundEffect, effectPhrases } from "../../ui/sound-effects";
+import {
+ alarmNextRingMs,
+ createAlarm,
+ createTimer,
+ emptyTimersState,
+ formatDurationWords,
+ formatTimeOfDay,
+ parseTimersState,
+ pushRecentDuration,
+ serializeTimersState,
+ stopwatchElapsedMs,
+ timerRemainingMs,
+ type Alarm,
+ type CountdownTimer,
+ type TimersState,
+} from "./timer-model";
+
+const STATE_KEY = "timers.state";
+
+/**
+ * An expiry that passed longer ago than this while the process was down
+ * (phone off, app killed) is marked rung silently rather than blaring on
+ * the glasses hours late; the phone notification already fired on time.
+ */
+const RING_GRACE_MS = 5 * 60_000;
+/** How often the buzzer repeats while something is ringing. */
+const RING_REPEAT_MS = 3_000;
+/** Stop buzzing an item this long after it started ringing (it stays "rung"). */
+const RING_MAX_MS = 2 * 60_000;
+/**
+ * Upper bound between deadline checks even with nothing due, so a JS timer
+ * delayed by Doze or a clock jump can't leave a due item unnoticed for long.
+ */
+const MAX_ARM_MS = 30_000;
+/** How often the phone is reminded of the glasses' status (it distrusts stale reports). */
+const GLASSES_STATUS_HEARTBEAT_MS = 60_000;
+/** How often the phone-side reliability self-check reruns while something is armed. */
+const RELIABILITY_CHECK_MS = 5 * 60_000;
+
+export const timersSoundSetting = new ConfigSettingBoolean({
+ id: "timersSound",
+ label: "Sound on glasses",
+ storageKey: "timers.soundOnGlasses",
+ defaultValue: true,
+ description: "Play the glasses buzzer while a timer or alarm is ringing.",
+});
+
+export const timersWakeSetting = new ConfigSettingBoolean({
+ id: "timersWake",
+ label: "Wake glasses when ringing",
+ storageKey: "timers.wakeGlasses",
+ defaultValue: true,
+ description: "Turn the display on and show the Timers app when a timer or alarm goes off.",
+});
+
+export type SnoozeMinutes = "5" | "10" | "15";
+export const timersSnoozeSetting = new ConfigSettingEnum({
+ id: "timersSnooze",
+ label: "Snooze length",
+ storageKey: "timers.snoozeMinutes",
+ defaultValue: "10",
+ values: ["5", "10", "15"],
+ formatValue: (value) => `${value} min`,
+});
+
+export type RingingItem = { kind: "timer"; timer: CountdownTimer } | { kind: "alarm"; alarm: Alarm };
+
+export type TimerEngineHooks = {
+ /** Play one buzzer sequencer payload on the glasses (no-op when disconnected). */
+ playBuzzer: (payload: Uint8Array) => Promise | void;
+ /** Something started ringing audibly: bring the app forward, wake the glasses. */
+ onRing: (item: RingingItem) => void;
+};
+
+const noopHooks: TimerEngineHooks = { playBuzzer: () => {}, onRing: () => {} };
+
+export class TimerEngine {
+ state: TimersState;
+ private hooks: TimerEngineHooks = noopHooks;
+ private readonly listeners = new Set<() => void>();
+ private deadlineTimer: ReturnType | null = null;
+ private ringTimer: ReturnType | null = null;
+ private booted = false;
+ private reliabilityIssues: AlarmReliabilityIssue[] = [];
+ private reliabilityCheckedAtMs = 0;
+
+ constructor(private readonly now: () => number = () => Date.now()) {
+ this.state = emptyTimersState();
+ }
+
+ /**
+ * Install the side-effect hooks and reconcile persisted state against the
+ * clock: anything that came due while the process was down rings (or is
+ * marked rung silently past the grace window), and the Android alarms are
+ * re-armed for what is still pending.
+ */
+ boot(hooks: TimerEngineHooks): void {
+ this.hooks = hooks;
+ if (this.booted) return;
+ this.booted = true;
+ // Loaded here rather than at module evaluation, so the settings store is
+ // certainly up before the first read.
+ this.state = parseTimersState(getStringSetting(STATE_KEY, ""));
+ // What the wearer did on the phone while this side was down comes first,
+ // so a dismissed alarm is not rung again by the check below.
+ for (const action of drainPhoneAlarmJournal()) this.applyPhoneAction(action);
+ onPhoneAlarmAction((action) => {
+ this.applyPhoneAction(action);
+ this.commit();
+ });
+ this.pushGlassesStatus();
+ onGlassesPresenceChanged(() => this.pushGlassesStatus());
+ setInterval(() => this.pushGlassesStatus(), GLASSES_STATUS_HEARTBEAT_MS);
+ this.check();
+ for (const timer of this.state.timers) {
+ if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
+ }
+ for (const alarm of this.state.alarms) this.schedulePhoneAlarm(alarm);
+ this.save();
+ this.refreshReliability(true);
+ setInterval(() => this.refreshReliability(false), RELIABILITY_CHECK_MS);
+ }
+
+ /**
+ * The glasses are showing a ringing item (the window is up and the screen
+ * on). The phone's 30-second acknowledgement clock starts from here; without
+ * this, the phone adds its sound within seconds.
+ */
+ markDeliveredToGlasses(item: RingingItem): void {
+ if (!glassesCanCarryAlert()) return;
+ phoneAlarmDeliveredToGlasses(item.kind === "timer" ? item.timer.id : item.alarm.id);
+ }
+
+ private pushGlassesStatus(): void {
+ const presence = getGlassesPresence();
+ setPhoneAlarmGlassesStatus(presence.connected, presence.worn === true, presence.charging);
+ }
+
+ /**
+ * Replay a phone-side dismiss or snooze. The item may be ringing here too,
+ * may not have been noticed yet (the phone rang it while this side slept),
+ * or may already be gone; each case lands on the same end state.
+ */
+ private applyPhoneAction(action: PhoneAlarmAction): void {
+ const at = action.atMs || this.now();
+ const timer = this.findTimer(action.id);
+ if (timer) {
+ if (action.action === "dismiss") {
+ this.state.timers = this.state.timers.filter((candidate) => candidate.id !== timer.id);
+ } else {
+ const extra = Math.max(1, action.minutes) * 60_000;
+ timer.rungAtMs = null;
+ timer.pausedRemainingMs = null;
+ timer.durationMs = extra;
+ timer.endsAtMs = at + extra;
+ }
+ return;
+ }
+ const alarm = this.findAlarm(action.id);
+ if (!alarm) return;
+ alarm.ringingSinceMs = null;
+ alarm.lastFiredAtMs = Math.max(alarm.lastFiredAtMs ?? 0, at);
+ if (action.action === "dismiss") {
+ alarm.snoozedUntilMs = null;
+ if (alarm.days === 0) alarm.enabled = false;
+ } else {
+ alarm.snoozedUntilMs = at + Math.max(1, action.minutes) * 60_000;
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Phone reliability
+
+ /** Conditions under which the phone may fail to ring, most serious first (cached). */
+ phoneReliabilityIssues(): AlarmReliabilityIssue[] {
+ return this.reliabilityIssues;
+ }
+
+ /**
+ * One-line warning for the UI, or "" when nothing is armed that could
+ * suffer (no enabled alarm, no running timer) or nothing is wrong.
+ */
+ phoneReliabilityMessage(): string {
+ if (this.reliabilityIssues.length === 0) return "";
+ const armed =
+ this.state.alarms.some((alarm) => alarm.enabled) ||
+ this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null);
+ if (!armed) return "";
+ return `The phone may not ring for alarms: ${this.reliabilityIssues[0]!.message}`;
+ }
+
+ /** Open the system screen for the most serious fixable issue, if any. */
+ openPhoneReliabilityFix(): void {
+ const issue = this.reliabilityIssues.find((candidate) => candidate.fixable);
+ if (issue) openPhoneAlarmReliabilityFix(issue.code);
+ }
+
+ /** Re-run the phone self-check (rate-limited unless forced) and notify on change. */
+ refreshReliability(force: boolean): void {
+ const now = this.now();
+ if (!force && now - this.reliabilityCheckedAtMs < 30_000) return;
+ this.reliabilityCheckedAtMs = now;
+ let issues: AlarmReliabilityIssue[];
+ try {
+ issues = checkPhoneAlarmReliability();
+ } catch (error) {
+ console.warn(`alarm reliability check failed: ${error}`);
+ return;
+ }
+ const changed =
+ issues.length !== this.reliabilityIssues.length ||
+ issues.some((issue, index) => issue.code !== this.reliabilityIssues[index]?.code);
+ this.reliabilityIssues = issues;
+ if (changed) this.notify();
+ }
+
+ onChange(listener: () => void): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ /** True while anything on screen changes by itself once a second. */
+ isDynamic(): boolean {
+ return (
+ this.state.stopwatch.runningSinceMs !== null ||
+ this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null) ||
+ this.ringingItems().length > 0
+ );
+ }
+
+ ringingItems(): RingingItem[] {
+ const items: RingingItem[] = [];
+ for (const timer of this.state.timers) {
+ if (timer.rungAtMs !== null) items.push({ kind: "timer", timer });
+ }
+ for (const alarm of this.state.alarms) {
+ if (alarm.ringingSinceMs !== null) items.push({ kind: "alarm", alarm });
+ }
+ return items;
+ }
+
+ // -------------------------------------------------------------------------
+ // Timers
+
+ findTimer(id: number): CountdownTimer | undefined {
+ return this.state.timers.find((timer) => timer.id === id);
+ }
+
+ startTimer(durationMs: number, label = ""): CountdownTimer {
+ const timer = createTimer(durationMs, label, this.now());
+ this.state.timers.push(timer);
+ this.state.recentDurationsMs = pushRecentDuration(this.state.recentDurationsMs, durationMs);
+ this.schedulePhoneNotification(timer);
+ this.commit();
+ return timer;
+ }
+
+ pauseTimer(id: number): void {
+ const timer = this.findTimer(id);
+ if (!timer || timer.endsAtMs === null || timer.rungAtMs !== null) return;
+ timer.pausedRemainingMs = Math.max(0, timer.endsAtMs - this.now());
+ timer.endsAtMs = null;
+ cancelPhoneAlarm(timer.id);
+ this.commit();
+ }
+
+ resumeTimer(id: number): void {
+ const timer = this.findTimer(id);
+ if (!timer || timer.pausedRemainingMs === null) return;
+ timer.endsAtMs = this.now() + timer.pausedRemainingMs;
+ timer.pausedRemainingMs = null;
+ this.schedulePhoneNotification(timer);
+ this.commit();
+ }
+
+ /** Add time to a timer; a rung timer becomes a running one with just the added time. */
+ addTimerTime(id: number, deltaMs: number): void {
+ const timer = this.findTimer(id);
+ if (!timer) return;
+ if (timer.rungAtMs !== null) {
+ timer.rungAtMs = null;
+ timer.durationMs = deltaMs;
+ timer.endsAtMs = this.now() + deltaMs;
+ cancelPhoneAlarm(timer.id);
+ this.schedulePhoneNotification(timer);
+ } else if (timer.pausedRemainingMs !== null) {
+ timer.pausedRemainingMs += deltaMs;
+ timer.durationMs += deltaMs;
+ } else if (timer.endsAtMs !== null) {
+ timer.endsAtMs += deltaMs;
+ timer.durationMs += deltaMs;
+ this.schedulePhoneNotification(timer);
+ }
+ this.commit();
+ }
+
+ /** Start the timer over at its set duration ("Again" on a rung timer). */
+ restartTimer(id: number): void {
+ const timer = this.findTimer(id);
+ if (!timer) return;
+ timer.rungAtMs = null;
+ timer.pausedRemainingMs = null;
+ timer.endsAtMs = this.now() + timer.durationMs;
+ cancelPhoneAlarm(timer.id);
+ this.schedulePhoneNotification(timer);
+ this.commit();
+ }
+
+ setTimerLabel(id: number, label: string): void {
+ const timer = this.findTimer(id);
+ if (!timer) return;
+ timer.label = label.trim();
+ if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
+ this.commit();
+ }
+
+ /** Cancel a timer, or dismiss a rung one. */
+ removeTimer(id: number): void {
+ const index = this.state.timers.findIndex((timer) => timer.id === id);
+ if (index < 0) return;
+ acknowledgePhoneAlarm(id);
+ this.state.timers.splice(index, 1);
+ this.commit();
+ }
+
+ // -------------------------------------------------------------------------
+ // Stopwatch
+
+ stopwatchToggle(): void {
+ const stopwatch = this.state.stopwatch;
+ const now = this.now();
+ if (stopwatch.runningSinceMs === null) {
+ stopwatch.runningSinceMs = now;
+ } else {
+ stopwatch.accumulatedMs += Math.max(0, now - stopwatch.runningSinceMs);
+ stopwatch.runningSinceMs = null;
+ }
+ this.commit();
+ }
+
+ stopwatchStart(): void {
+ if (this.state.stopwatch.runningSinceMs === null) this.stopwatchToggle();
+ }
+
+ stopwatchStop(): void {
+ if (this.state.stopwatch.runningSinceMs !== null) this.stopwatchToggle();
+ }
+
+ stopwatchLap(): void {
+ const stopwatch = this.state.stopwatch;
+ if (stopwatch.runningSinceMs === null) return;
+ stopwatch.lapsMs.push(stopwatchElapsedMs(stopwatch, this.now()));
+ this.commit();
+ }
+
+ stopwatchReset(): void {
+ this.state.stopwatch = { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] };
+ this.commit();
+ }
+
+ // -------------------------------------------------------------------------
+ // Alarms
+
+ findAlarm(id: number): Alarm | undefined {
+ return this.state.alarms.find((alarm) => alarm.id === id);
+ }
+
+ addAlarm(hour: number, minute: number, days: number, label = ""): Alarm {
+ const alarm = createAlarm(hour, minute, days, label, this.now());
+ this.state.alarms.push(alarm);
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ return alarm;
+ }
+
+ setAlarmTime(id: number, hour: number, minute: number): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm) return;
+ alarm.hour = hour;
+ alarm.minute = minute;
+ alarm.enabled = true;
+ alarm.snoozedUntilMs = null;
+ alarm.ringingSinceMs = null;
+ alarm.lastFiredAtMs = null;
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ setAlarmDays(id: number, days: number): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm) return;
+ alarm.days = days;
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ setAlarmEnabled(id: number, enabled: boolean): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm) return;
+ alarm.enabled = enabled;
+ alarm.snoozedUntilMs = null;
+ alarm.ringingSinceMs = null;
+ if (enabled) alarm.lastFiredAtMs = null;
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ setAlarmLabel(id: number, label: string): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm) return;
+ alarm.label = label.trim();
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ deleteAlarm(id: number): void {
+ const index = this.state.alarms.findIndex((alarm) => alarm.id === id);
+ if (index < 0) return;
+ cancelPhoneAlarm(id);
+ this.state.alarms.splice(index, 1);
+ this.commit();
+ }
+
+ snoozeAlarm(id: number, minutes = Number(timersSnoozeSetting.get())): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm || alarm.ringingSinceMs === null) return;
+ alarm.ringingSinceMs = null;
+ alarm.snoozedUntilMs = this.now() + minutes * 60_000;
+ acknowledgePhoneAlarm(alarm.id);
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ /** Stop a ringing alarm; a one-off alarm switches itself off. */
+ dismissAlarm(id: number): void {
+ const alarm = this.findAlarm(id);
+ if (!alarm || alarm.ringingSinceMs === null) return;
+ alarm.ringingSinceMs = null;
+ alarm.snoozedUntilMs = null;
+ if (alarm.days === 0) alarm.enabled = false;
+ acknowledgePhoneAlarm(alarm.id);
+ this.schedulePhoneAlarm(alarm);
+ this.commit();
+ }
+
+ /** Dismiss whatever is ringing (timers and alarms alike). Returns how many. */
+ dismissAllRinging(): number {
+ const items = this.ringingItems();
+ for (const item of items) {
+ if (item.kind === "timer") this.removeTimer(item.timer.id);
+ else this.dismissAlarm(item.alarm.id);
+ }
+ return items.length;
+ }
+
+ // -------------------------------------------------------------------------
+ // Deadlines and ringing
+
+ /**
+ * Fire anything due and re-arm for the next deadline. Called on every
+ * change, on the deadline timer, and by the window before it paints, so a
+ * timer never shows 0:00 without also being rung.
+ */
+ check(): void {
+ const now = this.now();
+ let changed = false;
+ for (const timer of this.state.timers) {
+ if (timer.endsAtMs === null || timer.rungAtMs !== null || timer.endsAtMs > now) continue;
+ timer.rungAtMs = timer.endsAtMs;
+ timer.endsAtMs = null;
+ changed = true;
+ // Late (found due after a restart): the phone rang or missed it on
+ // its own schedule; only a fresh expiry starts the phone flow here.
+ const late = now - timer.rungAtMs > RING_GRACE_MS;
+ if (!late) {
+ ringPhoneAlarm(timer.id, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
+ this.startRinging({ kind: "timer", timer });
+ }
+ }
+ for (const alarm of this.state.alarms) {
+ if (alarm.ringingSinceMs !== null) continue;
+ const due = this.alarmDueMs(alarm, now);
+ if (due === null || due > now) continue;
+ alarm.ringingSinceMs = now;
+ alarm.snoozedUntilMs = null;
+ alarm.lastFiredAtMs = due;
+ changed = true;
+ const late = now - due > RING_GRACE_MS;
+ if (late) {
+ // Missed by too much to ring now: fall through to the next occurrence.
+ alarm.ringingSinceMs = null;
+ if (alarm.days === 0) alarm.enabled = false;
+ this.schedulePhoneAlarm(alarm);
+ } else {
+ ringPhoneAlarm(alarm.id, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
+ this.startRinging({ kind: "alarm", alarm });
+ }
+ }
+ this.arm(now);
+ this.syncRingLoop(now);
+ if (changed) this.commit();
+ }
+
+ /**
+ * The occurrence an alarm should ring for next: the pending snooze, or the
+ * first occurrence after (now - grace) that it has not already rung for.
+ * Inside the grace window this returns a time in the past, which check()
+ * fires; beyond it the missed occurrence is skipped.
+ */
+ private alarmDueMs(alarm: Alarm, now: number): number | null {
+ return alarmNextRingMs(alarm, now - RING_GRACE_MS);
+ }
+
+ private startRinging(item: RingingItem): void {
+ try {
+ this.hooks.onRing(item);
+ } catch (error) {
+ console.warn(`timers onRing hook failed: ${error}`);
+ }
+ }
+
+ /** Re-arm the single deadline timer for the soonest pending expiry. */
+ private arm(now: number): void {
+ if (this.deadlineTimer !== null) {
+ clearTimeout(this.deadlineTimer);
+ this.deadlineTimer = null;
+ }
+ const deadlines: number[] = [];
+ for (const timer of this.state.timers) {
+ if (timer.rungAtMs === null && timer.endsAtMs !== null) deadlines.push(timer.endsAtMs);
+ }
+ for (const alarm of this.state.alarms) {
+ if (alarm.ringingSinceMs !== null) continue;
+ const due = this.alarmDueMs(alarm, now);
+ if (due !== null) deadlines.push(due);
+ }
+ if (deadlines.length === 0) return;
+ const delay = Math.min(MAX_ARM_MS, Math.max(0, Math.min(...deadlines) - now));
+ this.deadlineTimer = setTimeout(() => {
+ this.deadlineTimer = null;
+ this.check();
+ }, delay);
+ }
+
+ /** Run the buzzer repeat loop while anything is (still audibly) ringing. */
+ private syncRingLoop(now: number): void {
+ const audible = this.ringingItems().some((item) => this.ringAgeMs(item, now) < RING_MAX_MS);
+ if (audible && this.ringTimer === null) {
+ this.playRingSound();
+ this.ringTimer = setInterval(() => {
+ const at = this.now();
+ if (!this.ringingItems().some((item) => this.ringAgeMs(item, at) < RING_MAX_MS)) {
+ this.syncRingLoop(at);
+ return;
+ }
+ this.playRingSound();
+ }, RING_REPEAT_MS);
+ } else if (!audible && this.ringTimer !== null) {
+ clearInterval(this.ringTimer);
+ this.ringTimer = null;
+ }
+ }
+
+ private ringAgeMs(item: RingingItem, now: number): number {
+ const since = item.kind === "timer" ? item.timer.rungAtMs : item.alarm.ringingSinceMs;
+ return since === null ? Infinity : Math.max(0, now - since);
+ }
+
+ private playRingSound(): void {
+ if (!timersSoundSetting.get()) return;
+ const effect = findSoundEffect("alarm");
+ if (!effect) return;
+ const phrase = effectPhrases(effect.make())[0];
+ if (!phrase) return;
+ try {
+ void this.hooks.playBuzzer(buildSoundSequencePayload(phrase));
+ } catch (error) {
+ console.warn(`timers buzzer failed: ${error}`);
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Phone notifications
+
+ private schedulePhoneNotification(timer: CountdownTimer): void {
+ if (timer.endsAtMs === null) return;
+ schedulePhoneAlarm(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
+ }
+
+ /** (Re)arm or cancel the phone alarm for an alarm's next occurrence. */
+ private schedulePhoneAlarm(alarm: Alarm): void {
+ const due = alarm.ringingSinceMs === null ? this.alarmDueMs(alarm, this.now()) : null;
+ if (due === null) {
+ cancelPhoneAlarm(alarm.id);
+ return;
+ }
+ schedulePhoneAlarm(alarm.id, due, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
+ }
+
+ // -------------------------------------------------------------------------
+ // Change plumbing
+
+ private commit(): void {
+ this.save();
+ this.check();
+ this.notify();
+ if (this.booted) this.refreshReliability(false);
+ }
+
+ private save(): void {
+ try {
+ setStringSetting(STATE_KEY, serializeTimersState(this.state));
+ } catch (error) {
+ console.warn(`timers state save failed: ${error}`);
+ }
+ }
+
+ private notify(): void {
+ for (const listener of Array.from(this.listeners)) {
+ try {
+ listener();
+ } catch (error) {
+ console.warn(`timers listener failed: ${error}`);
+ }
+ }
+ }
+}
+
+function snoozeMinutes(): number {
+ return Number(timersSnoozeSetting.get()) || 10;
+}
+
+function timerNotificationText(timer: CountdownTimer): string {
+ const duration = formatDurationWords(timer.durationMs);
+ return timer.label ? `${timer.label} (${duration}) is up` : `${duration} timer is up`;
+}
+
+function alarmNotificationText(alarm: Alarm): string {
+ const time = formatTimeOfDay(alarm.hour, alarm.minute, timeFormatSetting.get() === "12h");
+ return alarm.label ? `${time} · ${alarm.label}` : time;
+}
+
+/** Remaining time of the timer that ends soonest, for the tray icon; null when none runs. */
+export function soonestRunningTimerRemainingMs(engine: TimerEngine, now = Date.now()): number | null {
+ let soonest: number | null = null;
+ for (const timer of engine.state.timers) {
+ if (timer.endsAtMs === null || timer.rungAtMs !== null) continue;
+ const remaining = timerRemainingMs(timer, now);
+ if (soonest === null || remaining < soonest) soonest = remaining;
+ }
+ return soonest;
+}
+
+export const timerEngine = new TimerEngine();
diff --git a/app/apps/timer/timer-model.ts b/app/apps/timer/timer-model.ts
new file mode 100644
index 00000000..3afc6860
--- /dev/null
+++ b/app/apps/timer/timer-model.ts
@@ -0,0 +1,460 @@
+/**
+ * Pure data model for the Timers app: countdown timers, the stopwatch, and
+ * alarms, plus the formatting and scheduling arithmetic they need. No
+ * NativeScript imports, so tests/timer-model.test.cjs can run it under plain
+ * node. Side effects (persistence, Android alarms, the buzzer, waking the
+ * glasses) live in timer-engine.ts; drawing lives in timer-app.ts.
+ */
+
+// ---------------------------------------------------------------------------
+// Types
+
+/**
+ * A countdown timer. Exactly one of the three phases holds at a time:
+ * running (endsAtMs set), paused (pausedRemainingMs set), or rung
+ * (rungAtMs set). A rung timer stays until dismissed so a missed one still
+ * reads "Time's up".
+ */
+export type CountdownTimer = {
+ /** Unique across restarts and safe as a Java long (see newItemId). */
+ id: number;
+ /** Wearer-given name; "" for an unlabelled timer (shown by duration). */
+ label: string;
+ durationMs: number;
+ endsAtMs: number | null;
+ pausedRemainingMs: number | null;
+ rungAtMs: number | null;
+ createdAtMs: number;
+};
+
+export type StopwatchState = {
+ /** Time accumulated over previous running stretches. */
+ accumulatedMs: number;
+ /** Start of the current running stretch, or null while stopped. */
+ runningSinceMs: number | null;
+ /** Cumulative elapsed time at each lap mark, oldest first. */
+ lapsMs: number[];
+};
+
+/** Day-of-week bits for Alarm.days, Monday first (Mon = bit 0 ... Sun = bit 6). */
+export const DAY_BITS = [1, 2, 4, 8, 16, 32, 64] as const;
+export const DAY_LETTERS = ["M", "T", "W", "T", "F", "S", "S"] as const;
+export const DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
+export const DAY_FULL_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] as const;
+export const WEEKDAYS_MASK = 1 | 2 | 4 | 8 | 16;
+export const WEEKEND_MASK = 32 | 64;
+export const EVERY_DAY_MASK = 127;
+
+export type Alarm = {
+ id: number;
+ hour: number;
+ minute: number;
+ /** Repeat days as DAY_BITS; 0 means a one-off alarm (disabled after it rings). */
+ days: number;
+ label: string;
+ enabled: boolean;
+ /** Set while a snooze is pending; the alarm rings again at this time. */
+ snoozedUntilMs: number | null;
+ /** Set while ringing; cleared by dismiss or snooze. */
+ ringingSinceMs: number | null;
+ /**
+ * For a repeating alarm: the occurrence most recently rung (or dismissed
+ * from ringing), so the same occurrence does not ring twice after a
+ * dismiss that lands before the minute is over.
+ */
+ lastFiredAtMs: number | null;
+};
+
+export type TimersState = {
+ timers: CountdownTimer[];
+ stopwatch: StopwatchState;
+ alarms: Alarm[];
+ /** Durations the wearer started most recently, newest first. */
+ recentDurationsMs: number[];
+};
+
+export function emptyTimersState(): TimersState {
+ return {
+ timers: [],
+ stopwatch: { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] },
+ alarms: [],
+ recentDurationsMs: [],
+ };
+}
+
+/** How many recent durations to keep for the "New timer" menu. */
+export const RECENT_DURATION_COUNT = 3;
+
+// ---------------------------------------------------------------------------
+// Ids
+
+let idSerial = 1;
+
+/**
+ * Millisecond epoch plus a small serial: unique across restarts, ordered by
+ * creation, and still exactly representable through the JS -> Java long
+ * bridge.
+ */
+export function newItemId(nowMs: number): number {
+ return nowMs * 100 + (idSerial++ % 100);
+}
+
+// ---------------------------------------------------------------------------
+// Duration ladder (the "New timer" dial)
+
+const SECOND = 1000;
+const MINUTE = 60 * SECOND;
+const HOUR = 60 * MINUTE;
+
+/**
+ * The durations the dial scrolls through: fine steps where timers are
+ * usually short, coarser steps as they get long, so anything from ten
+ * seconds to a day is a few dozen scroll clicks away at most.
+ */
+export const DURATION_LADDER_MS: readonly number[] = (() => {
+ const ladder: number[] = [10 * SECOND, 15 * SECOND, 20 * SECOND, 30 * SECOND, 45 * SECOND, MINUTE, 90 * SECOND];
+ for (let minutes = 2; minutes <= 20; minutes++) ladder.push(minutes * MINUTE);
+ for (let minutes = 25; minutes <= 60; minutes += 5) ladder.push(minutes * MINUTE);
+ for (let minutes = 75; minutes <= 180; minutes += 15) ladder.push(minutes * MINUTE);
+ for (let minutes = 210; minutes <= 360; minutes += 30) ladder.push(minutes * MINUTE);
+ for (let hours = 7; hours <= 12; hours++) ladder.push(hours * HOUR);
+ ladder.push(18 * HOUR, 24 * HOUR);
+ return ladder;
+})();
+
+/** Index of the ladder rung closest to a duration (ties go to the shorter). */
+export function nearestLadderIndex(durationMs: number): number {
+ let best = 0;
+ let bestDistance = Infinity;
+ for (let index = 0; index < DURATION_LADDER_MS.length; index++) {
+ const distance = Math.abs(DURATION_LADDER_MS[index]! - durationMs);
+ if (distance < bestDistance) {
+ best = index;
+ bestDistance = distance;
+ }
+ }
+ return best;
+}
+
+export const DEFAULT_TIMER_DURATION_MS = 10 * MINUTE;
+export const MAX_TIMER_DURATION_MS = 24 * HOUR;
+
+// ---------------------------------------------------------------------------
+// Timers
+
+export function timerRemainingMs(timer: CountdownTimer, nowMs: number): number {
+ if (timer.pausedRemainingMs !== null) return timer.pausedRemainingMs;
+ if (timer.endsAtMs !== null) return Math.max(0, timer.endsAtMs - nowMs);
+ return 0;
+}
+
+export type TimerPhase = "running" | "paused" | "rung";
+
+export function timerPhase(timer: CountdownTimer): TimerPhase {
+ if (timer.rungAtMs !== null) return "rung";
+ if (timer.pausedRemainingMs !== null) return "paused";
+ return "running";
+}
+
+/** 0..1 progress toward the end (1 once rung). */
+export function timerProgress(timer: CountdownTimer, nowMs: number): number {
+ if (timer.rungAtMs !== null || timer.durationMs <= 0) return 1;
+ return Math.min(1, Math.max(0, 1 - timerRemainingMs(timer, nowMs) / timer.durationMs));
+}
+
+export function createTimer(durationMs: number, label: string, nowMs: number): CountdownTimer {
+ return {
+ id: newItemId(nowMs),
+ label,
+ durationMs,
+ endsAtMs: nowMs + durationMs,
+ pausedRemainingMs: null,
+ rungAtMs: null,
+ createdAtMs: nowMs,
+ };
+}
+
+/** Running timers soonest first, then paused, then rung (oldest ring first). */
+export function sortTimers(timers: readonly CountdownTimer[], nowMs: number): CountdownTimer[] {
+ const rank = (timer: CountdownTimer) => (timer.rungAtMs !== null ? 0 : timer.pausedRemainingMs !== null ? 2 : 1);
+ return [...timers].sort((a, b) => {
+ const rankDelta = rank(a) - rank(b);
+ if (rankDelta !== 0) return rankDelta;
+ if (a.rungAtMs !== null && b.rungAtMs !== null) return a.rungAtMs - b.rungAtMs;
+ return timerRemainingMs(a, nowMs) - timerRemainingMs(b, nowMs) || a.createdAtMs - b.createdAtMs;
+ });
+}
+
+export function pushRecentDuration(recent: readonly number[], durationMs: number): number[] {
+ return [durationMs, ...recent.filter((value) => value !== durationMs)].slice(0, RECENT_DURATION_COUNT);
+}
+
+// ---------------------------------------------------------------------------
+// Stopwatch
+
+export function stopwatchElapsedMs(stopwatch: StopwatchState, nowMs: number): number {
+ const running = stopwatch.runningSinceMs === null ? 0 : Math.max(0, nowMs - stopwatch.runningSinceMs);
+ return stopwatch.accumulatedMs + running;
+}
+
+export function stopwatchIsRunning(stopwatch: StopwatchState): boolean {
+ return stopwatch.runningSinceMs !== null;
+}
+
+// ---------------------------------------------------------------------------
+// Alarms
+
+export function createAlarm(hour: number, minute: number, days: number, label: string, nowMs: number): Alarm {
+ return {
+ id: newItemId(nowMs),
+ hour,
+ minute,
+ days,
+ label,
+ enabled: true,
+ snoozedUntilMs: null,
+ ringingSinceMs: null,
+ lastFiredAtMs: null,
+ };
+}
+
+/** Monday-first weekday index (0..6) of a Date, from JS's Sunday-first getDay. */
+export function mondayFirstDay(date: Date): number {
+ return (date.getDay() + 6) % 7;
+}
+
+/**
+ * When the alarm next goes off, given the current time: the pending snooze
+ * if there is one, otherwise the next wall-clock occurrence of hour:minute
+ * on an enabled day (any day for a one-off), strictly after `nowMs` and
+ * after the occurrence it last rang for. Null when the alarm is disabled.
+ * Wall-clock arithmetic runs in the local zone via Date, so DST changes
+ * land on the right local time.
+ */
+export function alarmNextRingMs(alarm: Alarm, nowMs: number): number | null {
+ if (!alarm.enabled) return null;
+ if (alarm.snoozedUntilMs !== null) return alarm.snoozedUntilMs;
+ const floor = Math.max(nowMs, alarm.lastFiredAtMs ?? 0);
+ const start = new Date(nowMs);
+ for (let dayOffset = 0; dayOffset <= 7; dayOffset++) {
+ const candidate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + dayOffset, alarm.hour, alarm.minute, 0, 0);
+ if (candidate.getTime() <= floor) continue;
+ if (alarm.days !== 0 && !(alarm.days & DAY_BITS[mondayFirstDay(candidate)]!)) continue;
+ return candidate.getTime();
+ }
+ return null;
+}
+
+/** Alarms by time of day, then by creation. */
+export function sortAlarms(alarms: readonly Alarm[]): Alarm[] {
+ return [...alarms].sort((a, b) => a.hour * 60 + a.minute - (b.hour * 60 + b.minute) || a.id - b.id);
+}
+
+export function formatDays(days: number): string {
+ if (days === 0) return "Once";
+ if (days === EVERY_DAY_MASK) return "Every day";
+ if (days === WEEKDAYS_MASK) return "Weekdays";
+ if (days === WEEKEND_MASK) return "Weekends";
+ return DAY_NAMES.filter((_, index) => days & DAY_BITS[index]!).join(" ");
+}
+
+// ---------------------------------------------------------------------------
+// Formatting
+
+function pad2(value: number): string {
+ return String(value).padStart(2, "0");
+}
+
+/** Countdown / elapsed digits: m:ss below an hour, h:mm:ss above. */
+export function formatClockDigits(totalSeconds: number): string {
+ const seconds = totalSeconds % 60;
+ const totalMinutes = Math.floor(totalSeconds / 60);
+ const minutes = totalMinutes % 60;
+ const hours = Math.floor(totalMinutes / 60);
+ return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${minutes}:${pad2(seconds)}`;
+}
+
+/** Remaining time as a countdown reads it: rounds up, so 0:00 means done. */
+export function formatCountdown(remainingMs: number): string {
+ return formatClockDigits(Math.max(0, Math.ceil(remainingMs / 1000)));
+}
+
+/** Elapsed time as a stopwatch reads it: rounds down, plus optional tenths. */
+export function formatElapsed(elapsedMs: number, tenths: boolean): string {
+ const clamped = Math.max(0, elapsedMs);
+ const digits = formatClockDigits(Math.floor(clamped / 1000));
+ return tenths ? `${digits}.${Math.floor(clamped / 100) % 10}` : digits;
+}
+
+/** A set duration in words: "20 min", "1h 30m", "45s", "2m 30s". */
+export function formatDurationWords(durationMs: number): string {
+ const totalSeconds = Math.round(durationMs / 1000);
+ const seconds = totalSeconds % 60;
+ const totalMinutes = Math.floor(totalSeconds / 60);
+ const minutes = totalMinutes % 60;
+ const hours = Math.floor(totalMinutes / 60);
+ if (hours > 0) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
+ if (minutes > 0) return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes} min`;
+ return `${seconds}s`;
+}
+
+/** A span until something: "9h 12m", "12m", "45s". Coarse on purpose. */
+export function formatSpanWords(spanMs: number): string {
+ const totalSeconds = Math.max(0, Math.round(spanMs / 1000));
+ if (totalSeconds < 60) return `${totalSeconds}s`;
+ const totalMinutes = Math.floor(totalSeconds / 60);
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
+ if (hours === 0) return `${minutes}m`;
+ if (hours < 24) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
+ const days = Math.floor(hours / 24);
+ const restHours = hours % 24;
+ return restHours > 0 ? `${days}d ${restHours}h` : `${days}d`;
+}
+
+/** Wall-clock time of day in the wearer's chosen format. */
+export function formatTimeOfDay(hour24: number, minute: number, twelveHour: boolean): string {
+ const minutes = pad2(minute);
+ if (!twelveHour) return `${hour24}:${minutes}`;
+ const hour12 = ((hour24 + 11) % 12) + 1;
+ return `${hour12}:${minutes} ${hour24 < 12 ? "AM" : "PM"}`;
+}
+
+export function formatClockAt(timestampMs: number, twelveHour: boolean): string {
+ const date = new Date(timestampMs);
+ return formatTimeOfDay(date.getHours(), date.getMinutes(), twelveHour);
+}
+
+/** Row/stage label for a timer: its label, else its set duration. */
+export function timerDisplayName(timer: CountdownTimer): string {
+ return timer.label || formatDurationWords(timer.durationMs);
+}
+
+// ---------------------------------------------------------------------------
+// Persistence shape
+
+/**
+ * Parse a persisted state blob defensively: anything malformed falls back to
+ * a field default rather than failing the whole load, so a bad record loses
+ * itself and nothing else.
+ */
+export function parseTimersState(raw: string | null | undefined): TimersState {
+ const state = emptyTimersState();
+ if (!raw) return state;
+ let parsed: any;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return state;
+ }
+ if (!parsed || typeof parsed !== "object") return state;
+ if (Array.isArray(parsed.timers)) {
+ for (const item of parsed.timers) {
+ if (!item || typeof item !== "object" || !isFiniteNumber(item.id) || !isFiniteNumber(item.durationMs)) continue;
+ state.timers.push({
+ id: item.id,
+ label: typeof item.label === "string" ? item.label : "",
+ durationMs: item.durationMs,
+ endsAtMs: isFiniteNumber(item.endsAtMs) ? item.endsAtMs : null,
+ pausedRemainingMs: isFiniteNumber(item.pausedRemainingMs) ? item.pausedRemainingMs : null,
+ rungAtMs: isFiniteNumber(item.rungAtMs) ? item.rungAtMs : null,
+ createdAtMs: isFiniteNumber(item.createdAtMs) ? item.createdAtMs : 0,
+ });
+ }
+ }
+ const stopwatch = parsed.stopwatch;
+ if (stopwatch && typeof stopwatch === "object") {
+ state.stopwatch = {
+ accumulatedMs: isFiniteNumber(stopwatch.accumulatedMs) ? Math.max(0, stopwatch.accumulatedMs) : 0,
+ runningSinceMs: isFiniteNumber(stopwatch.runningSinceMs) ? stopwatch.runningSinceMs : null,
+ lapsMs: Array.isArray(stopwatch.lapsMs) ? stopwatch.lapsMs.filter(isFiniteNumber) : [],
+ };
+ }
+ if (Array.isArray(parsed.alarms)) {
+ for (const item of parsed.alarms) {
+ if (!item || typeof item !== "object" || !isFiniteNumber(item.id)) continue;
+ if (!isFiniteNumber(item.hour) || !isFiniteNumber(item.minute)) continue;
+ state.alarms.push({
+ id: item.id,
+ hour: Math.min(23, Math.max(0, Math.floor(item.hour))),
+ minute: Math.min(59, Math.max(0, Math.floor(item.minute))),
+ days: isFiniteNumber(item.days) ? item.days & EVERY_DAY_MASK : 0,
+ label: typeof item.label === "string" ? item.label : "",
+ enabled: item.enabled !== false,
+ snoozedUntilMs: isFiniteNumber(item.snoozedUntilMs) ? item.snoozedUntilMs : null,
+ ringingSinceMs: isFiniteNumber(item.ringingSinceMs) ? item.ringingSinceMs : null,
+ lastFiredAtMs: isFiniteNumber(item.lastFiredAtMs) ? item.lastFiredAtMs : null,
+ });
+ }
+ }
+ if (Array.isArray(parsed.recentDurationsMs)) {
+ state.recentDurationsMs = parsed.recentDurationsMs.filter(isFiniteNumber).slice(0, RECENT_DURATION_COUNT);
+ }
+ return state;
+}
+
+export function serializeTimersState(state: TimersState): string {
+ return JSON.stringify(state);
+}
+
+function isFiniteNumber(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value);
+}
+
+// ---------------------------------------------------------------------------
+// Tool-argument parsing (shared by the assistant tools)
+
+/**
+ * Parse a time of day from the forms an assistant is likely to pass:
+ * "7:30", "07:30", "7:30 am", "7pm", "19:30", "noon", "midnight".
+ * Returns null when unparseable.
+ */
+export function parseTimeOfDay(text: string): { hour: number; minute: number } | null {
+ const trimmed = text.trim().toLowerCase();
+ if (trimmed === "noon") return { hour: 12, minute: 0 };
+ if (trimmed === "midnight") return { hour: 0, minute: 0 };
+ const match = /^(\d{1,2})(?::(\d{2}))?\s*(a\.?m\.?|p\.?m\.?)?$/.exec(trimmed);
+ if (!match) return null;
+ let hour = parseInt(match[1]!, 10);
+ const minute = match[2] ? parseInt(match[2], 10) : 0;
+ const meridiem = match[3]?.replace(/\./g, "");
+ if (minute > 59) return null;
+ if (meridiem) {
+ if (hour < 1 || hour > 12) return null;
+ hour = hour % 12;
+ if (meridiem === "pm") hour += 12;
+ } else if (hour > 23) {
+ return null;
+ }
+ return { hour, minute };
+}
+
+/** Parse repeat days from names ("mon", "tuesday"), "weekdays", "weekends", "daily"/"every day", "once". */
+export function parseRepeatDays(values: readonly string[] | string | null | undefined): number | null {
+ if (values === null || values === undefined) return 0;
+ const list =
+ typeof values === "string"
+ ? values.toLowerCase().replace(/every\s*day/g, "daily").split(/[,\s]+/)
+ : values.map((value) => String(value).toLowerCase().replace(/every\s*day/g, "daily"));
+ let mask = 0;
+ for (const raw of list) {
+ const value = String(raw).trim().toLowerCase();
+ if (!value || value === "once" || value === "none") continue;
+ if (value === "weekdays") {
+ mask |= WEEKDAYS_MASK;
+ continue;
+ }
+ if (value === "weekends" || value === "weekend") {
+ mask |= WEEKEND_MASK;
+ continue;
+ }
+ if (value === "daily" || value === "every day" || value === "everyday" || value === "all") {
+ mask |= EVERY_DAY_MASK;
+ continue;
+ }
+ const index = DAY_FULL_NAMES.findIndex((name) => name.toLowerCase().startsWith(value.slice(0, 3)));
+ if (index < 0 || value.length < 2) return null;
+ mask |= DAY_BITS[index]!;
+ }
+ return mask;
+}
diff --git a/app/apps/transcribe/transcribe-app.ts b/app/apps/transcribe/transcribe-app.ts
index b51f0139..b0a17639 100644
--- a/app/apps/transcribe/transcribe-app.ts
+++ b/app/apps/transcribe/transcribe-app.ts
@@ -57,10 +57,18 @@ export function createTranscribeAppWindow(options: TranscribeAppOptions): InProc
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(layer),
+ menuItems: () => [{
+ label: "Save",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ layer.saveTranscript();
+ },
+ }],
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
+ layer.onRemoved();
options.stopContinuousVoiceCapture();
shell.setTrayIcon(TRAY_ICON_ID, null);
options.onClosed();
diff --git a/app/apps/transcribe/transcribe.ts b/app/apps/transcribe/transcribe.ts
index 0b6de439..8c056c52 100644
--- a/app/apps/transcribe/transcribe.ts
+++ b/app/apps/transcribe/transcribe.ts
@@ -1,33 +1,35 @@
-import { GrayImage, type UiFont } from "../../graphics/image";
+import { GrayImage } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { lineStep } from "../../ui/metrics";
import { writeTextToDownloads } from "../../native/file-access";
-import { voiceControlBridge, type VoiceTranscriptEvent } from "../../native/voice-control";
+import { voiceControlBridge } from "../../native/voice-control";
import { Layer, type LayerContext } from "../../ui/layers";
+import { type InputEvent } from "../../ui/gestures";
+import { TranscriptModel, TranscriptScroll, wrapTranscribeText } from "./transcript-model";
/**
* Live transcription view. Continuous mic capture is owned by the app wrapper
* (createTranscribeAppWindow); this layer accumulates the transcript, shows
- * it, and saves it to Downloads on click.
+ * it, and saves it to Downloads from the app menu.
*/
-import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
export class TranscribeLayer implements Layer {
private status = "Listening...";
- // Finalized utterances, plus the live (replace-semantics) partial appended
- // when painting.
- private finalizedText = "";
- private liveText = "";
+ private readonly transcript = new TranscriptModel();
+ private readonly scroll = new TranscriptScroll();
private saveNotice = "";
private unsubscribeTranscript: (() => void) | null = null;
+ private unsubscribePause: (() => void) | null = null;
private unsubscribeStatus: (() => void) | null = null;
start(requestRender: () => void): void {
this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => {
- this.onTranscript(event);
+ this.transcript.accept(event);
requestRender();
});
+ this.unsubscribePause = voiceControlBridge.onSpeechPause(() => this.transcript.pause());
this.unsubscribeStatus = voiceControlBridge.onStatus((state) => {
this.status = state.status;
+ this.saveNotice = "";
requestRender();
});
}
@@ -36,29 +38,34 @@ export class TranscribeLayer implements Layer {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
- const text = this.displayText() || "Listening...";
- const wrapped = wrapTranscribeText(font, text, width - 64);
+ const text = this.transcript.text || "Listening...";
+ const wrapped = wrapTranscribeText((text) => font.measureText(text), text, width - 64);
image.drawText(font, 24, 20, "Transcribe", 200);
image.drawText(font, 24, 40, this.saveNotice || this.status, 110);
const step = lineStep(font) + 2;
const bodyTop = 62;
- const footerY = height - font.lineHeight - 6;
- const bodyLines = Math.max(1, Math.floor((footerY - bodyTop) / step));
- const firstLine = Math.max(0, wrapped.length - bodyLines);
- for (let index = firstLine; index < wrapped.length; index++) {
+ const bodyLines = Math.max(1, Math.floor((height - 6 - bodyTop - font.lineHeight) / step) + 1);
+ const firstLine = this.scroll.layout(wrapped.length, bodyLines);
+ for (let index = firstLine; index < Math.min(wrapped.length, firstLine + bodyLines); index++) {
const y = bodyTop + (index - firstLine) * step;
image.drawText(font, 32, y, wrapped[index]!, 230);
}
- image.drawText(font, 24, footerY, `${GESTURE_CLICK} save ${GESTURE_DOUBLE_CLICK} back`, 110);
+ if (wrapped.length > bodyLines) {
+ const trackHeight = height - bodyTop - 6;
+ const thumbHeight = Math.max(8, Math.round(trackHeight * bodyLines / wrapped.length));
+ const thumbY = bodyTop + Math.round((trackHeight - thumbHeight) * firstLine / (wrapped.length - bodyLines));
+ image.fillRect(width - 14, bodyTop, 2, trackHeight, 45);
+ image.fillRect(width - 14, thumbY, 2, thumbHeight, 140);
+ }
return image;
}
handleInput(event: InputEvent, ctx: LayerContext): void {
- if (event.type === "click") {
- this.saveTranscript();
+ if (event.type === "scroll-up" || event.type === "scroll-down") {
+ this.scroll.scroll(event.type === "scroll-up" ? -3 : 3);
ctx.actions.requestRender();
return;
}
@@ -68,14 +75,16 @@ export class TranscribeLayer implements Layer {
}
onRemoved(): void {
+ this.unsubscribePause?.();
+ this.unsubscribePause = null;
this.unsubscribeTranscript?.();
this.unsubscribeTranscript = null;
this.unsubscribeStatus?.();
this.unsubscribeStatus = null;
}
- private saveTranscript(): void {
- const text = this.displayText().trim();
+ saveTranscript(): void {
+ const text = this.transcript.text.trim();
if (!text) {
this.saveNotice = "Nothing to save yet.";
return;
@@ -84,25 +93,6 @@ export class TranscribeLayer implements Layer {
const path = writeTextToDownloads(filename, `${text}\n`);
this.saveNotice = path ? `Saved ${filename}` : "Save failed (check file access).";
}
-
- private displayText(): string {
- if (!this.finalizedText) return this.liveText;
- if (!this.liveText) return this.finalizedText;
- return `${this.finalizedText} ${this.liveText}`;
- }
-
- private onTranscript(event: VoiceTranscriptEvent): void {
- if (event.isFinal) {
- const finalText = event.text.trim() || this.liveText.trim();
- if (finalText) {
- this.finalizedText = this.finalizedText ? `${this.finalizedText} ${finalText}` : finalText;
- }
- this.liveText = "";
- } else {
- // Replace semantics: the live partial is the whole current best transcript.
- this.liveText = event.text.trim();
- }
- }
}
function transcriptTimestamp(): string {
@@ -113,22 +103,3 @@ function transcriptTimestamp(): string {
`-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
);
}
-
-function wrapTranscribeText(font: UiFont, text: string, maxWidth: number): string[] {
- const words = text.split(/\s+/).filter(Boolean);
- const lines: string[] = [];
- let line = "";
- for (const word of words) {
- const candidate = line ? `${line} ${word}` : word;
- if (line && font.measureText(candidate) > maxWidth) {
- lines.push(line);
- line = word;
- } else {
- line = candidate;
- }
- }
- if (line) {
- lines.push(line);
- }
- return lines.length ? lines : [""];
-}
diff --git a/app/apps/transcribe/transcript-model.ts b/app/apps/transcribe/transcript-model.ts
new file mode 100644
index 00000000..8b0e811a
--- /dev/null
+++ b/app/apps/transcribe/transcript-model.ts
@@ -0,0 +1,83 @@
+type TranscriptEvent = {
+ text: string;
+ isFinal: boolean;
+ transcribeText?: string;
+ paragraphBreakAfter?: boolean;
+};
+
+/** Text accumulation belongs to this app, not the shared dictation stream. */
+export class TranscriptModel {
+ private finalized = "";
+ private live = "";
+ private separator = " ";
+ private breakAfterLive = false;
+
+ get text(): string {
+ return this.finalized && this.live ? this.finalized + this.separator + this.live : this.finalized || this.live;
+ }
+
+ accept(event: TranscriptEvent): void {
+ const text = (event.transcribeText ?? event.text).trim();
+ if (!event.isFinal) {
+ this.live = text;
+ return;
+ }
+ const finalText = text || this.live;
+ if (finalText) this.finalized = this.finalized ? this.finalized + this.separator + finalText : finalText;
+ this.live = "";
+ if (finalText) this.separator = event.paragraphBreakAfter || this.breakAfterLive ? "\n" : " ";
+ this.breakAfterLive = false;
+ }
+
+ /** The onboard recognizer may finalize just before or just after the pause. */
+ pause(): void {
+ if (this.live) this.breakAfterLive = true;
+ else if (this.finalized) this.separator = "\n";
+ }
+}
+
+/** An absolute history position, with an explicit follow-tail mode. */
+export class TranscriptScroll {
+ firstLine = 0;
+ private maximum = 0;
+ private following = true;
+
+ layout(totalLines: number, visibleLines: number): number {
+ this.maximum = Math.max(0, totalLines - visibleLines);
+ this.firstLine = this.following ? this.maximum : Math.min(this.firstLine, this.maximum);
+ return this.firstLine;
+ }
+
+ scroll(delta: number): void {
+ this.firstLine = Math.max(0, Math.min(this.maximum, this.firstLine + delta));
+ this.following = this.firstLine === this.maximum;
+ }
+}
+
+export function wrapTranscribeText(measure: (text: string) => number, text: string, maxWidth: number): string[] {
+ const lines: string[] = [];
+ for (const paragraph of text.split("\n")) {
+ let line = "";
+ for (const word of paragraph.split(/\s+/).filter(Boolean)) {
+ const candidate = line ? `${line} ${word}` : word;
+ if (line && measure(candidate) > maxWidth) {
+ lines.push(line);
+ line = "";
+ }
+ if (measure(word) <= maxWidth) {
+ line = line ? `${line} ${word}` : word;
+ continue;
+ }
+ // Long URLs and unspaced languages must not run off the display.
+ for (const char of (line ? " " : "") + word) {
+ if (line && measure(line + char) > maxWidth) {
+ lines.push(line);
+ line = "";
+ }
+ line += char;
+ }
+ }
+ lines.push(line);
+ }
+ return lines;
+}
diff --git a/app/assistant/conversations.ts b/app/assistant/conversations.ts
new file mode 100644
index 00000000..7e5df8f8
--- /dev/null
+++ b/app/assistant/conversations.ts
@@ -0,0 +1,95 @@
+import { AssistantSession, type AssistantBackendConfig, type AssistantSessionHistory } from "./session";
+import { ASSISTANT_MODEL_VALUES, type AssistantModel } from "./models";
+
+export type ReasoningLevel = "default" | "low" | "medium" | "high";
+export type Conversation = {
+ id: string;
+ model: AssistantModel;
+ reasoning: ReasoningLevel;
+ session: AssistantSession | null;
+ history?: AssistantSessionHistory;
+};
+type SavedConversation = Omit;
+type SavedConversations = { selectedId: string; conversations: SavedConversation[] };
+
+/** Shared selection and history for every assistant entry point. No credentials are saved. */
+export class AssistantConversations {
+ private records: Conversation[] = [];
+ private selectedId = "";
+ private readonly listeners = new Set<() => void>();
+
+ constructor(
+ private readonly resolve: (model: AssistantModel, reasoning: ReasoningLevel) => AssistantBackendConfig | null,
+ private readonly defaultModel: () => AssistantModel,
+ private readonly persist: (value: string) => void,
+ saved = "",
+ ) {
+ try {
+ const data: SavedConversations = JSON.parse(saved);
+ if (Array.isArray(data.conversations)) {
+ this.records = data.conversations.filter((record) =>
+ typeof record.id === "string" && ASSISTANT_MODEL_VALUES.includes(record.model) &&
+ ["default", "low", "medium", "high"].includes(record.reasoning) &&
+ Array.isArray(record.history?.messages) && Array.isArray(record.history?.transcript),
+ ).map((record) => ({ ...record, session: null }));
+ this.selectedId = data.selectedId;
+ }
+ } catch { /* First launch or invalid saved state. */ }
+ if (!this.records.length) this.records.push(this.makeConversation());
+ if (!this.records.some((record) => record.id === this.selectedId)) this.selectedId = this.records[0]!.id;
+ }
+
+ current(): Conversation { return this.records.find((record) => record.id === this.selectedId)!; }
+ list(): readonly Conversation[] { return this.records; }
+ title(record = this.current()): string {
+ const transcript = record.session?.transcript ?? record.history?.transcript ?? [];
+ return transcript.find((entry) => entry.role === "user")?.text.replace(/\s+/g, " ").slice(0, 60) || "New session";
+ }
+ onChanged(listener: () => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+ private changed(save = true): void {
+ if (save) this.persist(JSON.stringify({ selectedId: this.selectedId, conversations: this.records.map(
+ ({ session, ...record }) => ({ ...record, history: session?.history() ?? record.history ?? { messages: [], transcript: [] } }),
+ ) }));
+ for (const listener of this.listeners) listener();
+ }
+ private makeConversation(): Conversation {
+ return { id: `${Date.now()}-${Math.random().toString(36).slice(2)}`, model: this.defaultModel(), reasoning: "default", session: null };
+ }
+ create(): boolean {
+ if (this.current().session?.isTurnActive()) return false;
+ const record = this.makeConversation();
+ this.records.push(record);
+ this.selectedId = record.id;
+ this.changed();
+ return true;
+ }
+ select(id: string): boolean {
+ if (this.current().session?.isTurnActive() || !this.records.some((record) => record.id === id)) return false;
+ this.selectedId = id;
+ this.changed();
+ return true;
+ }
+ configure(model: AssistantModel, reasoning: ReasoningLevel): boolean {
+ const record = this.current();
+ if (record.session?.isTurnActive() || !this.resolve(model, reasoning)) return false;
+ record.model = model;
+ record.reasoning = reasoning;
+ this.ensureSession();
+ this.changed();
+ return true;
+ }
+ available(model: AssistantModel, reasoning: ReasoningLevel): boolean { return this.resolve(model, reasoning) !== null; }
+ ensureSession(): AssistantSession | null {
+ const record = this.current();
+ const config = this.resolve(record.model, record.reasoning);
+ if (!config) return null;
+ if (!record.session) {
+ record.session = new AssistantSession(config, undefined, record.history);
+ record.session.onChanged(() => this.changed(!record.session!.isTurnActive()));
+ } else record.session.configure(config);
+ return record.session;
+ }
+}
diff --git a/app/assistant/direct-backend.ts b/app/assistant/direct-backend.ts
index 12e5cbbc..451abdf6 100644
--- a/app/assistant/direct-backend.ts
+++ b/app/assistant/direct-backend.ts
@@ -50,6 +50,7 @@ export class DirectAssistantBackend {
const startMs = Date.now();
let cancelled = false;
let streamHandle: LlmStreamHandle | null = null;
+ let priorText = "";
const finishError = (message: string) => {
if (cancelled) return;
@@ -78,7 +79,7 @@ export class DirectAssistantBackend {
tools: options.buildTools(),
onTextDelta: (delta, textSoFar) => {
if (cancelled) return;
- options.callbacks.onTextDelta(delta, textSoFar);
+ options.callbacks.onTextDelta(delta, priorText + textSoFar);
},
onDone: (result) => {
streamHandle = null;
@@ -87,6 +88,9 @@ export class DirectAssistantBackend {
finishError("The assistant declined this request");
return;
}
+ const fullText = priorText + result.text;
+ options.callbacks.onTextDelta("", fullText);
+ priorText = fullText ? `${fullText}\n\n` : "";
// Record what the model produced this iteration.
const assistantContent: LlmContentBlock[] = result.content.length
? result.content
diff --git a/app/assistant/navigate-tools.ts b/app/assistant/navigate-tools.ts
index b644ac59..127cea41 100644
--- a/app/assistant/navigate-tools.ts
+++ b/app/assistant/navigate-tools.ts
@@ -23,7 +23,7 @@ export function registerNavigateTools(
{
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.",
+ "Start turn-by-turn navigation on the glasses to a destination given as free text (place name, business, or address near the user), or the name of one of the user's saved destinations such as 'home' or 'work'. 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: {
diff --git a/app/assistant/roam-tools.ts b/app/assistant/roam-tools.ts
index 057d9173..c052f117 100644
--- a/app/assistant/roam-tools.ts
+++ b/app/assistant/roam-tools.ts
@@ -57,7 +57,7 @@ async function callAppTool(
args: unknown,
): Promise {
if (roamGraphNameSetting.get().length === 0 || roamApiTokenSetting.get().length === 0) {
- return err("Roam is not configured; the user must set the graph name and API token from the Roam app's long-press menu.");
+ return err("Roam is not configured; the user must set the graph name and API token from the Roam app's context menu (tap, then hold).");
}
return callAppToolWithLaunch(registry, launchApp, "roam", unprefixedName, args);
}
diff --git a/app/assistant/session.ts b/app/assistant/session.ts
index 604095a9..69a915fc 100644
--- a/app/assistant/session.ts
+++ b/app/assistant/session.ts
@@ -15,26 +15,20 @@ import type {
AssistantTurnHandle,
} from "./types";
-/**
- * One assistant conversation. Owns the message history and turn state and
- * drives either the on-phone provider loop (direct) or the external agent
- * bridge. The UI talks only to this surface, so AssistantLayer is
- * backend-agnostic.
- *
- * Sessions are cheap and idle-expire (see isExpired): the shell starts a fresh
- * one for a new wakeword and reuses the current one for a follow-up. In
- * external mode the conversation history lives on the agent's machine (one
- * long-lived session there), so expiry here only affects the overlay UI.
- */
+/** One shared conversation, independent of the voice overlay or chat window. */
+export type AssistantTranscriptEntry = { role: "user" | "assistant"; text: string };
+export type AssistantSessionHistory = {
+ messages: LlmMessage[];
+ transcript: AssistantTranscriptEntry[];
+ /** Model identity for safe replay after Auto resolves differently on restart. */
+ engine?: string;
+};
/** Which engine answers utterances, plus what it needs to do so. */
export type AssistantBackendConfig =
| { kind: "direct"; llm: ResolvedAssistantModel }
| { kind: "external"; bridge: AssistantBridgeConfig };
-/** A new PTT after this much idle starts a fresh conversation. */
-const SESSION_IDLE_MS = 10 * 60 * 1000;
-
/** Trim history from the head once it grows past this many messages. */
const MAX_HISTORY_MESSAGES = 40;
@@ -42,38 +36,61 @@ export class AssistantSession {
private readonly directBackend = new DirectAssistantBackend();
private readonly messages: LlmMessage[] = [];
private turnHandle: AssistantTurnHandle | null = null;
- private lastActivityMs = Date.now();
+ readonly transcript: AssistantTranscriptEntry[] = [];
+ status = "";
+ private readonly listeners = new Set<() => void>();
+ private turnGeneration = 0;
// API-safe tool name -> canonical registry name. Provider APIs restrict tool
// names, so dotted registry names are sanitized and mapped back on calls.
private readonly toolNameMap = new Map();
constructor(
- private readonly config: AssistantBackendConfig,
+ private config: AssistantBackendConfig,
private readonly registry: ToolRegistry = toolRegistry,
- ) {}
-
- matchesConfiguration(config: AssistantBackendConfig): boolean {
- if (this.config.kind !== config.kind) return false;
- if (this.config.kind === "direct" && config.kind === "direct") {
- return (
- this.config.llm.provider === config.llm.provider &&
- this.config.llm.model === config.llm.model &&
- this.config.llm.apiKey === config.llm.apiKey
- );
+ history?: AssistantSessionHistory,
+ ) {
+ if (history) {
+ this.messages.push(...history.messages);
+ this.transcript.push(...history.transcript);
+ if (history.engine !== this.engine()) this.rebuildTextHistory();
}
- if (this.config.kind === "external" && config.kind === "external") {
- return (
- this.config.bridge.host === config.bridge.host &&
- this.config.bridge.port === config.bridge.port &&
- this.config.bridge.token === config.bridge.token
- );
- }
- return false;
}
- /** Whether this session has been idle long enough to retire. */
- isExpired(nowMs = Date.now()): boolean {
- return nowMs - this.lastActivityMs > SESSION_IDLE_MS;
+ onChanged(listener: () => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ private changed(): void {
+ for (const listener of this.listeners) {
+ try { listener(); } catch (error) { console.warn("assistant history listener failed", error); }
+ }
+ }
+
+ history(): AssistantSessionHistory {
+ return { messages: this.messages, transcript: this.transcript, engine: this.engine() };
+ }
+
+ configure(config: AssistantBackendConfig): void {
+ if (this.isTurnActive()) return;
+ // Opaque reasoning/tool provider items are only replayable on their
+ // original model. Preserve visible conversation when switching engines.
+ if (this.config.kind !== config.kind ||
+ (this.config.kind === "direct" && config.kind === "direct" &&
+ (this.config.llm.model !== config.llm.model || this.config.llm.provider !== config.llm.provider))) {
+ this.rebuildTextHistory();
+ }
+ this.config = config;
+ }
+
+ private engine(): string {
+ return this.config.kind === "direct" ? `${this.config.llm.provider}:${this.config.llm.model}` : "external";
+ }
+
+ private rebuildTextHistory(): void {
+ this.messages.splice(0, this.messages.length, ...this.transcript
+ .filter((entry) => entry.text.trim())
+ .map((entry) => ({ role: entry.role, content: entry.text })));
}
isTurnActive(): boolean {
@@ -86,20 +103,44 @@ export class AssistantSession {
callbacks.onError("The assistant is still working on the previous request");
return;
}
- this.lastActivityMs = Date.now();
+ text = text.trim();
+ if (!text) return;
+ const generation = ++this.turnGeneration;
+ const reply: AssistantTranscriptEntry = { role: "assistant", text: "" };
+ this.transcript.push({ role: "user", text }, reply);
+ this.status = "Thinking...";
+ // Install a sentinel before calling providers: some failures are synchronous.
+ this.turnHandle = { cancel: () => {} };
+ this.changed();
const finish = () => {
+ ++this.turnGeneration;
this.turnHandle = null;
- this.lastActivityMs = Date.now();
+ this.changed();
};
const wrappedCallbacks: AssistantTurnCallbacks = {
- onTextDelta: callbacks.onTextDelta,
- onToolActivity: callbacks.onToolActivity,
+ onTextDelta: (delta, full) => {
+ if (generation !== this.turnGeneration) return;
+ reply.text = full;
+ this.status = "Thinking...";
+ this.changed();
+ callbacks.onTextDelta(delta, full);
+ },
+ onToolActivity: (label) => {
+ if (generation !== this.turnGeneration) return;
+ this.status = `→ ${label}`;
+ this.changed();
+ callbacks.onToolActivity(label);
+ },
onTurnDone: (result) => {
+ if (generation !== this.turnGeneration) return;
+ this.status = "";
finish();
callbacks.onTurnDone(result);
},
onError: (message) => {
+ if (generation !== this.turnGeneration) return;
+ this.status = message;
finish();
callbacks.onError(message);
},
@@ -108,7 +149,8 @@ export class AssistantSession {
if (this.config.kind === "external") {
// History and the agent loop live on the agent's machine; the phone just
// streams this turn. The overlay keeps its own display state.
- this.turnHandle = assistantBridge.sendUtterance(text, ctx, wrappedCallbacks);
+ const handle = assistantBridge.sendUtterance(text, ctx, wrappedCallbacks);
+ if (generation === this.turnGeneration && this.turnHandle) this.turnHandle = handle;
return;
}
@@ -123,24 +165,48 @@ export class AssistantSession {
content: isLocal ? `${text}\n\n(${describeAssistantContext(ctx)})` : text,
});
this.trimHistory();
- this.turnHandle = this.directBackend.runTurn({
+ // Work on a turn-local array: cancelled tools may finish later, and must
+ // never append orphan results into a subsequent turn's context.
+ const turnMessages = this.messages.slice();
+ const handle = this.directBackend.runTurn({
provider: llm.provider,
apiKey: llm.apiKey,
model: llm.model,
effort: llm.effort,
system: isLocal ? ASSISTANT_SYSTEM_PROMPT_BASE : buildAssistantSystemPrompt(ctx),
- messages: this.messages,
+ messages: turnMessages,
buildTools: () => this.buildToolDefinitions(),
registry: this.registry,
resolveToolName: (apiName) => this.toolNameMap.get(apiName) ?? apiName,
- callbacks: wrappedCallbacks,
+ callbacks: {
+ ...wrappedCallbacks,
+ onTurnDone: (result) => {
+ if (generation !== this.turnGeneration) return;
+ this.messages.splice(0, this.messages.length, ...turnMessages);
+ wrappedCallbacks.onTurnDone(result);
+ },
+ onError: (message) => {
+ if (generation !== this.turnGeneration) return;
+ // Retain the visible partial answer, without incomplete tool pairs.
+ if (reply.text) this.messages.push({ role: "assistant", content: reply.text });
+ wrappedCallbacks.onError(message);
+ },
+ },
});
+ if (generation === this.turnGeneration && this.turnHandle) this.turnHandle = handle;
}
cancel(): void {
- this.turnHandle?.cancel();
+ if (!this.turnHandle) return;
+ ++this.turnGeneration;
+ this.turnHandle.cancel();
this.turnHandle = null;
- this.lastActivityMs = Date.now();
+ const reply = this.transcript[this.transcript.length - 1];
+ if (reply?.role === "assistant" && reply.text) {
+ this.messages.push({ role: "assistant", content: reply.text });
+ }
+ this.status = "Cancelled";
+ this.changed();
}
private buildToolDefinitions(): LlmToolDefinition[] {
diff --git a/app/assistant/timer-tools.ts b/app/assistant/timer-tools.ts
index 088a271a..a9fe1171 100644
--- a/app/assistant/timer-tools.ts
+++ b/app/assistant/timer-tools.ts
@@ -1,76 +1,433 @@
/**
- * Shell-side timer.* assistant tools. The Timer app's own tools are
- * window-scoped ("open" tier), but "start a 5 minute timer" must work with no
- * Timer window open — so these always-available wrappers launch the app,
- * wait for its tools to register, and forward the call. Timer state lives in
- * the app's worker, which outlives its window, so list/cancel also route
- * through the app rather than answering "no timers" from the shell.
+ * The assistant's timer.* / stopwatch.* / alarm.* tools. They talk to the
+ * Timers app's engine directly (it boots with the shell), so every one works
+ * with no Timers window open; timer.set and alarm.set also bring the window
+ * forward so the wearer sees what was set.
*/
-import { toolRegistry, type ToolRegistry } from "./tool-registry";
-import { callAppToolWithLaunch } from "./launch-on-call";
+import {
+ alarmNextRingMs,
+ formatClockAt,
+ formatCountdown,
+ formatDays,
+ formatDurationWords,
+ formatElapsed,
+ formatSpanWords,
+ formatTimeOfDay,
+ MAX_TIMER_DURATION_MS,
+ parseRepeatDays,
+ parseTimeOfDay,
+ sortAlarms,
+ sortTimers,
+ stopwatchElapsedMs,
+ stopwatchIsRunning,
+ timerDisplayName,
+ timerPhase,
+ timerRemainingMs,
+ type Alarm,
+ type CountdownTimer,
+} from "../apps/timer/timer-model";
+import { timerEngine } from "../apps/timer/timer-engine";
+import { timeFormatSetting } from "../ui/dashboard-settings";
+import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
let registered = false;
-// Wrapper timeout: covers a first-launch worker spawn (up to the 5 s
-// tool-appear wait in callAppToolWithLaunch) plus the forwarded call's own
-// 10 s default budget.
-const TIMER_WRAPPER_TIMEOUT_MS = 20_000;
+function twelveHour(): boolean {
+ return timeFormatSetting.get() === "12h";
+}
-export function registerTimerTools(
- launchApp: (appId: string) => Promise,
- registry: ToolRegistry = toolRegistry,
-): void {
+/** Timers in the order the app lists them, so "timer 2" means the same thing in both places. */
+function listedTimers(): CountdownTimer[] {
+ return sortTimers(timerEngine.state.timers, Date.now());
+}
+
+function listedAlarms(): Alarm[] {
+ return sortAlarms(timerEngine.state.alarms);
+}
+
+function describeTimer(timer: CountdownTimer, number: number, now: number): string {
+ const name = timerDisplayName(timer);
+ switch (timerPhase(timer)) {
+ case "rung":
+ return `Timer ${number} (${name}): finished ${formatSpanWords(now - timer.rungAtMs!)} ago, still ringing until dismissed.`;
+ case "paused":
+ return `Timer ${number} (${name}): paused with ${formatCountdown(timerRemainingMs(timer, now))} left.`;
+ default:
+ return `Timer ${number} (${name}): ${formatCountdown(timerRemainingMs(timer, now))} left, ends at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`;
+ }
+}
+
+function describeAlarm(alarm: Alarm, number: number, now: number): string {
+ const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour());
+ const name = alarm.label ? ` (${alarm.label})` : "";
+ if (alarm.ringingSinceMs !== null) return `Alarm ${number}: ${time}${name}, ringing now.`;
+ if (!alarm.enabled) return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}, off.`;
+ const next = alarmNextRingMs(alarm, now);
+ const when = next === null ? "" : `, rings in ${formatSpanWords(next - now)}`;
+ const snoozed = alarm.snoozedUntilMs !== null ? " (snoozed)" : "";
+ return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}${when}${snoozed}.`;
+}
+
+/** Resolve a 1-based "timer"/"alarm" argument, or the only item when omitted. */
+function pickItem(items: T[], raw: unknown, noun: string, describe: (item: T, number: number) => string): T | ToolResult {
+ if (items.length === 0) return { ok: false, error: `No ${noun}s are set.` };
+ if (raw === undefined || raw === null) {
+ if (items.length === 1) return items[0]!;
+ return {
+ ok: false,
+ error: `There are ${items.length} ${noun}s; give the ${noun} number.\n${items.map(describe).join("\n")}`,
+ };
+ }
+ const index = Math.floor(Number(raw));
+ if (!Number.isFinite(index) || index < 1 || index > items.length) {
+ return { ok: false, error: `No ${noun} ${raw}; there are ${items.length} ${noun}s.` };
+ }
+ return items[index - 1]!;
+}
+
+function isResult(value: unknown): value is ToolResult {
+ return !!value && typeof value === "object" && "ok" in (value as object) && !("id" in (value as object));
+}
+
+function durationField(value: unknown, label: string): number {
+ if (value === undefined || value === null || value === "") return 0;
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`Invalid ${label} value: ${value}`);
+ return parsed;
+}
+
+const NUMBER_ARG = (noun: string, listTool: string) => ({
+ type: "number",
+ description: `1-based ${noun} number, as shown by ${listTool}. May be omitted when only one ${noun} exists.`,
+});
+
+export function registerTimerTools(launchApp: (appId: string) => Promise, registry: ToolRegistry = toolRegistry): void {
if (registered) return;
registered = true;
+ const showApp = () => {
+ void launchApp("timer").catch((error) => console.warn(`timer tool launch failed: ${error}`));
+ };
+
+ // --- timers ---
+
registry.registerSystemTool(
{
name: "timer.set",
description:
- "Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds; at least one must be nonzero. Opens the Timer app if it isn't already open. Returns the timer's number and when it will finish.",
+ "Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds (at least one nonzero) and optionally a label such as \"pasta\". Returns the timer's number and when it will finish.",
inputSchema: {
type: "object",
properties: {
hours: { type: "number", description: "Hours component of the duration (default 0)." },
minutes: { type: "number", description: "Minutes component of the duration (default 0)." },
seconds: { type: "number", description: "Seconds component of the duration (default 0)." },
+ label: { type: "string", description: "Optional short name for the timer." },
},
additionalProperties: false,
},
- timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
- (args) => callAppToolWithLaunch(registry, launchApp, "timer", "set_timer", args ?? {}),
+ (args) => {
+ const durationMs = Math.round(
+ ((durationField(args?.hours, "hours") * 60 + durationField(args?.minutes, "minutes")) * 60 +
+ durationField(args?.seconds, "seconds")) *
+ 1000,
+ );
+ if (durationMs <= 0) return { ok: false, error: "timer.set requires a duration longer than zero." };
+ if (durationMs > MAX_TIMER_DURATION_MS) return { ok: false, error: "Timers can run for at most 24 hours." };
+ const label = typeof args?.label === "string" ? args.label.trim() : "";
+ const timer = timerEngine.startTimer(durationMs, label);
+ showApp();
+ const number = listedTimers().indexOf(timer) + 1;
+ return {
+ ok: true,
+ content: `Started a ${formatDurationWords(durationMs)} timer${label ? ` "${label}"` : ""} (timer ${number}), finishing at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`,
+ };
+ },
);
registry.registerSystemTool(
{
name: "timer.list",
description:
- "List the countdown timers on the glasses: each timer's number, its original duration, and the time remaining (or that it has finished). Opens the Timer app if it isn't already open — timers keep running while its window is closed.",
+ "List the countdown timers on the glasses: each timer's number, name, time remaining (or paused / finished), and end time.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
- timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
- () => callAppToolWithLaunch(registry, launchApp, "timer", "list_timers", {}),
+ () => {
+ const timers = listedTimers();
+ if (timers.length === 0) return { ok: true, content: "No timers are set." };
+ const now = Date.now();
+ return { ok: true, content: timers.map((timer, index) => describeTimer(timer, index + 1, now)).join("\n") };
+ },
);
registry.registerSystemTool(
{
name: "timer.cancel",
description:
- "Cancel a running countdown timer on the glasses, or dismiss a finished one. Give the timer number from timer.list; it may be omitted when only one timer exists. Pass all=true to clear every timer. Opens the Timer app if it isn't already open.",
+ "Cancel a countdown timer, or dismiss a finished one. Give the timer number from timer.list (omit it when only one exists), or all=true to clear every timer.",
inputSchema: {
type: "object",
properties: {
- timer: { type: "number", description: "1-based timer number, as shown by timer.list." },
+ timer: NUMBER_ARG("timer", "timer.list"),
all: { type: "boolean", description: "Clear all timers instead of a single one." },
},
additionalProperties: false,
},
- timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
- (args) => callAppToolWithLaunch(registry, launchApp, "timer", "cancel_timer", args ?? {}),
+ (args) => {
+ const timers = listedTimers();
+ if (args?.all === true) {
+ if (timers.length === 0) return { ok: true, content: "No timers are set." };
+ for (const timer of timers) timerEngine.removeTimer(timer.id);
+ return { ok: true, content: timers.length === 1 ? "Cleared the timer." : `Cleared ${timers.length} timers.` };
+ }
+ const now = Date.now();
+ const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
+ if (isResult(picked)) return picked;
+ const description = describeTimer(picked, timers.indexOf(picked) + 1, now);
+ timerEngine.removeTimer(picked.id);
+ return { ok: true, content: `${timerPhase(picked) === "rung" ? "Dismissed" : "Canceled"}: ${description}` };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "timer.pause",
+ description: "Pause a running countdown timer, or resume a paused one. Give the timer number from timer.list (omit it when only one exists).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ timer: NUMBER_ARG("timer", "timer.list"),
+ resume: { type: "boolean", description: "true to resume a paused timer instead of pausing." },
+ },
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const timers = listedTimers();
+ const now = Date.now();
+ const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
+ if (isResult(picked)) return picked;
+ const phase = timerPhase(picked);
+ if (phase === "rung") return { ok: false, error: "That timer has already finished; dismiss it with timer.cancel." };
+ const resume = args?.resume === true || phase === "paused";
+ if (resume) timerEngine.resumeTimer(picked.id);
+ else timerEngine.pauseTimer(picked.id);
+ const updated = timerEngine.findTimer(picked.id)!;
+ return { ok: true, content: `${resume ? "Resumed" : "Paused"} ${describeTimer(updated, timers.indexOf(picked) + 1, Date.now())}` };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "timer.add_time",
+ description: "Add minutes to a countdown timer (a finished one restarts with just the added time). Give the timer number from timer.list (omit it when only one exists).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ timer: NUMBER_ARG("timer", "timer.list"),
+ minutes: { type: "number", description: "Minutes to add (default 1)." },
+ },
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const timers = listedTimers();
+ const now = Date.now();
+ const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
+ if (isResult(picked)) return picked;
+ const minutes = args?.minutes === undefined ? 1 : Number(args.minutes);
+ if (!Number.isFinite(minutes) || minutes <= 0) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` };
+ timerEngine.addTimerTime(picked.id, Math.round(minutes * 60_000));
+ const updated = timerEngine.findTimer(picked.id)!;
+ return { ok: true, content: `Added ${formatDurationWords(minutes * 60_000)}. ${describeTimer(updated, listedTimers().indexOf(updated) + 1, Date.now())}` };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "timer.dismiss",
+ description: "Stop whatever is ringing on the glasses right now: finished timers are cleared and ringing alarms dismissed.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ proactive: true,
+ },
+ () => {
+ const count = timerEngine.dismissAllRinging();
+ return { ok: true, content: count === 0 ? "Nothing is ringing." : `Dismissed ${count === 1 ? "it" : `${count} items`}.` };
+ },
+ );
+
+ // --- stopwatch ---
+
+ registry.registerSystemTool(
+ {
+ name: "stopwatch.control",
+ description:
+ "Control the stopwatch on the glasses: action start, stop, lap, reset, or read (report the elapsed time and laps without changing anything).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: { type: "string", enum: ["start", "stop", "lap", "reset", "read"], description: "What to do." },
+ },
+ required: ["action"],
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const action = String(args?.action ?? "read");
+ switch (action) {
+ case "start":
+ timerEngine.stopwatchStart();
+ showApp();
+ break;
+ case "stop":
+ timerEngine.stopwatchStop();
+ break;
+ case "lap":
+ if (!stopwatchIsRunning(timerEngine.state.stopwatch)) return { ok: false, error: "The stopwatch is not running." };
+ timerEngine.stopwatchLap();
+ break;
+ case "reset":
+ timerEngine.stopwatchReset();
+ break;
+ case "read":
+ break;
+ default:
+ return { ok: false, error: `Unknown stopwatch action: ${action}` };
+ }
+ const stopwatch = timerEngine.state.stopwatch;
+ const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, Date.now()), true);
+ const state = stopwatchIsRunning(stopwatch) ? "running" : "stopped";
+ const laps = stopwatch.lapsMs.length > 0 ? ` Laps: ${stopwatch.lapsMs.map((lap) => formatElapsed(lap, true)).join(", ")}.` : "";
+ return { ok: true, content: `Stopwatch ${state} at ${elapsed}.${laps}` };
+ },
+ );
+
+ // --- alarms ---
+
+ registry.registerSystemTool(
+ {
+ name: "alarm.set",
+ description:
+ "Set an alarm on the glasses. Give the time of day (e.g. \"7:30\", \"7:30 am\", \"19:30\"), optional repeat days (day names, \"weekdays\", \"weekends\", \"every day\"; default once), and an optional label.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ time: { type: "string", description: "Time of day, 12- or 24-hour." },
+ days: {
+ type: "array",
+ items: { type: "string" },
+ description: "Repeat days: day names or weekdays / weekends / every day. Omit for a one-off alarm.",
+ },
+ label: { type: "string", description: "Optional short name for the alarm." },
+ },
+ required: ["time"],
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const time = parseTimeOfDay(String(args?.time ?? ""));
+ if (!time) return { ok: false, error: `Could not understand the time "${args?.time}". Use a form like 7:30 am or 19:30.` };
+ const days = parseRepeatDays(args?.days);
+ if (days === null) return { ok: false, error: `Could not understand the repeat days ${JSON.stringify(args?.days)}.` };
+ const label = typeof args?.label === "string" ? args.label.trim() : "";
+ const alarm = timerEngine.addAlarm(time.hour, time.minute, days, label);
+ showApp();
+ const now = Date.now();
+ return { ok: true, content: `Set. ${describeAlarm(alarm, listedAlarms().indexOf(alarm) + 1, now)}` };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "alarm.list",
+ description: "List the alarms on the glasses: each alarm's number, time, repeat days, label, and whether it is on.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ proactive: true,
+ },
+ () => {
+ const alarms = listedAlarms();
+ if (alarms.length === 0) return { ok: true, content: "No alarms are set." };
+ const now = Date.now();
+ return { ok: true, content: alarms.map((alarm, index) => describeAlarm(alarm, index + 1, now)).join("\n") };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "alarm.enable",
+ description: "Turn an alarm on or off without deleting it. Give the alarm number from alarm.list (omit it when only one exists).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ alarm: NUMBER_ARG("alarm", "alarm.list"),
+ enabled: { type: "boolean", description: "true to turn the alarm on, false to turn it off." },
+ },
+ required: ["enabled"],
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const alarms = listedAlarms();
+ const now = Date.now();
+ const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now));
+ if (isResult(picked)) return picked;
+ timerEngine.setAlarmEnabled(picked.id, args?.enabled !== false);
+ const updated = timerEngine.findAlarm(picked.id)!;
+ return { ok: true, content: describeAlarm(updated, alarms.indexOf(picked) + 1, Date.now()) };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "alarm.delete",
+ description: "Delete an alarm. Give the alarm number from alarm.list (omit it when only one exists).",
+ inputSchema: {
+ type: "object",
+ properties: { alarm: NUMBER_ARG("alarm", "alarm.list") },
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const alarms = listedAlarms();
+ const now = Date.now();
+ const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now));
+ if (isResult(picked)) return picked;
+ const description = describeAlarm(picked, alarms.indexOf(picked) + 1, now);
+ timerEngine.deleteAlarm(picked.id);
+ return { ok: true, content: `Deleted: ${description}` };
+ },
+ );
+
+ registry.registerSystemTool(
+ {
+ name: "alarm.snooze",
+ description: "Snooze the alarm that is ringing now. Optionally give the snooze length in minutes (default: the Timers app's snooze setting).",
+ inputSchema: {
+ type: "object",
+ properties: { minutes: { type: "number", description: "Snooze length in minutes." } },
+ additionalProperties: false,
+ },
+ proactive: true,
+ },
+ (args) => {
+ const ringing = timerEngine.state.alarms.filter((alarm) => alarm.ringingSinceMs !== null);
+ if (ringing.length === 0) return { ok: false, error: "No alarm is ringing." };
+ const minutes = args?.minutes === undefined ? undefined : Number(args.minutes);
+ if (minutes !== undefined && (!Number.isFinite(minutes) || minutes <= 0)) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` };
+ for (const alarm of ringing) timerEngine.snoozeAlarm(alarm.id, minutes);
+ const updated = timerEngine.findAlarm(ringing[0]!.id)!;
+ return { ok: true, content: `Snoozed until ${formatClockAt(updated.snoozedUntilMs!, twelveHour())}.` };
+ },
);
}
diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts
index ab8117b8..70800f24 100644
--- a/app/g2/dashboard-controller.ts
+++ b/app/g2/dashboard-controller.ts
@@ -12,7 +12,8 @@ import * as frameTimings from "../native/frame-timings";
import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service";
import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout-bridge";
-import { onAndroidNotificationPosted } from "../native/notification-icons";
+import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, readActiveNotifications } from "../native/notification-icons";
+import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage } from "./firmware-compat";
@@ -52,11 +53,12 @@ import { getDefaultMediumFont } from "../graphics/ui-fonts";
import { wrapText } from "../graphics/textwrap";
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
import { registerSystemTools } from "../assistant/system-tools";
+import { updateGlassesPresence } from "./glasses-presence";
+import { timerEngine } from "../apps/timer/timer-engine";
import { registerNavigateTools } from "../assistant/navigate-tools";
import { registerRoamTools } from "../assistant/roam-tools";
import { assistantBridge } from "../assistant/bridge-client";
import { registerWindowTools } from "../assistant/window-tools";
-import { registerTimerTools } from "../assistant/timer-tools";
import { WorkerAppHost } from "../ui/shell/worker-window";
import { ALL_APPS } from "../apps/all-apps";
import { type AppContext, type AppDefinition, type AppLaunchParams, type TextEditorHost } from "../apps/app-definition";
@@ -64,7 +66,8 @@ import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-p
import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-apps-persistence";
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
-import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
+import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
+import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, displayModeSetting, navigateDisplayModeSetting, navigateVerticalPositionSetting, terminalDisplayModeSetting, terminalVerticalPositionSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -72,6 +75,8 @@ import {
uninstallEvenHubPackage,
} from "../apps/evenhub/installed-apps";
import { closeRunningPackage, launchInstalledPackage } from "../apps/evenhub/manager";
+import { openEvenHubStoreForPackage } from "../apps/evenhub";
+import { isInstalledPackagePresent } from "../apps/evenhub/updates";
import { wearerVerificationOptions } from "../apps/microphones/speakers";
import { micSession } from "../apps/microphones/mic-session";
import { glassesDisplayLabel } from "./glasses-display-state";
@@ -102,6 +107,13 @@ export type DashboardSnapshot = {
activeTextEditorToggleLabel: string;
activeTextEditorToggleValue: boolean;
activeTextEditorToggleVisible: boolean;
+ /**
+ * The keyboard dialog is up on the glasses (opened by the phone's keyboard
+ * button): the phone shows its typing panel, with a send button per
+ * destination in the glasses menu's row order.
+ */
+ keyboardInputActive: boolean;
+ keyboardInputTargets: ReadonlyArray<{ id: string; label: string }>;
evenAppConflictMessage: string;
evenAppConflictWarningVisible: boolean;
firmwareWarningMessage: string;
@@ -109,6 +121,8 @@ export type DashboardSnapshot = {
screenRecordingActive: boolean;
batteryOptimizationWarningVisible: boolean;
fontsMissingWarningVisible: boolean;
+ /** Why the phone may fail to ring for a set alarm; "" when nothing is wrong or armed. */
+ alarmReliabilityMessage: string;
/**
* True while the headless preview display is standing in for a glasses
* connection (preview-only mode): the mirror is live and interactive, but
@@ -122,6 +136,8 @@ type DashboardListener = (snapshot: DashboardSnapshot) => void;
// The shell chrome (sidebar + top bar + overlays) composites above all app
// window surfaces with color-key transparency.
const SHELL_SURFACE_ID = "shell";
+/** The shell chrome composites above every window surface (zOrder 0). */
+const SHELL_SURFACE_Z_ORDER = 1;
const LOCK_SCREEN_SURFACE_ID = "lock-screen";
const LOCK_SCREEN_MESSAGE = "Glasses locked; unlock the phone to unlock the glasses.";
// Top-bar clock refresh; the phone-side preview polls the Java composite so
@@ -210,6 +226,7 @@ class DashboardController {
private firmwareWarningMessage = "";
private batteryOptimizationWarningVisible = false;
private fontsMissingWarningVisible = false;
+ private alarmReliabilityMessage = "";
// Sticky positive: the extracted-font file doesn't vanish mid-session, so a
// successful check spares later refreshes the file read and JSON parse.
private extractedFontsConfirmed = false;
@@ -265,11 +282,16 @@ class DashboardController {
/** Input frame that requested the next shell render; see requestShellRender. */
private pendingShellRenderCauseFrameId = 0;
private nextShellRenderWantsFreshData = false;
+ /** The under-shell dim last sent to the display (see Shell.underlayDim); 1 = none. */
+ private appliedUnderlayDim = 1;
// One shared worker per app hosts all its windows; spawned on first launch.
private readonly appHosts = new Map();
// The window hosting the on-glasses text-setting editor (the Settings app
// registers itself); edit flows from the phone UI reach it through this.
private textEditorHost: TextEditorHost | null = null;
+ // The open keyboard dialog's session (see Shell.startKeyboardInput); the
+ // phone's typing panel feeds it.
+ private keyboardInput: KeyboardInputSession | null = null;
// Other in-process singleton apps, keyed by windowId.
private readonly inProcessApps = new Map();
private sharedActions!: Omit;
@@ -297,7 +319,7 @@ class DashboardController {
toggle?: TextSettingsEditToggle,
) => this.startTextSettingsEdit(settings, title, onFinish, toggle),
endTextSettingEdit: () => this.endTextSettingEdit(),
- startVoiceCapture: () => this.startVoiceCapture(),
+ startVoiceCapture: (endpointing = false) => this.startVoiceCapture(endpointing),
stopVoiceCapture: () => this.stopVoiceCapture(),
startContinuousVoiceCapture: () => this.startContinuousVoiceCapture(),
stopContinuousVoiceCapture: () => this.stopContinuousVoiceCapture(),
@@ -311,8 +333,6 @@ class DashboardController {
registerNavigateTools((appId) => this.launchApp(appId));
// roam.* tools launch the Roam app on demand likewise.
registerRoamTools((appId) => this.launchApp(appId));
- // timer.* tools launch the Timer app on demand likewise.
- registerTimerTools((appId) => this.launchApp(appId));
// apps.* tools mirror the launcher grid and sidebar (launch, focus, close).
registerWindowTools({
apps: LAUNCHABLE_APPS,
@@ -329,6 +349,10 @@ class DashboardController {
getScreenTimeoutMs: () => screenTimeoutSettingToMs(screenTimeoutSetting.get()),
requestShellRender: () => this.requestShellRender(),
prepareVoiceCapture: () => this.prepareVoiceCapture(),
+ onKeyboardInputChanged: (session) => {
+ this.keyboardInput = session;
+ this.emit();
+ },
onWindowsChanged: () => {
this.persistOpenApps();
// The foreground title is mirrored on both remote-control faces.
@@ -345,11 +369,13 @@ class DashboardController {
for (const app of ALL_APPS) {
app.boot?.(this.buildAppContext(app));
}
+ timerEngine.onChange(() => this.refreshAlarmReliabilityWarning());
this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => {
void this.handleAndroidNotificationPosted(notificationKey).catch((error) => {
this.appendLog(`notification wake failed: ${this.formatError(error)}`);
});
});
+ readActiveNotifications(ALL_NOTIFICATIONS);
// Settings toggled from the glasses can change what the phone UI shows
// (e.g. the text-setting editor), so re-emit the snapshot on any change.
onAnySettingChanged(() => {
@@ -360,6 +386,7 @@ class DashboardController {
this.syncEvenHubScreenOffSetting();
this.applyVerticalPositionIfChanged();
this.applyDisplayModeIfChanged();
+ this.applyAppLayoutsIfChanged();
this.syncAssistantBridgeIfChanged();
this.syncLockScreenSettingIfChanged();
// A Preview color change should show on the mirror at once, not at the
@@ -437,8 +464,8 @@ class DashboardController {
/**
* Display mode changed (Settings > Display, or the phone page's picker):
* every window's viewport size changes. In-process windows re-measure in
- * place; worker windows get their canvas once at open, so they are closed
- * and launched again at the new size.
+ * place; workers that support resizing receive the new viewport. Other
+ * worker windows are closed and launched again at the new size.
*/
private applyDisplayModeIfChanged(): void {
const mode = displayModeSetting.get();
@@ -474,6 +501,31 @@ class DashboardController {
});
}
+ private lastAppLayouts = this.appLayouts();
+
+ private appLayouts(): Record {
+ return {
+ navigate: `${navigateDisplayModeSetting.get()}:${navigateVerticalPositionSetting.get()}`,
+ terminal: `${terminalDisplayModeSetting.get()}:${terminalVerticalPositionSetting.get()}`,
+ };
+ }
+
+ private applyAppLayoutsIfChanged(): void {
+ const layouts = this.appLayouts();
+ const changed = Object.keys(layouts).filter((appId) => layouts[appId] !== this.lastAppLayouts[appId]);
+ if (!changed.length) return;
+ this.lastAppLayouts = layouts;
+ void (async () => {
+ for (const window of Array.from(shell.getWindows())) {
+ if (!changed.includes(window.appId)) continue;
+ await this.configureWindowSurface(window.surfaceId, window.windowId === shell.foregroundWindow()?.windowId, window.heightMode);
+ window.relayout?.();
+ }
+ shell.foregroundWindow()?.requestRender();
+ this.requestShellRender();
+ })().catch((error) => this.appendLog(`app layout change failed: ${this.formatError(error)}`));
+ }
+
private applyVerticalPositionIfChanged(): void {
const position = verticalPositionSetting.get();
if (position === this.lastVerticalPosition) return;
@@ -546,6 +598,7 @@ class DashboardController {
private handleWearState(wearing: boolean): void {
this.glassesWorn = wearing;
+ updateGlassesPresence({ worn: wearing });
this.appendLog(wearing ? "glasses wear state: ON_HEAD" : "glasses wear state: OFF_HEAD");
this.wearRemote?.schedulePublish();
if (!wearing && this.phoneLocked && lockScreenEnabledSetting.get()) {
@@ -905,6 +958,8 @@ class DashboardController {
activeTextEditorToggleLabel: this.activeTextEditorToggle?.label ?? "",
activeTextEditorToggleValue: this.activeTextEditorToggle?.setting.get() ?? false,
activeTextEditorToggleVisible: this.activeTextEditorToggle !== null,
+ keyboardInputActive: this.keyboardInput !== null,
+ keyboardInputTargets: this.keyboardInput?.targets ?? [],
evenAppConflictMessage: this.evenAppConflictMessage,
evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0,
firmwareWarningMessage: this.firmwareWarningMessage,
@@ -912,6 +967,7 @@ class DashboardController {
screenRecordingActive: this.screenRecordingActive,
batteryOptimizationWarningVisible: this.batteryOptimizationWarningVisible,
fontsMissingWarningVisible: this.fontsMissingWarningVisible,
+ alarmReliabilityMessage: this.alarmReliabilityMessage,
previewMode: this.isPreviewDisplayActive(),
};
}
@@ -1003,9 +1059,35 @@ class DashboardController {
}
}
+ /**
+ * Mirror the Timers engine's phone self-check into the warnings modal. The
+ * engine re-checks on its own schedule and on every timer/alarm change;
+ * a page load forces a fresh check so a just-fixed setting clears at once.
+ */
+ refreshAlarmReliabilityWarning(force = false): void {
+ if (force) timerEngine.refreshReliability(true);
+ const message = timerEngine.phoneReliabilityMessage();
+ if (message !== this.alarmReliabilityMessage) {
+ this.alarmReliabilityMessage = message;
+ this.emit();
+ }
+ }
+
+ openAlarmReliabilityFix(): void {
+ timerEngine.openPhoneReliabilityFix();
+ // The system screen is asynchronous with no result; poll briefly so the
+ // warning clears once the setting is changed.
+ let checksLeft = 12;
+ const poll = setInterval(() => {
+ this.refreshAlarmReliabilityWarning(true);
+ if (!this.alarmReliabilityMessage || --checksLeft <= 0) clearInterval(poll);
+ }, 5_000);
+ }
+
refreshEvenAppStatus(): void {
this.refreshBatteryOptimizationStatus();
this.refreshEvenHubFontStatus();
+ this.refreshAlarmReliabilityWarning(true);
const state = readEvenAppNotificationState();
const wasActive = this.evenNotificationActive;
this.evenNotificationActive = state.evenNotificationActive;
@@ -1041,6 +1123,39 @@ class DashboardController {
this.previewOrRenderAfterTextSettingChange();
}
+ /**
+ * The phone's keyboard button: open the keyboard dialog on the glasses
+ * (the typed twin of the mic button's wakeword). Needs a display to draw
+ * on and, like ring input, does nothing while the glasses are locked.
+ */
+ startKeyboardInput(): void {
+ if (this.phase !== "connected" && this.phase !== "charging" && !this.isPreviewDisplayActive()) return;
+ if (this.glassesLocked) {
+ this.appendLog("keyboard input ignored while the glasses are locked");
+ return;
+ }
+ shell.startKeyboardInput();
+ }
+
+ /** The phone's typing panel changed: mirror the text on the glasses. */
+ setKeyboardInputText(text: string): void {
+ shell.noteUserActivity();
+ this.keyboardInput?.setText(text);
+ }
+
+ /** Send to one destination, or (no id: the IME's send key) the one highlighted on the glasses. */
+ sendKeyboardInput(targetId?: string): void {
+ if (targetId) {
+ this.keyboardInput?.sendTo(targetId);
+ } else {
+ this.keyboardInput?.send();
+ }
+ }
+
+ discardKeyboardInput(): void {
+ this.keyboardInput?.discard();
+ }
+
setActiveTextEditorToggleValue(value: boolean): void {
if (!this.activeTextEditorToggle || this.activeTextEditorToggle.setting.get() === value) return;
this.activeTextEditorToggle.setting.set(value);
@@ -1084,9 +1199,13 @@ class DashboardController {
y: 0,
width: G2_LENS_WIDTH,
height: G2_LENS_HEIGHT,
- zOrder: 1,
+ zOrder: SHELL_SURFACE_Z_ORDER,
transparency: "color-key",
});
+ // A fresh (or reused) compositor starts undimmed; the shell render
+ // loop re-applies the current dim from here.
+ await target.setUnderlayDim(SHELL_SURFACE_Z_ORDER, 1);
+ this.appliedUnderlayDim = 1;
const foregroundWindowId = shell.foregroundWindow()?.windowId;
for (const window of shell.getWindows()) {
await this.configureWindowSurface(
@@ -1233,6 +1352,7 @@ class DashboardController {
// the transport comes back, so do not make lock decisions from a
// stale pre-disconnect value in the meantime.
this.glassesWorn = null;
+ updateGlassesPresence({ worn: null });
// The mic enable was session-scoped too: park any live capture so
// the next session restarts it, instead of leaving a holder that
// makes every later request think the mic is already running.
@@ -1270,10 +1390,16 @@ class DashboardController {
// especially while the glasses remain reachable in their case.
const hasBatteryLevel = Number.isInteger(state.battery) && state.battery >= 0 && state.battery <= 100;
if (hasBatteryLevel) this.lastHeadsetBattery = state.battery;
+ const ringBattery = state.ringBattery;
+ const hasRingBattery = typeof ringBattery === "number" && Number.isInteger(ringBattery)
+ && ringBattery >= 0 && ringBattery <= 100;
shell.setBatteryLevels({
headset: hasBatteryLevel ? state.battery : this.lastHeadsetBattery,
headsetCharging: state.chargingStatus > 0,
+ ring: hasRingBattery ? ringBattery : null,
+ ringCharging: hasRingBattery ? state.ringChargingStatus === 1 : null,
});
+ updateGlassesPresence({ charging: state.chargingStatus > 0 || this.phase === "charging" });
if ((this.phase === "connected" || this.phase === "charging") && this.communicator) {
// Repaint the top bar (battery indicators live in the shell chrome).
this.requestShellRender();
@@ -1364,9 +1490,13 @@ class DashboardController {
y: 0,
width: G2_LENS_WIDTH,
height: G2_LENS_HEIGHT,
- zOrder: 1,
+ zOrder: SHELL_SURFACE_Z_ORDER,
transparency: "color-key",
});
+ // A fresh (or reused) compositor starts undimmed; the shell render
+ // loop re-applies the current dim from here.
+ await communicator.setUnderlayDim(SHELL_SURFACE_Z_ORDER, 1);
+ this.appliedUnderlayDim = 1;
await this.configureLockSurface(communicator);
const foregroundWindowId = shell.foregroundWindow()?.windowId;
for (const window of shell.getWindows()) {
@@ -1684,7 +1814,7 @@ class DashboardController {
}
const x = Math.round(Math.min(1, Math.max(0, nx)) * G2_LENS_WIDTH);
const y = Math.round(Math.min(1, Math.max(0, ny)) * G2_LENS_HEIGHT);
- const stripShown = sidebarStripVisible(shell.getFocus());
+ const stripShown = sidebarStripVisible(shell.getFocus(), shell.foregroundWindow()?.appId);
this.appendLog(`mirror tap at ${x},${y}`);
if (!shell.hasOverlay() && stripShown && x < SIDEBAR_WIDTH) {
const target = shell.windowAtSidebarPoint(x, y);
@@ -1698,7 +1828,7 @@ class DashboardController {
}
const window = shell.foregroundWindow();
if (window && !shell.hasOverlay()) {
- const rect = appViewportRect(window.heightMode);
+ const rect = appViewportRect(window.heightMode, window.appId);
const inside = x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
if (shell.getFocus() !== "window") {
shell.focusWindow(window.windowId);
@@ -1749,11 +1879,14 @@ class DashboardController {
* push-to-talk and the Transcribe app. Android mic permission is the consent
* gate even though the audio source is the G2 mic over BLE.
*/
- private startVoiceCapture(endpointing = false): void {
- this.beginVoiceCapture("ptt", endpointing);
+ private pttCaptureGeneration = 0;
+
+ private startVoiceCapture(endpointing = false): Promise {
+ return this.beginVoiceCapture("ptt", endpointing);
}
private stopVoiceCapture(): void {
+ ++this.pttCaptureGeneration;
voiceControlBridge.stopPushToTalk();
}
@@ -1819,7 +1952,8 @@ class DashboardController {
return granted;
}
- private beginVoiceCapture(kind: "ptt" | "continuous", endpointing = false): void {
+ private async beginVoiceCapture(kind: "ptt" | "continuous", endpointing = false): Promise {
+ const pttGeneration = kind === "ptt" ? ++this.pttCaptureGeneration : 0;
// Preview mode captures from the phone mic (voiceCaptureOptions with a
// null communicator); otherwise a live glasses session must be the source.
const previewCapture = this.isPreviewDisplayActive();
@@ -1827,8 +1961,9 @@ class DashboardController {
return;
}
const communicator = this.communicator;
- void ensureVoicePermissions()
+ await ensureVoicePermissions()
.then(() => {
+ if (kind === "ptt" && pttGeneration !== this.pttCaptureGeneration) return;
if (previewCapture) {
if (!this.isPreviewDisplayActive()) return;
} else if (this.phase !== "connected" || this.communicator !== communicator) {
@@ -2156,6 +2291,13 @@ class DashboardController {
const installed = getInstalledEvenHubAppById(appId);
if (installed) {
const host = ALL_APPS.find((entry) => entry.appId === "evenhub")!;
+ if (!isInstalledPackagePresent(installed.packageId)) {
+ // The registry knows the app but its package is gone (a settings
+ // import after a reinstall): offer the store's Reinstall page.
+ this.appendLog(`evenhub: package missing for ${installed.packageId}; opening store page`);
+ await openEvenHubStoreForPackage(this.buildAppContext(host), installed);
+ return;
+ }
await launchInstalledPackage(this.buildAppContext({ ...host, appId }), installed);
return;
}
@@ -2184,7 +2326,7 @@ class DashboardController {
): Promise {
if (!target) return;
await target.configureSurface(surfaceId, {
- ...appViewportRect(heightMode),
+ ...appViewportRect(heightMode, shell.getWindows().find((window) => window.surfaceId === surfaceId)?.appId),
zOrder: 0,
transparency: "opaque",
});
@@ -2292,6 +2434,14 @@ class DashboardController {
frameTimings.finishFrame(frameId, "discarded: shell render with no display target");
return;
}
+ // A shell overlay that dims what it covers (a context menu) must dim the
+ // window surfaces too, which live below the shell surface in the
+ // compositor: forward the factor before this frame composites.
+ const underlayDim = shell.underlayDim();
+ if (underlayDim !== this.appliedUnderlayDim) {
+ this.appliedUnderlayDim = underlayDim;
+ await display.setUnderlayDim(SHELL_SURFACE_Z_ORDER, underlayDim);
+ }
const fingerprint = frameTimings.span(frameId, "fingerprint", () => planesFingerprint(planes));
const { image, draws } = frameTimings.span(frameId, "flatten", () => flattenPlanesWithDraws(planes));
const buffer = frameTimings.span(frameId, "to8bpp", () => image.to8bppBuffer());
@@ -2326,7 +2476,8 @@ class DashboardController {
}
private async handleAndroidNotificationPosted(notificationKey: string): Promise {
- if (!notificationKey) {
+ const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
+ if (!notification || !shouldShowNotificationOnGlasses(notification.packageName)) {
this.requestShellRender();
return;
}
@@ -2386,6 +2537,14 @@ class DashboardController {
private setPhase(phase: ConnectionPhase): void {
if (this.phase === phase) return;
this.phase = phase;
+ if (phase !== "connected" && phase !== "charging") {
+ shell.setBatteryLevels({ ring: null, ringCharging: null });
+ }
+ // "charging" is a live BLE link with the glasses in their case.
+ updateGlassesPresence({
+ connected: phase === "connected" || phase === "charging",
+ charging: phase === "charging" || (shell.getBatteryLevels().headsetCharging ?? false),
+ });
if (phase === "disconnected") {
// Kept across "connecting": silent mode blocks app launches, so it can
// itself cause the reconnect churn, and Java re-reports it either way.
@@ -2494,6 +2653,7 @@ class DashboardController {
| "scroll-down"
| "long-press"
| "long-press-release"
+ | "short-then-long-press"
| "wakeword"
| "swipe-left"
| "swipe-right"
@@ -2553,6 +2713,17 @@ class DashboardController {
systemExitReasonCode: 0,
frameId,
};
+ case "short-then-long-press":
+ // Discrete, unlike a hold: the firmware's later generic release is a
+ // hardware artifact the shell ignores, so synthetic sources send none.
+ return {
+ kind: "sys-event",
+ containerName: "",
+ eventType: OsEventTypeList.SHORT_THEN_LONG_PRESS_EVENT,
+ eventSource,
+ systemExitReasonCode: 0,
+ frameId,
+ };
case "click":
return {
kind: "sys-event",
diff --git a/app/g2/events.ts b/app/g2/events.ts
index 139c261e..877dd901 100644
--- a/app/g2/events.ts
+++ b/app/g2/events.ts
@@ -69,6 +69,8 @@ export const OsEventTypeList = {
IMU_DATA_REPORT: 8,
RING_LONG_PRESS_EVENT: 9,
RING_LONG_PRESS_RELEASE_EVENT: 10,
+ /** CFW extension: the 2.2.9 tap-then-hold Menu gesture. */
+ SHORT_THEN_LONG_PRESS_EVENT: 11,
} as const;
export const OsEventTypeName: Record = {
@@ -83,4 +85,5 @@ export const OsEventTypeName: Record = {
8: "IMU_DATA_REPORT",
9: "RING_LONG_PRESS_EVENT",
10: "RING_LONG_PRESS_RELEASE_EVENT",
+ 11: "SHORT_THEN_LONG_PRESS_EVENT",
};
diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts
index 4d2c4f3a..cd728af0 100644
--- a/app/g2/firmware-builder.ts
+++ b/app/g2/firmware-builder.ts
@@ -1,6 +1,7 @@
/**
* Builds the Faceclaw custom firmware on-device: downloads the stock Even
- * Realities G2 2.2.6.10 image from Even's CDN, verifies its SHA-256, applies
+ * Realities G2 image the patch set was built against (CFW_PATCH_SET.base,
+ * currently 2.2.9.22) from Even's CDN, verifies its SHA-256, applies
* the committed byte-patch set (cfw-patches.ts), extracts the stock EvenHub
* fonts for phone-side rendering, verifies the patched SHA-256, and writes the
* result to app storage.
@@ -24,9 +25,15 @@ import { EvenHubFont } from "../graphics/evenhub-font";
declare const com: any;
-const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/e28738432d7b612d625331b00383149b.bin";
-const CFW_OUTPUT_FILENAME = "g2_2.2.6.10_cfw.bin";
-const STOCK_OUTPUT_FILENAME = "g2_2.2.6.10.bin";
+// The CDN names firmware files by MD5. This must be the image whose SHA-256 is
+// CFW_PATCH_SET.baseSha256 — keep it in sync with FW_URL in g2flash/build_cfw.sh
+// whenever cfw-patches.ts is regenerated against a new stock base.
+// (2.2.9.22 = fc250b05…; the older 2.2.6.10 base was e2873843….)
+const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/fc250b05e98a9ff998b4b68f5f99f994.bin";
+// Output names follow the patch set's base name (e.g. g2_2.2.9.22.bin →
+// g2_2.2.9.22_cfw.bin) so a rebase can't leave stale version numbers here.
+const STOCK_OUTPUT_FILENAME = CFW_PATCH_SET.base;
+const CFW_OUTPUT_FILENAME = CFW_PATCH_SET.base.replace(/\.bin$/, "") + "_cfw.bin";
export type FirmwareProgress =
| { phase: "downloading" }
diff --git a/app/g2/firmware-compat.ts b/app/g2/firmware-compat.ts
index 9eb37c6c..0620fec0 100644
--- a/app/g2/firmware-compat.ts
+++ b/app/g2/firmware-compat.ts
@@ -13,8 +13,10 @@ const REQUIRED_FIRMWARE_EXTENSIONS = ["img640", "fbguard", "wearnotify"] as cons
// The stock firmware release Faceclaw's custom image is built from. Stock at or
// below this can be flashed with our patched image; a newer stock version is
// unrecognized (its layout may differ from what our patch set targets).
-export const FLASHABLE_STOCK_VERSION = [2, 2, 9, 22];
-export const FLASHABLE_STOCK_VERSION_TEXT = FLASHABLE_STOCK_VERSION.join(".");
+export const BASE_STOCK_VERSION = [2, 2, 9, 22];
+export const BASE_STOCK_VERSION_TEXT = BASE_STOCK_VERSION.join(".");
+export const VALIDATED_STOCK_VERSION = [2, 2, 10, 10];
+export const VALIDATED_STOCK_VERSION_TEXT = VALIDATED_STOCK_VERSION.join(".");
function parseDottedVersion(version: string): number[] {
return version
@@ -89,6 +91,15 @@ export function hasMicControl(info: FirmwareInfo): boolean {
return info.capabilities.trim().split(/\s+/).includes("micctl");
}
+/**
+ * True when the firmware advertises the optional ambient-light extension:
+ * image-handler mode 16 (query / passive polling of the OPT3001 light sensor)
+ * with field-105 reports, used to drive a phone-side brightness policy.
+ */
+export function hasAmbientLightSensor(info: FirmwareInfo): boolean {
+ return info.capabilities.trim().split(/\s+/).includes("als16");
+}
+
/** The higher of the two arms' reported versions, or "" if none reported. */
export function reportedFirmwareVersion(info: FirmwareInfo): string {
const versions = [info.leftVersion, info.rightVersion].map((v) => v.trim()).filter(Boolean);
@@ -102,10 +113,12 @@ export function reportedFirmwareVersion(info: FirmwareInfo): string {
* How the pre-flash firmware check should treat the connected glasses:
* - "custom": Faceclaw's firmware is already installed — nothing to flash.
* - "flashable-stock": stock firmware at or below the version we build from.
- * - "newer-stock": stock firmware newer than we recognize — flash only on override.
+ * - "newer-stock-validated": stock firmware newer than the version we build
+ * from, on which the downgrade has been tested successfully
+ * - "newer-stock-unvalidated": stock firmware newer than we recognize — flash only on override.
* - "unknown": no version could be read (treated as a probe/connection failure).
*/
-export type OnboardingFirmwareKind = "custom" | "flashable-stock" | "newer-stock" | "unknown";
+export type OnboardingFirmwareKind = "custom" | "flashable-stock" | "newer-stock-validated" | "newer-stock-unvalidated" | "unknown";
export function classifyOnboardingFirmware(info: FirmwareInfo): {
kind: OnboardingFirmwareKind;
@@ -118,6 +131,16 @@ export function classifyOnboardingFirmware(info: FirmwareInfo): {
if (!version) {
return { kind: "unknown", version: "" };
}
- const comparison = compareVersions(parseDottedVersion(version), FLASHABLE_STOCK_VERSION);
- return { kind: comparison <= 0 ? "flashable-stock" : "newer-stock", version };
+ if (compareVersions(parseDottedVersion(version), BASE_STOCK_VERSION) <= 0) {
+ return { kind: "flashable-stock", version };
+ } else if (compareVersions(parseDottedVersion(version), VALIDATED_STOCK_VERSION) <= 0) {
+ return { kind: "newer-stock-validated", version };
+ } else {
+ return { kind: "newer-stock-unvalidated", version };
+ }
+}
+
+/** Cached R1 battery reports in settings field 106 and query mode 17. */
+export function hasRingBattery(info: FirmwareInfo): boolean {
+ return info.capabilities.trim().split(/\s+/).includes("ringbat17");
}
diff --git a/app/g2/firmware-fonts.ts b/app/g2/firmware-fonts.ts
index 5da89d1d..58df3769 100644
--- a/app/g2/firmware-fonts.ts
+++ b/app/g2/firmware-fonts.ts
@@ -21,10 +21,16 @@ type FontSpec = {
};
// Priority order is the stock EvenHub fallback chain (before the CJK font).
+// These are lv_font_fmt_txt_dsc_t addresses in the stock image the patch set
+// is built against (CFW_PATCH_SET.base), so they move on every firmware
+// rebase: run scripts/find-firmware-fonts.py against the new stock .bin and
+// match rows by cmap count / code-point count (12/8081, 9/9566, 4/11590).
+// 2.2.9.22: 0x007a8954, 0x007a8968, 0x007a8878
+// 2.2.6.10: 0x0077f414, 0x0077f428, 0x0077f374
const FONT_SPECS: FontSpec[] = [
- { descriptor: 0x0077f414, lineHeight: 27, baseLine: 5 },
- { descriptor: 0x0077f428, lineHeight: 26, baseLine: 5 },
- { descriptor: 0x0077f374, lineHeight: 20, baseLine: 2 },
+ { descriptor: 0x007a8954, lineHeight: 27, baseLine: 5 },
+ { descriptor: 0x007a8968, lineHeight: 26, baseLine: 5 },
+ { descriptor: 0x007a8878, lineHeight: 20, baseLine: 2 },
];
type ExtractedGlyph = {
diff --git a/app/g2/firmware/cfw-patches.ts b/app/g2/firmware/cfw-patches.ts
index ba0d5707..704730e8 100644
--- a/app/g2/firmware/cfw-patches.ts
+++ b/app/g2/firmware/cfw-patches.ts
@@ -1,6 +1,6 @@
// AUTO-GENERATED from g2flash/patches/cfw_patches.json — do not edit by hand.
// Regenerate with scripts/update_deltas.sh.
-// Turns the stock G2 2.2.6.10 image into the Faceclaw custom firmware.
+// Turns the stock G2 2.2.9.22 image into the Faceclaw custom firmware.
export type FirmwarePatchOp = {
offset: number;
@@ -17,164 +17,176 @@ export type FirmwarePatchSet = {
};
export const CFW_PATCH_SET: FirmwarePatchSet = {
- "base": "g2_2.2.6.10.bin",
- "baseSha256": "f4dfb0b49ad3de3c2daf17f8a27a157c3dc98411d6a0d3ab2cfd0918f41b9afa",
- "outputSha256": "d4054ab1519c7184fcc4450104de18f9ff714180c80b3a579f91106536a274cd",
+ "base": "g2_2.2.9.22.bin",
+ "baseSha256": "a03fbea9f68a9de6bc271daabb9f3a41c59053d1086622c76a4e990f829cc561",
+ "outputSha256": "12e1669fe091a94016ecc31b3940eaffb9ac1fbcb1e7807003c1f68e7f85ead3",
"patches": [
{
- "offset": 1089903,
+ "offset": 1124178,
"old": "5ff43432",
"new": "5ff43332",
"desc": "reserve final 1 KiB of primary TLSF arena for CFW context anchor"
},
{
- "offset": 1449549,
+ "offset": 1524180,
"old": "bdf82c10",
"new": "40f24120",
"desc": "container width <= 576"
},
{
- "offset": 1449749,
+ "offset": 1524380,
"old": "bdf82e00",
"new": "40f22111",
"desc": "container height movw #0x121"
},
{
- "offset": 1449753,
+ "offset": 1524384,
"old": "9128",
"new": "8842",
"desc": "container height cmp r0,r1"
},
{
- "offset": 1447919,
- "old": "7ef7fefd",
- "new": "bcf23afb",
- "desc": "bl snapshot_side @ 0x4db968"
+ "offset": 1516784,
+ "old": "70f775ff",
+ "new": "d6f2fffa",
+ "desc": "bl snapshot_side @ 0x4ec0ee (shared image-complete helper)"
},
{
- "offset": 1448931,
- "old": "7ef704fc",
- "new": "bcf240f9",
- "desc": "bl snapshot_side @ 0x4dbd5c"
+ "offset": 1516816,
+ "old": "30d0",
+ "new": "1cd0",
+ "desc": "image-complete success -> immediate ACK (pipelining-safe)"
},
{
- "offset": 1165461,
- "old": "45f0cefd",
- "new": "01f3ebfa",
+ "offset": 1222660,
+ "old": "49f0daff",
+ "new": "1ef379f9",
"desc": "bl image_deferred (deferred consumer -> FIFO restore + worker, both lenses)"
},
{
- "offset": 1186287,
- "old": "d9f7d4ff",
- "new": "fdf21afa",
+ "offset": 1242342,
+ "old": "d4f790fb",
+ "new": "1af320fd",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
- "offset": 1183983,
- "old": "f4f75aff",
- "new": "fdf2bafb",
+ "offset": 1240038,
+ "old": "f5f710f9",
+ "new": "1af3b6fe",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
- "offset": 926945,
- "old": "08f068fa",
- "new": "3cf3ddf8",
- "desc": "bl faceclaw_display_start @ 0x45c65a (fail-open double-tap takeover)"
+ "offset": 939336,
+ "old": "0bf02af9",
+ "new": "64f321f9",
+ "desc": "bl faceclaw_display_start @ 0x45f146 (fail-open double-tap takeover)"
},
{
- "offset": 927137,
- "old": "08f008fa",
- "new": "3cf37df8",
- "desc": "bl faceclaw_display_start @ 0x45c71a (fail-open double-tap takeover)"
+ "offset": 939528,
+ "old": "0bf0caf8",
+ "new": "64f3c1f8",
+ "desc": "bl faceclaw_display_start @ 0x45f206 (fail-open double-tap takeover)"
},
{
- "offset": 822553,
- "old": "28f003f8",
- "new": "56f3e5fd",
- "desc": "bl evenhub_longpress (Faceclaw lease gates custom event vs stock dialog)"
+ "offset": 831036,
+ "old": "1df057fc",
+ "new": "80f33df9",
+ "desc": "bl gesture_press (Faceclaw lease gates event 9 vs stock UI event 8)"
},
{
- "offset": 823369,
- "old": "1cf09bfb",
- "new": "56f371fc",
- "desc": "bl ring_release (forward source-qualified release-long-press)"
+ "offset": 831042,
+ "old": "24f023f9",
+ "new": "80f3def9",
+ "desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
},
{
- "offset": 1474137,
+ "offset": 831800,
+ "old": "1df0d9fa",
+ "new": "7ff3c3ff",
+ "desc": "bl gesture_release (source-qualified event 10 vs stock UI event 0x4a)"
+ },
+ {
+ "offset": 1553752,
"old": "7fb50600",
- "new": "b6f2d3bf",
+ "new": "cef2d5bc",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
- "offset": 1022741,
- "old": "f8f7c1fe",
- "new": "20f30ffc",
- "desc": "bl display_copy_hook @ 0x473c8e (640x480 direct framebuffer)"
+ "offset": 1047796,
+ "old": "f6f7edff",
+ "new": "45f33df9",
+ "desc": "bl display_copy_hook @ 0x4798f2 (640x480 direct framebuffer)"
},
{
- "offset": 1022959,
- "old": "f8f754fe",
- "new": "20f3a2fb",
- "desc": "bl display_copy_hook @ 0x473d68 (640x480 direct framebuffer)"
+ "offset": 1048112,
+ "old": "f6f74fff",
+ "new": "45f39ff8",
+ "desc": "bl display_copy_hook @ 0x479a2e (640x480 direct framebuffer)"
},
{
- "offset": 1198787,
- "old": "dff770fb",
- "new": "f9f2f4fc",
- "desc": "bl faceclaw_send_wear_event @ 0x49ec3c (outside onboarding)"
+ "offset": 1255404,
+ "old": "d9f758ff",
+ "new": "16f3cdfe",
+ "desc": "bl faceclaw_send_wear_event @ 0x4ac3ea (outside onboarding)"
},
{
- "offset": 1198881,
- "old": "dff741fb",
- "new": "f9f2c5fc",
- "desc": "bl faceclaw_send_wear_event @ 0x49ec9a (outside onboarding)"
+ "offset": 1255504,
+ "old": "d9f726ff",
+ "new": "16f39bfe",
+ "desc": "bl faceclaw_send_wear_event @ 0x4ac44e (outside onboarding)"
},
{
- "offset": 823567,
- "old": "1cf038fb",
- "new": "51f3d2f8",
- "desc": "bl compass_event_forward (global IMU heading -> stock nav BLE notifier)"
+ "offset": 1297700,
+ "old": "65f0affd",
+ "new": "0cf3a1f9",
+ "desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
},
{
- "offset": 4301227,
+ "offset": 1296176,
+ "old": "fff759fc",
+ "new": "0cf315fd",
+ "desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
+ },
+ {
+ "offset": 4476518,
"old": "",
- "new": "02fb01f000e000bfb0b546f27424c2f22a040146206846f23f52c5f28802b2eb500f40f2543044f281124cf67e25c2f20000c0f24802caf2101518bf25609047002804bf691c2160b0bd00bf0846ffe7014640f2543044f29f22c2f20000c0f24802104770b500284ed001684ef66862ccf2ff02914218bf70bd90f8081190f8095142f6c52c8d42c0f2500c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b149f29942c0f244022146bde87040104770bd00bf70b54ff6fd03c0f2450314460d46984746f27021c2f22a010e6831466ff39601b1f1005f0ad131684ef66862ccf2ff02914218bf0026412d03d070bd0026412dfbd1002cf9d04af26951c0f2450105468847002e01462846efd00129edd196f807120029e9d02168002948bf70bd47f25d02c0f2580208469047284670bd00bf2de9f04f9db046f2702ac2f22a0adaf800b058466ff39600b0f1005f40f07d81dbf800004ef66867ccf2ff07b84240f074819bf82802002800f05d81dbf82442002c00f0588140f2b870c2f20000d0f8008004a802f0caffb8f1000f00f01982032045f24075cff68070a4f1600108f160026ff0bf03c0f2020500bf0e6ed41826664e6ec03366668e6eab42a666ce6ee6660e6f26674e6f66678e6fa667ce6fe667d1f88060c4f88060d1f88460c4f88460d1f88860c4f88860d1f88c60c4f88c60d1f89060c4f89060d1f89460c4f89460d1f89860c4f89860d1f89c60c4f89c60d1f8a060c4f8a060d1f8a460c4f8a460d1f8a860c4f8a860d1f8ac60c4f8ac60d1f8b060c4f8b060d1f8b460c4f8b460d1f8b860c4f8b860d1f8bc60c4f8bc6051f8c06fc4f8c0604e68c4f8c4608e68c4f8c860ce68c4f8cc600e69c4f8d0604e69c4f8d4608e69c4f8d860ce69c4f8dc600e6ac4f8e0604e6ac4f8e4608e6ac4f8e860ce6ac4f8ec600e6bc4f8f0604e6bc4f8f4608e6bc4f8f860ce6bc4f8fc600e6cc4f800614e6cc4f804618e6cc4f80861ce6cc4f80c610e6dc4f810614e6dc4f814618e6dc4f81861ce6dc4f81c617ff462afdaf800603040b0f1005f40f0b2803068b84240f0ae8096f8ce00002840f0708196f8dc10002000298df8140000f0e88105a90a5c002a00f0bb810a185378002b00f079819378002b00f07781d378002b00f075811379002b00f073815379002b00f071819379002b00f06f81d379002b00f06d81137a002b00f06b81537a002b00f06981937a002b00f06781d37a002b00f06581137b002b00f06381537b002b00f06181937b002b00f05f81d37b002b00f05d81137c002b00f05b81537c002b00f05981937c002b00f05781d37c002b00f05581137d002b00f05381537d002b00f05181937d002b00f04f81d37d002b00f04d81137e002b00f04b81537e002b00f04981937e002b00f04781d37e002b00f04581137f002b00f04381537f002b00f04181937f002b00f03f81d27f002a00f03d81203060287ff47baf5ce19bf82a0270b1dbf82c0240b144f63421c2f207010968401a002800f3ea8000208bf82a024cf61520c0f246001db0bde8f04f00474ff41b7004f063fe002800f0bd804ff69451cff6ff71002200bf43183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e000208bf82802cbf824028bf82a0201208bf829024cf61520c0f24600804715e00020caf8000000208bf82802cbf824024ff4163045f20f11069005a8c0f24701cdf81480884701208bf82a0204a802f0aafecbf8d4001db0bde8f08f01303ae0023038e0033036e0043034e0053032e0063030e007302ee008302ce009302ae00a3028e00b3026e00c3024e00d3022e00e3020e00f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f2821d84ff052020a541dd0014445225e284a7018d04f225d288a7014d052225c28ca7010d044225b280a710cd045225a284a7108d0522259288a7104d020225828ca7142f0168500208df87300012096f8dd10002900f0c280002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf54e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2915d84ff05303535411d00a444b235e2953700cd049235d29937008d050235c29d37004d020235b29137140f0c28200218df87310013096f8de10002900f0be80002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf50e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2911d84ff0440353540dd00a4455235e29537008d050235d29937004d020235c29d37040f08e8000218df87310013096f8df10002900f0cd80002005a90a5c002a00f0a3800a185378002b5ed09378002b5dd0d378002b5cd01379002b5bd05379002b5ad09379002b59d0d379002b58d0137a002b57d0537a002b56d0937a002b55d0d37a002b54d0137b002b53d0537b002b52d0937b002b51d0d37b002b53d0137c002b52d0537c002b51d0937c002b50d0d37c002b4fd0137d002b4ed0537d002b4dd0937d002b4cd0d37d002b4bd0137e002b4ad0537e002b49d0937e002b48d0d37e002b47d0137f002b46d0537f002b45d0937f002b44d0d27f002a43d0203060287ff49aaf5fe001303de002303be0033039e0043037e0053035e0063033e0073031e008302fe009302de00a302be00b3029e00c3027e00d3025e00e3023e00021117171e70f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f281dd84ff053020a5419d001444e225e284a7014d041225d288a7010d050225c28ca700cd04f225b280a7108d046225a284a7104d0202259288a7142f0b28200208df873000120daf8041046f23f52c5f28802b2eb510f40f08b80c90700f08e80002005a90a5c002a00f083810a185378002b00f0f7809378002b00f0f780d378002b00f0f7801379002b00f0f7805379002b00f0f7809379002b00f0f780d379002b00f0f780137a002b00f0fa80537a002b00f0fa80937a002b00f0fa80d37a002b00f0fa80137b002b00f0fa80537b002b00f0fa80937b002b00f0fa80d37b002b00f0fa80137c002b00f0fa80537c002b00f0fa80937c002b00f0fa80d37c002b00f0fa80137d002b00f0fa80537d002b00f0fa80937d002b00f0fa80d37d002b00f0fa80137e002b00f0fa80537e002b00f0fa80937e002b00f0fa80d37e002b00f0fa80137f002b00f00b81537f002b00f00981937f002b00f00781d27f002a00f00581203060287ff47baf1be14cf67e21caf21011caf80410002840f01681002005a90a5c002a00f0d9800a185378002b5ed09378002b5dd0d378002b5cd01379002b5bd05379002b5cd09379002b5dd0d379002b5ed0137a002b5fd0537a002b60d0937a002b61d0d37a002b65d0137b002b66d0537b002b67d0937b002b68d0d37b002b69d0137c002b6ad0537c002b6bd0937c002b6cd0d37c002b6dd0137d002b6ed0537d002b6fd0937d002b70d0d37d002b71d0137e002b72d0537e002b73d0937e002b74d0d37e002b75d0137f002b76d0537f002b77d0937f002b78d0d27f002a79d0203060287ff49aafa9e0013073e0023071e003306fe004306de0013084e0053069e0023080e0063065e003307ce0073061e0043078e008305de0053074e0093059e0063070e00a3055e007306ce0002151713de50b304ee0083065e00c304ae0093061e00d3046e00a305de00e3042e00b3059e00f303ee00c3055e010303ae00d3051e0113036e00e304de0123032e00f3049e013302ee0103045e014302ae0113041e0153026e012303de0163022e0133039e017301ee0143035e018301ae0153031e0193016e016302de01a3012e0173029e01b300ee0183025e01c300ae0193021e01d3006e01a301de01e3002e01b3019e01f305f2831d84ff04f020a542dd001444b225e284a7028d020225d288a7024d00020c87024e01c3004e01d3002e01e3000e01f305f2818d84ff041020a5414d001444c225e284a700fd05d288a700cd04f225c28ca7008d043225b280a7104d020225a284a7142f0018100208df8730005a80021cdf80880804618f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff0770008f8010003d100208df8730003e008eb010000214170d6f8d0704ff0000918f80900002800f0c48008eb09014878002862d08878002862d0c878002862d00879002862d04879002862d08879002862d0c879002862d0087a002862d0487a002862d0887a002862d0c87a002862d0087b002862d0487b002862d0887b002862d0c87b002862d0087c002862d0487c002862d0887c002862d0c87c002862d0087d002862d0487d002862d0887d002862d0c87d002862d0087e002862d0487e002862d0887e002862d0c87e002862d0087f002862d0487f002862d0887f002862d0c87f002862d009f12009b9f1600f7ff496af4ff060095be009f1010958e009f1020955e009f1030952e009f104094fe009f105094ce009f1060949e009f1070946e009f1080943e009f1090940e009f10a093de009f10b093ae009f10c0937e009f10d0934e009f10e0931e009f10f092ee009f110092be009f1110928e009f1120925e009f1130922e009f114091fe009f115091ce009f1160919e009f1170916e009f1180913e009f1190910e009f11a090de009f11b090ae009f11c0907e009f11d0904e009f11e0901e009f11f090a2f4ff0010103961ed364204ff47a7542f2107401eb81035b00b7fbf3f60a2e11d301fb00f3b7fbf3f60a2e0bd301fb05f3b7fbf3f60a2e05d36143b7fbf1f3092be7d800e01946cc46b9f15f0f98bf4ff05f0cccf1000e1eeb090052d0b7fbf1f34cf6cd4203f13004ccf6cc4208f809400a29a1fb025446d3451c42d003fb1173e608b3fbf6f448f21f5204f1300508eb0907c5f2eb127d706429a1fb025835d3851c36d004fb16334fea5814b3fbf4f644f6d35206f13005c1f26202bd70b1f57a7fa1fb022526d303300df1140818d006fb1430aa0941f25974b0fbf2f3cdf2b714a1fb044503f13004fc7003fb120742f2107009f1040981424fea5531aad20de0e1460be009f1010908e009f1020903e0e14601e009f103090df11408039b002108f8091018f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af52e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2913d84ff0750008f801000ed008eb010073225e29427008d020225d29827004d070225c29c27040f09e8000208df87300d3f8d4104ff0000918f80900002800f0c78008eb09035878002862d09878002862d0d878002862d01879002862d05879002862d09879002862d0d879002862d0187a002862d0587a002862d0987a002862d0d87a002862d0187b002862d0587b002862d0987b002862d0d87b002865d0187c002865d0587c002865d0987c002865d0d87c002865d0187d002865d0587d002865d0987d002865d0d87d002865d0187e002865d0587e002865d0987e002865d0d87e002865d0187f002865d0587f002865d0987f002865d0d87f002865d009f12009b9f1600f7ff496af4ff060095ee009f101095be009f1020958e009f1030955e009f1040952e009f105094fe009f106094ce009f1070949e009f1080946e009f1090943e009f10a0940e009f10b093de009f10c093ae009f10d0937e009f10e0934e00021017161e709f10f092ee009f110092be009f1110928e009f1120925e009f1130922e009f114091fe009f115091ce009f1160919e009f1170916e009f1180913e009f1190910e009f11a090de009f11b090ae009f11c0907e009f11d0904e009f11e0901e009f11f0901230a291ed364204ff47a7742f2107503eb83067600b1fbf6f40a2c11d303fb00f6b1fbf6f40a2c0bd303fb07f6b1fbf6f40a2c05d36b43b1fbf3f6092ee7d800e03346ce46b9f15f0f98bf4ff05f0ecef1000842f2107c18eb09004ed0b1fbf3f405aa04f1300502f809504cf6cd42ccf6cc420a2ba3fb025641d3451c3dd004fb1317f608b7fbf6f405a948f21f5204f130054944c5f2eb124d70642ba3fb022530d3821c29d004fb16776c09b7fbf4f6b3f57a7f06f130028a7044f6d352c1f26202a3fb022520d3033016d006fb1470aa0941f25975b0fbf2f4cdf2b715a3fb055604f13005cd7004fb120109f1040963454fea5633aed209e0f14607e009f1010904e009f1020901e009f1030900210df1140808f80910ddf8089018f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af4ae001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f290bd84ff0750008f8010006d008eb010073225e29427040f00f8100208df8730040f23c3cc2f2000cdcf81c104bf67060c2f2130048f668638142c2f2200328d1dcf82810b1f54d2f23d1dcf82c1081421fd14cf6e4240022c2f213044cf639471d1d4ff0ff3eac4213d8216831f0030000f0a683a34228bf0c290cd31e1bb04209d8c90718bf02442044013f00f10404e9d14ff0ff3e44f63420c2f20700d0f8880003f1080149f268638842c2f2270321d149f6e4250022c2f2200546f6b974181d854217d8296831f0030700f0d980ab424ff0ff36039628bf0c290ed35e1bb7420bd8c90705eb070118bf3a44013c01f10405e5d14ff0ff300390dcf8001003f1080081422bd1dcf80c10b1f5333f26d1dcf81010814222d14af2e4230021c2f2270342f6f932aaf10404aaf108004ff0ff3ca34213d81e6836f0030500f04683984228bf0c2e0cd3c71abd4209d8f7072b4418bf2944013a03f10403e9d14ff0ff3c002118f80100002800f0aa8008eb01046078002861d0a078002860d0e07800285fd0207900285ed0607900285dd0a07900285cd0e07900285bd0207a00285ad0607a002859d0a07a002858d0e07a002857d0207b002856d0607b002855d0a07b002854d0e07b002853d0207c002852d0607c002851d0a07c002856d0e07c002855d0207d002854d0607d002853d0a07d002852d0e07d002851d0207e002850d0607e00284fd0a07e00284ed0e07e00284dd0207f00284cd0607f00284bd0a07f00284ad0e07f002849d0203160297ff498af77e000218170f0e6013140e002313ee003313ce004313ae0053138e0063136e0073134e0083132e0093130e00a312ee00b312ce00c312ae00d3128e00e3126e00f3124e0103122e0113120e0854218bf4ff0ff32039236e7123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f292fd84ff0200008f801002ad008eb010366205e29587024d031205d29987020d033205c29d8701cd02f205b29187118d032205a29587114d030205929987110d02f205829d8710cd032205729187208d037205629587204d03d205529987241f0928200208df873001ef10100cdf804c000f090804fea9e214ff0000a18f80a00002800f0898108eb0a046078002800f00b81a078002800f00a81e078002800f009812079002800f008816079002800f00781a079002800f00681e079002800f00581207a002800f00481607a002800f00381a07a002800f00281e07a002800f00181207b002800f00081607b002800f0ff80a07b002800f0fe80e07b002800f0fd80207c002800f0fc80607c002800f0fb80a07c002800f0fc80e07c002800f0fd80207d002800f0fe80607d002800f0ff80a07d002800f00081e07d002800f00181207e002800f00281607e002800f00381a07e002800f00481e07e002800f00581207f002800f00681607f002800f00781a07f002800f00881e07f002800f009810af1200abaf1600f7ff477af4ff0600a01e1039b002118f80100002800f0ba8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f03b81203160297ff479af3de10af1010a74e00af1020a71e00af1030a6ee00af1040a6be00af1050a68e00af1060a65e00af1070a62e00af1080a5fe00af1090a5ce00af10a0a59e00af10b0a56e00af10c0a53e00af10d0a50e00af10e0a4de00af10f0a4ae00af1100a47e00af1110a44e0013101e10af1120a3fe00231fce00af1130a3ae00331f7e00af1140a35e00431f2e00af1150a30e00531ede00af1160a2be00631e8e00af1170a26e00731e3e00af1180a21e00831dee00af1190a1ce00931d9e00af11a0a17e00a31d4e00af11b0a12e00b31cfe00af11c0a0de00c31cae00af11d0a08e00d31c5e00af11e0a03e00e31c0e00af11f0a0122bef5205f1ed364204ff47a7342f2107502eb82077f00b1fbf7f40a2c11d302fb00f7b1fbf7f40a2c0bd302fb03f7b1fbf7f40a2c05d36a43b1fbf2f7092fe7d800e03a46d146baf15f0f98bf4ff05f09c9f1000842f2107e18eb0a004ed0b1fbf2f305af03f1300407f80a404cf6cd47ccf6cc470a2aa2fb075441d3451c3dd003fb1217e308b7fbf3f405a948f21f5604f130055144c5f2eb164d70642aa2fb06c530d3861c29d004fb13736c09b3fbf4f7b2f57a7f07f130068e7044f6d356c1f26206a2fb066520d3033016d007fb1430ab0941f25976b0fbf3f7cdf2b716a2fb066507f13006ce7007fb13010af1040a72454fea5532aed209e0ca4607e00af1010a04e00af1020a01e00af1030a00200df11408dde9029308f80a003ce00f312be0103129e0113127e0123125e0133123e0143121e015311fe016311de017311be0183119e0193117e01a3115e01b3113e01c3111e01d310fe01e310de0ac4218bf4ff0ff329646fff764bca34218bf4ff0ff318c46c4e41f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff02f0008f8010003d100208df8730003e008eb010000214170ddf804a0581c00f08f80990a4ff0000c18f80c00002800f0888108eb0c046078002800f00a81a078002800f00981e078002800f008812079002800f007816079002800f00681a079002800f00581e079002800f00481207a002800f00381607a002800f00281a07a002800f00181e07a002800f00081207b002800f0ff80607b002800f0fe80a07b002800f0fd80e07b002800f0fc80207c002800f0fb80607c002800f0fa80a07c002800f0fb80e07c002800f0fc80207d002800f0fd80607d002800f0fe80a07d002800f0ff80e07d002800f00081207e002800f00181607e002800f00281a07e002800f00381e07e002800f00481207f002800f00581607f002800f00681a07f002800f00781e07f002800f008810cf1200cbcf1600f7ff477af4ff0600c00e1002118f80100002800f0ad8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f02e81203160297ff479af30e10cf1010c74e00cf1020c71e00cf1030c6ee00cf1040c6be00cf1050c68e00cf1060c65e00cf1070c62e00cf1080c5fe00cf1090c5ce00cf10a0c59e00cf10b0c56e00cf10c0c53e00cf10d0c50e00cf10e0c4de00cf10f0c4ae00cf1100c47e00cf1110c44e00131f4e00cf1120c3fe00231efe00cf1130c3ae00331eae00cf1140c35e00431e5e00cf1150c30e00531e0e00cf1160c2be00631dbe00cf1170c26e00731d6e00cf1180c21e00831d1e00cf1190c1ce00931cce00cf11a0c17e00a31c7e00cf11b0c12e00b31c2e00cf11c0c0de00c31bde00cf11d0c08e00d31b8e00cf11e0c03e00e31b3e00cf11f0c0124b3f5205f1ed364204ff47a7342f2107704eb84067600b1fbf6f50a2d11d304fb00f6b1fbf6f50a2d0bd304fb03f6b1fbf6f50a2d05d37c43b1fbf4f6092ee7d800e03446e146bcf15f0f98bf4ff05f09c9f1000842f2107e18eb0c004ed0b1fbf4f305aa03f1300702f80c704cf6cd42ccf6cc420a2ca4fb027541d3471c3dd003fb1417eb08b7fbf3f505a948f21f5205f130066144c5f2eb124e70642ca4fb022630d3821c29d005fb13737509b3fbf5f7b4f57a7f07f130028a7044f6d352c1f26202a4fb022620d3033016d007fb1530b20941f25975b0fbf2f3cdf2b715a4fb055603f13005cd7003fb12010cf1040c74454fea5634aed209e0cc4607e00cf1010c04e00cf1020c01e00cf1030c00200df11408ddf8089008f80c002fe00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff02f0008f8010003d100208df8730003e008eb0100002141701af1010000f090804fea9a214ff0000918f80900002800f0888108eb09046078002800f00a81a078002800f00981e078002800f008812079002800f007816079002800f00681a079002800f00581e079002800f00481207a002800f00381607a002800f00281a07a002800f00181e07a002800f00081207b002800f0ff80607b002800f0fe80a07b002800f0fd80e07b002800f0fc80207c002800f0fb80607c002800f0fa80a07c002800f0fb80e07c002800f0fc80207d002800f0fd80607d002800f0fe80a07d002800f0ff80e07d002800f00081207e002800f00181607e002800f00281a07e002800f00381e07e002800f00481207f002800f00581607f002800f00681a07f002800f00781e07f002800f0088109f12009b9f1600f7ff477af4ff0600900e1002118f80100002800f0ad8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f02e81203160297ff479af30e109f1010974e009f1020971e009f103096ee009f104096be009f1050968e009f1060965e009f1070962e009f108095fe009f109095ce009f10a0959e009f10b0956e009f10c0953e009f10d0950e009f10e094de009f10f094ae009f1100947e009f1110944e00131f4e009f112093fe00231efe009f113093ae00331eae009f1140935e00431e5e009f1150930e00531e0e009f116092be00631dbe009f1170926e00731d6e009f1180921e00831d1e009f119091ce00931cce009f11a0917e00a31c7e009f11b0912e00b31c2e009f11c090de00c31bde009f11d0908e00d31b8e009f11e0903e00e31b3e009f11f090123baf5205f1ed364204ff47a7742f2107603eb83056d00b1fbf5f40a2c11d303fb00f5b1fbf5f40a2c0bd303fb07f5b1fbf5f40a2c05d37343b1fbf3f5092de7d800e02b46ce46b9f15f0f98bf4ff05f0ecef1000842f2107c18eb09004ed0b1fbf3f405aa04f1300502f809504cf6cd42ccf6cc420a2ba3fb025741d3451c3dd004fb1316ff08b6fbf7f405a948f21f5204f130054944c5f2eb124d70642ba3fb022530d3821c29d004fb17676c09b7fbf4f6b3f57a7f06f130028a7044f6d352c1f26202a3fb022520d3033016d006fb1470aa0941f25975b0fbf2f4cdf2b715a3fb055604f13005cd7004fb120109f1040963454fea5633aed209e0f14607e009f1010904e009f1020901e009f1030900200df1140808f80900ddf808902fe00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff06b0008f8010003d100208df8730003e008eb0100002141709df814a0baf1000f10d0022208eb020010f8013c63b118f8023063b143784bb1807804320028f1d1023a04e0002005e0013a00e0013202eb4200400040eae070821c09f5207c00f1010e02f0030822f0030709f5a0724ff0ff3504e001350d2d02f5a07268d005eb8500bef1030f0ceb801405d24ff0ff30b8f1000f2dd1ede70020164603e0874206f1020621d0431cdb09042b03d8337803f0f0033370831cdb09042b03d8737803f00f037370c31cdb09042b03d8737803f0f00373700430c309042bdfd84308e15c01f00f01e154d9e70138b8f1000fc0d0861cf109042908d87108635cc6076ff00f0608bf0f2633406354b8f1010fb0d0c61cf109042909d87108635cc6074ff00f0608bf6ff00f0633406354b8f1020f9fd0061df10904299bd87108c007635c6ff00f0008bf0f201840605491e7baf1000f00f0ab800298022200f281280df1140e40f27d2940f27a2c08e01ef801af0632baf1000f08f1030800f09780aaf17f0010f15f0ff1d346f25641c0f200010aeb4a00794401eb8000a0f5c0710027d409404605e000bf02370c2f00f52070dcd0cb57042c06d8b3f1ff3f03dc067846f0f0060670042cdeb206d816f0400303d0037843f00f030370b30605d54a4503d8437843f0f0034370f30606d5b2f51f7f03d8437843f00f03437033074fea920305d59e2b03d8857845f0f0058570750705d5624503d8857845f00f058570cd1995f90160042c08d8b6f1ff3f05dc90f8405145f0f00580f84051042cf6b208d816f0400505d090f8405145f00f0580f84051b50607d54a4505d890f8415145f0f00580f84151f50608d5b2f51f7f05d890f8415145f00f0580f84151350707d59e2b05d890f8423143f0f00380f8423173077ff588af62453ff685af90f8423143f00f0380f842317de7ddf80880fdf776ba0020c871fdf74dbd00208871fdf7febe00200872fdf7e9ba0020d872fef76dbdf0b581b041f204054cf65561cef20005ccf2ac51c5f8ac1f4ef6fc51cef200010a6846f2702642f080720a6055f8041cc2f22a0641f0010145f8041c316807460a466ff39602b2f1005f07d108684ef66862ccf2ff02904200f0b9804ff41b7001f0d4ff002800f0ea8001464ff69450cff6ff70002200bf0b183e3083f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66860ccf2ff000860012081f8ce004ff0ff30a1f8e000a1f8e200a1f8e400a1f8e600a1f8e800a1f8ea00a1f8ec00a1f8ee00a1f8f000a1f8f200a1f8f400a1f8f600a1f8f800a1f8fa00a1f8fc00a1f8fe003160d1f8d800b0bb44f6342245f6e464c2f20702cff6f8741368204616689e420ed116689e420bd116689e4208d116689e4203d1002800f10400efd19e421ad02b6816681068b0420ed11068b0420bd11068b04208d11068b04203d1002c04f10404efd1b04206d02868c01ac1f8d80001e0002030602868386001b0f0bd00bf2de9f04141f2040846f27027cef20008c2f22a070146d8f8004038680d6801466ff39601b1f1005f07d101684ef66862ccf2ff02914200f0b8804ff41b7001f0bffe002800f0c1804ff69451cff6ff71002200bf43183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe103860d0f8d81081b144f6d350c1f26200a1fb0001880901284ff0010088bf88094ce000203860fa2048e044f6342245f6e466c2f20702cff6f8761368314600bf17689f420ed117689f420bd117689f4208d117689f4203d1002901f10401efd19f422ad0d8f80030176800bf1168b9420ed11168b9420bd11168b94208d11168b94203d1002e06f10406efd1b94214d0d8f8001044f6d357ca1ac1f26207a2fb0776c0f8d820b00901284ff0010088bfb009994208bffa2000e0fa20611bb1fbf0f0bde8f08100bf2de9f04f85b0044618b1a069002840f0ce8046f27025c2f22a05286801466ff39601b1f1005f07d101684ef66862ccf2ff02914200f0b7804ff41b7001f088fd002800f0af804ff69451cff6ff71002243183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe102860002c18bf002807d14af26950c0f2450005b0bde8f04f0047d4f80cc0bcf1000ff2d0d4f820a0baf1000fedd0d4f844e000f104094ff0ff38002700264ff0ff3105e06037c02f06f1060600f0eb81c3195a68002a50d01a69013205d01a6942453cbfd3f8108031465a69002a06f1010241d01d6a013505d01d6a45453cbfd3f8208011465a6a002a06f1020233d01d6b013505d01d6b45453cbfd3f8308011465a6b002a06f1030225d01d6c013505d01d6c45453cbfd3f8408011465a6c002a06f1040217d01d6d013505d01d6d45453cbfd3f8508011465a6d002a06f1050209d01d6e0135acd01d6e45453cbfd3f860801146a5e71646002e019600f1a281f24500f29f810aeb0c0102910eeb0c0100220491cdf80c9000bf130159f80330a34224d109eb02135f68674507d30499b94204d304999e68cd1bae4208d9df68013714d00021196059609960d9600ee00299b9420bd9df68013708d00021196059609960d960012180f8df1000bf01320c2ad2d1049e04e000bfbef1000f00f0ba80b6eb0c02c0f0b880924500f2b5803546a6eb0a0b00224ff0000e02e06032c02aead000eb0208d8f80430a34217d1d8f80830a3b1d8f80c90002709eb03018b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f81410a14216d1d8f818309bb1d8f81c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f82410a14216d1d8f828309bb1d8f82c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f83410a14216d1d8f838309bb1d8f83c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f84410a14216d1d8f848309bb1d8f84c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f85410a1427ff46eafd8f85830002b3ff469afd8f85c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e4653e7554562d1ddf80c904ff0ff36002200274ff0ff3505e000bf6032c02a07f1060744d083185968a14207d11969013104d01969a9423cbf1d693e465969a14207d1196a013104d0196aa9423cbf1d6a7e1c596aa14207d1196b013104d0196ba9423cbf1d6bbe1c596ba14207d1196c013104d0196ca9423cbf1d6cfe1c596ca14207d1196d013104d0196da9423cbf1d6d3e1d596da142bfd1196e0131bcd0196ea9423cbf1d6e7e1db6e700bf002e4ed409eb06113301002249f803204a608a60ca60012180f8df10ace6dc4543d21af00303524615d0aaf101021cf80210012b0bf802100dd0aaf102021cf80210022b0bf8021005d0aaf103021cf802100bf80210baf1040f5dd3abf10203acf10406b118cf789d186f708f789f54497805f8011cb15c043a05f8021cf1d14ae000290dd409eb01120b01002549f8035055609560d56001220e4680f8df2059e6012180f8df10dde535d90af0030e5fea9a024ff0000317d0a3eb82080bf101060cf101026ff003055119cf787319df700f7904351f714f795f71897908eb050704379971f0d12b1dbef1000f13d01cf80310bef1010f0bf803100cd0591c1cf80120bef1020f0bf8012004d0991c1cf801200bf80120039b019a03eb021112019c50d0f8c420c1f804b0531cc1f808a024bf01230022c0f8c430ca6092e538464146fff7b8bc2de9f047044648b1a06938b14cf2af53c0f24d032046bde8f047184746f27028c2f22a08d8f8005028466ff39600b0f1005f07d128684ef66863ccf2ff03984200f0bc804ff41b700f46164601f038fa0546002800f048814ff69450cff6ff70002100bf2a183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff002860012085f8ce004ff0ff30a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200a5f8f400a5f8f600a5f8f800a5f8fa00a5f8fc00a5f8fe00c8f8005005f1040a4ff000094ff0ff38002015e0002948bfbde8f0870aeb01170e017968ba682046c7f80c8000f088f84af80690c7f80490c7f80890c7f80c90daf80010a14205d04ff0ff314ff0ff3205e000bf29690131f6d02a6900216b69a34204d12b6a93423cbf2a6a01216b6aa34204d12b6b93423cbf2a6b02216b6ba34204d12b6c93423cbf2a6c03216b6ca34204d12b6d93423cbf2a6d04216b6da34204d12b6e93423cbf2a6e05216b6ea34204d12b6f93423cbf2a6f06216b6fa34206d1d5f8803093423cbfd5f880200721d5f88430a34206d1d5f8903093423cbfd5f890200821d5f89430a34206d1d5f8a03093423cbfd5f8a0200921d5f8a430a34206d1d5f8b03093423cbfd5f8b0200a21d5f8b430a3427ff47bafd5f8c0309342bff476afd5f8c0000b2175e7204639463246c8f80050bde8f047ffe72de9f047a4b0804640f6bb4046f27027c0f24e0091468a46c2f22a0780473c68002021466ff39601b1f1005f02908df80c0007d120684ef66861ccf2ff01884200f0b9804ff41b7001f0bef80446002800f0b0804ff69450cff6ff70002100bf22183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe003c60baf1000f4ff0010618bfb9f1000f23d101af3846fef7f7ff02ad404651464a460123009501f029fb05463846fff711f9002e064608d19df80c0028b943f61f00c0f247004c308047002c18bfc4f8d060284624b0bde8f0879af8001001f07f00a0f1100212f1040f09d80b2807d001f07e01082903d0032801d00628c8d13cb143f61f00c0f24700804794f8280210b14ff0ff35dce70026bae746f27020c2f22a00016808466ff39600b0f1005f16d108684ef66862ccf2ff0290420fd1d1f8fc0160b144f63422c2f207021268801a0028cebf01200020c1f8fc0170470020704746f27020c2f22a00026810466ff39600b0f1005f28d110684ef66861ccf2ff01884221d1d2f82c02f0b144f63421c2f207010968401a0028c4bf01207047d2f8301200200029c2f82c0282f82a0208bf704710b5c2f8300204460846fbf7cefe2046bde81040704700207047f0b101684ef66862ccf2ff02914218bf704790f8061299b110b544f62f344ff0000cc0f24604864680f806c20120002100220023aef804c2a446bde810406047704700bf70b546f27026c2f22a063468054621466ff39601b1f1005f07d120684ef66861ccf2ff01884200f0b8804ff41b7000f027ff002800f0d98004464ff69450cff6ff70002122183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe00346000230820032184f81b322a2384f8180284f81912102184f81c32042384f81e02012045f61b4c04f5067284f81a1284f81d3284f81f0284f82012002d18bf0125c0f2470c0a2384f82152bde8704060470020306070bd2de9f04146f27027c2f22a073f684ff000083c466ff39604b4f1005f07d13e684ef66865ccf2ff05ae4208bfb84601280fd11c4615460f460646fff76dfe2346044639462a463046002c18bfb8f1000f06d144f62f3cc0f2460cbde8f041604798f8060270b1d8f800020021002888f80612a8f804123ed049f2d941c0f24401884738e0b8f804020121013080b2012898bf0846a8f80402d8f8000249f2d944c0f2440488f8061268b94ff61350cff6ff70a4f594777844002142460023b847c8f8000240b1a047d8f80002a4f140024ff4c8719047c8b198f80602002808bfbde8f081d8f80002002188f80612a8f8041200b1a04744f62f3cc0f2460c0120002100220023bde8f04160474af26950c0f245008047012830d1082088f80802032088f80902102088f80a02002088f80b02b22088f80c02062088f80d0288f80e024620b8f8041288f80f02432088f8100201200f0a45f6153c08f5027288f8110288f8120288f81312c0f2470c09210d2388f81472bde8f0416047bde8f08170b50446d0f8000249f2b1360d46c0f2440668b94ff62d40cff6ff707844002122460023b0470028c4f8000208bf70bd06f594718847d4f8000206f1e8022946bde87040104700bf2de9f04f81b04568002d00f0bf828368002b00f0bb8205eb030a4ff000080026002412e046f27020c2f22a000099c0f8008020463246bc460ceb0903002653451d464ff0000480f0a182ab461bf9013b03f07f07b740002b44ea070410d404f00703012b16dc0bb3012b40f08f82aaeb0b03082bc0f08a8205f10903dee700bfd34580f08382182e06f107065d46dcd97ce200bf022b3ad0052b40f07782aaeb0b03042bc0f072826b1dc7e7d34580f06d8295f90130002b05f10203bed5534580f0648295f90230b3f1ff3f05f10303b4dc534580f05a8295f90330b3f1ff3f05f10403aadc534580f0508295f90430b3f1ff3f05f10503a0dc534580f0468295f90530002b00f14182ab1d96e7d34580f03c8295f9013005f1020c002b03f07f091fd5d44580f0318295f90260eb1c06f07f07b6f1ff3f49eac71902dde3469c460fe0534580f0218295f9037005f1040c07f07f06b7f1ff3f49ea863940f33f819b46aaeb0c03994500f20f82e308672b00f02881652b7ff45eafb9f1060ffff45aaf9cf80030462b7ff455af9bf80230432b7ff450af9bf80330012b7ff44baf46f27023c2f22a031d682b466ff39603b3f1005f07d12b684ef66867ccf2ff07bb4200f0c38004464ff41b7067460091164600f078fc00283ff423af4ff6945300990546cff6ff7320463246bc46ec183e3384f86c8284f86d8284f86e8284f86f8284f8708284f8718284f8728284f8738284f8748284f8758284f8768284f8778284f8788284f8798284f87a8284f87b8284f87c8284f87d8284f87e8284f87f8284f8808284f8818284f8828284f8838284f8848284f8858284f8868284f8878284f8888284f8898284f88a8284f88b8284f88c8284f88d8284f88e8284f88f8284f8908284f8918284f8928284f8938284f8948284f8958284f8968284f8978284f8988284f8998284f89a8284f89b8284f89c8284f89d8284f89e8284f89f8284f8a08284f8a18284f8a28284f8a38284f8a48284f8a58284f8a68284f8a78284f8a88284f8a9827ff480af4ef66863ccf2ff032b60012385f8ce304ff0ff33a5f8e030a5f8e230a5f8e430a5f8e630a5f8e830a5f8ea30a5f8ec30a5f8ee30a5f8f030a5f8f230a5f8f430a5f8f630a5f8f830a5f8fa30a5f8fc30a5f8fe3046f27023c2f22a031d609bf804309bf805709bf80660032b47ea062459dd052b7adc042b00f0a780052b7ff463aed5f82c323bb144f63427c2f207073f68db1b002b11dcd5f8303285f82a8263b183461846c5f8308216460c466746fbf7f8fabc4621463246584644f63423c2f207031b6845f69077c0f201073b44c5f82c3238e6044660460d4649461646674600f0d3fbbc462946324620462be6d44580f0d38095f904706b1d07f07f06b7f1ff3f49ea46593ff7a1ae534580f0c58095f90560002e00f1c08005f1060c49ea0679a5e6012b42d0022b00f08f80032b7ff409ae009016468b466746fff78ffb03460098bc4659463246002b3ff4fbad95f80632002b3ff4f6ad284641f28831a5f80442fff7affd55e0062b58d0072b7ff4e9ad83464ef68f30c0f2490015460e466446804703465f1ea44631462a465846012f3ff6d7ad981eb0fa80f04009fff7d9fba44631462a465846cbe544f63423c2f207031b6845f69077c0f201073b44c5f8fc31bee5009016468b466746fff745fb03460098bc4659463246002b3ff4b1ad95f80632002b3ff4acadb5f80432a3427ff4a7add5f8003285f80682002ba5f804823ff49ead49f2d9411846c0f2440188470098bc465946324692e5d5f83032c5f82c82002b85f82a823ff48aad04461846c5f8308215460e466746fbf72ffabc4631462a464ee795f80632c5f8fc81002b3ff476ad0446d5f800028b461646cdf800c085f80682a5f8048220b149f2d941c0f24401884744f62f370120002100220023c0f24607b847ddf800c020463246594655e540f22113c0f2490301b0bde8f04f18477fb50646002806d1fff7d4fa002807d19de80f00064641f6d77cc0f24e0c60477fbd00bf092940f0e9802de9f04f89b0882b38d8a22602eb030cd65406268cf8016075268cf8026044f26e7ec0f2000e0026fe441ef806500ceb06040eeb0607e5707d7897f8028097f8039097f804a0257184f8058084f8069084f807a07d790d362572bd79752e6572fd79a5723d7ae5727d7a2573bd7a6573fd7aa5733d7be573d7d1783346f27027c2f22a07d7f8008045466ff39605b5f1005f40d1d8f800704ef66866ccf2ff06b74238d198f8347298f83962009798f835724af26955029798f8377298f83a92049798f83872c0f245050797b8f83c72019605973f0a0697b8f83e7298f83b6208973f0a03971c4617468b468246a847d8f840525946cb463a4623468446504637464fea15294fea154a2e0e4ff0a008e82b19d95ae000244ff0000800264ff0000a4ff0000900254ff0000c00274ff0000b0894cde90644cde90444cde90244cde90044e82b41d802eb030e06248ef8014015248ef802404d248ef8034043248ef8044001248ef80540009c8ef810708ef80640029c00278ef80740049c8ef817708ef80840079cc2278ef80940019cd7548ef80a40059c18338ef80b40069c8ef80fb08ef80c40089c8ef811c08ef80d40039c8ef812508ef80e408ef813908ef814a08ef815608ef8168009b0bde8f04f45f6153cc0f2470c604700bf2de9f04f89b046f27023c2f22a031d680c4629466ff39601b1f1005f38d129684ef66863ccf2ff0399424bd195f83412b5f83c82039195f8351295f83862019195f8371295f83a92079195f8391295f83b7204914fea18210891b5f83e1282460291090a05914af26951c0f2450193468847d5f840525a46290c06910199be463346844650462e0a4fea156aa02734e0002100234ff0000b00274ff0000a0691002600254ff0000c4ff0000e4ff000090591029108934ff0000804910791cdf80cb01ae0002100234ff0000b4ff0000a00260027069300254ff0000c4ff0000e4ff000090593029308934ff000080493cdf81ca08a4603965e46121b28bf182a2cd3c22202552044c17107990622017204994270152282704d2281720299c270432202710122417305994271039a817306998271089a017500211834437280f80b80027380f80f9080f810e080f811c08574c67480f815a08775c175204609b0bde8f08f2de9f04f81b046f27020c2f22a00066830466ff39600b0f1005f0dd130684ef66863ccf2ff03984206d196f8340218b1002a18bf002902d101b0bde8f08f96f83b020028f8d0d6f844020028f4d044f6342ac2f2070adaf80030c01a0128ebdb96f83502012802d14ff0010b06e096f837b2bbf1010f18bf4ff0020b96f83a520020eb078846adf80200adf8000013d0bbf1020f10d196f8390268b96b4641f6fd370df10201c0f25907404614461a46b84796f83a5222461446b2f5c86f28bf4ff4c86404f115094846174600f078f80028b1d0b7f5c86f88bf45f08005daf80010d6f8402253230271120a42710a0a8171c2710a0c090e03704d234172a02143700123c17200218370c570027280f80ab0017396f8392283734273bdf80020bdf80230c273120a02741a0a8274220a0275621e032a04f0030c4374c47414d340f2fc7104ea010308f1010700217d1815f8014c421854757c5c043194756c788b42d475ad781576f1d1bcf1000f12d018f8017000f11503bcf1010f5f540ad04f1c18f80750bcf1020fdd5503d0023118f801205a5445f67952c0f24702494605469047d6f8400244f617510130c6f84002c0f247012846884701b0bde8f08fb0b546f27424c2f22a04216846f23f52c5f28802b2eb510f44f6d3414cf67e25c0f24701caf2101518bf25608847002804bf691c2160b0bd10b301684ef66862ccf2ff0291421bd190f83b12c1b1d0f84412b1b144f63422c2f207021368cb1a012b0edb1268d0f84802002808bf7047891a49f29942c0f2440208bf01211047704710b500214af6d142c0f8441280f83b12c0f25702002044f2436190474ff24b74c0f25804a04704f1bc00bde81040004700bf70b50429c0f0f180024600784d2840f0ec805078432840f0e8809078012840f0e48046f27024c2f22a04206803466ff39603b3f1005f07d103684ef66866ccf2ff06b34200f0bb804ff41b700d461646fff77cff002800f0c6804ff69451cff6ff71002243183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe10324629462060d378022b06dc012b11d0022b0ed1bde87040e6e0032b73d0042b07d190f8341221b1bde87040aae00020206070bd0d2938bf70bd90f83b12b1b100214af6d14380f83b12c0f257030446002044f24361154698474ff24b76c0f25806b04706f1bc0080472a46204611790446012988bf002180f83512517901f00303012b4ff0010198bf0b4680f837329679012e88bf002680f83862d679022e88bf002680f83962167a557a46ea0526502e98bf5026b6f5f07f28bf4ff4f076a0f83c62967ad57a46ea052641f28835ae4238bf3546a0f83e52127b80f8341202f0030280f83a2203f0010202eb5302002180f83622c0f8401200f00bf8204600f040f802e0044600f0def82046bde8704069e0b0b5044690f83a02800758bfb0bd94f835024ff29b650128c0f2580507d105f1b000804705f58b71002088470ee005f5b670804794f83502012801d1002004e094f83702013818bf0120a8474ff66522cff6ff724af679337a44c0f25703002044f243619847012084f83b02b0bd00bf70b5044644f63420c2f20700006894f83b1245f69075c0f2010500292844c4f8440208bf70bdd4f8480249f2b136c0f2440658b94ff60940cff6ff707844002122460023b047c4f8480250b106f594718847d4f8480206f1e8022946bde87040104770bd70b5044600f51375082084f84c02032084f84d02102084f84e02c22084f85002062084f851024d2084f85302432084f85402012084f8550294f8340294f8351284f8560284f8571294f83902b4f83c1284f85a0284f85b12080ab4f83e1284f85c02080a84f85e0294f83a0294f8372294f8383284f85d1294f83b1284f85f024af269500026c0f2450084f84f6284f8582284f8593284f860128047d4f8401284f86102080a84f86302080c84f86402080e84f86502a02084f86762152645f6153c84f8621284f86602c0f2470c012009212a461c2384f85262bde87040604770b546f27020c2f22a00046820466ff39600b0f1005f33d120684ef66861ccf2ff01884218bf70bd94f83b020025c4f8445288b14af6d142c0f25702002044f2436184f83b5290474ff24b76c0f25806b04706f1bc008047d4f8480284f8345270b149f2d945c0f24405a847d4f8480205f166018847002804bf0020c4f8480270bd00bfb0b582b00c460546fef786fd90b14df63040c2f2340000784af26b1401900025c0f24d0400200021002209230095a04702b0b0bd4af69d62c0f246022846214602b0bde8b0401047f0b583b04ff6e70714460d460646c0f24507fef75dfde8b144f2d040c2f207000068b847b0b10068e02813d14df63040c2f2340000784af26b1601900027c0f24d060020002100220a230097b047012003b0f0bd07f1160330462946224603b0bde8f040184700bf2de9f04f95b0002918bf002a04d115b0bde8f04f01f048b90e78ddf878b006f07f070a2f00f3f480052f00f01d81072f00f0fd820a2f40f0f480022ac1f07b8046f27024c2f22a04206802466ff39602b2f1005f07d102684ef66863ccf2ff039a4200f0b9804ff41b700d46fff794fc002800f09a874ff69451cff6ff71002243183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe10294620604978012900f01e87002940f0a887002480f807424af26950c0f24500804701462046012940f0a88745f26d60c0f2540015b0bde8f04f00470b2f00f016810c2f00f01d83422f3ff4f6aea7f10d05022d00f2f7848568002d00f08187b0f84060b0f842406643b6f5163fc0f0788701310e2fa2f101029846064628465b4600f068870d2f40f0688701f09cf800f066bf46f27028c2f22a08022a2cbf4d78ff25d8f8004020466ff39600b0f1005f07d120684ef66863ccf2ff03984200f0bd804ff41b7016460f46fff77afb002800f00b8504464ff69450cff6ff700021324623183e3083f86c1283f86d1283f86e1283f86f1283f8701283f8711283f8721283f8731283f8741283f8751283f8761283f8771283f8781283f8791283f87a1283f87b1283f87c1283f87d1283f87e1283f87f1283f8801283f8811283f8821283f8831283f8841283f8851283f8861283f8871283f8881283f8891283f88a1283f88b1283f88c1283f88d1283f88e1283f88f1283f8901283f8911283f8921283f8931283f8941283f8951283f8961283f8971283f8981283f8991283f89a1283f89b1283f89c1283f89d1283f89e1283f89f1283f8a01283f8a11283f8a21283f8a31283f8a41283f8a51283f8a61283f8a71283f8a81283f8a9127ff480af4ef66860ccf2ff002060012084f8ce004ff0ff303946a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe00c8f8004094f8080170b1d4f8040140b149f2d943c0f244030e46174698473a463146002084f808010123032a80f0498400f053bc46f27026c2f22a06346820466ff39600b0f1005f40f07a8620684ef66867ccf2ff07b8424ff0000040f07186c4f82c0284f82a0284f82802d4f83012c4f8240284f8290221b1c4f830020846faf7e9f9d4f80401032549f2d948cff68075c0f244080021a4f8081150b1c047d4f8040108f166018847002804bf0020c4f8040142f6c520c0f250008047366806ea0500b0f1005f2ad13068b84227d196f83b020025c6f8445288b14af6d142c0f25702002044f2436186f83b5290474ff24b77c0f25807b84707f1bc008047d6f8480286f8345250b1c047d6f8480208f166018847002804bf0020c6f8480294f80702002584f8075258b14af26950c0f245008047012804d145f26d60c0f254008047d4f8000294f80662c4f8fc5184f80652a4f8045250b1c047d4f8000208f166018847002804bf0020c4f8000200200121002e6060a060e06020616061a061e06120626062a062e06220636063a063e06320646064a064e06420656065a065e06520666066a066e06620676067a067e067c4f88000c4f88400c4f88800c4f88c00c4f89000c4f89400c4f89800c4f89c00c4f8a000c4f8a400c4f8a800c4f8ac00c4f8b000c4f8b400c4f8b800c4f8bc00c4f8c000c4f8c40084f8ce1000f09f8544f62f37c0f2460701200021002200230024b847204615b0bde8f08f46f27024c2f22a04236818466ff39600b0f1005f07d118684ef66867ccf2ff07b84200f0bd804ff41b7015460e46fff79cf90346002800f0b0804ff69450cff6ff70002100bf1a183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff001860012083f8ce004ff0ff30a3f8e000a3f8e200a3f8e400a3f8e600a3f8e800a3f8ea00a3f8ec00a3f8ee00a3f8f000a3f8f200a3f8f400a3f8f600a3f8f800a3f8fa00a3f8fc00a3f8fe0031462a462360022a2cbf4978ff21002b00f0b98402294ff0000000f0dd83012900f0d683002940f0af844cf67e21caf21011c3f8dc0061604ff0ff31a3f8cc00c3f8c800a3f8e010a3f8e210a3f8e410a3f8e610a3f8e810a3f8ea10a3f8ec10a3f8ee10a3f8f010a3f8f210a3f8f410a3f8f610a3f8f810a3f8fa10a3f8fc10a3f8fe1083f8000115b0bde8f08fb2f1010900f0788401f1010b0023002200bfa9eb03000428c0f062840beb0306b078f7781c1d40ea0727a9eb040087424ff0ff3000f261841bf80330767843ea06233b44b3f5803f00f25784002f07eb040318bf01224b45dbd3002a00f04c848846fef7d6f8002800f03a8446f27027c2f22a073c6820466ff39600b0f1005f07d120684ef66861ccf2ff01884200f0b8804ff41b70fff754f8002800f0a08404464ff69450cff6ff70002122183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe003c60d4f8300200286fd14ff48030f9f7dafe002800f0648300210022831881544032b2f5803f59709970d970197159719971d971197259729972d972197359739973d973197459749974d974197559759975d975197659769976d976197759779977d97783f8201083f8211083f8221083f8231083f8241083f8251083f8261083f8271083f8281083f8291083f82a1083f82b1083f82c1083f82d1083f82e1083f82f1083f8301083f8311083f8321083f8331083f8341083f8351083f8361083f8371083f8381083f8391083f83a1083f83b1083f83c1083f83d1083f83e1083f83f109ad1c4f830020021cdf80c8006e007eb0a0149454ff0000080f0fd820beb01039878da7801f1040a50ea0227efd012025b7802441bf80160013a1d02032a00f0030e04a8e0c001d2002224e00398a7eb0e030844a919002200bf8618d4f830c296f805800ceb010707f80280d4f83072b5790f4417447d70d4f83072f5790f441744bd70d4f83072367a0f44174404329342fe70e1d1069fdde90465bef1000fb5d0d4f830120beb0a00835c31442944bef1010f8b54aad0d4f83032511c10f801c033442b44bef1020f03f801c09ed0911cd4f83022405c32442a44505496e7092f00f08a80082f40f012810746002b4ff0ff3000f08f824af28973cff6fd73d61802339e42c0f0868291f801803846b8f1000f00f07b820226b71c974200f26d828b198e5d5b7856ea032300f06682de19964200f26282cc5d04f07f0cacf1100515f1030f0ad804f07b05092d06d0bcf1030f03d0bcf1060f40f04f8214460d4639441a4600230746cdf800b0fff7aaf9002840f04282b8f10108294622463846cad143e20023c8f80030002439463246032a0bd355b98878082800f23a8242f6c521c0f250019631884732e2052a1ad3012d18d18d78681e06284ff0000000f22982cb78032b00f225820a79002a00f0218242f6c520c0f2500000f59a7728461946b84715e2022d40f0448142f6c520c0f2500080470ce237064ff0210658bf1126b242c0f0f981002f01f101050ed54af26952c0f245020f4604461e469047334601462046022918bf07f1110584462879697950ea01264ff0ff301ebfa979ea7951ea022900f0e581297b6a7b41ea02218e4240f0de81a97bea7b41ea0221894540f0d7812878697840ea01217018b0f5207f4ff0ff3000f2cc81aa78ec7842ea042209eb0204b4f5f07f00f2c2812c7a6f7a44ea072806eb0807b7f5207f00f2b881af7aed7a47ea052509eb0507b7f5f07f00f2ae81dcf80800002800f09c81bcf84070bcf842406743b7f5163fc0f093819a4643466446cde90169009501f0feffdbf800000f280ad80bebc0010130a1f806800d814e81a1f80c90cbf80000baf1000f00f0848120467ee1fd1e18bf0125bc1f18bf0124032afff4d9a825407ff4d6a800254c1ca2f1010c8df81c508df81d508df820508df824508df825508df826508df827508df828508df829508df82a508df82b508df82c508df82d508df82e508df82f508df830508df831508df832508df833508df834508df835508df836508df837508df838508df839508df83a508df83b508df848508df849508df84a508df84b508df84c508df84d508df84e508df84f508df850508df851508df852508df85350cde9074c49f6ff04cff6ff747c440f9449f63f14cff6ff747c44032f1094119500f01681062f40f003810646002000211d4602f07af9b168002900f0f980b6f84020b6f842005043b0f5163fc0f0f08007a84ff4a0724ff4f07302f0b0fa002800f0e680dbf800000f280dd80bebc0010022ca800a814ff420724a814ff4f07201308a81cbf80000002d304640f0d980dae0012083f8ce00d6e083f8ce0015b0bde8f08f00202060c2e0072a51d3032d4fd18878cb780a7940ea03204d798e7901284ff0010498bf204644f62061884228bf084642f6c521c0f25001642a28bf642201f5e2731146984744f20450c2f207000068002800f0a78045ea0621012988bf0c4649f2d941c0f24401a1f140022146904798e00121044680f807124af26950c0f245008047012840f08d8045f26d60c0f2540088388047014600284ff0000000f0828084f80702084615b0bde8f08f032a4ff0000077d32f1fb7fa87f77f093b4071d0d01e4cf6cd42ccf6cc428b78a0fb0202b3eb920f88bf9308302b184628bf3020002b00f0f88000eb800303f0030c03f4fe770023ce18f578e21882f80a513579043382f80b5175799f4282f80c51b67982f80d61eed1bcf1000f10d01944ca782344bcf1010f83f80a2108d00a79bcf1020f83f80b211cbf497983f80c1184f80801d4f8040149f2d945c0f24405002184f8091170b949f26770cff6ff70a5f59477784422460023b8470028c4f8040100f0b780a5f140020121904711e000f0d3fc01e001f024f920b14ff0ff3015b0bde8f08fb8f1000f03d03046594601f063fd002015b0bde8f08f370670d4082aebd381464ff0070c4ff0050e0127cc1994f802a04ff0ff30baf1000fead0e678002ee7d011f807804fea8a0505eb8807b7f5207fded86478760006eb4407b7f5f07fd7d801eb0e000395cdf81890894611f80e104078674641ea002081b20120cde9043202f036f80028c2d1069988680028b2d0b1f84020b1f842105143b1f5163faad309eb0701079105994fea4a02c91b089104eb840100ebc11000eb480107a8334602f060f9002896d0dbf800000f280cd84fea88010bebc003d9800399620001301a8159819e81cbf800000498002806987ff48aaf8be7002038607ce70c2afff47aafcf78ce79b7427ff475af0f790e7ab7427ff470af4af26954c0f245040d46164680461f46a0473b46052732462946c146022808bf01274ff00b0c4ff0090e73e70020a4f8080115b0bde8f08f42f6c5200025c0f2500084f808518047284615b0bde8f08f00bff0b583b046f27023c2f22a031f683b466ff39603b3f1005f09d13b684ef66866ccf2ff06b34204bf002387f82a32002958d0362a56d30b78422b53d14b784d2b50d10b7f4f7f43ea0723042b4ad18b7dcf7d0e7e43ea072343ea06434f7e8e7ccd7c53ea076346ea05270e7d4d7d47ea064747ea05641d4648bf5d42b0f84070002b4ff00003c8bf0123bc422ad1b0f84270bd4226d18f7ace7a91f80cc047ea06274e7b47ea0c4747ea0667974219d2621c032606eb5202866822f0030cca19cde901c30746304621462346009502f0edfa3846314622462b4602f081fb002003b0f0bd4cf2af53c0f24d0303b0bde8f0401847072a1cbf4ff0ff3070472de9f04f8db00e4683461d46fdf759fb002800f05b8346f27027c2f22a07386801466ff39601b1f1005f07d101684ef66862ccf2ff02914200f0b8804ff41b70fef7d7fa002800f03f834ff69451cff6ff71002200bf43183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1038603178727841ea02274ff6ff718f424ff0ff3200f08a82d0f830121046002900f08182cb5d4ff0ff30002b00f07b8239444a78002a00f0768202fb03f001f1020a4ff0000c4ff000010195009278b34ff6fe794ff6fd78cd194d4500f061828e4651440a78140904d00125a0421bd257e200bf454500f054824c781cb10225a04211d24de24ff6fb72aa1a042ac0f048828a78c97852ea012400f042820425a042c0f03e8200bf001b05eb0e01d3d10691b078f178b77940ea0129b8060f213279757907f00f0601eae07000fb06f189204143c90a8df824100e2142ea0525069a17f0200f08bf4ff00f0c08bf012106fb01f100fb01f14fead1218df825104ff00d0108bf022106fb01f100fb01f14fead1218df826104ff00c0108bf032106fb01f100fb01f14fead1218df827104ff00b0108bf042106fb01f100fb01f14fead1218df828104ff00a0108bf052106fb01f100fb01f14fead1218df829104ff0090108bf062106fb01f100fb01f14fead1218df82a104ff0080108bf072106fb01f100fb01f14fead1218df82b104ff0070108bf082106fb01f100fb01f14fead1218df82c104ff0060108bf092106fb01f100fb01f14fead1218df82d104ff0050108bf0a2106fb01f100fb01f14fead1218df82e104ff0040108bf0b2106fb01f100fb01f14fead1218df82f104ff0030108bf0c2106fb01f100fb01f14fead1218df830104ff0020108bf0d2106fb01f100fb01f14fead1218df831104ff0010108bf0e2171434143c90a8df832100cfb06f148434ff0010ec00a002a8df8330000f0768107f010008eea1010002604904ff00008cdf814a009e000bfdde90706069a0644ddf814a0964280f061811af806000896040901d0012113e0971b012f00f056810aeb06014c780cb1022109e0042fc0f04d818a78c97852ea012400f047810421079110f00f0109a810f801a018bf012104984fea0a1e40ea010c14f00300474600f08080b8fbf3f100224f19b7f1ff3fc8bf012202ea0c02012a1dd101fb13814944ca09042a17d87a090e2a14d807eb87020beb82124f08d65dc9076ff00f01029608bf0f210390504608bf7046029e314001430398d155012808f1010751d0b7fbf3f100264a19b2f1ff3fc8bf012606ea0c06012e1ad101fb13714944ce09042e14d856090e2e11d802eb82020beb82124e08c9070390905d6ff00f01574604bf0f2177460140039839439155022808f1020726d0b7fbf3f100224e19b6f1ff3fc8bf012202ea0c02012a18d101fb13714944ca09042a12d872090e2a0fd806eb86020beb82124e08c907905d6ff00f01574604bf0f21774601403943915508f10307611e0329a04405d244e700bf0437b8453ff440afb7fbf3f600227119b1f1ff3fc8bf012202ea0c02012a19d106fb137202eb0906f209042a12d84a090e2a0fd801eb81010beb811172088c5cf6076ff00f06504604bf0f2670463440204388547e1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c00012819d102fb136000eb0906f009042812d848090e280fd801eb81000beb80107108425cf4076ff00f04564604bf0f247646224032434254be1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c00012819d102fb136000eb0906f009042812d848090e280fd801eb81000beb80107108425cf4076ff00f04564604bf0f247646224032434254fe1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c0001287ff47aaf02fb136000eb0906f00904283ff672af48090e283ff66eaf01eb81000beb80107108425cf4076ff00f04564604bf0f2476462240324342545ce7002038604ff0ff300db0bde8f08f10460db0bde8f08f009909eb03002944b0f5207fa8bf4ff42070b1f5f07fa8bf4ff4f071019f484588bfa94203d800200db0bde8f08f3a680f2af8d8a0eb090007ebc203491b5881501ca3f806901d8199813860ebe700bf082a3cbf4ff0ff3070472de9f04f93b015460c4682461f46fcf7bcff002800f02b82e67906f1080085424ff0ff3040f025822178627841ea02254ff640718d4200f21c8246f27029c2f22a09d9f8000094f8068001466ff39601b1f1005f07d101684ef66862ccf2ff02914200f0b8804ff41b70fdf726ff002800f0fa814ff69451cff6ff71002243183e3183f86c2283f86d2283f86e2283f86f2283f8702283f8712283f8722283f8732283f8742283f8752283f8762283f8772283f8782283f8792283f87a2283f87b2283f87c2283f87d2283f87e2283f87f2283f8802283f8812283f8822283f8832283f8842283f8852283f8862283f8872283f8882283f8892283f88a2283f88b2283f88c2283f88d2283f88e2283f88f2283f8902283f8912283f8922283f8932283f8942283f8952283f8962283f8972283f8982283f8992283f89a2283f89b2283f89c2283f89d2283f89e2283f89f2283f8a02283f8a12283f8a22283f8a32283f8a42283f8a52283f8a62283f8a72283f8a82283f8a9227ff480af4ef66861ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe10c9f80000d0f830b2bbf1000f00f04681a1784fea88620e9121790f230d9108f00f0103eae2724a434ff0890c02fb0cf2d20a8df83c200e2294f8039094f805e0cdf8248018f0200f08bf012201fb02f202fb0cf24fead2228df83d204ff00d0208bf022201fb02f202fb0cf24fead2228df83e204ff00c0208bf032201fb02f202fb0cf24fead2228df83f204ff00b0208bf042201fb02f202fb0cf24fead2228df840204ff00a0208bf052201fb02f202fb0cf24fead2228df841204ff0090208bf062201fb02f202fb0cf24fead2228df842204ff0080208bf072201fb02f202fb0cf24fead2228df843204ff0070208bf082201fb02f202fb0cf24fead2228df844204ff0060208bf092201fb02f202fb0cf24fead2228df845204ff0050208bf0a2201fb02f202fb0cf24fead2228df846204ff0040208bf0b2201fb02f202fb0cf24fead2228df847204ff0030208bf0c2201fb02f202fb0cf24fead2228df848204ff0020208bf0d2201fb02f202fb0cf24fead2228df849204ff0010208bf0e2201fb02f202fb0cf24fead2228df84a204ff0000208bf0f22514301fb0cf10023c90a002e8df84b1000f08a820e9a0b9642ea09260d9a0beb05010a9104f1080142ea0e224ff000084ff6fe790e920897cde90c1a05e00b9908f1010888450c995fd011f808104a1e1f2af4d34ab2202a52db0a9a02eb410111f8402c11f83f1c42ea01274ff6ff718f4245d01bf807104ff0ff33002900f053820beb07025478002c00f04d82931c61434ff0000c00bf0ceb07044c452fd003eb0c0215785fea151e05d04ff0010a71451dd224e000bf4ff6fd75ac421fd092f801e0bef1000f04d04ff0020a71450ed215e04ff6fb75651b042d10d39578d27855ea022e0bd04ff0040a714507d3b1eb0e01d444cfd1a1e70020c9f800004ff0ff3013b0bde8f08f08990122063101910999002501f010014ff6ff7c82ea111106910c994a5d1f2a03d8b1180b9c0b39f3e1d0f830124ff0ff33002900f0f3810a9f07eb420212f8407c12f83f2c47ea0222624500f0e78111f802e0bef1000f00f0e18111444c78002c00f0dc8104fb0ef34ff6fd7c002bcde9024500f099818c1c4ff0000b4ff6fe780beb02054545b5d004eb0b073978090901d0012710e06545acd0797809b102270ae04ff6fb71691a0429a3d3b978ff7851ea07219ed004278b429bd35b1abb44ded1bbf1000f00f06f8100254ff00008059406e0099d0799059c0d445d4580f06381615d09950f0901d0012213e0abeb0503012b00f05881621957780fb1022209e0042bc0f050819378d27853ea022700f04a810422079211f00f010faa12f801c018bf0121069a4fea0c1942ea010a17f00304424600f08680b8fbfef5002305fb1e823244b2f1ff3fc8bf012303ea0a03012b1bd10e996d1818d4d309042b15d86b090e2b12d80d9905eb850301eb83135508d20704945c5d6ff00f02614604bf0f2249462240049c0a435a55012c08f1010257d0b2fbfef5002305fb1e223244b2f1ff3fc8bf012303ea0a03012b1bd10e996d1818d4d309042b15d86b090e2b12d80d9905eb8503049401eb83145508d207615d6ff00f02634604bf0f224b460a401a436255049c022c08f1020229d0b2fbfef3002503fb1e223244b2f1ff3fc8bf012505ea0a05012d19d10e995b1816d4d509042d13d85d090e2d10d80d9903eb830301eb83145508d207615d6ff00f02634604bf0f224b460a401a43625508f103027b1e032bb84404d241e7043290453ff43eafb2fbfef5002705fb1e233344b3f1ff3fc8bf012707ea0a07012f19d10e996d1816d4df09042f13d86f090e2f10d80d9905eb850501eb85155f08db07ec5d6ff00f03614604bf0f23494623401943e955511cb1fbfef505fb1e118b190021b3f1ff3fc8bf012101ea0a010e9f012919d1ed1917d4d909042914d869090e2911d80d9c05eb850104eb81115c08db070d5d6ff00f03674604bf0f234f462b403b430e9f0b55911cb1fbfef505fb1e118b190021b3f1ff3fc8bf012101ea0a01012919d1ed1917d4d909042914d869090e2911d80d9c05eb850104eb81115c08db070d5d6ff00f03674604bf0f234f462b403b430e9f0b55d11cb1fbfef505fb1e118b190021b3f1ff3fc8bf012101ea0a0101297ff471afed193ff56eafd90904293ff66aaf69090e293ff666af0d9c05eb850104eb81115c08db070d5d6ff00f03674604bf0f234f462b403b430b5553e70e9d029a06eb0e01ab18b1f5207f0f4626eae672a8bf4ff42077b3f5f07fa8bf4ff4f07397421bdd0b9cab4219d9ddf82080d8f800500f2d13d8ddf838e0019ea3eb0e0cbf1a06ebc50326f835206a1ca3f802e09f80a3f806c0c8f8002000e00b9c039d4ff6ff7c01350023a5420e467ff4fead184613b0bde8f08f062a3cbf4ff0ff3070472de9f04fadf2944d9a46154688460f90fcf767fb002800f0d68098f80510881d854240f0298444f2dc60c2f20700d0f800b0bbf1000f00f01f849bf80c009bf80d209bf80e309bf80f7040ea022040ea034040ea0769a9f1810010f1800f4ff0ff30c0f0b2809bf810209bf811309bf8137042ea03229bf8123042ea034242ea07620692813a12f5817f40f29e800029cdf828b000f09d8008f1060b002426aa4ff4e01c00270ae000bf05f1004042f8240001378f4204f1010480f08e801bf80750681e1e28f0d968b21f2801dd012075e0a5f1c2000beb07061d28a1eb07000fd8012800f0c88396f9010010f1410f00f3c28300f03f0365f38a1302201d465de005f0f003e02b24d10328c0f0b48396f9013013f1410f00f3ae8396f9020010f1410f00f3a883e02ddeb202d1a02ec0f0a283ed2d02d19f2e00f29d832b039bb206f03f0643ea861300f03f001d18032034e004284ff0ff3036d3a5f1f50313f1050f31d396f9013013f1410f2cdc96f9020010f1410f00f37e8396f9036016f1410f00f37883f02ddbb202d1902bc0f07283f42d02d18f2b00f26d830cea854e03f03f054eea053300f03f0043ea801006f03f0326aac518042000bf074442f8245076e74ff0ff300df2944dbde8f08f0021012007915ee0002c57d0a4f1010bcdf86090cdf810a000250df1780a5f46914608e026aaab4505f1010509f10409a7f1010739d052f825100029f3d400202b4687421dd009eb80067268b2f1ff3f18dc5a1c934514d0b268b2f1ff3f11dc9a1c93450dd0f268b2f1ff3f0adcda1c934506d032690433002a00f10400e0d400e000220a9853461aae009601f082fa002800f008831a980028c3d045f265615046c0f24d018847bce7ddf810a0ddf828b0ddf860900020079404e00020ddf828b00790012098f804400f21a20604f00f0501eae271694389225143c90a8df8681001260e2198f800c098f801e098f8023098f8037014f0200f08bf0e2608bf012105fb01f102fb01f14fead1218df869104ff00d0108bf022105fb01f102fb01f14fead1218df86a104ff00c0108bf032105fb01f102fb01f14fead1218df86b104ff00b0108bf042105fb01f102fb01f14fead1218df86c104ff00a0108bf052105fb01f102fb01f14fead1218df86d104ff0090108bf062105fb01f102fb01f14fead1218df86e104ff0080108bf072105fb01f102fb01f14fead1218df86f104ff0070108bf082105fb01f102fb01f14fead1218df870104ff0060108bf092105fb01f102fb01f14fead1218df871104ff0050108bf0a2105fb01f102fb01f14fead1218df872104ff0040108bf0b2105fb01f102fb01f14fead1218df873104ff0030108bf0c2105fb01f102fb01f14fead1218df874104ff0020108bf0d2105fb01f102fb01f14fead1218df8751006fb05f102fb01f14fead1218df876104ff0000108bf0f2169435143c90a00284ff000008df877107ff4cdae43ea0720079a484403904cea0e290af10600571e00260df198080190cdf810a0029718e000bf45f265611ea8c0f24d0188479df87c009df87d10dde90ab9029fdde9072640ea01200df1980801369642814400f0ff8158f82610b1f1ff3f1edd33469f421fd008eb83004268b2f1ff3f1adc0133bb4216d08268b2f1ff3f13dc0133bb420fd0c268b2f1ff3f0cdc0133bb4208d002690133002ae2d404e001f01f000b38d2e7002258461eab19ad009501f041f9002800f0c781199900290d9100f0ba819df880209df881309df87e009df87f1052ea03259df8822040ea01279df8833010979df884704fea024208969df8856042ea0362069b4fea074747ea06672b4403eb2743039fcdf82c90a7eb030609eb22491aaf149500f05e810902109b014400f0030809f101004ff0010c099009f102000ceb530305900d980c934b1e0e930b9b0130121415900ceb510003eb020e9a1acde91180a1eb08001890d0074ff0000a17904feace70169013960ae014980af1010a824512981599139e0144159100f029810aeb06014b090e2befd810980028ecd00e9801eb810103280f984ff0000600eb811e80f0848011980028ded0dde90c105feac67c0afb01084fea560018f8000000f00f03c1b208bf0b09b3fa83f0400910ea141f14d106eb0901c80904280fd848081ef80020fb5c02f00f0b02f0f0021a431aafc90708bf4bea03120ef8002011980128b1d0701c400818f80000bcf1000fc1b24fea111308bf00f00f03d8b2b0fa80f0400910ea141f14d109983118c80904280fd848081ef80020fb5c02f00f0b02f0f0021a431aafc90708bf4bea03120ef80020119802283ff486afb01c400818f80000bcf1000f00f00f01c2b208bf1109b1fa81f0400910ea141f7ff474af05983318d80904283ff66eaf58081ef80020795c02f00f0602f0f0020a43db0708bf46ea01120ef800205de7ddf8548007e000bf18980436b04208f102083ff471af18f8011c0023c9b2102938bf012313ea141f09eb060c16d14feadc13042b12d84fea5c0309091ef80320795c02f00f0b02f0f0020a431aaf5feac97008bf4bea01120ef8032018f8010c00f00f01b1fa81f0400910ea141f15d10cf10103d809042810d858081ef80020795c02f00f03179d43ea011302f0f002002d08bf42ea01030ef8003098f80000c1b210294ff0000038bf012010ea141f15d10cf10203d809042810d8080959081ef80120385c02f00f0302f0f002169d0243002d08bf43ea00120ef8012098f8000000f00f01b1fa81f0400910ea141f8ad10cf10303d80904283ff685af58081ef80020795c02f00f03179d43ea011302f0f002002d08bf42ea01030ef8003072e700bf109809eb00011498b1f5207f06eb000229eae970a8bf4ff42071b2f5f07fa8bf4ff4f072ddf810a081427ff70fae26eae6739a427ff70aaedaf800700f2f3ff605ae019dd21a091a05ebc70625f83700781c7380b180f280caf80000f6e59df87c009df87d10079a40ea012001e64ff0ff300df2944dbde8f08f00200df2944dbde8f08f2de9f04182b046f27027c2f22a073d68884629466ff39601b1f1005f064607d128684ef66861ccf2ff01884200f0b9804ff41b70fcf7a6fe0546002800f0b0804ff69450cff6ff70002100bf2a183e3082f86c1282f86d1282f86e1282f86f1282f8701282f8711282f8721282f8731282f8741282f8751282f8761282f8771282f8781282f8791282f87a1282f87b1282f87c1282f87d1282f87e1282f87f1282f8801282f8811282f8821282f8831282f8841282f8851282f8861282f8871282f8881282f8891282f88a1282f88b1282f88c1282f88d1282f88e1282f88f1282f8901282f8911282f8921282f8931282f8941282f8951282f8961282f8971282f8981282f8991282f89a1282f89b1282f89c1282f89d1282f89e1282f89f1282f8a01282f8a11282f8a21282f8a31282f8a41282f8a51282f8a61282f8a71282f8a81282f8a9127ff480af4ef66860ccf2ff002860012085f8ce004ff0ff30a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200a5f8f400a5f8f600a5f8f800a5f8fa00a5f8fc00a5f8fe003d60b068002818bf002d02d102b0bde8f081b6f84010b6f842205143b1f5163ff4d3c5f8240201264ff4f07085f8286201904ff4207044f267040090c0f2470400200021002200230027a04730b185f82872c5f8247202b0bde8f08188f8046002b0bde8f08100bf2de9f04f8ab0dde914a5089243ea010242ea0a02d207864640f0c4800eeb51004ff0ff374fea5a0c0eeb53068646012207eb5a00bcf1010f88bf4fea5a02069002f003000790caf341006ff00107059007eb5a006ff00207019007eb5a00009022f00302701c544203900ef101004ff0000b09960290cdf810e004e00bf1010bab4500f0c3810898139e5f466fea0b02864288bfaf183a183744099802eb820207eb87070eeb82198b4200eb871835d9059e6246b6b10698012e19f8002008f8002002460ed00198022e19f8002008f80020024606d0009819f8002008f80020024600bf06980328c8d300bf09eb020717f8016c08eb020000f8016c17f8026c043a00f8026c17f8036c00f8036c17f8047c00f8047ce9d1b0e700bfbaf1080f02d2002223e000bf03989601ba0102440298e64600eb060a6ff0030c0aeb0c00c67802eb0c07fe7006790cf1040c3e7146797e71807904eb0c060436b871edd10cf10402dde914a5f446ddf810e0079800283ff483af079e19f80200012e08f802003ff47baf501c079e19f80070022e08f800703ff472af901c19f8002008f800206be74ff6fc7000ea0a000af0030b0990aaf1010000240490cde905be07e0079c159d0134ddf850a0ac4200f01e81089f139ee0432246be42079488bf2a18d01900eb80000eeb801c901900eb8000baf1040f0eeb80184ff00009c0f09880ddf810a0ddf850e048468b4288bf504600eb010400eb03054fea54001cf800706ff0010080ea090009f1010288bf0eeb00026ff0020089ea000609f1020088bf0eeb06006ff0030686ea090609f1030b4feac47488bf0eeb060b07f00f06002c4fea550408bf3e0918f80470ed0707f00f0507f0f007374408bf45ea061708f80470541865081cf805501a44e40705f00f064fea520408bf2e0918f80450d20705f00f0205f0f005354408bf42ea0615421808f8045054081cf804401844d20704f00f054fea500208bf250918f80240c00704f00f0004f0f0042c4408bf40ea05140beb010008f8024042081cf802200beb0304c00702f00f054fea540008bf150918f80020e40702f00f0402f0f0022a4408bf44ea051208f80020099809f104098145aaf1040a7ff46eafdde905bebbf1000f3ff444af6fea09004a468b42149f88bf3a18501845081a44c0071cf805504fea520018f8007005f00f0408bf2c0907f00f0507f0f0072744d20708bf45ea0417bbf1010f08f800703ff420af149809f10102a0eb090a8b4288bfaaf10202541865081a44e4071cf805504fea520418f8040005f00f0708bf2f0900f00f0500f0f0003844d20708bf45ea0710bbf1020f08f804003ff4faae09f102008b4288bfaaf10300421854081844d2071cf804704fea500218f8024007f00f0508bf3d0904f00f0704f0f0042c44c00708bf47ea051408f80240d9e60ab0bde8f08f00bf70b546f27026c2f22a0632680c4611466ff39601b1f1005f054607d110684ef66861ccf2ff01884200f0b9804ff41b70fcf79afb002800f0fc8002464ff69450cff6ff70002100bf13183e3083f86c1283f86d1283f86e1283f86f1283f8701283f8711283f8721283f8731283f8741283f8751283f8761283f8771283f8781283f8791283f87a1283f87b1283f87c1283f87d1283f87e1283f87f1283f8801283f8811283f8821283f8831283f8841283f8851283f8861283f8871283f8881283f8891283f88a1283f88b1283f88c1283f88d1283f88e1283f88f1283f8901283f8911283f8921283f8931283f8941283f8951283f8961283f8971283f8981283f8991283f89a1283f89b1283f89c1283f89d1283f89e1283f89f1283f8a01283f8a11283f8a21283f8a31283f8a41283f8a51283f8a61283f8a71283f8a81283f8a9127ff480af4ef66860ccf2ff001060012082f8ce004ff0ff30a2f8e000a2f8e200a2f8e400a2f8e600a2f8e800a2f8ea00a2f8ec00a2f8ee00a2f8f000a2f8f200a2f8f400a2f8f600a2f8f800a2f8fa00a2f8fc00a2f8fe0032600120002d82f8cc0047d0104630f8e01fa1423bd0b2f8e210a14237d0b2f8e410a14233d0b2f8e610a1422fd0b2f8e810a1422bd0b2f8ea10a14227d0b2f8ec10a14223d0b2f8ee10a1421fd0b2f8f010a1421bd0b2f8f210a14217d0b2f8f410a14213d0b2f8f610a1420fd0b2f8f810a1420bd0b2f8fa10a14207d0b2f8fc10a14203d0b2f8fe10a1420ad1012082f8de0070bd0020306070bd82f8cd00002070bd92f8cd1081b9b2f8c810611a0bb2b3f1ff3f06dd89b2022924bf012182f8dd1002e0012182f8dc10b2f8ca30002182f8cd109c42a2f8c84088bfa2f8ca4092f8001120f81140481c00f00f0082f80001002070bd2de9f04fcdb04ef687249246c0f25b044df2546298460e4604f13c07c0f278020f2138230546b84718b12846a047002423e20afb08f040000b960295059001250da94ff4807004f585724ff0000b4ff0000947464ff000080023564604930a930697cdf820a00192029ce1602061204600219047e1680daa891a07910da900f0e681ddf82ce00021002400900be000bf04940c9c002101234ff0030807980134844200f0d181002940f0e0810da80c94045db8f1020febd0b8f1010f00f09280b8f1000f40f0968004f00f000a900598210900f0a6808842c0f08880401a05900a9800eb00140001039014e01cf80b000a9a00f0f00010440cf80b000bf1010b01390125b34524bf4ff0000b09f10109002900f08c81b9454ff000084ff0000338bf012380f0028109eb8900002d0eeb801cdbd0cdf82490a946a6eb0b05b5eb510f88bf4d088db3a8080ceb0b0820d0002708f10102a7eb80006ff0030600bf02eb060e043600eb060a1af104078ef803408ef804408ef805408ef80640efd1301d069f089eddf82ce015f0030204d10ce0002015f0030208d0012a08f8004004d04044022a447018bf8470a1eb4501ab4489b1b34510d21cf80b00039a00f00f001043ddf824900cf80b00013900250029a0d12be100bf00214d46ddf8249090e700bfbcb10598a04228d201214ff0000821e0ddf810a005985aea042a16d00c9c5045cdf810a080f0938001214ff00008002342e70c9c002101234ff002083ce70c9c00214ff00108012336e7002001214ff0000804900c9c00232ee7001b05900a9800eb00110001099015e000bf1af80b200a9802f0f00202430af80b200bf1010b013c0125b34524bf4ff0000b09f10109002c00f0da80b9454ff000084ff0000338bf012350d209eb8902002d0eeb821adcd0ac46a6eb0b05b5eb540f88bf650855b3ae080aeb0b0818d0002008f10102a0eb860e6ff00306901904360eeb06070437c170017141718171f5d1069fddf82ce0321d15f0030604d10de0002215f0030609d0012e08f8021005d04244022e517018bf917000bfa4eb4504ab447cb1089eb3450ed21af80b00099a00f00f0010430af80b00013c0025002cabd184e0089e002465469de70c9c0121b4e6a0eb0a0005900a9800eb00110001099015e01cf80b000a9a00f0f00010430cf80b000bf1010baaf1010a0125b34524bf4ff0000b09f10109baf1000f65d0b9454ff000084ff0000338bf01235bd20b9a09eb8900002d02eb801cdad0ce46a946a6eb0b05b5eb5a0f88bf4fea5a0545b3a8080ceb0b0817d0002408f10102a4eb80006ff003069719043684190434f97039717971b971f6d1301d069f089e0c9c15f0030204d10ce0002015f0030208d0012a08f8001004d04044022a417018bf8170aaeb450abaf1000fab4411d0b34511d21cf80b00099a00f00f0010430cf80b00aaf1010a0025f146baf1000fa6d10be04ff0000a4d46f14697e70c9c4ff00008002131e6012102e04ff000080021ddf82ce029e600980da973b1012817d04ff0000450b90798019ab0fa80f040094ff480703ff4ffad00e0002402984ef68721c0f25b01884720464db0bde8f08f059840ea0800b0fa80f04409eee72de9f04f83b00c9e0292002e019000f08e80019823f00304471c029803f0030ac4f1000c01384ff00008009005e000bf08f10108b0450f4479d00e98c14600286fea080418bf06eb0409002bf0d0042b06d24ff0000bbaf1000f2ed1e8e700bf0d98b64609fb00f400986ff003050444607800f0f00242ea10107a19d0706078043500f00f0646ea0010107114f8020f00f0f00646ea10105071207800f00f0646ea00100ceb050604369071e0d105f1040b7646baf1000fbad002980d9a4fea5b0509fb0204019814f805e008fb01050ef00f025feacb7908bf4fea1e1242ea0212baf1010f05f80b20a1d00bf1010e4fea5e00205cb9f1000f4fea101208bf00f00f0242ea0210baf1020f05f80e008ed00bf102004208a25cb9f1000f02f00f0408bf140944ea04122a5480e703b0bde8f08f2de9f04182b003fb02f68846cde9001645f20f1107466846c0f247011c461546884740f2196047f8240f788948f2816245ea0040b86045ea044057f8204c7860c0f2490220463946fe60c7f81080904740f25761c0f244012046884702b0bde8f08100bf2de9f04188b045f213661c46c0f24d0613460a46ddf83880002706f1ae05214627706770a770e77027716771a771e77127726772a772e77227736773a773e77327746774a774e77427756775a775e77527766776a776e77627776777a777e777a8470028c8f800705cd020786178a278e3780843104318434ff0010008d0e179a27911431ebf617a227a51ea020102d108b0bde8f081a07b14284ff00000f7d1217d8df8040041f0010121758df805008df806008df807008df808008df809008df80a008df80b008df80c008df80d008df80e008df80f008df810008df811008df812008df813008df814008df815008df816008df817008df818008df819008df81a008df81b008df81c008df81d008df81e008df81f0001a92046b047c8f8000018b1012008b0bde8f08106f1520120468847d8f80000002818bf012008b0bde8f0814556454e4346572f313620696d6736343020696d677a20726c652077616b656c65617365206469726563746662206662677561726420776561726e6f7469667920636c65616e75703131207465786361636865313220746578696d67313320746578737472313420666f6e743135206d696363746c0000000000000000000000000000002020202020002020000000505050000000000000000000005050f85050f85050000000002070a8a07028a8702000000048a85010202854480000000020505020689090680000002020200000000000000000000010204040404020100000000040201010101020400000000000005020f82050000000000000002020f82020000000000000000000000020204000000000000000f800000000000000000000000000202000000000080810102020404000000000708898a8c88888700000000020602020202020700000000070888808102040f8000000007088083008088870000000000818284888f8080800000000f88080f00808887000000000708080f08888887000000000f808081010202020000000007088887088888870000000007088888878080870000000000000202000002020000000000000202000002020400000000008102040201008000000000000f80000f8000000000000004020100810204000000000708888102000202000000000708898a8a89880780000000070888888f888888800000000f08888f0888888f000000000708880808080887000000000e0908888888890e000000000f88080f0808080f800000000f88080f0808080800000000070888080b888887000000000888888f888888888000000007020202020202070000000003810101010909060000000008890a0c0c0a090880000000080808080808080f80000000088d8a8a888888888000000008888c8a89888888800000000708888888888887000000000f0888888f080808000000000708888888888a87008000000f0888888f0a0908800000000708880700808887000000000f8202020202020200000000088888888888888700000000088888850505020200000000088888888a8a8d88800000000888850202050888800000000888850502020202000000000f8081020408080f8000000007040404040404070000000004040202010100808000000007010101010101070000000205088000000000000000000000000000000000000f80040200000000000000000000000000000700878888878000000008080f088888888f00000000000007088808088700000000008087888888888780000000000007088f8808078000000001820702020202020000000000000788888888878087000008080f08888888888000000202000602020202070000000080800180808080808483000004040485060605048000000006020202020202070000000000000f0a8a8a8a8a8000000000000f08888888888000000000000708888888870000000000000f088888888f0808000000000788888888878080800000000b8c0808080800000000000007880700808f00000000020207020202020180000000000008888888888780000000000008888505020200000000000008888a8a8a870000000000000885020205088000000000000888888888878087000000000f810204080f800000000182020402020201800000000202020202020202000000000601010081010106000000048a8900000000000000000",
+ "new": "02fb01f000e000bfb0b54ff2ac44c2f229040146206846f23f52c5f28802b2eb500f40f258304cf2e9124cf67e25c2f20000c0f24802caf2101518bf25609047002804bf691c2160b0bd00bf0846ffe7014640f258304cf20732c2f20000c0f24802104770b500284ed001684ef66a62ccf2ff02914218bf70bd90f8081190f8095146f6756c8d42c0f2510c2ad205eb8501014491f80d2191f80e4191f80ae191f80b3191f80c1142ea0424012c4ff0010298bf14466e1c054680f80961b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f80811bde870406047e047d5f8040138b142f64d42c0f244022146bde87040104770bd00bf2de9f04f9db04ff2a84ac2f2290adaf800b058466ff39600b0f1005f40f07d81dbf800004ef66a67ccf2ff07b84240f074819bf82802002800f05d81dbf82442002c00f0588140f6b400c2f20000d0f8008004a802f0d4ffb8f1000f00f02382032045f24075cff68070a4f1600108f160026ff0bf03c0f2020500bf0e6ed41826664e6ec03366668e6eab42a666ce6ee6660e6f26674e6f66678e6fa667ce6fe667d1f88060c4f88060d1f88460c4f88460d1f88860c4f88860d1f88c60c4f88c60d1f89060c4f89060d1f89460c4f89460d1f89860c4f89860d1f89c60c4f89c60d1f8a060c4f8a060d1f8a460c4f8a460d1f8a860c4f8a860d1f8ac60c4f8ac60d1f8b060c4f8b060d1f8b460c4f8b460d1f8b860c4f8b860d1f8bc60c4f8bc6051f8c06fc4f8c0604e68c4f8c4608e68c4f8c860ce68c4f8cc600e69c4f8d0604e69c4f8d4608e69c4f8d860ce69c4f8dc600e6ac4f8e0604e6ac4f8e4608e6ac4f8e860ce6ac4f8ec600e6bc4f8f0604e6bc4f8f4608e6bc4f8f860ce6bc4f8fc600e6cc4f800614e6cc4f804618e6cc4f80861ce6cc4f80c610e6dc4f810614e6dc4f814618e6dc4f81861ce6dc4f81c617ff462afdaf800603040b0f1005f40f0b2803068b84240f0ae8096f8ce00002840f07a8196f8dc10002000298df8140000f0f28105a90a5c002a00f0c5810a185378002b00f083819378002b00f08181d378002b00f07f811379002b00f07d815379002b00f07b819379002b00f07981d379002b00f07781137a002b00f07581537a002b00f07381937a002b00f07181d37a002b00f06f81137b002b00f06d81537b002b00f06b81937b002b00f06981d37b002b00f06781137c002b00f06581537c002b00f06381937c002b00f06181d37c002b00f05f81137d002b00f05d81537d002b00f05b81937d002b00f05981d37d002b00f05781137e002b00f05581537e002b00f05381937e002b00f05181d37e002b00f04f81137f002b00f04d81537f002b00f04b81937f002b00f04981d27f002a00f04781203060287ff47baf66e19bf82a0270b1dbf82c0240b146f68051c2f207010968401a002800f3f48000208bf82a0240f6d100c0f247001db0bde8f04f00474ff4497005f0e5f8002800f0c7804ff6dc41cff6ff71002200bf4318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af012180f8ce104ff0ff310760a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1010e000208bf82802cbf824028bf82a0201208bf8290240f6d100c0f24700804715e00020caf8000000208bf82802cbf824024ff416304cf60361069005a8c0f24701cdf81480884701208bf82a0204a802f0b4fecbf8d4001db0bde8f08f01303ae0023038e0033036e0043034e0053032e0063030e007302ee008302ce009302ae00a3028e00b3026e00c3024e00d3022e00e3020e00f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f2821d84ff052020a541dd0014445225e284a7018d04f225d288a7014d052225c28ca7010d044225b280a710cd045225a284a7108d0522259288a7104d020225828ca7142f0168500208df87300012096f8dd10002900f0c280002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf54e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2915d84ff05303535411d00a444b235e2953700cd049235d29937008d050235c29d37004d020235b29137140f0c28200218df87310013096f8de10002900f0be80002105aa535c002b00f0a08057187b78002b5ed0bb78002b5dd0fb78002b5cd03b79002b5bd07b79002b5ad0bb79002b59d0fb79002b58d03b7a002b57d07b7a002b56d0bb7a002b55d0fb7a002b54d03b7b002b53d07b7b002b52d0bb7b002b51d0fb7b002b50d03b7c002b4fd07b7c002b4ed0bb7c002b4dd0fb7c002b4cd03b7d002b4bd07b7d002b4ad0bb7d002b49d0fb7d002b48d03b7e002b47d07b7e002b46d0bb7e002b45d0fb7e002b44d03b7f002b43d07b7f002b42d0bb7f002b41d0fb7f002b40d0203160297ff49aaf50e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2911d84ff0440353540dd00a4455235e29537008d050235d29937004d020235c29d37040f08e8000218df87310013096f8df10002900f0cd80002005a90a5c002a00f0a3800a185378002b5ed09378002b5dd0d378002b5cd01379002b5bd05379002b5ad09379002b59d0d379002b58d0137a002b57d0537a002b56d0937a002b55d0d37a002b54d0137b002b53d0537b002b52d0937b002b51d0d37b002b53d0137c002b52d0537c002b51d0937c002b50d0d37c002b4fd0137d002b4ed0537d002b4dd0937d002b4cd0d37d002b4bd0137e002b4ad0537e002b49d0937e002b48d0d37e002b47d0137f002b46d0537f002b45d0937f002b44d0d27f002a43d0203060287ff49aaf5fe001303de002303be0033039e0043037e0053035e0063033e0073031e008302fe009302de00a302be00b3029e00c3027e00d3025e00e3023e00021117171e70f301ee010301ce011301ae0123018e0133016e0143014e0153012e0163010e017300ee018300ce019300ae01a3008e01b3006e01c3004e01d3002e01e3000e01f305f281dd84ff053020a5419d001444e225e284a7014d041225d288a7010d050225c28ca700cd04f225b280a7108d046225a284a7104d0202259288a7142f0b28200208df873000120daf8041046f23f52c5f28802b2eb510f40f08b80c90700f08e80002005a90a5c002a00f083810a185378002b00f0f7809378002b00f0f780d378002b00f0f7801379002b00f0f7805379002b00f0f7809379002b00f0f780d379002b00f0f780137a002b00f0fa80537a002b00f0fa80937a002b00f0fa80d37a002b00f0fa80137b002b00f0fa80537b002b00f0fa80937b002b00f0fa80d37b002b00f0fa80137c002b00f0fa80537c002b00f0fa80937c002b00f0fa80d37c002b00f0fa80137d002b00f0fa80537d002b00f0fa80937d002b00f0fa80d37d002b00f0fa80137e002b00f0fa80537e002b00f0fa80937e002b00f0fa80d37e002b00f0fa80137f002b00f00b81537f002b00f00981937f002b00f00781d27f002a00f00581203060287ff47baf1be14cf67e21caf21011caf80410002840f01681002005a90a5c002a00f0d9800a185378002b5ed09378002b5dd0d378002b5cd01379002b5bd05379002b5cd09379002b5dd0d379002b5ed0137a002b5fd0537a002b60d0937a002b61d0d37a002b65d0137b002b66d0537b002b67d0937b002b68d0d37b002b69d0137c002b6ad0537c002b6bd0937c002b6cd0d37c002b6dd0137d002b6ed0537d002b6fd0937d002b70d0d37d002b71d0137e002b72d0537e002b73d0937e002b74d0d37e002b75d0137f002b76d0537f002b77d0937f002b78d0d27f002a79d0203060287ff49aafa9e0013073e0023071e003306fe004306de0013084e0053069e0023080e0063065e003307ce0073061e0043078e008305de0053074e0093059e0063070e00a3055e007306ce0002151713de50b304ee0083065e00c304ae0093061e00d3046e00a305de00e3042e00b3059e00f303ee00c3055e010303ae00d3051e0113036e00e304de0123032e00f3049e013302ee0103045e014302ae0113041e0153026e012303de0163022e0133039e017301ee0143035e018301ae0153031e0193016e016302de01a3012e0173029e01b300ee0183025e01c300ae0193021e01d3006e01a301de01e3002e01b3019e01f305f2831d84ff04f020a542dd001444b225e284a7028d020225d288a7024d00020c87024e01c3004e01d3002e01e3000e01f305f2818d84ff041020a5414d001444c225e284a700fd05d288a700cd04f225c28ca7008d043225b280a7104d020225a284a7142f0018100208df8730005a80021cdf80880804618f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff0770008f8010003d100208df8730003e008eb010000214170d6f8d0704ff0000918f80900002800f0c48008eb09014878002862d08878002862d0c878002862d00879002862d04879002862d08879002862d0c879002862d0087a002862d0487a002862d0887a002862d0c87a002862d0087b002862d0487b002862d0887b002862d0c87b002862d0087c002862d0487c002862d0887c002862d0c87c002862d0087d002862d0487d002862d0887d002862d0c87d002862d0087e002862d0487e002862d0887e002862d0c87e002862d0087f002862d0487f002862d0887f002862d0c87f002862d009f12009b9f1600f7ff496af4ff060095be009f1010958e009f1020955e009f1030952e009f104094fe009f105094ce009f1060949e009f1070946e009f1080943e009f1090940e009f10a093de009f10b093ae009f10c0937e009f10d0934e009f10e0931e009f10f092ee009f110092be009f1110928e009f1120925e009f1130922e009f114091fe009f115091ce009f1160919e009f1170916e009f1180913e009f1190910e009f11a090de009f11b090ae009f11c0907e009f11d0904e009f11e0901e009f11f090a2f4ff0010103961ed364204ff47a7542f2107401eb81035b00b7fbf3f60a2e11d301fb00f3b7fbf3f60a2e0bd301fb05f3b7fbf3f60a2e05d36143b7fbf1f3092be7d800e01946cc46b9f15f0f98bf4ff05f0cccf1000e1eeb090052d0b7fbf1f34cf6cd4203f13004ccf6cc4208f809400a29a1fb025446d3451c42d003fb1173e608b3fbf6f448f21f5204f1300508eb0907c5f2eb127d706429a1fb025835d3851c36d004fb16334fea5814b3fbf4f644f6d35206f13005c1f26202bd70b1f57a7fa1fb022526d303300df1140818d006fb1430aa0941f25974b0fbf2f3cdf2b714a1fb044503f13004fc7003fb120742f2107009f1040981424fea5531aad20de0e1460be009f1010908e009f1020903e0e14601e009f103090df11408039b002108f8091018f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af52e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2913d84ff0750008f801000ed008eb010073225e29427008d020225d29827004d070225c29c27040f09e8000208df87300d3f8d4104ff0000918f80900002800f0c78008eb09035878002862d09878002862d0d878002862d01879002862d05879002862d09879002862d0d879002862d0187a002862d0587a002862d0987a002862d0d87a002862d0187b002862d0587b002862d0987b002862d0d87b002865d0187c002865d0587c002865d0987c002865d0d87c002865d0187d002865d0587d002865d0987d002865d0d87d002865d0187e002865d0587e002865d0987e002865d0d87e002865d0187f002865d0587f002865d0987f002865d0d87f002865d009f12009b9f1600f7ff496af4ff060095ee009f101095be009f1020958e009f1030955e009f1040952e009f105094fe009f106094ce009f1070949e009f1080946e009f1090943e009f10a0940e009f10b093de009f10c093ae009f10d0937e009f10e0934e00021017161e709f10f092ee009f110092be009f1110928e009f1120925e009f1130922e009f114091fe009f115091ce009f1160919e009f1170916e009f1180913e009f1190910e009f11a090de009f11b090ae009f11c0907e009f11d0904e009f11e0901e009f11f0901230a291ed364204ff47a7742f2107503eb83067600b1fbf6f40a2c11d303fb00f6b1fbf6f40a2c0bd303fb07f6b1fbf6f40a2c05d36b43b1fbf3f6092ee7d800e03346ce46b9f15f0f98bf4ff05f0ecef1000842f2107c18eb09004ed0b1fbf3f405aa04f1300502f809504cf6cd42ccf6cc420a2ba3fb025641d3451c3dd004fb1317f608b7fbf6f405a948f21f5204f130054944c5f2eb124d70642ba3fb022530d3821c29d004fb16776c09b7fbf4f6b3f57a7f06f130028a7044f6d352c1f26202a3fb022520d3033016d006fb1470aa0941f25975b0fbf2f4cdf2b715a3fb055604f13005cd7004fb120109f1040963454fea5633aed209e0f14607e009f1010904e009f1020901e009f1030900210df1140808f80910ddf8089018f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af4ae001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f290bd84ff0750008f8010006d008eb010073225e29427040f00f8100208df8730040f2403cc2f2000cdcf81c1045f2a800c2f2130042f2a0038142c2f2200328d1dcf82810b1f54d2f23d1dcf82c1081421fd145f61c540022c2f213044cf639471d1d4ff0ff3eac4213d8216831f0030000f0a683a34228bf0c290cd31e1bb04209d8c90718bf02442044013f00f10404e9d14ff0ff3e46f68050c2f20700d0f8880003f1080142f6a0038842c2f2270321d142f61c550022c2f2200546f6b974181d854217d8296831f0030700f0d980ab424ff0ff36039628bf0c290ed35e1bb7420bd8c90705eb070118bf3a44013c01f10405e5d14ff0ff300390dcf8001003f1080081422bd1dcf80c10b1f5333f26d1dcf81010814222d143f21c530021c2f2270342f6f932aaf10404aaf108004ff0ff3ca34213d81e6836f0030500f04683984228bf0c2e0cd3c71abd4209d8f7072b4418bf2944013a03f10403e9d14ff0ff3c002118f80100002800f0aa8008eb01046078002861d0a078002860d0e07800285fd0207900285ed0607900285dd0a07900285cd0e07900285bd0207a00285ad0607a002859d0a07a002858d0e07a002857d0207b002856d0607b002855d0a07b002854d0e07b002853d0207c002852d0607c002851d0a07c002856d0e07c002855d0207d002854d0607d002853d0a07d002852d0e07d002851d0207e002850d0607e00284fd0a07e00284ed0e07e00284dd0207f00284cd0607f00284bd0a07f00284ad0e07f002849d0203160297ff498af77e000218170f0e6013140e002313ee003313ce004313ae0053138e0063136e0073134e0083132e0093130e00a312ee00b312ce00c312ae00d3128e00e3126e00f3124e0103122e0113120e0854218bf4ff0ff32039236e7123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f292fd84ff0200008f801002ad008eb010366205e29587024d031205d29987020d033205c29d8701cd02f205b29187118d032205a29587114d030205929987110d02f205829d8710cd032205729187208d037205629587204d03d205529987241f0928200208df873001ef10100cdf804c000f090804fea9e214ff0000a18f80a00002800f0898108eb0a046078002800f00b81a078002800f00a81e078002800f009812079002800f008816079002800f00781a079002800f00681e079002800f00581207a002800f00481607a002800f00381a07a002800f00281e07a002800f00181207b002800f00081607b002800f0ff80a07b002800f0fe80e07b002800f0fd80207c002800f0fc80607c002800f0fb80a07c002800f0fc80e07c002800f0fd80207d002800f0fe80607d002800f0ff80a07d002800f00081e07d002800f00181207e002800f00281607e002800f00381a07e002800f00481e07e002800f00581207f002800f00681607f002800f00781a07f002800f00881e07f002800f009810af1200abaf1600f7ff477af4ff0600a01e1039b002118f80100002800f0ba8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f03b81203160297ff479af3de10af1010a74e00af1020a71e00af1030a6ee00af1040a6be00af1050a68e00af1060a65e00af1070a62e00af1080a5fe00af1090a5ce00af10a0a59e00af10b0a56e00af10c0a53e00af10d0a50e00af10e0a4de00af10f0a4ae00af1100a47e00af1110a44e0013101e10af1120a3fe00231fce00af1130a3ae00331f7e00af1140a35e00431f2e00af1150a30e00531ede00af1160a2be00631e8e00af1170a26e00731e3e00af1180a21e00831dee00af1190a1ce00931d9e00af11a0a17e00a31d4e00af11b0a12e00b31cfe00af11c0a0de00c31cae00af11d0a08e00d31c5e00af11e0a03e00e31c0e00af11f0a0122bef5205f1ed364204ff47a7342f2107502eb82077f00b1fbf7f40a2c11d302fb00f7b1fbf7f40a2c0bd302fb03f7b1fbf7f40a2c05d36a43b1fbf2f7092fe7d800e03a46d146baf15f0f98bf4ff05f09c9f1000842f2107e18eb0a004ed0b1fbf2f305af03f1300407f80a404cf6cd47ccf6cc470a2aa2fb075441d3451c3dd003fb1217e308b7fbf3f405a948f21f5604f130055144c5f2eb164d70642aa2fb06c530d3861c29d004fb13736c09b3fbf4f7b2f57a7f07f130068e7044f6d356c1f26206a2fb066520d3033016d007fb1430ab0941f25976b0fbf3f7cdf2b716a2fb066507f13006ce7007fb13010af1040a72454fea5532aed209e0ca4607e00af1010a04e00af1020a01e00af1030a00200df11408dde9029308f80a003ce00f312be0103129e0113127e0123125e0133123e0143121e015311fe016311de017311be0183119e0193117e01a3115e01b3113e01c3111e01d310fe01e310de0ac4218bf4ff0ff329646fff764bca34218bf4ff0ff318c46c4e41f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff02f0008f8010003d100208df8730003e008eb010000214170ddf804a0581c00f08f80990a4ff0000c18f80c00002800f0888108eb0c046078002800f00a81a078002800f00981e078002800f008812079002800f007816079002800f00681a079002800f00581e079002800f00481207a002800f00381607a002800f00281a07a002800f00181e07a002800f00081207b002800f0ff80607b002800f0fe80a07b002800f0fd80e07b002800f0fc80207c002800f0fb80607c002800f0fa80a07c002800f0fb80e07c002800f0fc80207d002800f0fd80607d002800f0fe80a07d002800f0ff80e07d002800f00081207e002800f00181607e002800f00281a07e002800f00381e07e002800f00481207f002800f00581607f002800f00681a07f002800f00781e07f002800f008810cf1200cbcf1600f7ff477af4ff0600c00e1002118f80100002800f0ad8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f02e81203160297ff479af30e10cf1010c74e00cf1020c71e00cf1030c6ee00cf1040c6be00cf1050c68e00cf1060c65e00cf1070c62e00cf1080c5fe00cf1090c5ce00cf10a0c59e00cf10b0c56e00cf10c0c53e00cf10d0c50e00cf10e0c4de00cf10f0c4ae00cf1100c47e00cf1110c44e00131f4e00cf1120c3fe00231efe00cf1130c3ae00331eae00cf1140c35e00431e5e00cf1150c30e00531e0e00cf1160c2be00631dbe00cf1170c26e00731d6e00cf1180c21e00831d1e00cf1190c1ce00931cce00cf11a0c17e00a31c7e00cf11b0c12e00b31c2e00cf11c0c0de00c31bde00cf11d0c08e00d31b8e00cf11e0c03e00e31b3e00cf11f0c0124b3f5205f1ed364204ff47a7342f2107704eb84067600b1fbf6f50a2d11d304fb00f6b1fbf6f50a2d0bd304fb03f6b1fbf6f50a2d05d37c43b1fbf4f6092ee7d800e03446e146bcf15f0f98bf4ff05f09c9f1000842f2107e18eb0c004ed0b1fbf4f305aa03f1300702f80c704cf6cd42ccf6cc420a2ca4fb027541d3471c3dd003fb1417eb08b7fbf3f505a948f21f5205f130066144c5f2eb124e70642ca4fb022630d3821c29d005fb13737509b3fbf5f7b4f57a7f07f130028a7044f6d352c1f26202a4fb022620d3033016d007fb1530b20941f25975b0fbf2f3cdf2b715a4fb055603f13005cd7003fb12010cf1040c74454fea5634aed209e0cc4607e00cf1010c04e00cf1020c01e00cf1030c00200df11408ddf8089008f80c002fe00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff02f0008f8010003d100208df8730003e008eb0100002141701af1010000f090804fea9a214ff0000918f80900002800f0888108eb09046078002800f00a81a078002800f00981e078002800f008812079002800f007816079002800f00681a079002800f00581e079002800f00481207a002800f00381607a002800f00281a07a002800f00181e07a002800f00081207b002800f0ff80607b002800f0fe80a07b002800f0fd80e07b002800f0fc80207c002800f0fb80607c002800f0fa80a07c002800f0fb80e07c002800f0fc80207d002800f0fd80607d002800f0fe80a07d002800f0ff80e07d002800f00081207e002800f00181607e002800f00281a07e002800f00381e07e002800f00481207f002800f00581607f002800f00681a07f002800f00781e07f002800f0088109f12009b9f1600f7ff477af4ff0600900e1002118f80100002800f0ad8108eb01025078002800f0b0809078002800f0b180d078002800f0b2801079002800f0b3805079002800f0b4809079002800f0b580d079002800f0b680107a002800f0b780507a002800f0b880907a002800f0b980d07a002800f0ba80107b002800f0bb80507b002800f0bc80907b002800f0bd80d07b002800f04e81107c002800f04c81507c002800f04a81907c002800f04881d07c002800f04681107d002800f04481507d002800f04281907d002800f04081d07d002800f03e81107e002800f03c81507e002800f03a81907e002800f03881d07e002800f03681107f002800f03481507f002800f03281907f002800f03081d07f002800f02e81203160297ff479af30e109f1010974e009f1020971e009f103096ee009f104096be009f1050968e009f1060965e009f1070962e009f108095fe009f109095ce009f10a0959e009f10b0956e009f10c0953e009f10d0950e009f10e094de009f10f094ae009f1100947e009f1110944e00131f4e009f112093fe00231efe009f113093ae00331eae009f1140935e00431e5e009f1150930e00531e0e009f116092be00631dbe009f1170926e00731d6e009f1180921e00831d1e009f119091ce00931cce009f11a0917e00a31c7e009f11b0912e00b31c2e009f11c090de00c31bde009f11d0908e00d31b8e009f11e0903e00e31b3e009f11f090123baf5205f1ed364204ff47a7742f2107603eb83056d00b1fbf5f40a2c11d303fb00f5b1fbf5f40a2c0bd303fb07f5b1fbf5f40a2c05d37343b1fbf3f5092de7d800e02b46ce46b9f15f0f98bf4ff05f0ecef1000842f2107c18eb09004ed0b1fbf3f405aa04f1300502f809504cf6cd42ccf6cc420a2ba3fb025741d3451c3dd004fb1316ff08b6fbf7f405a948f21f5204f130054944c5f2eb124d70642ba3fb022530d3821c29d004fb17676c09b7fbf4f6b3f57a7f06f130028a7044f6d352c1f26202a3fb022520d3033016d006fb1470aa0941f25975b0fbf2f4cdf2b715a3fb055604f13005cd7004fb120109f1040963454fea5633aed209e0f14607e009f1010904e009f1020901e009f1030900200df1140808f80900ddf808902fe00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff03f0008f8010003d100208df8730003e008eb010000214170002118f80100002800f0a18008eb0102507800285ed0907800285dd0d07800285cd0107900285bd0507900285ad09079002859d0d079002858d0107a002857d0507a002856d0907a002855d0d07a002854d0107b002853d0507b002852d0907b002851d0d07b002850d0107c00284fd0507c00284ed0907c00284dd0d07c00284cd0107d00284bd0507d00284ad0907d002849d0d07d002848d0107e002847d0507e002846d0907e002845d0d07e002844d0107f002843d0507f002842d0907f002841d0d07f002840d0203160297ff498af43e001313ae0023138e0033136e0043134e0053132e0063130e007312ee008312ce009312ae00a3128e00b3126e00c3124e00d3122e00e3120e00f311ee010311ce011311ae0123118e0133116e0143114e0153112e0163110e017310ee018310ce019310ae01a3108e01b3106e01c3104e01d3102e01e3100e01f315f2904d84ff06b0008f8010003d100208df8730003e008eb0100002141709df814a0baf1000f10d0022208eb020010f8013c63b118f8023063b143784bb1807804320028f1d1023a04e0002005e0013a00e0013202eb4200400040eae070821c09f5207c00f1010e02f0030822f0030709f5a0724ff0ff3504e001350d2d02f5a07268d005eb8500bef1030f0ceb801405d24ff0ff30b8f1000f2dd1ede70020164603e0874206f1020621d0431cdb09042b03d8337803f0f0033370831cdb09042b03d8737803f00f037370c31cdb09042b03d8737803f0f00373700430c309042bdfd84308e15c01f00f01e154d9e70138b8f1000fc0d0861cf109042908d87108635cc6076ff00f0608bf0f2633406354b8f1010fb0d0c61cf109042909d87108635cc6074ff00f0608bf6ff00f0633406354b8f1020f9fd0061df10904299bd87108c007635c6ff00f0008bf0f201840605491e7baf1000f00f0ab800298022200f281280df1140e40f27d2940f27a2c08e01ef801af0632baf1000f08f1030800f09780aaf17f0010f15f0ff1d347f23421c0f200010aeb4a00794401eb8000a0f5c0710027d409404605e000bf02370c2f00f52070dcd0cb57042c06d8b3f1ff3f03dc067846f0f0060670042cdeb206d816f0400303d0037843f00f030370b30605d54a4503d8437843f0f0034370f30606d5b2f51f7f03d8437843f00f03437033074fea920305d59e2b03d8857845f0f0058570750705d5624503d8857845f00f058570cd1995f90160042c08d8b6f1ff3f05dc90f8405145f0f00580f84051042cf6b208d816f0400505d090f8405145f00f0580f84051b50607d54a4505d890f8415145f0f00580f84151f50608d5b2f51f7f05d890f8415145f00f0580f84151350707d59e2b05d890f8423143f0f00380f8423173077ff588af62453ff685af90f8423143f00f0380f842317de7ddf80880fdf776ba0020c871fdf74dbd00208871fdf7febe00200872fdf7e9ba0020d872fef76dbdf0b581b041f204054cf65561cef20005ccf2ac51c5f8ac1f4ef6fc51cef200010a684ff2a84642f080720a6055f8041cc2f2290641f0010145f8041c316807460a466ff39602b2f1005f07d108684ef66a62ccf2ff02904200f0c3804ff4497002f04cfa002800f0f48001464ff6dc40cff6ff70002200bf0b18433083f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a60ccf2ff000860012081f8ce004ff0ff30a1f8e000a1f8e200a1f8e400a1f8e600a1f8e800a1f8ea00a1f8ec00a1f8ee00a1f8f000a1f8f200a1f8f400a1f8f600a1f8f800a1f8fa00a1f8fc00a1f8fe003160d1f8d800b0bb46f6805245f6e464c2f20702cff6f8741368204616689e420ed116689e420bd116689e4208d116689e4203d1002800f10400efd19e421ad02b6816681068b0420ed11068b0420bd11068b04208d11068b04203d1002c04f10404efd1b04206d02868c01ac1f8d80001e0002030602868386001b0f0bd00bf2de9f04141f204084ff2a847cef20008c2f229070146d8f8004038680d6801466ff39601b1f1005f07d101684ef66a62ccf2ff02914200f0c2804ff4497002f02df9002800f0cb804ff6dc41cff6ff71002200bf4318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe103860d0f8d81081b144f6d350c1f26200a1fb0001880901284ff0010088bf88094ce000203860fa2048e046f6805245f6e466c2f20702cff6f8761368314600bf17689f420ed117689f420bd117689f4208d117689f4203d1002901f10401efd19f422ad0d8f80030176800bf1168b9420ed11168b9420bd11168b94208d11168b94203d1002e06f10406efd1b94214d0d8f8001044f6d357ca1ac1f26207a2fb0776c0f8d820b00901284ff0010088bfb009994208bffa2000e0fa20611bb1fbf0f0bde8f08100bf2de9f04f85b0044618b1a069002840f0d8804ff2a845c2f22905286801466ff39601b1f1005f07d101684ef66a62ccf2ff02914200f0c1804ff4497001f0ecff002800f0b9804ff6dc41cff6ff7100224318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe102860002c18bf002807d14cf6dd70c0f2450005b0bde8f04f0047d4f80cc0bcf1000ff2d0d4f820a0baf1000fedd0d4f844e000f104094ff0ff38002700264ff0ff3105e06037c02f06f1060600f0eb81c3195a68002a50d01a69013205d01a6942453cbfd3f8108031465a69002a06f1010241d01d6a013505d01d6a45453cbfd3f8208011465a6a002a06f1020233d01d6b013505d01d6b45453cbfd3f8308011465a6b002a06f1030225d01d6c013505d01d6c45453cbfd3f8408011465a6c002a06f1040217d01d6d013505d01d6d45453cbfd3f8508011465a6d002a06f1050209d01d6e0135acd01d6e45453cbfd3f860801146a5e71646002e019600f1a281f24500f29f810aeb0c0102910eeb0c0100220491cdf80c9000bf130159f80330a34224d109eb02135f68674507d30499b94204d304999e68cd1bae4208d9df68013714d00021196059609960d9600ee00299b9420bd9df68013708d00021196059609960d960012180f8df1000bf01320c2ad2d1049e04e000bfbef1000f00f0ba80b6eb0c02c0f0b880924500f2b5803546a6eb0a0b00224ff0000e02e06032c02aead000eb0208d8f80430a34217d1d8f80830a3b1d8f80c90002709eb03018b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f81410a14216d1d8f818309bb1d8f81c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f82410a14216d1d8f828309bb1d8f82c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f83410a14216d1d8f838309bb1d8f83c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f84410a14216d1d8f848309bb1d8f84c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e46d8f85410a1427ff46eafd8f85830002b3ff469afd8f85c10002719448b454ff0000138bf01219d4288bf01279e4238bf33460f421cbf4ff0010e1e4653e7554562d1ddf80c904ff0ff36002200274ff0ff3505e000bf6032c02a07f1060744d083185968a14207d11969013104d01969a9423cbf1d693e465969a14207d1196a013104d0196aa9423cbf1d6a7e1c596aa14207d1196b013104d0196ba9423cbf1d6bbe1c596ba14207d1196c013104d0196ca9423cbf1d6cfe1c596ca14207d1196d013104d0196da9423cbf1d6d3e1d596da142bfd1196e0131bcd0196ea9423cbf1d6e7e1db6e700bf002e4ed409eb06113301002249f803204a608a60ca60012180f8df10ace6dc4543d21af00303524615d0aaf101021cf80210012b0bf802100dd0aaf102021cf80210022b0bf8021005d0aaf103021cf802100bf80210baf1040f5dd3abf10203acf10406b118cf789d186f708f789f54497805f8011cb15c043a05f8021cf1d14ae000290dd409eb01120b01002549f8035055609560d56001220e4680f8df2059e6012180f8df10dde535d90af0030e5fea9a024ff0000317d0a3eb82080bf101060cf101026ff003055119cf787319df700f7904351f714f795f71897908eb050704379971f0d12b1dbef1000f13d01cf80310bef1010f0bf803100cd0591c1cf80120bef1020f0bf8012004d0991c1cf801200bf80120039b019a03eb021112019c50d0f8c420c1f804b0531cc1f808a024bf01230022c0f8c430ca6092e520463146fff7aebc2de9f047044648b1a06938b14ef2bb33c0f24e032046bde8f04718474ff2a848c2f22908d8f8005028466ff39600b0f1005f07d128684ef66a63ccf2ff03984200f0c6804ff449700f46164601f092fc0546002800f052814ff6dc40cff6ff70002100bf2a18433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002860012085f8ce004ff0ff30a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200a5f8f400a5f8f600a5f8f800a5f8fa00a5f8fc00a5f8fe00c8f8005005f1040a4ff000094ff0ff38002015e0002948bfbde8f0870aeb01170e017968ba682046c7f80c8000f088f84af80690c7f80490c7f80890c7f80c90daf80010a14205d04ff0ff314ff0ff3205e000bf29690131f6d02a6900216b69a34204d12b6a93423cbf2a6a01216b6aa34204d12b6b93423cbf2a6b02216b6ba34204d12b6c93423cbf2a6c03216b6ca34204d12b6d93423cbf2a6d04216b6da34204d12b6e93423cbf2a6e05216b6ea34204d12b6f93423cbf2a6f06216b6fa34206d1d5f8803093423cbfd5f880200721d5f88430a34206d1d5f8903093423cbfd5f890200821d5f89430a34206d1d5f8a03093423cbfd5f8a0200921d5f8a430a34206d1d5f8b03093423cbfd5f8b0200a21d5f8b430a3427ff47bafd5f8c0309342bff476afd5f8c0000b2175e7204639463246c8f80050bde8f047ffe72de9f047a4b0804643f677504ff2a847c0f24f0091468a46c2f2290780473c68002021466ff39601b1f1005f02908df80c0007d120684ef66a61ccf2ff01884200f0c3804ff4497001f00efb0446002800f0ba804ff6dc40cff6ff70002100bf2218433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe003c60baf1000f4ff0010618bfb9f1000f23d101af3846fef7c5ff02ad404651464a460123009502f017f905463846fff7e9f8002e064608d19df80c0028b949f28340c0f247004c308047002c18bfc4f8d060284624b0bde8f0879af8001001f07f00a0f1100212f1040f09d80b2807d001f07e01082903d0032801d00628c8d13cb149f28340c0f24700804794f8280210b14ff0ff35dce70026bae7b0b54cf28544c0f251041d46a0474ff2a841c2f2290109680a466ff39602b2f1005f08d10a684ef66a63ccf2ff039a4218bf002100e00021421c18bf002900d1b0bd95f84d20002afad091f80722002a08bfb0bd45f2e823c2f206031a68132aeed8c2ebc20403eb04135b6801ebc2014ff40042c1f88432a1f88a222a7a01f52171002a0fbf802248f20112ca808122ab7c33b1ab7d23b1022342f002028b71ca7195f820303bb195f8243023b1032342f004028b71ca7195f846304bb195f8443042f008020b7195f84530ca714b71b0bd47f27e32c2f207021378002b14bf9378ff230b711378002b14bf5278ff224a71b0bd2de9f04f89b045f6e532c0f24b020c46054690474ff2a841c2f229010e6831466ff39601b1f1005f08d131684ef66a62ccf2ff02914208bf092d02d009b0bde8f08fe1082c29f9d896f807120029f5d04cf6dd71c0f2450105468847014628460129ebd145f2e821c2f206010b68581e13284ff0000047d8c3ebc30701eb07111a1fa1f5de7191f85471bf0618d4d71c3ad091f8e470bf0616d4971c34d091f87470bf0613d4571c2ed00f79bf0610d4043aa1f5e071171da3f10403e3d123e05a1e01f5a87104e09a1ee03101e0da1e703106ebc203d1f8009093f98b22b2f1ff3f11dc03f521710b684b450cd191f804804b798979029301914fea192a4fea194b4fea19610ce0ff2102914ff00009002200214ff0ff084ff0000a4ff0000b01910f278df80d70102708238df80e705227b4f5804f4ff080068df80c308df810708df8123038bf4ff48046b4f5001f6ff07f0c04f07f0338bf4ff0000c802c28bf80338df813309df815e09df816308df80f0004d29df814700226002416e0c4f3c610b4f5804f06eb000703d20326012400200be0b4f5001f03d204260224012003e00526032401200023e6468df8163004f108038df814708df815e08df81160f8b903a8a226c718c654062078700c20b8704320f8704d20387101207871029804f11703f871019887f80680387200207a72b87287f80b9087f80ca087f80db0b9734df60f1703aac0f2470701200821b847284609b0bde8f08f70b505464ef6a970c0f2470016460c46804770b147f2a620c2f207000188c8b2642809d8b1f5807f4ff0070138bf032104e0ff20002101e0ff200121321b28bf082a01d2204670bdd2232a192b5506235370052393705223d370422313710123083453719171d071204670bd024600284ff0ff3009d0022918bf70471078112801d1507810b14ff0ff30704710b584b04cf6dd70c0f24500804701284ff0000037d103900446029040f20830c0f2100001904ef6a970c0f24700804770b147f2a620c2f207000188c8b2642809d8b1f5807f4ff0070138bf032104e0ff20214601e0ff20012140f2d262c5f2052202924ff4a1724df60f14adf80c208df80e108df80f0001aac0f24704012009210c23a04704b010bd00bf4ff2a840c2f22900016808466ff39600b0f1005f16d108684ef66a62ccf2ff0290420fd1d1f8fc0160b146f68052c2f207021268801a0028cebf01200020c1f8fc017047002070474ff2a840c2f22900026810466ff39600b0f1005f28d110684ef66a61ccf2ff01884221d1d2f82c02f0b146f68051c2f207010968401a0028c4bf01207047d2f8301200200029c2f82c0282f82a0208bf704710b5c2f8300204460846fbf7befc2046bde81040704700207047f0b101684ef66a62ccf2ff02914218bf704790f8061299b110b54af29f344ff0000cc0f24604864680f806c20120002100220023aef804c2a446bde810406047704700bf70b54ff2a846c2f229063468054621466ff39601b1f1005f07d120684ef66a61ccf2ff01884200f0c2804ff4497000f059ff002800f0e38004464ff6dc40cff6ff7000212218433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe00346000230820032184f81b322a2384f8180284f81912102184f81c32042384f81e0201204df60f1c04f5067284f81a1284f81d3284f81f0284f82012002d18bf0125c0f2470c0a2384f82152bde8704060470020306070bd2de9f0414ff2a847c2f229073f684ff000083c466ff39604b4f1005f07d13e684ef66a65ccf2ff05ae4208bfb84601280fd11c4615460f460646fff763fe2346044639462a463046002c18bfb8f1000f06d14af29f3cc0f2460cbde8f041604798f8060270b1d8f800020021002888f80612a8f804123ed042f68d41c0f24401884738e0b8f804020121013080b2012898bf0846a8f80402d8f8000242f68d44c0f2440488f8061268b94ff6ff40cff6ff70a4f594777844002142460023b847c8f8000240b1a047d8f80002a4f140024ff4c8719047c8b198f80602002808bfbde8f081d8f80002002188f80612a8f8041200b1a0474af29f3cc0f2460c0120002100220023bde8f04160474cf6dd70c0f245008047012830d1082088f80802032088f80902102088f80a02002088f80b02b22088f80c02062088f80d0288f80e024620b8f8041288f80f02432088f8100201200f0a4df6090c08f5027288f8110288f8120288f81312c0f2470c09210d2388f81472bde8f0416047bde8f08170b50446d0f8000242f665360d46c0f2440668b94ff61940cff6ff707844002122460023b0470028c4f8000208bf70bd06f594718847d4f8000206f1e8022946bde87040104700bf2de9f04f81b04568002d00f0c9828368002b00f0c58205eb030a4ff000080026002412e04ff2a840c2f229000099c0f8008020463246bc460ceb0903002653451d464ff0000480f0ab82ab461bf9013b03f07f07b740002b44ea070410d404f00703012b16dc0bb3012b40f09982aaeb0b03082bc0f0948205f10903dee700bfd34580f08d82182e06f107065d46dcd986e200bf022b3ad0052b40f08182aaeb0b03042bc0f07c826b1dc7e7d34580f0778295f90130002b05f10203bed5534580f06e8295f90230b3f1ff3f05f10303b4dc534580f0648295f90330b3f1ff3f05f10403aadc534580f05a8295f90430b3f1ff3f05f10503a0dc534580f0508295f90530002b00f14b82ab1d96e7d34580f0468295f9013005f1020c002b03f07f091fd5d44580f03b8295f90260eb1c06f07f07b6f1ff3f49eac71902dde3469c460fe0534580f02b8295f9037005f1040c07f07f06b7f1ff3f49ea863940f349819b46aaeb0c03994500f21982e308672b00f03281652b7ff45eafb9f1060ffff45aaf9cf80030462b7ff455af9bf80230432b7ff450af9bf80330012b7ff44baf4ff2a843c2f229031d682b466ff39603b3f1005f07d12b684ef66a67ccf2ff07bb4200f0cd8004464ff4497067460091164600f0a0fc00283ff423af4ff6dc4300990546cff6ff7320463246bc46ec18433384f8248384f8258384f8268384f8278384f8288384f8298384f82a8384f82b8384f82c8384f82d8384f82e8384f82f8384f8308384f8318384f8328384f8338384f8348384f8358384f8368384f8378384f8388384f8398384f83a8384f83b8384f83c8384f83d8384f83e8384f83f8384f8408384f8418384f8428384f8438384f8448384f8458384f8468384f8478384f8488384f8498384f84a8384f84b8384f84c8384f84d8384f84e8384f84f8384f8508384f8518384f8528384f8538384f8548384f8558384f8568384f8578384f8588384f8598384f85a8384f85b8384f85c8384f85d8384f85e8384f85f8384f8608384f8618384f8628384f8638384f8648384f8658384f866837ff476af4ef66a63ccf2ff032b60012385f8ce304ff0ff33a5f8e030a5f8e230a5f8e430a5f8e630a5f8e830a5f8ea30a5f8ec30a5f8ee30a5f8f030a5f8f230a5f8f430a5f8f630a5f8f830a5f8fa30a5f8fc30a5f8fe304ff2a843c2f229031d609bf804309bf805709bf80660032b47ea062459dd052b7adc042b00f0a780052b7ff459aed5f82c323bb146f68057c2f207073f68db1b002b11dcd5f8303285f82a8263b183461846c5f8308216460c466746fbf7d4f8bc4621463246584646f68053c2f207031b6845f69077c0f201073b44c5f82c322ee6044660460d4649461646674600f0f1fbbc4629463246204621e6d44580f0d38095f904706b1d07f07f06b7f1ff3f49ea46593ff797ae534580f0c58095f90560002e00f1c08005f1060c49ea06799be6012b42d0022b00f08f80032b7ff4ffad009016468b466746fff77bfb03460098bc4659463246002b3ff4f1ad95f80632002b3ff4ecad284641f28831a5f80442fff7a5fd55e0062b58d0072b7ff4dfad83464cf23330c0f24a0015460e466446804703465f1ea44631462a465846012f3ff6cdad981eb0fa80f04009fff7c5fba44631462a465846c1e546f68053c2f207031b6845f69077c0f201073b44c5f8fc31b4e5009016468b466746fff731fb03460098bc4659463246002b3ff4a7ad95f80632002b3ff4a2adb5f80432a3427ff49dadd5f8003285f80682002ba5f804823ff494ad42f68d411846c0f2440188470098bc465946324688e5d5f83032c5f82c82002b85f82a823ff480ad04461846c5f8308215460e466746fbf70bf8bc4631462a464ee795f80632c5f8fc81002b3ff46cad0446d5f800028b461646cdf800c085f80682a5f8048220b142f68d41c0f2440188474af29f370120002100220023c0f24607b847ddf800c02046324659464be54df60923c0f2490301b0bde8f04f18477fb50646002806d1fff7c0fa002807d19de80f00064645f25b1cc0f24f0c60477fbd00bf092940f007812de9f04f89b0732b27d8a22602eb030cd65406268cf8016089268cf8026001268cf8036045f27c5ec0f2000e0026fe4400bf1ef806700ceb0604882e27710bd00eeb06077d7897f80280ff78657184f80680e7710436ece78d334ff2a847c2f22907d7f800b0cde907105c466ff39604b4f1005f7ad1dbf800004ef66a61ccf2ff01884272d19bf83502bbf83c9200909bf83702bbf83e7202909bf838029bf8348204904fea192003909bf83a029bf8395205909bf83b029a460690380a01904cf6dd70c0f2450016468047dbf8404232465346210a4fea144c4fea146b4ff0a00ae82b5bd802eb030e06268ef8016015268ef802604d268ef80a50039d8ef8036043268ef8046001268ef80c50019d8ef80560009e8ef80e50059d8ef80760029e8ef80f50069d8ef80860049e8ef8110000208ef810508ef812408ef81700c220144603f118058ef806808ef809608ef80b908ef80d708ef813108ef814c08ef815b08ef816a0d0541ae0002700264ff0000a4ff0000b4ff0000c002100240020cde90577019703964ff0000900250496029600964ff00008e82ba3d914461d464df60900c0f2470000f5bd50804778b147f2a620c2f207000288dde90710d7b2642f0ad80726b2f5807f38bf032606e0dde90710ff27002601e0ff2701262b462246f82b0fd8d224d518d45406246c700524ac705224ec7042242c71012408336c71ae71ef7109b0bde8f04f4df6090cc0f2470c604700bf2de9f04f89b04ff2a843c2f229031d680c4629466ff39601b1f1005f38d129684ef66a63ccf2ff0399424bd195f83412b5f83c82039195f8351295f83862019195f8371295f83a92079195f8391295f83b7204914fea18210891b5f83e1282460291090a05914cf6dd71c0f2450193468847d5f840525a46290c06910199be463346844650462e0a4fea156aa02734e0002100234ff0000b00274ff0000a0691002600254ff0000c4ff0000e4ff000090591029108934ff0000804910791cdf80cb01ae0002100234ff0000b4ff0000a00260027069300254ff0000c4ff0000e4ff000090593029308934ff000080493cdf81ca08a4603965e46121b28bf182a2cd3c22202552044c17107990622017204994270152282704d2281720299c270432202710122417305994271039a817306998271089a017500211834437280f80b80027380f80f9080f810e080f811c08574c67480f815a08775c175204609b0bde8f08f2de9f04f81b04ff2a840c2f22900066830466ff39600b0f1005f0dd130684ef66a63ccf2ff03984206d196f8340218b1002a18bf002902d101b0bde8f08f96f83b020028f8d0d6f844020028f4d046f6805ac2f2070adaf80030c01a0128ebdb96f83502012802d14ff0010b06e096f837b2bbf1010f18bf4ff0020b96f83a520020eb078846adf80200adf8000013d0bbf1020f10d196f8390268b96b464bf2f1270df10201c0f25a07404614461a46b84796f83a5222461446b2f5c86f28bf4ff4c86404f115094846174600f078f80028b1d0b7f5c86f88bf45f08005daf80010d6f8402253230271120a42710a0a8171c2710a0c090e03704d234172a02143700123c17200218370c570027280f80ab0017396f8392283734273bdf80020bdf80230c273120a02741a0a8274220a0275621e032a04f0030c4374c47414d340f2fc7104ea010308f1010700217d1815f8014c421854757c5c043194756c788b42d475ad781576f1d1bcf1000f12d018f8017000f11503bcf1010f5f540ad04f1c18f80750bcf1020fdd5503d0023118f801205a544df66d22c0f24702494605469047d6f8400248f2c7310130c6f84002c0f245012846884701b0bde8f08fb0b54ff2ac44c2f22904216846f23f52c5f28802b2eb510f48f283314cf67e25c0f24501caf2101518bf25608847002804bf691c2160b0bd10b301684ef66a62ccf2ff0291421bd190f83b12c1b1d0f84412b1b146f68052c2f207021368cb1a012b0edb1268d0f84802002808bf7047891a42f64d42c0f2440208bf01211047704710b5002143f2c942c0f8441280f83b12c0f25902002044f24361904748f65354c0f25a04a04704f1bc00bde81040004700bf70b50429c0f0fb80024600784d2840f0f6805078432840f0f2809078012840f0ee804ff2a844c2f22904206803466ff39603b3f1005f07d103684ef66a66ccf2ff06b34200f0c5804ff449700d461646fff77cff002800f0d0804ff6dc41cff6ff7100224318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe10324629462060d378022b06dc012b11d0022b0ed1bde87040e6e0032b73d0042b07d190f8341221b1bde87040aae00020206070bd0d2938bf70bd90f83b12b1b1002143f2c94380f83b12c0f259030446002044f243611546984748f65356c0f25a06b04706f1bc0080472a46204611790446012988bf002180f83512517901f00303012b4ff0010198bf0b4680f837329679012e88bf002680f83862d679022e88bf002680f83962167a557a46ea0526502e98bf5026b6f5f07f28bf4ff4f076a0f83c62967ad57a46ea052641f28835ae4238bf3546a0f83e52127b80f8341202f0030280f83a2203f0010202eb5302002180f83622c0f8401200f00bf8204600f040f802e0044600f0def82046bde8704069e0b0b5044690f83a02800758bfb0bd94f8350248f6a3450128c0f25a0507d105f1b000804705f58b71002088470ee005f5b670804794f83502012801d1002004e094f83702013818bf0120a8474ff65122cff6ff7243f271337a44c0f25903002044f243619847012084f83b02b0bd00bf70b5044646f68050c2f20700006894f83b1245f69075c0f2010500292844c4f8440208bf70bdd4f8480242f66536c0f2440658b94ff6f530cff6ff707844002122460023b047c4f8480250b106f594718847d4f8480206f1e8022946bde87040104770bd70b5044600f51375082084f84c02032084f84d02102084f84e02c22084f85002062084f851024d2084f85302432084f85402012084f8550294f8340294f8351284f8560284f8571294f83902b4f83c1284f85a0284f85b12080ab4f83e1284f85c02080a84f85e0294f83a0294f8372294f8383284f85d1294f83b1284f85f024cf6dd700026c0f2450084f84f6284f8582284f8593284f860128047d4f8401284f86102080a84f86302080c84f86402080e84f86502a02084f8676215264df6090c84f8621284f86602c0f2470c012009212a461c2384f85262bde87040604770b54ff2a840c2f22900046820466ff39600b0f1005f33d120684ef66a61ccf2ff01884218bf70bd94f83b020025c4f8445288b143f2c942c0f25902002044f2436184f83b52904748f65356c0f25a06b04706f1bc008047d4f8480284f8345270b142f68d45c0f24405a847d4f8480205f166018847002804bf0020c4f8480270bd00bf2de9f04182b04ff2a841c2f229010c6821466ff39601b1f1005f75d121684ef66a62ccf2ff0291426ed194f86c1279b394f86e02c0070ad0d4f82c0278b346f68051c2f207010968401a002827dd46f2d835c2f2070555f8040c002854d04ff27717c0f24b0747f62938002607f5437101a8c0f24b0801968847a8b1032084f86f622860b4f87002c04702b0bde8f081d4f87812c1b302b0bde8f0410847204602b0bde8f04133e001984ef6ed56c0f24b06a861b04706f5af708047e861b847012084f86f0203202860b4f87002c047d4f88002a0b10199d4f87c22b4f87272531a38bf8b1abb420ad2b4f8741259b146f68052c2f207021268101a884203d32046022100f06ef802b0bde8f08100bfb0b590f86c42002c42d043f60852c2f2000211880829114622d0114631f8083f082b1dd0114631f8103f082b18d0114631f8183f082b13d0114631f8203f082b0ed0114631f8283f082b09d0114631f8303f082b04d032f8381f0829114614d14a68b2f5870f10d36ff35602012a0cd14a684ff67363cff6ff737b449a4204d1d0f87822002a18bf4a60002180f86c1290f86d12b1b1002180f86d1244f68241c2f20701097869b946f2d431c2f20701096839b148f26111c0f24b010546042088472846002c08bfb0bd0321bde8b04000e000bfb0b588b004464cf6dd70c0f245000d468047012840f08f8008208df8010003208df8020010208df8030000208df80400ca208df8050006208df8060018208df8070046f2f030c2f2070050f81c2c94f86c12002a18bf0122002944f68141c2f207014b7818bf0232002b94f86f3218bf0432002b4ff0410318bf08328df808304c238df8093001238df80a308df80b508df80c2050f8182c4df609058df80d200268c0f24705130a8df80e208df80f30130c120e8df810308df811204268130a8df812208df81330130c120e8df814308df8152002698df81620120a8df8172009788df8181081688df819106821c2f2000109688df81a10090a8df81b1046f68051c2f207010a68130a8df81c208df81d30130c120e8df81e308df81f2000680df10102c4f87c0208680921c4f8800201201f23a84708b0b0bd00bf02293cbf4ff0ff3070472de9f0414ff2a84540f20108c2f22905cff680782c68074608f1020020400e46b0f1005f07d120684ef66a61ccf2ff01884200f0c3804ff44970fff766fb002800f0d48004464ff6dc40cff6ff70002100bf2218433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe002c604cf6dd70c0f24500804701281cbf0020bde8f081787802281bd001280ed048b9204600210024fff76afe2046bde8f081002028604ff0ff30bde8f081022e41f288300cd14ff4fa720021012341f2883721e02046fff7e9fd0020bde8f081b978052e10d3fa783b79072e42ea03220fd37b79bd79092e43ea0523e7d3fe793f7a46ea072707e041f288374ff4fa7201e041f288370123642a98bf6422824228bf024694f86c0284f86e12a4f87022a4f87232a4f8747278b146f2d430c2f207000068002852d020460121fff718fe0020c4f88002bde8f08143f60850c2f2000001880829014622d0014631f8082f082a1dd0014631f8102f082a18d0014631f8182f082a13d0014631f8202f082a0ed0014631f8282f082a09d0014631f8302f082a04d030f8381f0829014630d14a686ff00100b2f5870f38bfbde8f08102ea0802012a7ff478af4a684ff6c510cff6ff707844824214bfc4f87822d4f87822b2b14860012084f86c02a5e748f2ef01c0f24b010420884730b105462046fff754fd2846bde8f081012084f86d029ae76ff00100bde8f08100bf334600f005b800bf334600f037b800bf2de9f04182b042f2d7281e4614460d460746c0f24608fef7fbf9002e18bf002808d108f1160338462946224602b0bde8f041184746f26870c2f207000068c0470028eed00068e028ebd130784bf6d32601900027c0f24e0600200021002209230097b047012002b0bde8f0812de9f04182b042f2d7281e4614460d460746c0f24608fef7c5f9002e18bf002808d108f1160338462946224602b0bde8f041184746f26870c2f207000068c0470028eed00068e028ebd130784bf6d32601900027c0f24e060020002100220a230097b047012002b0bde8f08110b582b00446fef797f90146002c4ff0000018bf002901d102b010bd46f26870c2f20700006842f2d721c0f24601884790b10068e0284ff00000edd121784bf6d32c0191c0f24e0c002100220b230090e047012002b010bd002002b010bd00bf08b53046fff7ccff002805d002b044f6e970c0f24400004748f68b43c0f24603984708bd2de9f04f95b0002918bf002a04d115b0bde8f04f01f01eba0e78ddf878b006f07f070b2f00f32781092f00f33481052f00f0ec81072f40f0c6814ff2a844c2f22904236818466ff39600b0f1005f07d118684ef66a67ccf2ff07b84200f0c7804ff4497015460e46fff7eef80346002800f0ba804ff6dc40cff6ff70002100bf1a18433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff001860012083f8ce004ff0ff30a3f8e000a3f8e200a3f8e400a3f8e600a3f8e800a3f8ea00a3f8ec00a3f8ee00a3f8f000a3f8f200a3f8f400a3f8f600a3f8f800a3f8fa00a3f8fc00a3f8fe0031462a462360022a2cbf4978ff21002b01f0f28002294ff0000000f0d386012900f0cc86002941f0e8804cf67e21caf21011c3f8dc0061604ff0ff31a3f8cc00c3f8c800a3f8e010a3f8e210a3f8e410a3f8e610a3f8e810a3f8ea10a3f8ec10a3f8ee10a3f8f010a3f8f210a3f8f410a3f8f610a3f8f810a3f8fa10a3f8fc10a3f8fe1083f8000115b0bde8f08f102f00f39f800c2f00f0bb81102f40f09f800846114615b0bde8f04ffff74fbc0a2f00f099830b2f40f092804ff2a846c2f22906346820466ff39600b0f1005f41f0938020684ef66a67ccf2ff07b8424ff0000041f08a80c4f82c0284f82a0284f82802d4f83012c4f8240284f8290221b1c4f830020846f9f7cffcd4f8040140f2030942f68d48cff68079c0f244080021a4f8081150b1c047d4f8040108f166018847002804bf0020c4f8040146f67560c0f251008047356805ea0900b0f1005f2bd12868b84228d195f83b024ff0000ac5f844a288b143f2c942c0f25902002044f2436185f83ba2904748f6535bc0f25a0bd8470bf1bc008047d5f8480285f834a250b1c047d5f8480208f166018847002804bf0020c5f84802306800ea0901b1f1005f40f054870168b94240f0508790f86c12002900f04587fff7b7fa00f047bf112f00f0fe83422f3ff424aea7f10d05022d00f22b848568002d00f0ae86b0f84060b0f842406643b6f5163fc0f0a58601310e2fa2f101029846064628465b4600f095860d2f40f0958601f0a0f800f093be4ff2a848c2f22908022a2cbf4d78ff25d8f8004020466ff39600b0f1005f07d120684ef66a63ccf2ff03984200f0c7804ff4497016460f46fef700ff002800f03f8404464ff6dc40cff6ff70002132462318433083f8241383f8251383f8261383f8271383f8281383f8291383f82a1383f82b1383f82c1383f82d1383f82e1383f82f1383f8301383f8311383f8321383f8331383f8341383f8351383f8361383f8371383f8381383f8391383f83a1383f83b1383f83c1383f83d1383f83e1383f83f1383f8401383f8411383f8421383f8431383f8441383f8451383f8461383f8471383f8481383f8491383f84a1383f84b1383f84c1383f84d1383f84e1383f84f1383f8501383f8511383f8521383f8531383f8541383f8551383f8561383f8571383f8581383f8591383f85a1383f85b1383f85c1383f85d1383f85e1383f85f1383f8601383f8611383f8621383f8631383f8641383f8651383f866137ff476af4ef66a60ccf2ff002060012084f8ce004ff0ff303946a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe00c8f8004094f8080170b1d4f8040140b142f68d43c0f244030e46174698473a463146002084f808010123032a80f073837de3b2f1010900f0f08601f1010b00230022a9eb03000428c0f091850beb0306b078f7781c1d40ea0727a9eb040087424ff0ff3000f2da861bf80330767843ea06233b44b3f5803f00f2d086002f07eb040318bf01224b45dbd3002a00f0c5868846fdf72cfe002800f069854ff2a847c2f229073c6820466ff39600b0f1005f07d120684ef66a61ccf2ff01884200f0c2804ff44970fef7dcfd002800f0588604464ff6dc40cff6ff7000212218433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002060012084f8ce004ff0ff30a4f8e000a4f8e200a4f8e400a4f8e600a4f8e800a4f8ea00a4f8ec00a4f8ee00a4f8f000a4f8f200a4f8f400a4f8f600a4f8f800a4f8fa00a4f8fc00a4f8fe003c60d4f8300200286fd14ff48030f9f716fa002800f0898400210022831881544032b2f5803f59709970d970197159719971d971197259729972d972197359739973d973197459749974d974197559759975d975197659769976d976197759779977d97783f8201083f8211083f8221083f8231083f8241083f8251083f8261083f8271083f8281083f8291083f82a1083f82b1083f82c1083f82d1083f82e1083f82f1083f8301083f8311083f8321083f8331083f8341083f8351083f8361083f8371083f8381083f8391083f83a1083f83b1083f83c1083f83d1083f83e1083f83f109ad1c4f830020021cdf80c8006e007eb0a0149454ff0000080f06c850beb01039878da7801f1040a50ea0227efd012025b7802441bf80160013a1d02032a00f0030e04a8e0c001d2002224e00398a7eb0e030844a919002200bf8618d4f830c296f805800ceb010707f80280d4f83072b5790f4417447d70d4f83072f5790f441744bd70d4f83072367a0f44174404329342fe70e1d1069fdde90465bef1000fb5d0d4f830120beb0a00835c31442944bef1010f8b54aad0d4f83032511c10f801c033442b44bef1020f03f801c09ed0911cd4f83022405c32442a44505496e7022ac0f0b0834ff2a844c2f22904206803466ff39603b3f1005f07d103684ef66a67ccf2ff07bb4200f0c6804ff4497015460e46fef721fc002800f0d5824ff6dc41cff6ff71002200bf4318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1031462a4620604c78002c00f01782022c00f2d08240f0fb83062ac0f0cb828a78cb780f794e7942ea032147ea062232290791089280f0e5833221e7e3022a4ff0ff3008bf112e40f00c844878002840f0b1824cf6dd70c0f24500804701284ff0000040f0fe8309900446089040f20830c0f2100007904ef6a970c0f247008047002800f0188347f2a620c2f207000188c8b2642800f29a83b1f5807f4ff0070138bf032194e3092f00f08a80082f40f012810746002b4ff0ff3000f0d2834af28973cff6fd73d61802339e42c0f0c98391f801803846b8f1000f00f075820226b71c974200f266828b198e5d5b7856ea032300f05f82de19964200f25b82cc5d04f07f0cacf1100515f1030f0ad804f07b05092d06d0bcf1030f03d0bcf1060f40f0488214460d4639441a4600230746cdf800b0fff7a4f9002840f03b82b8f10108294622463846cad13de20023c8f80030002439463246032a0bd355b98878082800f27d8346f67561c0f251019631884775e3052a1ad3012d18d18d78681e06284ff0000000f26c83cb78032b00f268830a79002a00f0648346f67560c0f2510000f59a7728461946b84758e3022d40f0598146f67560c0f2510080474fe337064ff0210658bf1126b242c0f0f281002f01f101050ed54cf6dd72c0f245020f4604461e469047334601462046022918bf07f1110584462879697950ea01264ff0ff301ebfa979ea7951ea022900f02883297b6a7b41ea02218e4240f02183a97bea7b41ea0221894540f01a832878697840ea01217018b0f5207f4ff0ff3000f20f83aa78ec7842ea042209eb0204b4f5f07f00f205832c7a6f7a44ea072806eb0807b7f5207f00f2fb82af7aed7a47ea052509eb0507b7f5f07f00f2f182dcf80800002800f09581bcf84070bcf842406743b7f5163fc0f08c819a4643466446cde90169009502f0f2f8dbf800000f280ad80bebc0010130a1f806800d814e81a1f80c90cbf80000baf1000f00f0c782204678e1fd1e18bf0125bc1f18bf0124032afff4d3a825407ff4d0a800254c1ca2f1010c8df81c508df81d508df820508df824508df825508df826508df827508df828508df829508df82a508df82b508df82c508df82d508df82e508df82f508df830508df831508df832508df833508df834508df835508df836508df837508df838508df839508df83a508df83b508df848508df849508df84a508df84b508df84c508df84d508df84e508df84f508df850508df851508df852508df85350cde9074c48f61f54cff6ff747c440f9448f65f54cff6ff747c44032f1094119500f00d81062f40f0fc800646002000211d4602f06efab168002900f0f280b6f84020b6f842005043b0f5163fc0f0e98007a84ff4a0724ff4f07302f0aefb002800f0df80dbf800000f280dd80bebc0010022ca800a814ff420724a814ff4f07201308a81cbf80000002d304640f0d3801de2012083f8ce0019e283f8ce0015b0bde8f08f00202060bbe0002480f807424cf6dd70c0f24500804701462046012940f006824df25f50c0f2550015b0bde8f04f0047072a33d3032d31d18878cb780a7940ea03204d798e7901284ff0010498bf204644f62061884228bf084646f67561c0f25101642a28bf642201f5e2731146984746f2a070c2f207000068002800f0d58145ea0621012988bf0c4642f68d41c0f24401a1f1400221469047c6e1032a4ff00000c0f0c3812f1fb7fa87f77f093b4000f0bc81d01e4cf6cd42ccf6cc428b78a0fb0202b3eb920f88bf9308302b184628bf3020002b00f0cf8100eb800303f0030c03f4fe770023ce18f578e21882f80a513579043382f80b5175799f4282f80c51b67982f80d61eed1bcf1000f10d01944ca782344bcf1010f83f80a2108d00a79bcf1020f83f80b211cbf497983f80c1184f80801d4f8040142f68d45c0f24405002184f8091170b948f69530cff6ff70a5f59477784422460023b8470028c4f8040100f08e81a5f14002012190475be100f0b4fd01e001f015fa20b14ff0ff3015b0bde8f08fb8f1000f00f04d813046594601f053fe47e1370600f14981082aecd306464ff0070e4ff0050c0127cc1994f802804ff0ff30b8f1000f00f03581e578002d00f0318111f807a04fea880909eb8a07b7f5207f00f2278167786c00cde9043e0696164604eb4702b2f5f07f00f21b8101eb0c00039111f80c10407841ea002081b2012002f030f9002840f00b81069988680028b0d0b1f84020b1f842105143b1f5163fa8d30399059b4fea480219440791f11a089107eb870100ebc11000eb4a0107a8234602f063fa002894d0dbf800000f280cd84fea8a017a000bebc0030130d9801a81a3f80a909c81cbf8000004980028069889d1d4e0ff20214689e090f86d12002918bffef76efb94f80702002684f8076258b14cf6dd70c0f245008047012804d14df25f50c0f255008047d4f8000294f80652c4f8fc6184f80662a4f8046250b1c047d4f8000208f166018847002804bf0020c4f8000200200121002d6060a060e06020616061a061e06120626062a062e06220636063a063e06320646064a064e06420656065a065e06520666066a066e06620676067a067e067c4f88000c4f88400c4f88800c4f88c00c4f89000c4f89400c4f89800c4f89c00c4f8a000c4f8a400c4f8a800c4f8ac00c4f8b000c4f8b400c4f8b800c4f8bc00c4f8c000c4f8c40084f8ce105bd04af29f37c0f2460701200021002200230024b847204615b0bde8f08f00203860f3e6ff20012140f2d262c5f2052208924ff4a1724df60f17adf824208df826108df8270007aac0f24707012009210c23b84715b0bde8f08fb1f5fa6f02d94ff4fa6107910121054680f807124cf6dd70c0f24500804701281dd14df25f56c0f25506a6f188008047022c08bf002801d058b910e048f2d31207a9c0f24b020220904740b10446b0472046002185f8071215b0bde8f08f002015b0bde8f08f0c2afff4a3aecf78ce79b7427ff49eae814608790e46097a88427ff497ae4cf6dd70c0f245009846144680470527022808bf01274ff00b0e4ff0090c314622464e4643469be60020a4f8080115b0bde8f08f46f675600025c0f2510084f808518047284615b0bde8f08f00bff0b583b04ff2a843c2f229031f683b466ff39603b3f1005f09d13b684ef66a66ccf2ff06b34204bf002387f82a32002958d0362a56d30b78422b53d14b784d2b50d10b7f4f7f43ea0723042b4ad18b7dcf7d0e7e43ea072343ea06434f7e8e7ccd7c53ea076346ea05270e7d4d7d47ea064747ea05641d4648bf5d42b0f84070002b4ff00003c8bf0123bc422ad1b0f84270bd4226d18f7ace7a91f80cc047ea06274e7b47ea0c4747ea0667974219d2621c032606eb5202866822f0030cca19cde901c30746304621462346009502f01bfb3846314622462b4602f0affb002003b0f0bd4ef2bb33c0f24e0303b0bde8f0401847072a1cbf4ff0ff3070472de9f04f8db00e4683461d46fcf7a9fe002800f065834ff2a847c2f22907386801466ff39601b1f1005f07d101684ef66a62ccf2ff02914200f0c2804ff44970fdf759fe002800f049834ff6dc41cff6ff71002200bf4318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe1038603178727841ea02274ff6ff718f424ff0ff3200f08a82d0f830121046002900f08182cb5d4ff0ff30002b00f07b8239444a78002a00f0768202fb03f001f1020a4ff0000c4ff000010195009278b34ff6fe794ff6fd78cd194d4500f061828e4651440a78140904d00125a0421bd257e200bf454500f054824c781cb10225a04211d24de24ff6fb72aa1a042ac0f048828a78c97852ea012400f042820425a042c0f03e8200bf001b05eb0e01d3d10691b078f178b77940ea0129b8060f213279757907f00f0601eae07000fb06f189204143c90a8df824100e2142ea0525069a17f0200f08bf4ff00f0c08bf012106fb01f100fb01f14fead1218df825104ff00d0108bf022106fb01f100fb01f14fead1218df826104ff00c0108bf032106fb01f100fb01f14fead1218df827104ff00b0108bf042106fb01f100fb01f14fead1218df828104ff00a0108bf052106fb01f100fb01f14fead1218df829104ff0090108bf062106fb01f100fb01f14fead1218df82a104ff0080108bf072106fb01f100fb01f14fead1218df82b104ff0070108bf082106fb01f100fb01f14fead1218df82c104ff0060108bf092106fb01f100fb01f14fead1218df82d104ff0050108bf0a2106fb01f100fb01f14fead1218df82e104ff0040108bf0b2106fb01f100fb01f14fead1218df82f104ff0030108bf0c2106fb01f100fb01f14fead1218df830104ff0020108bf0d2106fb01f100fb01f14fead1218df831104ff0010108bf0e2171434143c90a8df832100cfb06f148434ff0010ec00a002a8df8330000f0768107f010008eea1010002604904ff00008cdf814a009e000bfdde90706069a0644ddf814a0964280f061811af806000896040901d0012113e0971b012f00f056810aeb06014c780cb1022109e0042fc0f04d818a78c97852ea012400f047810421079110f00f0109a810f801a018bf012104984fea0a1e40ea010c14f00300474600f08080b8fbf3f100224f19b7f1ff3fc8bf012202ea0c02012a1dd101fb13814944ca09042a17d87a090e2a14d807eb87020beb82124f08d65dc9076ff00f01029608bf0f210390504608bf7046029e314001430398d155012808f1010751d0b7fbf3f100264a19b2f1ff3fc8bf012606ea0c06012e1ad101fb13714944ce09042e14d856090e2e11d802eb82020beb82124e08c9070390905d6ff00f01574604bf0f2177460140039839439155022808f1020726d0b7fbf3f100224e19b6f1ff3fc8bf012202ea0c02012a18d101fb13714944ca09042a12d872090e2a0fd806eb86020beb82124e08c907905d6ff00f01574604bf0f21774601403943915508f10307611e0329a04405d244e700bf0437b8453ff440afb7fbf3f600227119b1f1ff3fc8bf012202ea0c02012a19d106fb137202eb0906f209042a12d84a090e2a0fd801eb81010beb811172088c5cf6076ff00f06504604bf0f2670463440204388547e1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c00012819d102fb136000eb0906f009042812d848090e280fd801eb81000beb80107108425cf4076ff00f04564604bf0f247646224032434254be1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c00012819d102fb136000eb0906f009042812d848090e280fd801eb81000beb80107108425cf4076ff00f04564604bf0f247646224032434254fe1cb6fbf3f200205119b1f1ff3fc8bf012000ea0c0001287ff47aaf02fb136000eb0906f00904283ff672af48090e283ff66eaf01eb81000beb80107108425cf4076ff00f04564604bf0f2476462240324342545ce7002038604ff0ff300db0bde8f08f10460db0bde8f08f009909eb03002944b0f5207fa8bf4ff42070b1f5f07fa8bf4ff4f071019f484588bfa94203d800200db0bde8f08f3a680f2af8d8a0eb090007ebc203491b5881501ca3f806901d8199813860ebe700bf082a3cbf4ff0ff3070472de9f04f93b015460c4680469a46fcf702fb002800f03382e77907f1080085424ff0ff3040f02d822178627841ea02254ff640718d4200f224824ff2a849c2f22909d9f80000a67901466ff39601b1f1005f07d101684ef66a62ccf2ff02914200f0c3804ff44970fdf79ffa002800f003824ff6dc41cff6ff71002200bf4318433183f8242383f8252383f8262383f8272383f8282383f8292383f82a2383f82b2383f82c2383f82d2383f82e2383f82f2383f8302383f8312383f8322383f8332383f8342383f8352383f8362383f8372383f8382383f8392383f83a2383f83b2383f83c2383f83d2383f83e2383f83f2383f8402383f8412383f8422383f8432383f8442383f8452383f8462383f8472383f8482383f8492383f84a2383f84b2383f84c2383f84d2383f84e2383f84f2383f8502383f8512383f8522383f8532383f8542383f8552383f8562383f8572383f8582383f8592383f85a2383f85b2383f85c2383f85d2383f85e2383f85f2383f8602383f8612383f8622383f8632383f8642383f8652383f866237ff476af4ef66a61ccf2ff010160012180f8ce104ff0ff31a0f8e010a0f8e210a0f8e410a0f8e610a0f8e810a0f8ea10a0f8ec10a0f8ee10a0f8f010a0f8f210a0f8f410a0f8f610a0f8f810a0f8fa10a0f8fc10a0f8fe10c9f80000d0f830c2bcf1000f00f04481a178b3060e9121790f220d9106f00f0102eae3724a434ff0890b02fb0bf2d20a8df83c200e2294f8039094f805e0099616f0200f08bf012201fb02f202fb0bf24fead2228df83d204ff00d0208bf022201fb02f202fb0bf24fead2228df83e204ff00c0208bf032201fb02f202fb0bf24fead2228df83f204ff00b0208bf042201fb02f202fb0bf24fead2228df840204ff00a0208bf052201fb02f202fb0bf24fead2228df841204ff0090208bf062201fb02f202fb0bf24fead2228df842204ff0080208bf072201fb02f202fb0bf24fead2228df843204ff0070208bf082201fb02f202fb0bf24fead2228df844204ff0060208bf092201fb02f202fb0bf24fead2228df845204ff0050208bf0a2201fb02f202fb0bf24fead2228df846204ff0040208bf0b2201fb02f202fb0bf24fead2228df847204ff0030208bf0c2201fb02f202fb0bf24fead2228df848204ff0020208bf0d2201fb02f202fb0bf24fead2228df849204ff0010208bf0e2201fb02f202fb0bf24fead2228df84a204ff0000208bf0f22514301fb0bf10023c90a002f8df84b1000f091820e9a0ceb050142ea09220e920d9a0a9104f1080142ea0e224ff0000b4ff6fe7946460d92cdf820a0cde90b7105e00b9f0bf1010b0c99bb455dd011f80b104a1e1f2af4d34ab2202a50db0a9a02eb410111f8402c11f83f1c42ea01274ff6ff718f4243d01cf807104ff0ff33002900f058820ceb07025578002d00f0528202f102086943002200bfd5194d452ed008eb020423785fea131a04d04ff0010e51451cd223e04ff6fd739d421fd094f801a0baf1000f04d04ff0020e51450ed215e04ff6fb73eb1a042b10d3a378e57853ea052a0bd04ff0040e514507d3b1eb0a017244d1d1a3e70020c9f800004ff0ff3013b0bde8f08f08990122063100910999002501f010014ff6ff7482ea111106910c994a5d1f2a03d80e9911440b39fae1d0f830124ff0ff33002900f0fa810a9f07eb420212f8407c12f83f2c47ea0222a24200f0ee8111f802e0bef1000f00f0e88111444c78002c00f0e38104fb0ef34ff6fd7c002bcde9024500f09d818c1c4ff0000b4ff6fe780beb02054545b5d004eb0b073978090901d0012710e06545acd0797809b102270ae04ff6fb71691a0429a3d3b978ff7851ea07219ed004278b429bd35b1abb44ded1bbf1000f00f0738100254ff00008059406e0099d0799059c0d445d4580f06781615d09950f0901d0012213e0abeb0503012b00f05c81621957780fb1022209e0042bc0f054819378d27853ea022700f04e810422079211f00f010faa12f801c018bf0121069a4fea0c1942ea010a17f00304424600f08980b8fbfef20e9b02fb1e8100251944b1f1ff3fc8bf012505ea0a05012d1dd10d9bd2181ad4cd09042d17d855090e2d14d802eb820206eb82124d08535dc9076ff00f01019308bf0f210494644608bf4c46019b19402143049c5155012c08f1010257d0b2fbfef505fb1e210e9a11440022b1f1ff3fc8bf012202ea0a02012a1ad10d9a521917d4cb09042b14d853090e2b11d802eb820206eb82124b08c9070494d45c6ff00f01654604bf0f214d462140049c2943d154022c08f1020229d0b2fbfef303fb1e210e9a11440022b1f1ff3fc8bf012202ea0a02012a18d10d9ad21815d4cb09042b12d853090e2b0fd802eb820206eb82124b08c907d45c6ff00f01654604bf0f214d4621402943d15408f10302791eb8440d9f032904d23de7043290453ff43aafb2fbfef30e9c03fb1e2100252144b1f1ff3fc8bf012505ea0a05012d18d1db1916d4cd09042d13d85d090e2d10d803eb830306eb83134d08c9075f5d6ff00f01644604bf0f214c4639400d9f21435955511cb1fbfef30e9c03fb1e1121440024b1f1ff3fc8bf012404ea0a04012c18d1db1916d4cc09042c13d85c090e2c10d803eb830306eb83134c08c9071d5d6ff00f01674604bf0f214f46294039430d9f1955911cb1fbfef30e9c03fb1e1121440024b1f1ff3fc8bf012404ea0a04012c18d1db1916d4cc09042c13d85c090e2c10d803eb830306eb83134c08c9071d5d6ff00f01674604bf0f214f46294039430d9f1955d11cb1fbfef30e9c03fb1e1121440024b1f1ff3fc8bf012404ea0a04012c7ff471afdb193ff56eafcc09042c3ff66aaf5c090e2c3ff666af03eb830306eb83134c08c9071d5d6ff00f01674604bf0f214f46294039430d9f195553e70e9a0d9f029b02eb0e013b44b1f5207f0c4622eae272a8bf4ff42074b3f5f07fa8bf4ff4f07394421dddbb420b9f1bd9ddf82080d8f800500f2d15d8ddf834e0a4eb0209a3eb0e0c009b03ebc50423f835206a1ca4f802e0a4f80490a4f806c0c8f8002000e00b9f039d4ff6ff7401350023bd420e917ff4f7ad184613b0bde8f08f00bf062a3cbf4ff0ff3070472de9f04fadf2944d9a46154688460f90fbf79dfe002800f0d68098f80510881d854240f0298446f6ac10c2f20700d0f800b0bbf1000f00f01f849bf80c009bf80d209bf80e309bf80f7040ea022040ea034040ea0769a9f1810010f1800f4ff0ff30c0f0b2809bf810209bf811309bf8137042ea03229bf8123042ea034242ea07620692813a12f5817f40f29e800029cdf828b000f09d8008f1060b002426aa4ff4e01c00270ae000bf05f1004042f8240001378f4204f1010480f08e801bf80750681e1e28f0d968b21f2801dd012075e0a5f1c2000beb07061d28a1eb07000fd8012800f0c88396f9010010f1410f00f3c28300f03f0365f38a1302201d465de005f0f003e02b24d10328c0f0b48396f9013013f1410f00f3ae8396f9020010f1410f00f3a883e02ddeb202d1a02ec0f0a283ed2d02d19f2e00f29d832b039bb206f03f0643ea861300f03f001d18032034e004284ff0ff3036d3a5f1f50313f1050f31d396f9013013f1410f2cdc96f9020010f1410f00f37e8396f9036016f1410f00f37883f02ddbb202d1902bc0f07283f42d02d18f2b00f26d830cea854e03f03f054eea053300f03f0043ea801006f03f0326aac518042000bf074442f8245076e74ff0ff300df2944dbde8f08f0021012007915ee0002c57d0a4f1010bcdf86090cdf810a000250df1780a5f46914608e026aaab4505f1010509f10409a7f1010739d052f825100029f3d400202b4687421dd009eb80067268b2f1ff3f18dc5a1c934514d0b268b2f1ff3f11dc9a1c93450dd0f268b2f1ff3f0adcda1c934506d032690433002a00f10400e0d400e000220a9853461aae009601f096fa002800f008831a980028c3d046f2a1415046c0f24e018847bce7ddf810a0ddf828b0ddf860900020079404e00020ddf828b00790012098f804400f21a20604f00f0501eae271694389225143c90a8df8681001260e2198f800c098f801e098f8023098f8037014f0200f08bf0e2608bf012105fb01f102fb01f14fead1218df869104ff00d0108bf022105fb01f102fb01f14fead1218df86a104ff00c0108bf032105fb01f102fb01f14fead1218df86b104ff00b0108bf042105fb01f102fb01f14fead1218df86c104ff00a0108bf052105fb01f102fb01f14fead1218df86d104ff0090108bf062105fb01f102fb01f14fead1218df86e104ff0080108bf072105fb01f102fb01f14fead1218df86f104ff0070108bf082105fb01f102fb01f14fead1218df870104ff0060108bf092105fb01f102fb01f14fead1218df871104ff0050108bf0a2105fb01f102fb01f14fead1218df872104ff0040108bf0b2105fb01f102fb01f14fead1218df873104ff0030108bf0c2105fb01f102fb01f14fead1218df874104ff0020108bf0d2105fb01f102fb01f14fead1218df8751006fb05f102fb01f14fead1218df876104ff0000108bf0f2169435143c90a00284ff000008df877107ff4cdae43ea0720079a484403904cea0e290af10600571e00260df198080190cdf810a0029718e000bf46f2a1411ea8c0f24e0188479df87c009df87d10dde90ab9029fdde9072640ea01200df1980801369642814400f0ff8158f82610b1f1ff3f1edd33469f421fd008eb83004268b2f1ff3f1adc0133bb4216d08268b2f1ff3f13dc0133bb420fd0c268b2f1ff3f0cdc0133bb4208d002690133002ae2d404e001f01f000b38d2e7002258461eab19ad009501f055f9002800f0c781199900290d9100f0ba819df880209df881309df87e009df87f1052ea03259df8822040ea01279df8833010979df884704fea024208969df8856042ea0362069b4fea074747ea06672b4403eb2743039fcdf82c90a7eb030609eb22491aaf149500f05e810902109b014400f0030809f101004ff0010c099009f102000ceb530305900d980c934b1e0e930b9b0130121415900ceb510003eb020e9a1acde91180a1eb08001890d0074ff0000a17904feace70169013960ae014980af1010a824512981599139e0144159100f029810aeb06014b090e2befd810980028ecd00e9801eb810103280f984ff0000600eb811e80f0848011980028ded0dde90c105feac67c0afb01084fea560018f8000000f00f03c1b208bf0b09b3fa83f0400910ea141f14d106eb0901c80904280fd848081ef80020fb5c02f00f0b02f0f0021a431aafc90708bf4bea03120ef8002011980128b1d0701c400818f80000bcf1000fc1b24fea111308bf00f00f03d8b2b0fa80f0400910ea141f14d109983118c80904280fd848081ef80020fb5c02f00f0b02f0f0021a431aafc90708bf4bea03120ef80020119802283ff486afb01c400818f80000bcf1000f00f00f01c2b208bf1109b1fa81f0400910ea141f7ff474af05983318d80904283ff66eaf58081ef80020795c02f00f0602f0f0020a43db0708bf46ea01120ef800205de7ddf8548007e000bf18980436b04208f102083ff471af18f8011c0023c9b2102938bf012313ea141f09eb060c16d14feadc13042b12d84fea5c0309091ef80320795c02f00f0b02f0f0020a431aaf5feac97008bf4bea01120ef8032018f8010c00f00f01b1fa81f0400910ea141f15d10cf10103d809042810d858081ef80020795c02f00f03179d43ea011302f0f002002d08bf42ea01030ef8003098f80000c1b210294ff0000038bf012010ea141f15d10cf10203d809042810d8080959081ef80120385c02f00f0302f0f002169d0243002d08bf43ea00120ef8012098f8000000f00f01b1fa81f0400910ea141f8ad10cf10303d80904283ff685af58081ef80020795c02f00f03179d43ea011302f0f002002d08bf42ea01030ef8003072e700bf109809eb00011498b1f5207f06eb000229eae970a8bf4ff42071b2f5f07fa8bf4ff4f072ddf810a081427ff70fae26eae6739a427ff70aaedaf800700f2f3ff605ae019dd21a091a05ebc70625f83700781c7380b180f280caf80000f6e59df87c009df87d10079a40ea012001e64ff0ff300df2944dbde8f08f00200df2944dbde8f08f2de9f04182b04ff2a847c2f229073d68884629466ff39601b1f1005f064607d128684ef66a61ccf2ff01884200f0c3804ff44970fcf70efa0546002800f0ba804ff6dc40cff6ff70002100bf2a18433082f8241382f8251382f8261382f8271382f8281382f8291382f82a1382f82b1382f82c1382f82d1382f82e1382f82f1382f8301382f8311382f8321382f8331382f8341382f8351382f8361382f8371382f8381382f8391382f83a1382f83b1382f83c1382f83d1382f83e1382f83f1382f8401382f8411382f8421382f8431382f8441382f8451382f8461382f8471382f8481382f8491382f84a1382f84b1382f84c1382f84d1382f84e1382f84f1382f8501382f8511382f8521382f8531382f8541382f8551382f8561382f8571382f8581382f8591382f85a1382f85b1382f85c1382f85d1382f85e1382f85f1382f8601382f8611382f8621382f8631382f8641382f8651382f866137ff476af4ef66a60ccf2ff002860012085f8ce004ff0ff30a5f8e000a5f8e200a5f8e400a5f8e600a5f8e800a5f8ea00a5f8ec00a5f8ee00a5f8f000a5f8f200a5f8f400a5f8f600a5f8f800a5f8fa00a5f8fc00a5f8fe003d60b068002818bf002d02d102b0bde8f081b6f84010b6f842205143b1f5163ff4d3c5f8240201264ff4f07085f8286201904ff4207049f683540090c0f2470400200021002200230027a04730b185f82872c5f8247202b0bde8f08188f8046002b0bde8f08100bf2de9f04f8ab0dde914a5089243ea010242ea0a02d207864640f0c4800eeb51004ff0ff374fea5a0c0eeb53068646012207eb5a00bcf1010f88bf4fea5a02069002f003000790caf341006ff00107059007eb5a006ff00207019007eb5a00009022f00302701c544203900ef101004ff0000b09960290cdf810e004e00bf1010bab4500f0c3810898139e5f466fea0b02864288bfaf183a183744099802eb820207eb87070eeb82198b4200eb871835d9059e6246b6b10698012e19f8002008f8002002460ed00198022e19f8002008f80020024606d0009819f8002008f80020024600bf06980328c8d300bf09eb020717f8016c08eb020000f8016c17f8026c043a00f8026c17f8036c00f8036c17f8047c00f8047ce9d1b0e700bfbaf1080f02d2002223e000bf03989601ba0102440298e64600eb060a6ff0030c0aeb0c00c67802eb0c07fe7006790cf1040c3e7146797e71807904eb0c060436b871edd10cf10402dde914a5f446ddf810e0079800283ff483af079e19f80200012e08f802003ff47baf501c079e19f80070022e08f800703ff472af901c19f8002008f800206be74ff6fc7000ea0a000af0030b0990aaf1010000240490cde905be07e0079c159d0134ddf850a0ac4200f01e81089f139ee0432246be42079488bf2a18d01900eb80000eeb801c901900eb8000baf1040f0eeb80184ff00009c0f09880ddf810a0ddf850e048468b4288bf504600eb010400eb03054fea54001cf800706ff0010080ea090009f1010288bf0eeb00026ff0020089ea000609f1020088bf0eeb06006ff0030686ea090609f1030b4feac47488bf0eeb060b07f00f06002c4fea550408bf3e0918f80470ed0707f00f0507f0f007374408bf45ea061708f80470541865081cf805501a44e40705f00f064fea520408bf2e0918f80450d20705f00f0205f0f005354408bf42ea0615421808f8045054081cf804401844d20704f00f054fea500208bf250918f80240c00704f00f0004f0f0042c4408bf40ea05140beb010008f8024042081cf802200beb0304c00702f00f054fea540008bf150918f80020e40702f00f0402f0f0022a4408bf44ea051208f80020099809f104098145aaf1040a7ff46eafdde905bebbf1000f3ff444af6fea09004a468b42149f88bf3a18501845081a44c0071cf805504fea520018f8007005f00f0408bf2c0907f00f0507f0f0072744d20708bf45ea0417bbf1010f08f800703ff420af149809f10102a0eb090a8b4288bfaaf10202541865081a44e4071cf805504fea520418f8040005f00f0708bf2f0900f00f0500f0f0003844d20708bf45ea0710bbf1020f08f804003ff4faae09f102008b4288bfaaf10300421854081844d2071cf804704fea500218f8024007f00f0508bf3d0904f00f0704f0f0042c44c00708bf47ea051408f80240d9e60ab0bde8f08f00bf70b54ff2a846c2f2290632680c4611466ff39601b1f1005f054607d110684ef66a61ccf2ff01884200f0c3804ff44970fbf7f8fe002800f0068102464ff6dc40cff6ff70002100bf1318433083f8241383f8251383f8261383f8271383f8281383f8291383f82a1383f82b1383f82c1383f82d1383f82e1383f82f1383f8301383f8311383f8321383f8331383f8341383f8351383f8361383f8371383f8381383f8391383f83a1383f83b1383f83c1383f83d1383f83e1383f83f1383f8401383f8411383f8421383f8431383f8441383f8451383f8461383f8471383f8481383f8491383f84a1383f84b1383f84c1383f84d1383f84e1383f84f1383f8501383f8511383f8521383f8531383f8541383f8551383f8561383f8571383f8581383f8591383f85a1383f85b1383f85c1383f85d1383f85e1383f85f1383f8601383f8611383f8621383f8631383f8641383f8651383f866137ff476af4ef66a60ccf2ff001060012082f8ce004ff0ff30a2f8e000a2f8e200a2f8e400a2f8e600a2f8e800a2f8ea00a2f8ec00a2f8ee00a2f8f000a2f8f200a2f8f400a2f8f600a2f8f800a2f8fa00a2f8fc00a2f8fe0032600120002d82f8cc0047d0104630f8e01fa1423bd0b2f8e210a14237d0b2f8e410a14233d0b2f8e610a1422fd0b2f8e810a1422bd0b2f8ea10a14227d0b2f8ec10a14223d0b2f8ee10a1421fd0b2f8f010a1421bd0b2f8f210a14217d0b2f8f410a14213d0b2f8f610a1420fd0b2f8f810a1420bd0b2f8fa10a14207d0b2f8fc10a14203d0b2f8fe10a1420ad1012082f8de0070bd0020306070bd82f8cd00002070bd92f8cd1081b9b2f8c810611a0bb2b3f1ff3f06dd89b2022924bf012182f8dd1002e0012182f8dc10b2f8ca30002182f8cd109c42a2f8c84088bfa2f8ca4092f8001120f81140481c00f00f0082f80001002070bd2de9f04fcdb046f22b149246c0f25d0447f2f85298460e4604f13c07c0f27b020f2138230546b84718b12846a047002423e20afb08f040000b960295059001250da94ff4807004f585724ff0000b4ff0000947464ff000080023564604930a930697cdf820a00192029ce1602061204600219047e1680daa891a07910da900f0e681ddf82ce00021002400900be000bf04940c9c002101234ff0030807980134844200f0d181002940f0e0810da80c94045db8f1020febd0b8f1010f00f09280b8f1000f40f0968004f00f000a900598210900f0a6808842c0f08880401a05900a9800eb00140001039014e01cf80b000a9a00f0f00010440cf80b000bf1010b01390125b34524bf4ff0000b09f10109002900f08c81b9454ff000084ff0000338bf012380f0028109eb8900002d0eeb801cdbd0cdf82490a946a6eb0b05b5eb510f88bf4d088db3a8080ceb0b0820d0002708f10102a7eb80006ff0030600bf02eb060e043600eb060a1af104078ef803408ef804408ef805408ef80640efd1301d069f089eddf82ce015f0030204d10ce0002015f0030208d0012a08f8004004d04044022a447018bf8470a1eb4501ab4489b1b34510d21cf80b00039a00f00f001043ddf824900cf80b00013900250029a0d12be100bf00214d46ddf8249090e700bfbcb10598a04228d201214ff0000821e0ddf810a005985aea042a16d00c9c5045cdf810a080f0938001214ff00008002342e70c9c002101234ff002083ce70c9c00214ff00108012336e7002001214ff0000804900c9c00232ee7001b05900a9800eb00110001099015e000bf1af80b200a9802f0f00202430af80b200bf1010b013c0125b34524bf4ff0000b09f10109002c00f0da80b9454ff000084ff0000338bf012350d209eb8902002d0eeb821adcd0ac46a6eb0b05b5eb540f88bf650855b3ae080aeb0b0818d0002008f10102a0eb860e6ff00306901904360eeb06070437c170017141718171f5d1069fddf82ce0321d15f0030604d10de0002215f0030609d0012e08f8021005d04244022e517018bf917000bfa4eb4504ab447cb1089eb3450ed21af80b00099a00f00f0010430af80b00013c0025002cabd184e0089e002465469de70c9c0121b4e6a0eb0a0005900a9800eb00110001099015e01cf80b000a9a00f0f00010430cf80b000bf1010baaf1010a0125b34524bf4ff0000b09f10109baf1000f65d0b9454ff000084ff0000338bf01235bd20b9a09eb8900002d02eb801cdad0ce46a946a6eb0b05b5eb5a0f88bf4fea5a0545b3a8080ceb0b0817d0002408f10102a4eb80006ff003069719043684190434f97039717971b971f6d1301d069f089e0c9c15f0030204d10ce0002015f0030208d0012a08f8001004d04044022a417018bf8170aaeb450abaf1000fab4411d0b34511d21cf80b00099a00f00f0010430cf80b00aaf1010a0025f146baf1000fa6d10be04ff0000a4d46f14697e70c9c4ff00008002131e6012102e04ff000080021ddf82ce029e600980da973b1012817d04ff0000450b90798019ab0fa80f040094ff480703ff4ffad00e00024029846f22b11c0f25d01884720464db0bde8f08f059840ea0800b0fa80f04409eee72de9f04f83b00c9e0292002e019000f08e80019823f00304471c029803f0030ac4f1000c01384ff00008009005e000bf08f10108b0450f4479d00e98c14600286fea080418bf06eb0409002bf0d0042b06d24ff0000bbaf1000f2ed1e8e700bf0d98b64609fb00f400986ff003050444607800f0f00242ea10107a19d0706078043500f00f0646ea0010107114f8020f00f0f00646ea10105071207800f00f0646ea00100ceb050604369071e0d105f1040b7646baf1000fbad002980d9a4fea5b0509fb0204019814f805e008fb01050ef00f025feacb7908bf4fea1e1242ea0212baf1010f05f80b20a1d00bf1010e4fea5e00205cb9f1000f4fea101208bf00f00f0242ea0210baf1020f05f80e008ed00bf102004208a25cb9f1000f02f00f0408bf140944ea04122a5480e703b0bde8f08f2de9f04182b003fb02f68846cde900164cf6036107466846c0f247011c461546884740f2196047f8240f788946f2c10245ea0040b86045ea044057f8204c7860c0f24a0220463946fe60c7f81080904740f69b51c0f244012046884702b0bde8f08100bf2de9f04188b046f24f461c46c0f24e0613460a46ddf83880002706f1ae05214627706770a770e77027716771a771e77127726772a772e77227736773a773e77327746774a774e77427756775a775e77527766776a776e77627776777a777e777a8470028c8f800705cd020786178a278e3780843104318434ff0010008d0e179a27911431ebf617a227a51ea020102d108b0bde8f081a07b14284ff00000f7d1217d8df8040041f0010121758df805008df806008df807008df808008df809008df80a008df80b008df80c008df80d008df80e008df80f008df810008df811008df812008df813008df814008df815008df816008df817008df818008df819008df81a008df81b008df81c008df81d008df81e008df81f0001a92046b047c8f8000018b1012008b0bde8f08106f1520120468847d8f80000002818bf012008b0bde8f08108031000000000000000000000000000000000000000000000002020202020002020000000505050000000000000000000005050f85050f85050000000002070a8a07028a8702000000048a85010202854480000000020505020689090680000002020200000000000000000000010204040404020100000000040201010101020400000000000005020f82050000000000000002020f82020000000000000000000000020204000000000000000f800000000000000000000000000202000000000080810102020404000000000708898a8c88888700000000020602020202020700000000070888808102040f8000000007088083008088870000000000818284888f8080800000000f88080f00808887000000000708080f08888887000000000f808081010202020000000007088887088888870000000007088888878080870000000000000202000002020000000000000202000002020400000000008102040201008000000000000f80000f8000000000000004020100810204000000000708888102000202000000000708898a8a89880780000000070888888f888888800000000f08888f0888888f000000000708880808080887000000000e0908888888890e000000000f88080f0808080f800000000f88080f0808080800000000070888080b888887000000000888888f888888888000000007020202020202070000000003810101010909060000000008890a0c0c0a090880000000080808080808080f80000000088d8a8a888888888000000008888c8a89888888800000000708888888888887000000000f0888888f080808000000000708888888888a87008000000f0888888f0a0908800000000708880700808887000000000f8202020202020200000000088888888888888700000000088888850505020200000000088888888a8a8d88800000000888850202050888800000000888850502020202000000000f8081020408080f8000000007040404040404070000000004040202010100808000000007010101010101070000000205088000000000000000000000000000000000000f80040200000000000000000000000000000700878888878000000008080f088888888f00000000000007088808088700000000008087888888888780000000000007088f8808078000000001820702020202020000000000000788888888878087000008080f08888888888000000202000602020202070000000080800180808080808483000004040485060605048000000006020202020202070000000000000f0a8a8a8a8a8000000000000f08888888888000000000000708888888870000000000000f088888888f0808000000000788888888878080800000000b8c0808080800000000000007880700808f00000000020207020202020180000000000008888888888780000000000008888505020200000000000008888a8a8a870000000000000885020205088000000000000888888888878087000000000f810204080f800000000182020402020201800000000202020202020202000000000601010081010106000000048a89000000000000000004556454e4346572f323220696d6736343020696d677a20726c652077616b656c65617365206469726563746662206662677561726420776561726e6f7469667920636c65616e75703131207465786361636865313220746578696d67313320746578737472313420666f6e743135206d696363746c207461706c6f6e6731312072696e67626174313700",
"desc": "append injected blobs to main-app payload"
},
{
- "offset": 777711,
- "old": "44c33500",
- "new": "4a5c3600",
+ "offset": 779114,
+ "old": "846a3800",
+ "new": "86113900",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
- "old": "c4c33500",
- "new": "ca5c3600",
+ "old": "046b3800",
+ "new": "06123900",
"desc": "main-app TOC entry size (ps + 128)"
},
{
- "offset": 777831,
- "old": "44c33504",
- "new": "4a5c3604",
+ "offset": 779234,
+ "old": "846a3804",
+ "new": "86113904",
"desc": "main-app preamble length (low 24 bits)"
},
{
- "offset": 777835,
- "old": "df8110c9",
- "new": "0aa0bcf3",
+ "offset": 779238,
+ "old": "85c355a2",
+ "new": "1a7d445b",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
- "old": "c1be0fb1",
- "new": "01fcf86d",
+ "old": "ed292ee4",
+ "new": "a7b82e22",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
- "offset": 777715,
- "old": "c1be0fb1",
- "new": "01fcf86d",
+ "offset": 779118,
+ "old": "ed292ee4",
+ "new": "a7b82e22",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
diff --git a/app/g2/glasses-presence.ts b/app/g2/glasses-presence.ts
new file mode 100644
index 00000000..ce8b75e8
--- /dev/null
+++ b/app/g2/glasses-presence.ts
@@ -0,0 +1,46 @@
+/**
+ * Whether the glasses could carry an alert right now: connected over BLE, on
+ * a head, and not charging. Fed by the dashboard controller from the
+ * transport's phase, wear-state and battery reports; consumed by the Timers
+ * engine, which mirrors it to the phone's alarm clock so the phone knows
+ * when to add its own sound.
+ */
+
+export type GlassesPresence = {
+ connected: boolean;
+ /** null until the firmware has reported a wear state this session. */
+ worn: boolean | null;
+ charging: boolean;
+};
+
+let presence: GlassesPresence = { connected: false, worn: null, charging: false };
+const listeners = new Set<(presence: GlassesPresence) => void>();
+
+export function getGlassesPresence(): GlassesPresence {
+ return presence;
+}
+
+/** True when a fresh, positive report says the glasses are worn and usable. */
+export function glassesCanCarryAlert(current: GlassesPresence = presence): boolean {
+ return current.connected && current.worn === true && !current.charging;
+}
+
+export function updateGlassesPresence(patch: Partial): void {
+ const next = { ...presence, ...patch };
+ if (next.connected === presence.connected && next.worn === presence.worn && next.charging === presence.charging) return;
+ presence = next;
+ for (const listener of Array.from(listeners)) {
+ try {
+ listener(presence);
+ } catch (error) {
+ console.warn(`glasses presence listener failed: ${error}`);
+ }
+ }
+}
+
+export function onGlassesPresenceChanged(listener: (presence: GlassesPresence) => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/app/g2/wear-remote.ts b/app/g2/wear-remote.ts
index d2b7f460..629d9d96 100644
--- a/app/g2/wear-remote.ts
+++ b/app/g2/wear-remote.ts
@@ -44,6 +44,7 @@ export type WearRemoteInputKind =
| "long-press"
| "long-press-start"
| "long-press-release"
+ | "short-then-long-press"
| "wakeword"
| "swipe-left"
| "swipe-right"
@@ -58,6 +59,7 @@ const INPUT_KINDS: readonly WearRemoteInputKind[] = [
"long-press",
"long-press-start",
"long-press-release",
+ "short-then-long-press",
"wakeword",
"swipe-left",
"swipe-right",
diff --git a/app/graphics/battery.ts b/app/graphics/battery.ts
index 2cba1b32..e3b0e1f0 100644
--- a/app/graphics/battery.ts
+++ b/app/graphics/battery.ts
@@ -1,20 +1,36 @@
import { GrayImage, imageFromAsciiArt } from "./image";
-const EMPTY_BATTERY_ICON = imageFromAsciiArt(
- [
- " ################## ",
- " #................# ",
- " #................###",
- " #................###",
- " #................###",
- " #................###",
- " #................###",
- " #................###",
- " #................# ",
- " ################## ",
- ],
- 120,
-);
+/**
+ * Top-bar battery gauge: a 10px-tall outlined body with a nub on the right,
+ * filled left-to-right in proportion to the charge. The fill is drawn as
+ * BATTERY_BAR_COUNT bars of BATTERY_BAR_WIDTH px separated by dimmed
+ * BATTERY_BAR_GAP-px columns; the body outline is sized from those
+ * constants so they can be tuned freely. The fill level is continuous (not
+ * quantized to whole bars): the rightmost lit bar is cut to a partial width.
+ */
+export const BATTERY_BAR_COUNT = 4;
+export const BATTERY_BAR_WIDTH = 3;
+export const BATTERY_BAR_GAP = 1;
+
+const OUTLINE_VALUE = 120;
+const BAR_VALUE = 190;
+/** The separator columns inside the lit portion of the fill. */
+const BAR_GAP_VALUE = 70;
+
+const ICON_HEIGHT = 10;
+/** Outline stroke plus one clear pixel between it and the fill, per side. */
+const BODY_INSET = 2;
+const NUB_WIDTH = 2;
+const NUB_TOP = 2;
+const NUB_HEIGHT = 6;
+
+const FILL_X = BODY_INSET;
+const FILL_Y = BODY_INSET;
+const FILL_WIDTH = BATTERY_BAR_COUNT * BATTERY_BAR_WIDTH + (BATTERY_BAR_COUNT - 1) * BATTERY_BAR_GAP;
+const FILL_HEIGHT = ICON_HEIGHT - 2 * BODY_INSET;
+const BODY_WIDTH = FILL_WIDTH + 2 * BODY_INSET;
+
+export const BATTERY_ICON_WIDTH = BODY_WIDTH + NUB_WIDTH;
const BATTERY_BOLT_ICON = imageFromAsciiArt(
[
@@ -29,25 +45,48 @@ const BATTERY_BOLT_ICON = imageFromAsciiArt(
255,
);
-export const BATTERY_ICON_WIDTH = EMPTY_BATTERY_ICON.width;
+/** The empty outline, built once from the geometry constants. */
+const EMPTY_BATTERY_ICON = buildEmptyBattery();
-const BATTERY_FILL_X = 3;
-const BATTERY_FILL_Y = 2;
-const BATTERY_FILL_WIDTH = 14;
-const BATTERY_FILL_HEIGHT = 6;
+function buildEmptyBattery(): GrayImage {
+ const icon = new GrayImage(BATTERY_ICON_WIDTH, ICON_HEIGHT, 0);
+ icon.fillRect(0, 0, BODY_WIDTH, 1, OUTLINE_VALUE);
+ icon.fillRect(0, ICON_HEIGHT - 1, BODY_WIDTH, 1, OUTLINE_VALUE);
+ icon.fillRect(0, 0, 1, ICON_HEIGHT, OUTLINE_VALUE);
+ icon.fillRect(BODY_WIDTH - 1, 0, 1, ICON_HEIGHT, OUTLINE_VALUE);
+ icon.fillRect(BODY_WIDTH, NUB_TOP, NUB_WIDTH, NUB_HEIGHT, OUTLINE_VALUE);
+ return icon;
+}
export function drawBattery(percentCharge: number, isCharging: boolean): GrayImage {
const icon = new GrayImage(EMPTY_BATTERY_ICON.width, EMPTY_BATTERY_ICON.height, 0);
icon.bitBlt(EMPTY_BATTERY_ICON, 0, 0);
const clamped = Math.max(0, Math.min(100, percentCharge));
- const fillWidth = Math.round((BATTERY_FILL_WIDTH * clamped) / 100);
- icon.fillRect(BATTERY_FILL_X, BATTERY_FILL_Y, fillWidth, BATTERY_FILL_HEIGHT, 190);
+ const litWidth = Math.round((FILL_WIDTH * clamped) / 100);
+ drawSegmentedFill(icon, litWidth);
if (isCharging) {
- overlayImage(icon, BATTERY_BOLT_ICON, 7, 1, clamped > 50 ? 0 : 255);
+ const boltX = FILL_X + (((FILL_WIDTH - BATTERY_BOLT_ICON.width) / 2) | 0);
+ overlayImage(icon, BATTERY_BOLT_ICON, boltX, 1, clamped > 50 ? 0 : 255);
}
return icon;
}
+/**
+ * Light the leftmost `litWidth` columns of the fill area as bars with dim
+ * separator columns. Columns past the lit width stay clear, so a partial
+ * charge ends mid-bar rather than snapping to a bar boundary. A separator is
+ * only drawn between two lit bars: when the lit width ends exactly on one it
+ * is left clear rather than dangling past the last bar.
+ */
+function drawSegmentedFill(icon: GrayImage, litWidth: number): void {
+ const pitch = BATTERY_BAR_WIDTH + BATTERY_BAR_GAP;
+ for (let column = 0; column < litWidth; column++) {
+ const isBar = column % pitch < BATTERY_BAR_WIDTH;
+ if (!isBar && column + BATTERY_BAR_GAP >= litWidth) continue;
+ icon.fillRect(FILL_X + column, FILL_Y, 1, FILL_HEIGHT, isBar ? BAR_VALUE : BAR_GAP_VALUE);
+ }
+}
+
function overlayImage(target: GrayImage, source: GrayImage, dx: number, dy: number, value: number): void {
for (let y = 0; y < source.height; y++) {
for (let x = 0; x < source.width; x++) {
diff --git a/app/graphics/icons.ts b/app/graphics/icons.ts
index af478732..bee9d8cf 100644
--- a/app/graphics/icons.ts
+++ b/app/graphics/icons.ts
@@ -18,6 +18,8 @@ const ICON_STROKE_WIDTH = 2;
// Lucide icons (MIT/ISC licensed). Kept verbatim so they can be diffed
// against upstream if an icon needs updating.
export const ICON_SVGS = {
+ "message-circle":
+ '',
"layout-grid":
'',
timer:
@@ -36,6 +38,8 @@ export const ICON_SVGS = {
'',
terminal:
'',
+ "scroll-text":
+ '',
"file-text":
'',
file:
@@ -87,9 +91,11 @@ export const ICON_SVGS = {
} as const;
export type IconName = keyof typeof ICON_SVGS;
+/** Idle prompt, or the visible/hidden phases of an activity cursor. */
+export type IconActivity = "idle" | "on" | "off";
-// The "_" element of the terminal icon, swapped out for a session glyph in
-// renderIconWithGlyph.
+// Prompt and session-marker elements replaced by renderIconWithGlyph.
+const TERMINAL_PROMPT = '';
const TERMINAL_UNDERSCORE = '';
/**
@@ -155,12 +161,23 @@ export function renderSvgIcon(cacheName: string, svg: string, size: number): Gra
/**
* Render an icon with a glyph character substituted in — currently only the
* terminal icon, whose "_" becomes the glyph (">3" instead of ">_"). Falls
- * back to the plain icon for other names or unsupported characters.
+ * back to the plain marker for unsupported characters. Active terminal icons
+ * replace the prompt with a blinking cursor, leaving the marker in place.
*/
-export function renderIconWithGlyph(name: IconName, glyph: string, size: number): GrayImage | null {
- const shape = name === "terminal" ? TERMINAL_GLYPH_SHAPES[glyph] : undefined;
- if (!shape) return renderIcon(name, size);
- return renderSvgCached(`${name}[${glyph}]`, ICON_SVGS.terminal.replace(TERMINAL_UNDERSCORE, shape), size);
+export function renderIconWithGlyph(name: IconName, glyph: string, size: number, activity: IconActivity = "idle"): GrayImage | null {
+ if (name !== "terminal") return renderIcon(name, size);
+ const shape = TERMINAL_GLYPH_SHAPES[glyph];
+ if (!shape && activity === "idle") return renderIcon(name, size);
+ let svg: string = ICON_SVGS.terminal;
+ if (shape) svg = svg.replace(TERMINAL_UNDERSCORE, shape);
+ if (activity !== "idle") {
+ // IconRenderer strokes all elements at width 2; the narrow rectangle
+ // therefore becomes a solid cursor without needing per-element fills.
+ svg = svg.replace(TERMINAL_PROMPT, activity === "on"
+ ? ''
+ : "");
+ }
+ return renderSvgCached(`${name}[${shape ? glyph : ""}]:${activity}`, svg, size);
}
function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null {
diff --git a/app/graphics/image.ts b/app/graphics/image.ts
index 4a5d472e..70028f61 100644
--- a/app/graphics/image.ts
+++ b/app/graphics/image.ts
@@ -520,6 +520,37 @@ export class GrayImage {
}
}
+ /**
+ * A copy of this image with its brightness scaled by `factor` (0..1):
+ * raster and glyph / firmware-text draws alike, keeping the draws deferred
+ * so they stay on the cached-glyph wire path. Transparent (0) pixels stay
+ * transparent and anything visible stays at least 1 (black), so the
+ * color-key convention survives. Image draws (icons) are baked into the
+ * raster first: their sources are immutable, content-addressed cache
+ * entries, and a dimmed variant of each would only pollute that cache.
+ */
+ dimmed(factor: number): GrayImage {
+ const scale = Math.max(0, Math.min(1, factor));
+ const copy = new GrayImage(this.width, this.height, 0);
+ copy.pixels.set(this.pixels);
+ for (const placed of this.drawList) {
+ if (placed.kind === "image") {
+ copy.bitBlt(placed.source, placed.x, placed.y, { transparentZero: true });
+ }
+ }
+ const pixels = copy.pixels;
+ for (let i = 0; i < pixels.length; i++) {
+ const value = pixels[i]!;
+ if (value !== 0) pixels[i] = dimValue(value, scale);
+ }
+ for (const placed of this.drawList) {
+ if (placed.kind !== "image") {
+ copy.drawList.push({ ...placed, value: dimValue(placed.value, scale) });
+ }
+ }
+ return copy;
+ }
+
/**
* This image with its deferred draws rasterized into the pixel buffer.
* Returns this image unchanged when there are none, otherwise a baked copy
@@ -612,6 +643,11 @@ function rasterizeGlyph(
}
}
+/** Scale a visible (non-zero) brightness, never below 1 (the color-key black). */
+function dimValue(value: number, scale: number): number {
+ return Math.max(1, Math.round(value * scale));
+}
+
function clampByte(value: number): number {
return Math.max(0, Math.min(255, Math.round(value)));
}
diff --git a/app/graphics/plane.ts b/app/graphics/plane.ts
index e29ff88f..15cf5c98 100644
--- a/app/graphics/plane.ts
+++ b/app/graphics/plane.ts
@@ -30,6 +30,11 @@ export function singlePlane(image: GrayImage): Plane[] {
return [{ image, x: 0, y: 0 }];
}
+/** The planes with their brightness scaled by `factor` (see GrayImage.dimmed). */
+export function dimPlanes(planes: readonly Plane[], factor: number): Plane[] {
+ return planes.map((plane) => ({ ...plane, image: plane.image.dimmed(factor) }));
+}
+
/**
* Flatten planes into one image: for each plane in order, blend its raster
* (0 = transparent) and then its glyphs on top. A later plane's raster covers
diff --git a/app/graphics/ui-fonts.ts b/app/graphics/ui-fonts.ts
index bcca0c53..9a04505e 100644
--- a/app/graphics/ui-fonts.ts
+++ b/app/graphics/ui-fonts.ts
@@ -34,10 +34,10 @@ const MAX_SIZE_GROWTH = 48;
/**
* Guaranteed line-height range of getDefaultSmallFont, which UI layouts may
* rely on (getDefaultMediumFont's range follows: 16..29). The font picker
- * disables sizes outside it, and resolution falls back to the bitmap face if
+ * hides sizes outside it, and resolution falls back to the bitmap face if
* a stored selection somehow lands outside (e.g. the font file changed).
*/
-export const SMALL_FONT_MIN_LINE_HEIGHT = 12;
+export const SMALL_FONT_MIN_LINE_HEIGHT = 8;
export const SMALL_FONT_MAX_LINE_HEIGHT = 21;
/** Whether a small-font selection at this path+size satisfies the UI bound. */
diff --git a/app/native/alarms.ts b/app/native/alarms.ts
new file mode 100644
index 00000000..ca44672c
--- /dev/null
+++ b/app/native/alarms.ts
@@ -0,0 +1,154 @@
+import { Utils } from "@nativescript/core";
+
+declare const com: any;
+
+/**
+ * Bridge to the Java alarm clock (FaceclawAlarms / FaceclawAlarmService):
+ * the durable phone side of the Timers app's timers and alarms. The phone
+ * schedules an exact alarm-clock alarm per item, re-arms them after reboots
+ * and time changes, and when one comes due shows it on the phone (silently
+ * at first) and adds phone sound if the glasses cannot carry it. Ids are the
+ * engine's item ids.
+ */
+
+export type AlarmKind = "timer" | "alarm";
+
+export type PhoneAlarmAction = { id: number; action: "dismiss" | "snooze"; minutes: number; atMs: number };
+
+export type AlarmReliabilityIssue = { code: string; message: string; fixable: boolean };
+
+function getContext(): android.content.Context | null {
+ if (!global.isAndroid) return null;
+ return Utils.android.getApplicationContext() ?? null;
+}
+
+/** Schedule (or move) the phone alarm that rings `title` / `text` at triggerAtMs. */
+export function schedulePhoneAlarm(
+ itemId: number,
+ triggerAtMs: number,
+ title: string,
+ text: string,
+ kind: AlarmKind,
+ snoozeMinutes: number,
+): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.schedule(context, itemId, triggerAtMs, title, text, kind, snoozeMinutes);
+}
+
+/** Cancel the pending phone alarm, stop it if ringing, and clear its notification. */
+export function cancelPhoneAlarm(itemId: number): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.cancel(context, itemId);
+}
+
+/** The engine's own expiry path: start the phone ringing flow (deduplicated against the alarm's). */
+export function ringPhoneAlarm(itemId: number, title: string, text: string, kind: AlarmKind, snoozeMinutes: number): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.ring(context, itemId, title, text, kind, snoozeMinutes);
+}
+
+/** The glasses are showing the item: the phone starts its 30-second acknowledgement clock. */
+export function phoneAlarmDeliveredToGlasses(itemId: number): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.deliveredToGlasses(context, itemId);
+}
+
+/** The wearer dealt with the item on the glasses: the phone goes quiet. */
+export function acknowledgePhoneAlarm(itemId: number): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.acknowledge(context, itemId);
+}
+
+/** Tell the phone whether the glasses could carry an alarm right now. */
+export function setPhoneAlarmGlassesStatus(connected: boolean, worn: boolean, charging: boolean): void {
+ if (!global.isAndroid) return;
+ com.faceclaw.app.FaceclawAlarms.setGlassesStatus(connected, worn, charging);
+}
+
+let retainedListenerProxy: any = null;
+const actionListeners = new Set<(action: PhoneAlarmAction) => void>();
+
+/** Live phone-side dismiss / snooze events (journaled ones arrive through drainPhoneAlarmJournal). */
+export function onPhoneAlarmAction(listener: (action: PhoneAlarmAction) => void): () => void {
+ if (retainedListenerProxy === null && global.isAndroid) {
+ retainedListenerProxy = new com.faceclaw.app.FaceclawAlarmListener({
+ onPhoneAction: (id: number, action: string, minutes: number) => {
+ const event: PhoneAlarmAction = {
+ id: Number(id),
+ action: String(action) === "snooze" ? "snooze" : "dismiss",
+ minutes: Number(minutes),
+ atMs: Date.now(),
+ };
+ for (const registered of Array.from(actionListeners)) {
+ try {
+ registered(event);
+ } catch (error) {
+ console.warn(`phone alarm action listener failed: ${error}`);
+ }
+ }
+ },
+ });
+ com.faceclaw.app.FaceclawAlarms.setListener(retainedListenerProxy);
+ }
+ actionListeners.add(listener);
+ return () => {
+ actionListeners.delete(listener);
+ };
+}
+
+/** Phone-side actions taken while the engine was not listening, oldest first; cleared on read. */
+export function drainPhoneAlarmJournal(): PhoneAlarmAction[] {
+ const context = getContext();
+ if (!context) return [];
+ let parsed: any;
+ try {
+ parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.drainJournal(context)));
+ } catch {
+ return [];
+ }
+ if (!Array.isArray(parsed)) return [];
+ return parsed
+ .filter((entry) => entry && typeof entry === "object" && Number.isFinite(Number(entry.id)))
+ .map((entry) => ({
+ id: Number(entry.id),
+ action: entry.action === "snooze" ? "snooze" : "dismiss",
+ minutes: Number(entry.minutes) || 0,
+ atMs: Number(entry.at) || 0,
+ }));
+}
+
+/** Conditions under which the phone may fail to ring, most serious first. */
+export function checkPhoneAlarmReliability(): AlarmReliabilityIssue[] {
+ const context = getContext();
+ if (!context) return [];
+ let parsed: any;
+ try {
+ parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.checkReliability(context)));
+ } catch (error) {
+ console.warn(`alarm reliability check failed: ${error}`);
+ return [];
+ }
+ if (!Array.isArray(parsed)) return [];
+ return parsed
+ .filter((entry) => entry && typeof entry === "object" && typeof entry.code === "string")
+ .map((entry) => ({ code: entry.code, message: String(entry.message ?? ""), fixable: entry.fixable !== false }));
+}
+
+/** Open the system screen where a reliability issue can be fixed. */
+export function openPhoneAlarmReliabilityFix(code: string): void {
+ const context = getContext();
+ if (!context) return;
+ com.faceclaw.app.FaceclawAlarms.openReliabilityFix(context, code);
+}
+
+/** The phone's ring / miss / action log, one line per entry, newest last. */
+export function readPhoneAlarmLog(): string {
+ const context = getContext();
+ if (!context) return "";
+ return String(com.faceclaw.app.FaceclawAlarms.readLog(context));
+}
diff --git a/app/native/ambient-light.ts b/app/native/ambient-light.ts
new file mode 100644
index 00000000..81f3b099
--- /dev/null
+++ b/app/native/ambient-light.ts
@@ -0,0 +1,157 @@
+/**
+ * Ambient light sensor access through the custom firmware (CFW image-handler
+ * mode 16, capability token "als16"; see g2flash/patches/als_sensor.c).
+ *
+ * The stock firmware only reads its OPT3001 light sensor while auto-brightness
+ * is on, and then steps the panel brightness itself (visible flicker). The CFW
+ * adds two things:
+ *
+ * - QUERY: one report from the driver's current state.
+ * - PASSIVE polling: the firmware opens and polls the sensor at our interval,
+ * the stock adjuster never touches the panel, and a report arrives when the
+ * reading moved by at least `minDelta` or `heartbeatMs` elapsed. The phone
+ * then applies brightness itself (setBrightness with autoAdjust=false), e.g.
+ * only while the display is blank or during a UI transition.
+ *
+ * Reports are 24-byte ['A','L',version,...] records on settings field 105.
+ */
+import { toUint8Array } from "../util/array-util";
+
+declare const com: any;
+declare const global: any;
+
+export const ALS_REPORT_VERSION = 1;
+
+export type AmbientLightReason = "query" | "started" | "poll" | "stopped";
+
+export type AmbientLightReport = {
+ reason: AmbientLightReason;
+ /** The sensor driver is open (readings are live). */
+ opened: boolean;
+ /** CFW passive polling is installed (stock auto-brightness is not stepping). */
+ passive: boolean;
+ /** The user's stock auto-brightness setting is on. */
+ autoBrightness: boolean;
+ /** The last passive read succeeded (only meaningful while passive). */
+ readOk: boolean;
+ /** Stock driver status: 1 start-read, 2 adjusting, 3 polling. */
+ status: number;
+ /** Ambient light in the stock driver's units (roughly tenths of a lux). */
+ alsValue: number;
+ /** Max of the last five readings (what the stock curve is applied to). */
+ peak: number;
+ /** Brightness level (0..100) the stock curve would choose for `peak`. */
+ stockTarget: number;
+ /** Current brightness setting (0..100). */
+ brightness: number;
+ /** Row of the stock brightness curve (0..5) for `peak`. */
+ gear: number;
+ /** Stock learned scale factor, Q10 (1024 = 1.0). */
+ scaleQ10: number;
+ /** Firmware millisecond tick when the report was built. */
+ tickMs: number;
+};
+
+const REASONS: AmbientLightReason[] = ["query", "started", "poll", "stopped"];
+
+function rd16(b: Uint8Array, i: number): number {
+ return b[i] | (b[i + 1] << 8);
+}
+
+function rd32(b: Uint8Array, i: number): number {
+ return (b[i] | (b[i + 1] << 8) | (b[i + 2] << 16) | (b[i + 3] << 24)) >>> 0;
+}
+
+/** Decode a field-105 record body, or null when it isn't one. */
+export function decodeAmbientLightReport(body: Uint8Array): AmbientLightReport | null {
+ if (body.length < 24 || body[0] !== 0x41 || body[1] !== 0x4c || body[2] !== ALS_REPORT_VERSION) {
+ return null;
+ }
+ const flags = body[4];
+ return {
+ reason: REASONS[body[3]] ?? "poll",
+ opened: (flags & 0x01) !== 0,
+ passive: (flags & 0x02) !== 0,
+ autoBrightness: (flags & 0x04) !== 0,
+ readOk: (flags & 0x08) !== 0,
+ status: body[5],
+ alsValue: rd32(body, 6),
+ peak: rd32(body, 10),
+ stockTarget: rd16(body, 14),
+ brightness: body[16],
+ gear: body[17],
+ scaleQ10: rd16(body, 18),
+ tickMs: rd32(body, 20),
+ };
+}
+
+export type AmbientLightPollingOptions = {
+ /** Poll period in ms; the firmware clamps to 100..5000. Default 500. */
+ intervalMs?: number;
+ /** Report when the reading moved by at least this much. Default 1. */
+ minDelta?: number;
+ /** Also report after this many ms without one (0 = never). Default 5000. */
+ heartbeatMs?: number;
+ /**
+ * Stop automatically when the Faceclaw framebuffer lease is released or
+ * lapses (the phone went away). Default true.
+ */
+ bindToLease?: boolean;
+};
+
+function activeCommunicator(): any {
+ if (!global.isAndroid) return null;
+ try {
+ return com.faceclaw.app.FaceclawBleCommunicator.getActive();
+ } catch {
+ return null;
+ }
+}
+
+/** Ask the firmware for one ambient-light report (delivered to listeners). */
+export function queryAmbientLight(): void {
+ try {
+ activeCommunicator()?.queryAmbientLight();
+ } catch (error) {
+ console.warn(`queryAmbientLight failed: ${error}`);
+ }
+}
+
+/**
+ * Start or stop CFW passive light-sensor polling. Starting is idempotent and
+ * re-opens the sensor if the stock firmware closed it, so it is safe to resend
+ * on every session start.
+ */
+export function setAmbientLightPolling(enabled: boolean, options: AmbientLightPollingOptions = {}): void {
+ try {
+ activeCommunicator()?.setAmbientLightPolling(
+ enabled,
+ options.intervalMs ?? 500,
+ options.minDelta ?? 1,
+ options.heartbeatMs ?? 5000,
+ options.bindToLease ?? true,
+ );
+ } catch (error) {
+ console.warn(`setAmbientLightPolling failed: ${error}`);
+ }
+}
+
+/** Subscribe to decoded ambient-light reports. Delivered on the main thread. */
+export function addAmbientLightListener(listener: (report: AmbientLightReport) => void): () => void {
+ const active = activeCommunicator();
+ if (!active) return () => {};
+ const proxy = new com.faceclaw.app.FaceclawAmbientLightListener({
+ onAmbientLight: (body: any) => {
+ const report = decodeAmbientLightReport(toUint8Array(body));
+ if (report) listener(report);
+ },
+ });
+ active.addAmbientLightListener(proxy);
+ return () => {
+ try {
+ activeCommunicator()?.removeAmbientLightListener(proxy);
+ } catch {
+ // The communicator may have been replaced during a disconnect.
+ }
+ };
+}
diff --git a/app/native/ble-traffic.ts b/app/native/ble-traffic.ts
new file mode 100644
index 00000000..38a76ecc
--- /dev/null
+++ b/app/native/ble-traffic.ts
@@ -0,0 +1,16 @@
+declare const com: any;
+
+export interface BleTrafficSample {
+ /** Outbound messages (writeFrames calls) since process start. */
+ messages: number;
+ /** Outbound payload bytes (sum of frame sizes) since process start. */
+ bytes: number;
+ /** Display frames whose last message was acked, since process start. */
+ frames: number;
+}
+
+/** Running totals of outbound BLE traffic, counted process-wide in FaceclawBleManager. */
+export function sampleBleTraffic(): BleTrafficSample {
+ const raw = com.faceclaw.app.FaceclawBleManager.sampleOutboundTraffic();
+ return { messages: Number(raw[0]), bytes: Number(raw[1]), frames: Number(raw[2]) };
+}
diff --git a/app/native/cloud-stt.ts b/app/native/cloud-stt.ts
index 83c9c76f..f9a77167 100644
--- a/app/native/cloud-stt.ts
+++ b/app/native/cloud-stt.ts
@@ -9,6 +9,9 @@
export type CloudSttTranscriptEvent = {
text: string;
isFinal: boolean;
+ /** Optional presentation for Transcribe only; dictation uses plain text. */
+ transcribeText?: string;
+ paragraphBreakAfter?: boolean;
};
export type CloudSttOptions = {
@@ -16,6 +19,8 @@ export type CloudSttOptions = {
onTranscript: (event: CloudSttTranscriptEvent) => void;
onStatus: (status: string) => void;
onError: (message: string) => void;
+ onReady?: () => void;
+ onDisconnected?: (message: string) => void;
};
export interface CloudSttClient {
@@ -25,6 +30,8 @@ export interface CloudSttClient {
acceptPcm(pcm: Uint8Array): void;
/** End of utterance: produce a final transcript. */
finish(): void;
+ /** Commit a pause boundary while keeping the audio session open. */
+ commitSegment?(): void;
/** Abandon the session without finalizing. */
stop(): void;
}
diff --git a/app/native/compass.ts b/app/native/compass.ts
index e8b5751e..8a0d6491 100644
--- a/app/native/compass.ts
+++ b/app/native/compass.ts
@@ -5,10 +5,23 @@ export const COMPASS_CHANGED = 15;
export const COMPASS_CALIBRATION_STARTED = 16;
export const COMPASS_CALIBRATION_COMPLETE = 17;
+export type CompassDiagnostics = {
+ /** 0 uncalibrated .. 3 well calibrated; -1 unavailable. */
+ magneticAccuracy: number;
+ /** 0 none, 1 small/temperature, 2 large; -1 unavailable. */
+ magneticAnomalies: number;
+ /** 0 unknown, 1 GRV (relative), 2 GMRV, 3 RV. */
+ orientationSource: number;
+ flags: number;
+ sampleTimeMs: number;
+};
+
export type CompassEvent = {
command: number;
/** Magnetic heading in degrees, or -1 for calibration-only events. */
headingDegrees: number;
+ /** Absent with stock/older CFW or an unrecognized diagnostic extension. */
+ diagnostics?: CompassDiagnostics;
};
function activeCommunicator(): any {
@@ -20,22 +33,37 @@ function activeCommunicator(): any {
}
}
-/** Request CFW mode 10 to start/stop the stock firmware compass. */
-export function setCompassEnabled(enabled: boolean): void {
+/**
+ * Request CFW mode 10 to start/stop the stock firmware compass on behalf of
+ * `owner`. The magnetometer is shared: it runs while any owner wants it and
+ * stops once the last one releases it, so apps can't switch each other off.
+ */
+export function setCompassEnabled(enabled: boolean, owner = "compass"): void {
try {
- activeCommunicator()?.setCompassEnabled(enabled);
+ activeCommunicator()?.setCompassEnabled(owner, enabled);
} catch (error) {
console.warn(`setCompassEnabled failed: ${error}`);
}
}
-/** Subscribe to stock compass heading/calibration notifications. */
+/**
+ * Subscribe to stock compass heading/calibration notifications. Events are
+ * delivered on the calling thread's Looper, so this works from app workers.
+ */
export function addCompassListener(listener: (event: CompassEvent) => void): () => void {
const active = activeCommunicator();
if (!active) return () => {};
const proxy = new com.faceclaw.app.FaceclawCompassListener({
- onCompassEvent: (command: number, headingDegrees: number) => {
- listener({ command: Number(command), headingDegrees: Number(headingDegrees) });
+ onCompassEvent: (command: number, headingDegrees: number, magneticAccuracy: number,
+ magneticAnomalies: number, orientationSource: number, diagnosticFlags: number, sampleTimeMs: number) => {
+ listener({
+ command: Number(command), headingDegrees: Number(headingDegrees),
+ diagnostics: diagnosticFlags >= 0 ? {
+ magneticAccuracy: Number(magneticAccuracy), magneticAnomalies: Number(magneticAnomalies),
+ orientationSource: Number(orientationSource), flags: Number(diagnosticFlags),
+ sampleTimeMs: Number(sampleTimeMs),
+ } : undefined,
+ });
},
});
active.addCompassListener(proxy);
diff --git a/app/native/elevenlabs-stt.ts b/app/native/elevenlabs-stt.ts
index 8d602078..6fa555fc 100644
--- a/app/native/elevenlabs-stt.ts
+++ b/app/native/elevenlabs-stt.ts
@@ -1,4 +1,4 @@
-import { encodeBase64 } from "./cloud-stt";
+import { type CloudSttOptions, type CloudSttTranscriptEvent, encodeBase64 } from "./cloud-stt";
declare const com: any;
@@ -18,17 +18,8 @@ const WS_URL = "wss://api.elevenlabs.io/v1/speech-to-text/realtime";
const MODEL_ID = "scribe_v2_realtime";
const SAMPLE_RATE = 16000;
-export type ElevenLabsTranscriptEvent = {
- text: string;
- isFinal: boolean;
-};
-
-export type ElevenLabsSttOptions = {
- apiKey: string;
- onTranscript: (event: ElevenLabsTranscriptEvent) => void;
- onStatus: (status: string) => void;
- onError: (message: string) => void;
-};
+export type ElevenLabsTranscriptEvent = CloudSttTranscriptEvent;
+export type ElevenLabsSttOptions = CloudSttOptions;
export class ElevenLabsSttClient {
private ws: any = null;
@@ -38,26 +29,32 @@ export class ElevenLabsSttClient {
// PCM that arrived before the socket finished opening; flushed on open.
private readonly pendingChunks: string[] = [];
private latestText = "";
+ private readonly commits: boolean[] = [];
constructor(private readonly options: ElevenLabsSttOptions) {}
start(): void {
- if (this.ws) return;
+ if (this.closed || this.ws) return;
const url = `${WS_URL}?model_id=${MODEL_ID}&audio_format=pcm_${SAMPLE_RATE}&commit_strategy=manual`;
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
onOpen: () => {
+ if (this.closed) return;
this.open = true;
for (const chunk of this.pendingChunks.splice(0)) {
this.sendChunk(chunk);
}
+ if (!this.closed) this.options.onReady?.();
+ },
+ onTextMessage: (message: string) => {
+ if (!this.closed) this.handleMessage(String(message));
},
- onTextMessage: (message: string) => this.handleMessage(String(message)),
onClosed: () => {
this.open = false;
+ if (!this.closed) this.options.onDisconnected?.("ElevenLabs connection closed.");
},
onFailure: (message: string) => {
if (this.closed) return;
- this.options.onError(`ElevenLabs connection failed: ${String(message)}`);
+ this.options.onDisconnected?.(`ElevenLabs connection failed: ${String(message)}`);
},
});
try {
@@ -67,7 +64,7 @@ export class ElevenLabsSttClient {
this.ws = new com.faceclaw.app.FaceclawWebSocket(url, this.listenerProxy, "xi-api-key", key);
this.options.onStatus("Connecting to ElevenLabs...");
} catch (error) {
- this.options.onError(`ElevenLabs connection failed: ${String((error as Error)?.message ?? error)}`);
+ this.options.onDisconnected?.(`ElevenLabs connection failed: ${String((error as Error)?.message ?? error)}`);
}
}
@@ -82,24 +79,25 @@ export class ElevenLabsSttClient {
}
}
+ commitSegment(): void {
+ this.commit(true);
+ }
+
/** End of utterance: flush and commit for a final transcript. */
finish(): void {
+ this.commit(false);
+ }
+
+ private commit(paragraphBreakAfter: boolean): void {
if (this.closed) return;
- const commitMessage = JSON.stringify({
- message_type: "input_audio_chunk",
- audio_base_64: "",
- commit: true,
- sample_rate: SAMPLE_RATE,
- });
- if (this.open) {
- this.trySend(commitMessage);
- } else {
- this.pendingChunks.push("__commit__");
- }
+ this.commits.push(paragraphBreakAfter);
+ if (this.open) this.sendChunk("__commit__");
+ else this.pendingChunks.push("__commit__");
}
stop(): void {
this.closed = true;
+ this.open = false;
if (this.ws) {
try {
this.ws.close(1000, "bye");
@@ -109,28 +107,26 @@ export class ElevenLabsSttClient {
this.ws = null;
}
this.listenerProxy = null;
+ this.pendingChunks.length = 0;
}
private sendChunk(base64OrCommit: string): void {
- if (base64OrCommit === "__commit__") {
- this.finish();
- return;
- }
- this.trySend(
- JSON.stringify({
- message_type: "input_audio_chunk",
- audio_base_64: base64OrCommit,
- commit: false,
- sample_rate: SAMPLE_RATE,
- }),
- );
+ const commit = base64OrCommit === "__commit__";
+ this.trySend(JSON.stringify({
+ message_type: "input_audio_chunk",
+ audio_base_64: commit ? "" : base64OrCommit,
+ commit,
+ sample_rate: SAMPLE_RATE,
+ }));
}
private trySend(message: string): void {
try {
- this.ws?.sendText(message);
+ if (this.ws?.sendText(message) === false) {
+ this.options.onDisconnected?.("ElevenLabs send failed.");
+ }
} catch (error) {
- console.warn("elevenlabs send failed", error);
+ this.options.onDisconnected?.(`ElevenLabs send failed: ${String(error)}`);
}
}
@@ -150,14 +146,19 @@ export class ElevenLabsSttClient {
this.options.onTranscript({ text: this.latestText, isFinal: false });
return;
case "committed_transcript":
- case "committed_transcript_with_timestamps":
this.latestText = String(message.text ?? this.latestText);
- this.options.onTranscript({ text: this.latestText, isFinal: true });
+ this.options.onTranscript({ text: this.latestText, isFinal: true, paragraphBreakAfter: this.commits.shift() ?? false });
+ this.latestText = "";
+ return;
+ case "committed_transcript_with_timestamps":
+ // The timestamp event follows the plain commit; do not append twice.
+ return;
+ case "rate_limited":
+ this.options.onDisconnected?.("ElevenLabs rate limited.");
return;
case "error":
case "auth_error":
case "quota_exceeded":
- case "rate_limited":
case "input_error":
this.options.onError(`ElevenLabs: ${String(message.error ?? message.message_type)}`);
return;
diff --git a/app/native/faceclaw-communicator.ts b/app/native/faceclaw-communicator.ts
index acca49ac..02773853 100644
--- a/app/native/faceclaw-communicator.ts
+++ b/app/native/faceclaw-communicator.ts
@@ -22,6 +22,8 @@ export type CommunicatorState = {
export type HeadsetBatteryState = {
battery: number;
chargingStatus: number;
+ ringBattery?: number;
+ ringChargingStatus?: number;
};
export type FrameMetrics = {
@@ -120,6 +122,11 @@ function nonNegativeNumber(value: number): number {
return Number.isFinite(numeric) ? Math.max(0, numeric) : 0;
}
+/** A 0..1 brightness factor as the compositor's 0..256 fixed-point form. */
+export function dimFactor256(factor: number): number {
+ return Math.round(Math.max(0, Math.min(1, factor)) * 256);
+}
+
export class FaceclawCommunicatorBridge {
private readonly communicator: any;
private readonly listenerProxy: any;
@@ -184,10 +191,12 @@ export class FaceclawCommunicatorBridge {
frameTimings.logFrame(event.frameId, "input event received on JS side");
this.emitAsync(this.ringListeners, event);
},
- onBatteryState: (headsetBattery: number, headsetCharging: number) => {
+ onBatteryState: (headsetBattery: number, headsetCharging: number, ringBattery: number, ringCharging: number) => {
const state = {
battery: Number(headsetBattery),
chargingStatus: Number(headsetCharging),
+ ringBattery: Number(ringBattery),
+ ringChargingStatus: Number(ringCharging),
};
this.emitAsync(this.batteryListeners, state);
},
@@ -524,6 +533,18 @@ export class FaceclawCommunicatorBridge {
});
}
+ /**
+ * Dim every compositor surface whose zOrder is below `belowZOrder` to
+ * `factor` (0..1; 1 = no dimming) of its brightness; takes effect at the
+ * next composite. How a shell overlay's Layer.dimUnderneath reaches the
+ * window surfaces beneath the shell surface.
+ */
+ async setUnderlayDim(belowZOrder: number, factor: number): Promise {
+ await this.enqueueJavaCall(() => {
+ this.communicator.setUnderlayDim(Math.round(belowZOrder), dimFactor256(factor));
+ });
+ }
+
/** Show or hide a compositor surface; takes effect at the next composite. */
async setSurfaceVisible(id: string, visible: boolean): Promise {
await this.enqueueJavaCall(() => {
diff --git a/app/native/flash-prompt-communicator.ts b/app/native/flash-prompt-communicator.ts
index a31cb420..547cd4c5 100644
--- a/app/native/flash-prompt-communicator.ts
+++ b/app/native/flash-prompt-communicator.ts
@@ -6,20 +6,32 @@ export type FlashPromptState =
| "connecting"
| "connected"
| "prompting"
+ | "battery"
| "result"
| "cancelled"
| "timeout"
| "disconnected"
| "error";
+/** Per-arm battery percent; null when that arm didn't answer. */
+export type FlashPromptBattery = { right: number | null; left: number | null };
+
+function normalizePercent(value: number): number | null {
+ const n = Number(value);
+ return Number.isFinite(n) && n >= 0 ? n : null;
+}
+
/**
* TS wrapper around the native FaceclawFlashPromptCommunicator — the
* stock-firmware-compatible BLE path that shows the pre-flash confirmation on
* the glasses and reports the user's Yes/No choice. Separate from
* FaceclawCommunicatorBridge on purpose (different, minimal protocol subset).
*
- * Talks to the right arm only: the lenses relay messages between themselves,
- * and acks/events always come from the right arm.
+ * Connects and authenticates both arms (so any OS pairing prompts happen up
+ * front, before flashing), shows the prompt via the right arm (the lenses relay
+ * messages between themselves, and acks/events always come from the right
+ * arm), then reads each arm's battery. With `skipPrompt` the on-glasses
+ * confirmation is omitted and only the battery is read.
*/
export class FlashPromptCommunicator {
private readonly communicator: any;
@@ -27,20 +39,32 @@ export class FlashPromptCommunicator {
private readonly logListeners = new Set<(line: string) => void>();
private readonly stateListeners = new Set<(state: FlashPromptState, detail: string) => void>();
private readonly resultListeners = new Set<(approved: boolean) => void>();
+ private readonly batteryListeners = new Set<(battery: FlashPromptBattery) => void>();
- constructor(rightAddress: string, warningText: string) {
+ constructor(
+ addresses: { right: string; left: string },
+ warningText: string,
+ options?: { skipPrompt?: boolean },
+ ) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.communicator = new com.faceclaw.app.FaceclawFlashPromptCommunicator(
context,
- rightAddress,
+ addresses.right,
+ addresses.left,
warningText,
+ Boolean(options?.skipPrompt),
);
this.listenerProxy = new com.faceclaw.app.FaceclawFlashPromptListener({
onLog: (line: string) => this.emit(this.logListeners, String(line)),
onState: (state: string, detail: string) =>
this.emit(this.stateListeners, String(state) as FlashPromptState, String(detail ?? "")),
+ onBattery: (rightPercent: number, leftPercent: number) =>
+ this.emit(this.batteryListeners, {
+ right: normalizePercent(rightPercent),
+ left: normalizePercent(leftPercent),
+ }),
onResult: (approved: boolean) => this.emit(this.resultListeners, Boolean(approved)),
});
this.communicator.setListener(this.listenerProxy);
@@ -56,6 +80,11 @@ export class FlashPromptCommunicator {
return () => this.stateListeners.delete(listener);
}
+ onBattery(listener: (battery: FlashPromptBattery) => void): () => void {
+ this.batteryListeners.add(listener);
+ return () => this.batteryListeners.delete(listener);
+ }
+
onResult(listener: (approved: boolean) => void): () => void {
this.resultListeners.add(listener);
return () => this.resultListeners.delete(listener);
diff --git a/app/native/g2mirror-client.ts b/app/native/g2mirror-client.ts
index b05112fc..038dfe03 100644
--- a/app/native/g2mirror-client.ts
+++ b/app/native/g2mirror-client.ts
@@ -84,6 +84,7 @@ type TerminalDataKind = "snapshot" | "output";
export class G2MirrorClient {
private ws: any = null;
private listenerProxy: any = null;
+ private connectionGeneration = 0;
private phase: G2MirrorPhase = "idle";
private status = "Not connected.";
private sessions: G2MirrorSession[] = [];
@@ -168,14 +169,21 @@ export class G2MirrorClient {
return () => this.titleListeners.delete(listener);
}
+ /** Grid dimensions for the next connection's handshake. */
+ setViewport(cols: number, rows: number): void {
+ this.options.cols = cols;
+ this.options.rows = rows;
+ }
+
start(): void {
if (this.ws) return;
this.stopped = false;
+ const generation = ++this.connectionGeneration;
const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`;
this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`);
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
onOpen: () => {
- if (this.stopped) return;
+ if (this.stopped || generation !== this.connectionGeneration) return;
this.setState("connecting", "Authenticating...");
this.send({
type: "init",
@@ -187,15 +195,15 @@ export class G2MirrorClient {
});
},
onTextMessage: (message: string) => {
- if (this.stopped) return;
+ if (this.stopped || generation !== this.connectionGeneration) return;
this.handleMessage(String(message));
},
onClosed: (code: number, reason: string) => {
- if (this.stopped) return;
+ if (this.stopped || generation !== this.connectionGeneration) return;
this.handleConnectionLost(`Connection closed (${Number(code)}${reason ? `: ${String(reason)}` : ""}).`);
},
onFailure: (message: string) => {
- if (this.stopped) return;
+ if (this.stopped || generation !== this.connectionGeneration) return;
this.handleConnectionLost(`Connection failed: ${shortenError(String(message))}`);
},
});
@@ -209,6 +217,7 @@ export class G2MirrorClient {
stop(): void {
this.stopped = true;
+ ++this.connectionGeneration;
this.rejectAllPendingLaunches("client stopped");
this.clearListRefreshTimer();
if (this.ws) {
diff --git a/app/native/geomagnetic.ts b/app/native/geomagnetic.ts
new file mode 100644
index 00000000..10e663dc
--- /dev/null
+++ b/app/native/geomagnetic.ts
@@ -0,0 +1,27 @@
+/**
+ * Magnetic declination from Android's built-in World Magnetic Model. Declination
+ * is the angle from magnetic north to true north (east positive), so
+ * `true = magnetic + declination`. No network access is involved; the model is
+ * baked into the platform and is accurate to well under a degree, which is far
+ * inside the magnetometer's own noise.
+ */
+declare const android: any;
+declare const global: any;
+
+/** Declination in degrees at a place and time, or null off-Android. */
+export function magneticDeclinationDegrees(
+ latitude: number,
+ longitude: number,
+ timestampMs: number = Date.now(),
+ altitudeMeters = 0,
+): number | null {
+ if (!global.isAndroid) return null;
+ try {
+ const field = new android.hardware.GeomagneticField(latitude, longitude, altitudeMeters, timestampMs);
+ const declination = Number(field.getDeclination());
+ return Number.isFinite(declination) ? declination : null;
+ } catch (error) {
+ console.warn(`GeomagneticField failed: ${error}`);
+ return null;
+ }
+}
diff --git a/app/native/image-files.ts b/app/native/image-files.ts
index 78a335e7..932861a8 100644
--- a/app/native/image-files.ts
+++ b/app/native/image-files.ts
@@ -15,6 +15,39 @@ export function isDecodableImageFile(name: string): boolean {
return DECODABLE_IMAGE.test(name);
}
+/**
+ * How source gray maps onto the display's 16 levels when converting to a
+ * GrayImage. The default (gamma 1, no dither) is a flat conversion with
+ * per-pixel rounding, right for UI raster such as icons and map tiles.
+ */
+export type GrayImageTone = {
+ /**
+ * Tone curve out = in^gamma (in 0..1). gamma > 1 darkens midtones: source
+ * pixels are sRGB-encoded but the G2 drives its levels roughly linearly,
+ * so untouched photos read washed out.
+ */
+ gamma?: number;
+ /**
+ * Floyd-Steinberg error diffusion onto the 16 display levels instead of
+ * rounding each pixel independently, which bands smooth gradients.
+ */
+ dither?: boolean;
+};
+
+/**
+ * Gamma for continuous-tone images (photos, album art): 2.2 undoes the sRGB
+ * encoding outright. Lower it toward ~1.8 if shadows crush.
+ */
+export const PHOTO_GAMMA = 2.2;
+
+/** Tone preset for continuous-tone images: sRGB gamma plus dithering. */
+export const PHOTO_TONE: Readonly> = { gamma: PHOTO_GAMMA, dither: true };
+
+/** Resolve a tone to the (gamma, dither) pair the Java helpers take. */
+export function resolveGrayImageTone(tone?: GrayImageTone): { gamma: number; dither: boolean } {
+ return { gamma: tone?.gamma ?? 1, dither: tone?.dither ?? false };
+}
+
/**
* Decode a gray packet ([widthLo, widthHi, heightLo, heightHi, pixels...],
* the format the Java helpers return) into a GrayImage; null when empty or
@@ -34,12 +67,20 @@ export function grayImageFromPacket(raw: ArrayLike | null | undefined):
/**
* Load an image file as grayscale, downscaled to fit maxWidth x maxHeight
* (aspect preserved, never upscaled); null when unreadable or undecodable.
+ * Pass PHOTO_TONE for continuous-tone images; the default is a flat
+ * conversion for UI raster.
*/
-export function loadImageFileAsGray(path: string, maxWidth: number, maxHeight: number): GrayImage | null {
+export function loadImageFileAsGray(
+ path: string,
+ maxWidth: number,
+ maxHeight: number,
+ tone?: GrayImageTone,
+): GrayImage | null {
if (!global.isAndroid) return null;
try {
+ const { gamma, dither } = resolveGrayImageTone(tone);
return grayImageFromPacket(
- com.faceclaw.app.ImageFileLoader.loadGray(path, Math.round(maxWidth), Math.round(maxHeight)),
+ com.faceclaw.app.ImageFileLoader.loadGray(path, Math.round(maxWidth), Math.round(maxHeight), gamma, dither),
);
} catch (error) {
console.warn(`loadImageFileAsGray failed for ${path}: ${error}`);
diff --git a/app/native/mapbox.ts b/app/native/mapbox.ts
index a8336f31..364d9252 100644
--- a/app/native/mapbox.ts
+++ b/app/native/mapbox.ts
@@ -18,6 +18,23 @@ 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";
+/**
+ * Render-time style override: a black background inserted beneath the road
+ * stack so land, landuse, water, and building fills all come out black on the
+ * lens (dark-v11's own fills are dark gray, which the lens shows as a lit
+ * haze). Static Images allows one added layer per request; `before_layer`
+ * must name a layer in the style, so candidates are tried in order and a
+ * rejected one is skipped for the rest of the session, ending with the plain
+ * style (the worker's levelling pass then does what it can client-side).
+ */
+const STYLE_OVERRIDE_LAYER = JSON.stringify({
+ id: "faceclaw-blackout",
+ type: "background",
+ paint: { "background-color": "#000000" },
+});
+/** First road layer of dark-v11, then a layer common to every Streets-based style. */
+const STYLE_OVERRIDE_BEFORE_LAYERS = ["tunnel-path-trail", "building"];
+let styleOverrideIndex = 0;
const FETCH_TIMEOUT_MS = 15_000;
export type RouteProfile = "driving" | "walking" | "cycling";
@@ -188,18 +205,32 @@ export async function fetchStaticMapGray(options: {
: `${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}`;
+ let bytes: ArrayBuffer;
+ for (;;) {
+ const beforeLayer = STYLE_OVERRIDE_BEFORE_LAYERS[styleOverrideIndex];
+ const params: Record = {
+ access_token: requireToken(),
+ logo: "false",
+ attribution: "false",
+ };
+ if (beforeLayer !== undefined) {
+ params.addlayer = STYLE_OVERRIDE_LAYER;
+ params.before_layer = beforeLayer;
+ }
+ const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${queryString(params)}`;
- const response = await fetchWithTimeout(url, "Mapbox static map");
- if (!response.ok) {
+ const response = await fetchWithTimeout(url, "Mapbox static map");
+ if (response.ok) {
+ bytes = await response.arrayBuffer();
+ break;
+ }
+ if (beforeLayer !== undefined && isStyleOverrideRejection(response.status)) {
+ console.warn(`Mapbox rejected the map style override (before_layer=${beforeLayer}, HTTP ${response.status}); falling back`);
+ styleOverrideIndex++;
+ continue;
+ }
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)),
@@ -281,6 +312,15 @@ async function fetchWithTimeout(url: string, label: string): Promise {
}
}
+/**
+ * A client error that plausibly blames the added layer (an unknown
+ * before_layer, or a style without it), as opposed to token or quota trouble
+ * that the plain request would hit just the same.
+ */
+function isStyleOverrideRejection(status: number): boolean {
+ return status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 429;
+}
+
function normalizeBearing(bearingDeg: number): number {
return ((bearingDeg % 360) + 360) % 360;
}
diff --git a/app/native/media-apps.ts b/app/native/media-apps.ts
new file mode 100644
index 00000000..20e1ec30
--- /dev/null
+++ b/app/native/media-apps.ts
@@ -0,0 +1,83 @@
+import { getStringSetting, setStringSetting } from "./settings-store";
+
+export const MEDIA_APPS_KEY = "music.apps";
+
+// Exact package IDs only: browsers, social feeds and messaging apps commonly
+// publish sessions for embedded clips. Users can explicitly enable any of them.
+export const DEFAULT_IGNORED_MEDIA_APPS: readonly string[] = [
+ "com.android.chrome",
+ "org.mozilla.firefox",
+ "com.microsoft.emmx",
+ "com.sec.android.app.sbrowser",
+ "com.facebook.katana",
+ "com.facebook.orca",
+ "com.instagram.android",
+ "com.whatsapp",
+ "org.telegram.messenger",
+ "com.snapchat.android",
+ "com.reddit.frontpage",
+ "com.twitter.android",
+ "com.discord",
+];
+
+export type MediaApp = {
+ packageName: string;
+ appName: string;
+ /** Absent until the user chooses; built-in defaults can evolve independently. */
+ enabled?: boolean;
+};
+
+/** Keep discovered apps after their sessions end, including ignored apps. */
+export function readMediaApps(): MediaApp[] {
+ try {
+ const parsed = JSON.parse(getStringSetting(MEDIA_APPS_KEY, "[]"));
+ if (!Array.isArray(parsed)) return [];
+ const apps = new Map();
+ for (const app of parsed) {
+ if (!app || typeof app.packageName !== "string" || !app.packageName) continue;
+ apps.set(app.packageName, {
+ packageName: app.packageName,
+ appName: typeof app.appName === "string" && app.appName ? app.appName : app.packageName,
+ ...(typeof app.enabled === "boolean" ? { enabled: app.enabled } : {}),
+ });
+ }
+ return Array.from(apps.values());
+ } catch {
+ return [];
+ }
+}
+
+export function rememberMediaApps(discovered: { packageName: string; appName: string }[]): void {
+ const apps = new Map(readMediaApps().map((app) => [app.packageName, app]));
+ let changed = false;
+ for (const app of discovered) {
+ if (!app.packageName) continue;
+ const previous = apps.get(app.packageName);
+ const appName = app.appName || previous?.appName || app.packageName;
+ if (!previous || previous.appName !== appName) {
+ apps.set(app.packageName, { ...previous, packageName: app.packageName, appName });
+ changed = true;
+ }
+ }
+ if (changed) setStringSetting(MEDIA_APPS_KEY, JSON.stringify(Array.from(apps.values())));
+}
+
+export function ignoredMediaPackages(): string[] {
+ const ignored = new Set(DEFAULT_IGNORED_MEDIA_APPS);
+ for (const app of readMediaApps()) {
+ if (app.enabled === true) ignored.delete(app.packageName);
+ else if (app.enabled === false) ignored.add(app.packageName);
+ }
+ return Array.from(ignored).sort();
+}
+
+export function isMediaAppEnabled(packageName: string): boolean {
+ return !ignoredMediaPackages().includes(packageName);
+}
+
+export function setMediaAppEnabled(app: MediaApp, enabled: boolean): void {
+ if (!app.packageName) return;
+ const apps = new Map(readMediaApps().map((item) => [item.packageName, item]));
+ apps.set(app.packageName, { packageName: app.packageName, appName: app.appName || app.packageName, enabled });
+ setStringSetting(MEDIA_APPS_KEY, JSON.stringify(Array.from(apps.values())));
+}
diff --git a/app/native/media-browser.ts b/app/native/media-browser.ts
index cfb05f4b..80bd73b4 100644
--- a/app/native/media-browser.ts
+++ b/app/native/media-browser.ts
@@ -1,4 +1,6 @@
import { Utils } from "@nativescript/core";
+import { ignoredMediaPackages, isMediaAppEnabled, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
+import { onSettingsStoreChanged } from "./settings-store";
declare const com: any;
@@ -34,11 +36,12 @@ export class FaceclawMediaBrowserBridge {
private readonly pendingConnects = new Map>();
private readonly pendingBrowses = new Map>();
private appsCache: MediaBrowserApp[] | null = null;
+ private connectedPackage = "";
/** Installed apps exposing a media browser service; cached after the first call. */
listBrowsableApps(refresh = false): MediaBrowserApp[] {
if (!global.isAndroid) return [];
- if (this.appsCache && !refresh) return this.appsCache;
+ if (this.appsCache && !refresh) return this.enabledApps();
this.ensureBrowser();
if (!this.browser) return [];
try {
@@ -52,11 +55,17 @@ export class FaceclawMediaBrowserBridge {
serviceClass: String(app.serviceClass ?? ""),
appName: String(app.appName ?? ""),
}));
+ rememberMediaApps(this.appsCache);
} catch (error) {
console.warn(`media browser app list parse failed: ${error}`);
this.appsCache = [];
}
- return this.appsCache;
+ return this.enabledApps();
+ }
+
+ private enabledApps(): MediaBrowserApp[] {
+ const ignored = new Set(ignoredMediaPackages());
+ return (this.appsCache ?? []).filter((app) => !ignored.has(app.packageName));
}
/**
@@ -65,9 +74,11 @@ export class FaceclawMediaBrowserBridge {
*/
connect(app: MediaBrowserApp): Promise {
if (!global.isAndroid) return Promise.reject(new Error("Android only"));
+ if (!isMediaAppEnabled(app.packageName)) return Promise.reject(new Error("App is ignored in Music settings"));
this.ensureBrowser();
if (!this.browser) return Promise.reject(new Error("Media browser unavailable"));
const requestId = this.nextRequestId++;
+ this.connectedPackage = app.packageName;
return new Promise((resolve, reject) => {
this.pendingConnects.set(requestId, { resolve, reject });
this.browser.connect(requestId, app.packageName, app.serviceClass);
@@ -77,6 +88,10 @@ export class FaceclawMediaBrowserBridge {
/** Fetch one level of the connected service's content tree. */
browse(parentId: string): Promise {
if (!global.isAndroid) return Promise.reject(new Error("Android only"));
+ if (this.connectedPackage && !isMediaAppEnabled(this.connectedPackage)) {
+ this.disconnect();
+ return Promise.reject(new Error("App is ignored in Music settings"));
+ }
this.ensureBrowser();
if (!this.browser) return Promise.reject(new Error("Media browser unavailable"));
const requestId = this.nextRequestId++;
@@ -89,6 +104,7 @@ export class FaceclawMediaBrowserBridge {
/** Start playback of a browsed item through the connected player's session. */
playFromMediaId(mediaId: string): void {
if (!global.isAndroid) return;
+ if (!this.connectedPackage || !isMediaAppEnabled(this.connectedPackage)) return;
this.browser?.playFromMediaId(mediaId);
}
@@ -96,6 +112,7 @@ export class FaceclawMediaBrowserBridge {
disconnect(): void {
if (!global.isAndroid) return;
this.rejectAllPending("Disconnected");
+ this.connectedPackage = "";
this.browser?.disconnect();
}
@@ -115,6 +132,11 @@ export class FaceclawMediaBrowserBridge {
throw new Error("Android application context unavailable");
}
this.browser = new com.faceclaw.app.FaceclawMediaBrowser(context);
+ onSettingsStoreChanged((key) => {
+ if (key === MEDIA_APPS_KEY && this.connectedPackage && !isMediaAppEnabled(this.connectedPackage)) {
+ this.disconnect();
+ }
+ });
this.listenerProxy = new com.faceclaw.app.FaceclawMediaBrowserListener({
onConnectResult: (requestId: number, connected: boolean, rootId: string, error: string) => {
const pending = this.pendingConnects.get(Number(requestId));
diff --git a/app/native/media-controller.ts b/app/native/media-controller.ts
index 0f629651..e685a123 100644
--- a/app/native/media-controller.ts
+++ b/app/native/media-controller.ts
@@ -1,17 +1,11 @@
import { Utils } from "@nativescript/core";
import { GrayImage } from "../graphics/image";
-import { grayImageFromPacket } from "./image-files";
+import { grayImageFromPacket, PHOTO_TONE } from "./image-files";
+import { ignoredMediaPackages, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
+import { onSettingsStoreChanged } from "./settings-store";
declare const com: any;
-/**
- * Tone curve applied to album art before it is dithered down to the display's
- * 16 gray levels (out = in^gamma, in 0..1). Cover art is sRGB-encoded but the
- * G2 drives its levels roughly linearly, so untouched art reads washed out;
- * 2.2 undoes the sRGB encoding. Lower it toward ~1.8 if shadows crush.
- */
-const ALBUM_ART_GAMMA = 2.2;
-
export type MediaQueueItem = {
id: number;
title: string;
@@ -141,16 +135,16 @@ export class FaceclawMediaControllerBridge {
}
/**
- * Album art for the current item, grayscale (gamma-corrected and dithered
- * onto the display's 16 levels), scaled to fit maxSize; null when the
- * player provides none.
+ * Album art for the current item, grayscale with the shared photo tone
+ * (gamma-corrected and dithered onto the display's 16 levels), scaled to
+ * fit maxSize; null when the player provides none.
*/
getAlbumArt(maxSize: number): GrayImage | null {
if (!global.isAndroid) return null;
this.ensureController();
if (!this.controller) return null;
return grayImageFromPacket(
- this.controller.getAlbumArtGray(Math.round(maxSize), ALBUM_ART_GAMMA),
+ this.controller.getAlbumArtGray(Math.round(maxSize), PHOTO_TONE.gamma, PHOTO_TONE.dither),
);
}
@@ -181,7 +175,22 @@ export class FaceclawMediaControllerBridge {
throw new Error("Android application context unavailable");
}
this.controller = new com.faceclaw.app.FaceclawMediaController(context);
+ // Install defaults and saved overrides before starting session discovery.
+ this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
+ onSettingsStoreChanged((key) => {
+ if (key === MEDIA_APPS_KEY) {
+ this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
+ }
+ });
this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({
+ onSessionAppsChanged: (appsJson: string) => {
+ try {
+ const apps = JSON.parse(String(appsJson));
+ rememberMediaApps(apps);
+ } catch (error) {
+ console.warn(`media session apps parse failed: ${error}`);
+ }
+ },
onStateChange: (
playbackState: string,
packageName: string,
diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts
index 8ce2a38e..5da6237d 100644
--- a/app/native/nightscout-bridge.ts
+++ b/app/native/nightscout-bridge.ts
@@ -1,4 +1,4 @@
-import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
+import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
import { fetchWithUserAgent } from "../util/http";
export type NightscoutPoint = {
@@ -33,6 +33,10 @@ export type NightscoutState = {
iob: number | null;
cob: number | null;
cageTimestampMs: number | null;
+ reservoirUnits: number | null;
+ batteryVoltage: number | null;
+ loopTimestampMs: number | null;
+ /** Pump communication age and operating state; measurements are separate. */
pumpStatus: string;
openapsStatusShort: string;
carbs: NightscoutCarbEvent[];
@@ -121,6 +125,9 @@ const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = {
iob: null,
cob: null,
cageTimestampMs: null,
+ reservoirUnits: null,
+ batteryVoltage: null,
+ loopTimestampMs: null,
pumpStatus: "",
openapsStatusShort: "--",
carbs: [],
@@ -259,6 +266,9 @@ export class NightscoutBridge {
iob: Number.isFinite(iob) ? iob : null,
cob,
cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null,
+ reservoirUnits: firstFiniteNumber(latestDeviceStatus?.pump?.reservoir),
+ batteryVoltage: firstFiniteNumber(latestDeviceStatus?.pump?.battery?.voltage),
+ loopTimestampMs: loopTimestampMs > 0 ? loopTimestampMs : null,
pumpStatus,
openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--",
carbs: parsedTreatments.carbs,
@@ -359,6 +369,8 @@ function parseTimestampMs(value: unknown): number {
function firstFiniteNumber(...values: unknown[]): number | null {
for (const value of values) {
+ if (typeof value !== "number" && typeof value !== "string") continue;
+ if (typeof value === "string" && !value.trim()) continue;
const numeric = Number(value);
if (Number.isFinite(numeric)) {
return numeric;
@@ -371,8 +383,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
if (!status?.pump) {
return "--";
}
- const reservoir = firstFiniteNumber(status.pump.reservoir);
- const voltage = firstFiniteNumber(status.pump.battery?.voltage);
const commTimestampMs = Math.max(
parseTimestampMs(status.pump.status?.timestamp),
parseTimestampMs(status.pump.clock),
@@ -380,12 +390,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
);
const stateLabel = summarizePumpState(status);
const parts: string[] = [];
- if (reservoir !== null) {
- parts.push(`${Math.round(reservoir)}U`);
- }
- if (voltage !== null) {
- parts.push(`${voltage.toFixed(2)}v`);
- }
if (commTimestampMs > 0) {
parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`);
}
diff --git a/app/native/notification-icons.ts b/app/native/notification-icons.ts
index aa06623a..d3f58d22 100644
--- a/app/native/notification-icons.ts
+++ b/app/native/notification-icons.ts
@@ -1,10 +1,13 @@
import { GrayImage } from "../graphics/image";
import { logCurrent, spanCurrent } from "./frame-timings";
import { toUint8Array } from "../util/array-util";
+import { rememberNotificationSources } from "./notification-sources";
declare const com: any;
const ICON_SIZE = 24;
+/** Ask the native listener for every active source, including those below the list's display limit. */
+export const ALL_NOTIFICATIONS = 0x7fffffff;
// Backstop TTL only: the icon caches are invalidated eagerly whenever a
// notification is posted or dismissed (see invalidateIconCaches callers), so
// the tray is kept fresh by invalidation, not by expiry. A short TTL just
@@ -158,7 +161,9 @@ export function readActiveNotifications(maxNotifications = 50): AndroidNotificat
);
const parsed = JSON.parse(json);
if (!Array.isArray(parsed)) return [];
- return parsed.map(normalizeNotification).filter((item): item is AndroidNotification => Boolean(item));
+ const notifications = parsed.map(normalizeNotification).filter((item): item is AndroidNotification => Boolean(item));
+ rememberNotificationSources(notifications);
+ return notifications;
} catch {
return [];
}
diff --git a/app/native/notification-sources.ts b/app/native/notification-sources.ts
new file mode 100644
index 00000000..cd00a5bb
--- /dev/null
+++ b/app/native/notification-sources.ts
@@ -0,0 +1,59 @@
+import { getStringSetting, setStringSetting } from "./settings-store";
+
+const SOURCES_KEY = "notifications.sources";
+
+export type NotificationSource = {
+ packageName: string;
+ appName: string;
+ showOnGlasses: boolean;
+};
+
+/** Sources outlive their active notifications so a muted app can always be re-enabled. */
+export function readNotificationSources(): NotificationSource[] {
+ try {
+ const parsed = JSON.parse(getStringSetting(SOURCES_KEY, "[]"));
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((source) => source && typeof source.packageName === "string" && source.packageName)
+ .map((source) => ({
+ packageName: source.packageName,
+ appName: typeof source.appName === "string" && source.appName ? source.appName : source.packageName,
+ showOnGlasses: source.showOnGlasses !== false,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+export function rememberNotificationSources(notifications: { packageName: string; appName: string }[]): void {
+ const sources = new Map(readNotificationSources().map((source) => [source.packageName, source]));
+ let changed = false;
+ for (const notification of notifications) {
+ if (!notification.packageName) continue;
+ const previous = sources.get(notification.packageName);
+ const appName = notification.appName || previous?.appName || notification.packageName;
+ if (!previous || previous.appName !== appName) {
+ sources.set(notification.packageName, {
+ packageName: notification.packageName,
+ appName,
+ showOnGlasses: previous?.showOnGlasses ?? true,
+ });
+ changed = true;
+ }
+ }
+ if (changed) setStringSetting(SOURCES_KEY, JSON.stringify(Array.from(sources.values())));
+}
+
+export function shouldShowNotificationOnGlasses(packageName: string): boolean {
+ return readNotificationSources().find((source) => source.packageName === packageName)?.showOnGlasses ?? true;
+}
+
+export function setNotificationSourceEnabled(source: { packageName: string; appName: string }, enabled: boolean): void {
+ if (!source.packageName) return;
+ const sources = new Map(readNotificationSources().map((item) => [item.packageName, item]));
+ sources.set(source.packageName, {
+ packageName: source.packageName,
+ appName: source.appName || source.packageName,
+ showOnGlasses: enabled,
+ });
+ setStringSetting(SOURCES_KEY, JSON.stringify(Array.from(sources.values())));
+}
diff --git a/app/native/openai-stt.ts b/app/native/openai-stt.ts
index e634f3cf..2949be00 100644
--- a/app/native/openai-stt.ts
+++ b/app/native/openai-stt.ts
@@ -30,28 +30,34 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
// Base64 audio (or the commit sentinel) queued until the socket opens.
private readonly pendingChunks: string[] = [];
private readonly upsampler = new PcmUpsampler();
- private latestText = "";
+ private readonly items = new Map();
+ private readonly commits: boolean[] = [];
private committed = false;
constructor(private readonly options: OpenAiSttOptions) {}
start(): void {
- if (this.ws) return;
+ if (this.closed || this.ws) return;
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
onOpen: () => {
+ if (this.closed) return;
this.open = true;
this.trySend(JSON.stringify(sessionConfig()));
for (const chunk of this.pendingChunks.splice(0)) {
this.sendChunk(chunk);
}
+ if (!this.closed) this.options.onReady?.();
+ },
+ onTextMessage: (message: string) => {
+ if (!this.closed) this.handleMessage(String(message));
},
- onTextMessage: (message: string) => this.handleMessage(String(message)),
onClosed: () => {
this.open = false;
+ if (!this.closed) this.options.onDisconnected?.("OpenAI connection closed.");
},
onFailure: (message: string) => {
if (this.closed) return;
- this.options.onError(`OpenAI connection failed: ${String(message)}`);
+ this.options.onDisconnected?.(`OpenAI connection failed: ${String(message)}`);
},
});
try {
@@ -63,7 +69,7 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
);
this.options.onStatus("Connecting to OpenAI...");
} catch (error) {
- this.options.onError(`OpenAI connection failed: ${String((error as Error)?.message ?? error)}`);
+ this.options.onDisconnected?.(`OpenAI connection failed: ${String((error as Error)?.message ?? error)}`);
}
}
@@ -80,9 +86,19 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
}
}
+ commitSegment(): void {
+ this.commit(true);
+ }
+
/** End of utterance: commit the buffer for a final transcript. */
finish(): void {
+ this.committed = true;
+ this.commit(false);
+ }
+
+ private commit(paragraphBreakAfter: boolean): void {
if (this.closed) return;
+ this.commits.push(paragraphBreakAfter);
if (this.open) {
this.sendChunk("__commit__");
} else {
@@ -92,6 +108,7 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
stop(): void {
this.closed = true;
+ this.open = false;
if (this.ws) {
try {
this.ws.close(1000, "bye");
@@ -101,11 +118,11 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
this.ws = null;
}
this.listenerProxy = null;
+ this.pendingChunks.length = 0;
}
private sendChunk(base64OrCommit: string): void {
if (base64OrCommit === "__commit__") {
- this.committed = true;
this.trySend(JSON.stringify({ type: "input_audio_buffer.commit" }));
return;
}
@@ -114,9 +131,11 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
private trySend(message: string): void {
try {
- this.ws?.sendText(message);
+ if (this.ws?.sendText(message) === false) {
+ this.options.onDisconnected?.("OpenAI send failed.");
+ }
} catch (error) {
- console.warn("openai send failed", error);
+ this.options.onDisconnected?.(`OpenAI send failed: ${String(error)}`);
}
}
@@ -132,23 +151,62 @@ export class OpenAiRealtimeSttClient implements CloudSttClient {
case "session.updated":
this.options.onStatus("Listening (OpenAI)...");
return;
- case "conversation.item.input_audio_transcription.delta":
- this.latestText += String(message.delta ?? "");
- this.options.onTranscript({ text: this.latestText, isFinal: false });
+ case "input_audio_buffer.committed": {
+ this.item(String(message.item_id)).paragraphBreakAfter = this.commits.shift() ?? false;
return;
- case "conversation.item.input_audio_transcription.completed":
- this.latestText = String(message.transcript ?? this.latestText);
- this.options.onTranscript({ text: this.latestText, isFinal: true });
- // The utterance is done; nothing further is coming after the commit.
- if (this.committed) this.stop();
+ }
+ case "conversation.item.input_audio_transcription.delta": {
+ this.item(String(message.item_id)).text += String(message.delta ?? "");
+ this.emitItems();
return;
+ }
+ case "conversation.item.input_audio_transcription.completed": {
+ const item = this.item(String(message.item_id));
+ item.text = String(message.transcript ?? item.text);
+ item.final = true;
+ this.emitItems();
+ if (this.committed && !this.items.size && !this.commits.length) this.stop();
+ return;
+ }
case "error":
+ if (message.error?.code === "rate_limit_exceeded" || message.error?.type === "server_error") {
+ this.options.onDisconnected?.(`OpenAI: ${String(message.error?.message)}`);
+ return;
+ }
this.options.onError(`OpenAI: ${String(message.error?.message ?? "unknown error")}`);
return;
default:
return;
}
}
+
+ private item(id: string): { text: string; final: boolean; paragraphBreakAfter: boolean } {
+ let item = this.items.get(id);
+ if (!item) {
+ item = { text: "", final: false, paragraphBreakAfter: false };
+ this.items.set(id, item);
+ }
+ return item;
+ }
+
+ private emitItems(): void {
+ // Committed notifications precede transcription events, so Map insertion
+ // order is audio order even when completion events arrive out of order.
+ for (const [id, item] of this.items) {
+ if (!item.final) break;
+ this.items.delete(id);
+ this.options.onTranscript({ text: item.text, isFinal: true, paragraphBreakAfter: item.paragraphBreakAfter });
+ }
+ if (this.items.size) {
+ const items = [...this.items.values()];
+ const text = items.map((item) => item.text.trim()).filter(Boolean).join(" ");
+ const transcribeText = items.map((item, index) =>
+ (index && items[index - 1]!.paragraphBreakAfter ? "\n" : index ? " " : "") + item.text.trim(),
+ ).join("");
+ this.options.onTranscript({ text, transcribeText, isFinal: false });
+ }
+ }
+
}
function sessionConfig(): object {
diff --git a/app/native/phone-rotation.ts b/app/native/phone-rotation.ts
new file mode 100644
index 00000000..652a1fd2
--- /dev/null
+++ b/app/native/phone-rotation.ts
@@ -0,0 +1,30 @@
+import { Application, isAndroid } from "@nativescript/core";
+import { getStringSetting, onSettingsStoreChanged } from "./settings-store";
+
+// Shared with phoneRotationSetting; keep startup independent of the glasses UI.
+const ROTATION_KEY = "phone.rotation";
+
+/** Installed once on the UI thread; also covers navigation and activity recreation. */
+export function registerPhoneRotation(): void {
+ if (!isAndroid) return;
+
+ const apply = (activity = Application.android.foregroundActivity ?? Application.android.startActivity): void => {
+ if (!activity) return;
+ const orientations = android.content.pm.ActivityInfo;
+ const requested = {
+ auto: orientations.SCREEN_ORIENTATION_UNSPECIFIED,
+ portrait: orientations.SCREEN_ORIENTATION_PORTRAIT,
+ landscape: orientations.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
+ }[getStringSetting(ROTATION_KEY, "auto")] ?? orientations.SCREEN_ORIENTATION_UNSPECIFIED;
+ if (activity.getRequestedOrientation() !== requested) {
+ activity.setRequestedOrientation(requested);
+ }
+ };
+
+ Application.android.on(Application.android.activityCreatedEvent, (args) => apply(args.activity));
+ Application.android.on(Application.android.activityResumedEvent, (args) => apply(args.activity));
+ onSettingsStoreChanged((key) => {
+ if (key === ROTATION_KEY) apply();
+ });
+ apply();
+}
diff --git a/app/native/preview-display.ts b/app/native/preview-display.ts
index c0fa7f4e..baad5305 100644
--- a/app/native/preview-display.ts
+++ b/app/native/preview-display.ts
@@ -1,5 +1,5 @@
import { ImageSource, Utils } from "@nativescript/core";
-import type { FaceclawCommunicatorBridge, SurfaceOptions } from "./faceclaw-communicator";
+import { dimFactor256, type FaceclawCommunicatorBridge, type SurfaceOptions } from "./faceclaw-communicator";
declare const com: any;
declare const java: any;
@@ -19,6 +19,7 @@ export type DisplayTarget = Pick<
| "configureSurface"
| "removeSurface"
| "setSurfaceVisible"
+ | "setUnderlayDim"
| "setScreenBlanked"
| "submitSurfaceFrame"
| "waitForFrameFinished"
@@ -96,6 +97,10 @@ export class PreviewDisplayTarget implements DisplayTarget {
this.compositor.setSurfaceVisible(id, Boolean(visible));
}
+ async setUnderlayDim(belowZOrder: number, factor: number): Promise {
+ this.compositor.setUnderlayDim(Math.round(belowZOrder), dimFactor256(factor));
+ }
+
async setScreenBlanked(blanked: boolean): Promise {
this.compositor.setScreenBlanked(Boolean(blanked));
}
diff --git a/app/native/reconnecting-stt.ts b/app/native/reconnecting-stt.ts
new file mode 100644
index 00000000..1221bb8d
--- /dev/null
+++ b/app/native/reconnecting-stt.ts
@@ -0,0 +1,141 @@
+import type { CloudSttClient, CloudSttOptions, CloudSttTranscriptEvent } from "./cloud-stt";
+import { SpeechPauseDetector } from "./speech-pause";
+
+// Ten seconds of unsent PCM. Never replay audio already sent: that would
+// duplicate words already shown. An extended outage drops the oldest audio.
+const MAX_PENDING_BYTES = 16000 * 2 * 10;
+
+/** Owns retries and audio buffering independently of the provider protocol. */
+export class ReconnectingSttClient implements CloudSttClient {
+ private client: CloudSttClient | null = null;
+ private generation = 0;
+ private stopped = false;
+ private finishing = false;
+ private ready = false;
+ private retry: ReturnType | null = null;
+ private finishTimeout: ReturnType | null = null;
+ private attempt = 0;
+ private pending: Uint8Array[] = [];
+ private pendingBytes = 0;
+ private latest: CloudSttTranscriptEvent | null = null;
+ private readonly pause = new SpeechPauseDetector();
+
+ constructor(
+ private readonly create: (options: CloudSttOptions) => CloudSttClient,
+ private readonly options: CloudSttOptions,
+ private readonly continuous: () => boolean,
+ ) {}
+
+ start(): void {
+ if (this.stopped || this.client || this.retry !== null) return;
+ const generation = ++this.generation;
+ const current = () => !this.stopped && generation === this.generation;
+ this.client = this.create({
+ ...this.options,
+ onReady: () => {
+ if (!current()) return;
+ this.ready = true;
+ const chunks = this.pending;
+ this.pending = [];
+ this.pendingBytes = 0;
+ for (const chunk of chunks) this.acceptPcm(chunk);
+ if (this.finishing) this.client?.finish();
+ },
+ onTranscript: (event) => {
+ if (!current()) return;
+ // A handshake alone can immediately be followed by another failure.
+ this.attempt = 0;
+ this.latest = event.isFinal ? null : event;
+ this.options.onTranscript(event);
+ },
+ onStatus: (status) => { if (current()) this.options.onStatus(status); },
+ onError: (message) => {
+ if (!current()) return;
+ this.stop();
+ this.options.onError(message);
+ },
+ onDisconnected: (message) => {
+ if (current()) this.disconnected(message);
+ },
+ });
+ try {
+ this.client.start();
+ } catch (error) {
+ this.disconnected(`Transcription connection failed: ${String(error)}`);
+ }
+ }
+
+ acceptPcm(pcm: Uint8Array): void {
+ if (this.stopped || !pcm.length) return;
+ if (!this.ready) {
+ const copy = pcm.slice(-MAX_PENDING_BYTES);
+ this.pending.push(copy);
+ this.pendingBytes += copy.length;
+ while (this.pendingBytes > MAX_PENDING_BYTES) this.pendingBytes -= this.pending.shift()!.length;
+ return;
+ }
+ this.client?.acceptPcm(pcm);
+ // A rejected send synchronously reports disconnection. Keep that packet
+ // with the unsent audio instead of losing it at the outage boundary.
+ if (!this.ready && !this.stopped) this.acceptPcm(pcm);
+ if (this.ready && !this.finishing && this.continuous() && this.pause.accept(pcm)) this.client?.commitSegment?.();
+ }
+
+ finish(): void {
+ if (this.stopped || this.finishing) return;
+ this.finishing = true;
+ // Releasing the last mic holder must not leave a reconnect loop alive.
+ if (this.retry !== null) {
+ this.preservePartial();
+ this.stop();
+ return;
+ }
+ this.finishTimeout = setTimeout(() => this.stop(), 5000);
+ if (this.ready) this.client?.finish();
+ }
+
+ stop(): void {
+ this.stopped = true;
+ ++this.generation;
+ if (this.retry !== null) clearTimeout(this.retry);
+ if (this.finishTimeout !== null) clearTimeout(this.finishTimeout);
+ this.retry = this.finishTimeout = null;
+ this.client?.stop();
+ this.client = null;
+ this.ready = false;
+ this.pending = [];
+ this.pendingBytes = 0;
+ this.latest = null;
+ }
+
+ private preservePartial(): void {
+ if (this.latest?.text.trim()) this.options.onTranscript({ ...this.latest, isFinal: true });
+ this.latest = null;
+ }
+
+ private disconnected(message: string): void {
+ if (this.stopped) return;
+ ++this.generation; // Ignore late finals / closes from the abandoned socket.
+ this.ready = false;
+ this.client?.stop();
+ this.client = null;
+ this.pause.reset();
+ this.preservePartial();
+ if (this.stopped) return; // A transcript listener can release capture.
+ if (/\b(401|402|403)\b/.test(message)) {
+ this.stop();
+ this.options.onError(message);
+ return;
+ }
+ if (this.finishing) {
+ this.stop();
+ return;
+ }
+ const delay = Math.min(1000 * 2 ** Math.min(this.attempt++, 5), 30000);
+ this.options.onStatus(`Connection lost. Reconnecting in ${delay / 1000}s...`);
+ this.retry = setTimeout(() => {
+ this.retry = null;
+ this.start();
+ }, delay);
+ }
+}
diff --git a/app/native/soniox-stt.ts b/app/native/soniox-stt.ts
index 6c9a6f33..e52454e7 100644
--- a/app/native/soniox-stt.ts
+++ b/app/native/soniox-stt.ts
@@ -1,4 +1,5 @@
import { CLOUD_STT_SAMPLE_RATE, CloudSttClient, CloudSttOptions, toJavaBytes } from "./cloud-stt";
+import { TimedTranscript } from "./transcript-format";
declare const com: any;
@@ -30,15 +31,18 @@ export class SonioxSttClient implements CloudSttClient {
// PCM queued until the socket opens and the config message is sent.
private readonly pendingPcm: Uint8Array[] = [];
private pendingFinish = false;
+ private finishing = false;
// Concatenation of all final tokens so far.
private finalText = "";
+ private formatted = new TimedTranscript();
constructor(private readonly options: SonioxSttOptions) {}
start(): void {
- if (this.ws) return;
+ if (this.closed || this.ws) return;
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
onOpen: () => {
+ if (this.closed) return;
// The API key rides in the config message; there is no auth header.
this.trySendText(
JSON.stringify({
@@ -47,8 +51,10 @@ export class SonioxSttClient implements CloudSttClient {
audio_format: "pcm_s16le",
sample_rate: CLOUD_STT_SAMPLE_RATE,
num_channels: 1,
+ enable_speaker_diarization: true,
}),
);
+ if (this.closed) return;
this.open = true;
for (const chunk of this.pendingPcm.splice(0)) {
this.sendPcm(chunk);
@@ -58,21 +64,25 @@ export class SonioxSttClient implements CloudSttClient {
this.finish();
}
this.options.onStatus("Listening (Soniox)...");
+ this.options.onReady?.();
+ },
+ onTextMessage: (message: string) => {
+ if (!this.closed) this.handleMessage(String(message));
},
- onTextMessage: (message: string) => this.handleMessage(String(message)),
onClosed: () => {
this.open = false;
+ if (!this.closed) this.options.onDisconnected?.("Soniox connection closed.");
},
onFailure: (message: string) => {
if (this.closed) return;
- this.options.onError(`Soniox connection failed: ${String(message)}`);
+ this.options.onDisconnected?.(`Soniox connection failed: ${String(message)}`);
},
});
try {
this.ws = new com.faceclaw.app.FaceclawWebSocket(WS_URL, this.listenerProxy, null, null);
this.options.onStatus("Connecting to Soniox...");
} catch (error) {
- this.options.onError(`Soniox connection failed: ${String((error as Error)?.message ?? error)}`);
+ this.options.onDisconnected?.(`Soniox connection failed: ${String((error as Error)?.message ?? error)}`);
}
}
@@ -89,6 +99,7 @@ export class SonioxSttClient implements CloudSttClient {
/** End of utterance: an empty text frame tells Soniox the audio is done. */
finish(): void {
if (this.closed) return;
+ this.finishing = true;
if (this.open) {
this.trySendText("");
} else {
@@ -96,8 +107,13 @@ export class SonioxSttClient implements CloudSttClient {
}
}
+ commitSegment(): void {
+ if (!this.closed && this.open) this.trySendText(JSON.stringify({ type: "finalize" }));
+ }
+
stop(): void {
this.closed = true;
+ this.open = false;
if (this.ws) {
try {
this.ws.close(1000, "bye");
@@ -107,21 +123,26 @@ export class SonioxSttClient implements CloudSttClient {
this.ws = null;
}
this.listenerProxy = null;
+ this.pendingPcm.length = 0;
}
private sendPcm(pcm: Uint8Array): void {
try {
- this.ws?.sendBinary(toJavaBytes(pcm));
+ if (this.ws?.sendBinary(toJavaBytes(pcm)) === false) {
+ this.options.onDisconnected?.("Soniox audio send failed.");
+ }
} catch (error) {
- console.warn("soniox send failed", error);
+ this.options.onDisconnected?.(`Soniox send failed: ${String(error)}`);
}
}
private trySendText(message: string): void {
try {
- this.ws?.sendText(message);
+ if (this.ws?.sendText(message) === false) {
+ this.options.onDisconnected?.("Soniox send failed.");
+ }
} catch (error) {
- console.warn("soniox send failed", error);
+ this.options.onDisconnected?.(`Soniox send failed: ${String(error)}`);
}
}
@@ -133,28 +154,42 @@ export class SonioxSttClient implements CloudSttClient {
return;
}
if (message?.error_code != null) {
- this.options.onError(`Soniox: ${String(message.error_message ?? message.error_code)}`);
+ const error = `Soniox: ${String(message.error_message ?? message.error_code)}`;
+ if (Number(message.error_code) === 429 || Number(message.error_code) >= 500) this.options.onDisconnected?.(error);
+ else this.options.onError(error);
return;
}
const tokens = Array.isArray(message?.tokens) ? message.tokens : [];
let nonFinal = "";
+ let preview: TimedTranscript | null = null;
for (const token of tokens) {
const tokenText = String(token?.text ?? "");
// Markers emitted by endpoint detection / manual finalize; not speech.
- if (tokenText === "" || tokenText === "") continue;
+ if (tokenText === "" || tokenText === "") {
+ if (token?.is_final && this.finalText) {
+ this.options.onTranscript({ text: this.finalText, transcribeText: this.formatted.text, isFinal: true, paragraphBreakAfter: true });
+ this.finalText = "";
+ this.formatted = new TimedTranscript();
+ }
+ continue;
+ }
if (token?.is_final) {
this.finalText += tokenText;
+ this.formatted.append({ ...token, text: tokenText });
} else {
nonFinal += tokenText;
+ preview ??= this.formatted.copy();
+ preview.append({ ...token, text: tokenText });
}
}
if (message?.finished) {
- this.options.onTranscript({ text: this.finalText, isFinal: true });
- this.stop();
+ this.options.onTranscript({ text: this.finalText, transcribeText: this.formatted.text, isFinal: true });
+ if (this.finishing) this.stop();
+ else this.options.onDisconnected?.("Soniox session ended; restarting transcription.");
return;
}
if (tokens.length > 0) {
- this.options.onTranscript({ text: this.finalText + nonFinal, isFinal: false });
+ this.options.onTranscript({ text: this.finalText + nonFinal, transcribeText: (preview ?? this.formatted).text, isFinal: false });
}
}
}
diff --git a/app/native/speech-pause.ts b/app/native/speech-pause.ts
new file mode 100644
index 00000000..08703ead
--- /dev/null
+++ b/app/native/speech-pause.ts
@@ -0,0 +1,44 @@
+/** Sample-clock pause detection: BLE/network delivery timing is not speech timing. */
+export const TRANSCRIPT_PAUSE_MS = 1500;
+
+export class SpeechPauseDetector {
+ private noiseFloor = 220;
+ private speaking = false;
+ private quietSamples = 0;
+
+ reset(): void {
+ this.noiseFloor = 220;
+ this.speaking = false;
+ this.quietSamples = 0;
+ }
+
+ /** PCM16LE, 16 kHz. Returns true once per pause after speech. */
+ accept(pcm: Uint8Array): boolean {
+ const count = pcm.length >> 1;
+ if (!count) return false;
+ let squares = 0;
+ for (let i = 0; i < count; i++) {
+ const unsigned = pcm[i * 2]! | (pcm[i * 2 + 1]! << 8);
+ const sample = unsigned >= 32768 ? unsigned - 65536 : unsigned;
+ squares += sample * sample;
+ }
+ const rms = Math.sqrt(squares / count);
+ const threshold = this.noiseFloor * (this.speaking ? 1.8 : 3);
+ if (rms >= threshold) {
+ this.speaking = true;
+ this.quietSamples = 0;
+ } else {
+ // Slowly follow background levels without learning speech as noise.
+ this.noiseFloor = Math.max(220, this.noiseFloor * 0.98 + rms * 0.02);
+ if (this.speaking) {
+ this.quietSamples += count;
+ if (this.quietSamples >= 16 * TRANSCRIPT_PAUSE_MS) {
+ this.speaking = false;
+ this.quietSamples = 0;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
diff --git a/app/native/timer-notifications.ts b/app/native/timer-notifications.ts
deleted file mode 100644
index f7524ee0..00000000
--- a/app/native/timer-notifications.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { Utils } from "@nativescript/core";
-
-declare const com: any;
-
-function getContext(): android.content.Context | null {
- if (!global.isAndroid) return null;
- return Utils.android.getApplicationContext() ?? null;
-}
-
-/** Schedule the durable Android alarm backing one on-glasses timer. */
-export function scheduleTimerNotification(timerId: number, triggerAtMs: number, durationLabel: string): void {
- const context = getContext();
- if (!context) return;
- com.faceclaw.app.FaceclawTimerNotifications.schedule(context, timerId, triggerAtMs, durationLabel);
-}
-
-/** Cancel both a pending alarm and any already-posted notification. */
-export function cancelTimerNotification(timerId: number): void {
- const context = getContext();
- if (!context) return;
- com.faceclaw.app.FaceclawTimerNotifications.cancel(context, timerId);
-}
-
-/** Prompt worker-side expiry path; Java deduplicates it against the alarm. */
-export function fireTimerNotification(timerId: number, durationLabel: string): void {
- const context = getContext();
- if (!context) return;
- com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, timerId, durationLabel);
-}
diff --git a/app/native/transcript-format.ts b/app/native/transcript-format.ts
new file mode 100644
index 00000000..23915030
--- /dev/null
+++ b/app/native/transcript-format.ts
@@ -0,0 +1,32 @@
+import { TRANSCRIPT_PAUSE_MS } from "./speech-pause";
+
+export type TranscriptToken = { text: string; start_ms?: number; end_ms?: number; speaker?: string };
+
+/** A separate presentation buffer keeps paragraph breaks out of dictation. */
+export class TimedTranscript {
+ text = "";
+ private endMs: number | undefined;
+ private speaker: string | undefined;
+
+ copy(): TimedTranscript {
+ const copy = new TimedTranscript();
+ copy.text = this.text;
+ copy.endMs = this.endMs;
+ copy.speaker = this.speaker;
+ return copy;
+ }
+
+ append(token: TranscriptToken): void {
+ const changedSpeaker = token.speaker != null && this.speaker != null && token.speaker !== this.speaker;
+ const paused = token.start_ms != null && this.endMs != null && token.start_ms - this.endMs >= TRANSCRIPT_PAUSE_MS;
+ if (token.text.trim() && this.text && (changedSpeaker || paused)) {
+ this.text = `${this.text.trimEnd()}\n${token.text.trimStart()}`;
+ } else {
+ this.text += token.text;
+ }
+ if (token.text.trim()) {
+ if (token.end_ms != null) this.endMs = token.end_ms;
+ if (token.speaker != null) this.speaker = token.speaker;
+ }
+ }
+}
diff --git a/app/native/voice-control.ts b/app/native/voice-control.ts
index 63bf8f9c..f0e5669a 100644
--- a/app/native/voice-control.ts
+++ b/app/native/voice-control.ts
@@ -1,6 +1,8 @@
import { Utils } from "@nativescript/core";
-import { CloudSttClient } from "./cloud-stt";
+import { type CloudSttTranscriptEvent, type CloudSttOptions, CloudSttClient } from "./cloud-stt";
+import { ReconnectingSttClient } from "./reconnecting-stt";
+import { SpeechPauseDetector } from "./speech-pause";
import { ElevenLabsSttClient } from "./elevenlabs-stt";
import { OpenAiRealtimeSttClient } from "./openai-stt";
import { SonioxSttClient } from "./soniox-stt";
@@ -14,7 +16,7 @@ export type VoiceControlState = {
export type VoiceProviderKind = "onboard" | "elevenlabs" | "whisper" | "soniox";
-export type VoiceTranscriptEvent = {
+export type VoiceTranscriptEvent = CloudSttTranscriptEvent & {
/**
* Complete best transcript of the current utterance. REPLACE semantics —
* render as-is, replacing any previous partial. Not a delta.
@@ -80,6 +82,8 @@ export type FrameMetaListener = (meta: MicFrameMeta) => void;
export class FaceclawVoiceControlBridge {
private readonly statusListeners = new Set<(state: VoiceControlState) => void>();
private readonly transcriptListeners = new Set<(event: VoiceTranscriptEvent) => void>();
+ private readonly speechPauseListeners = new Set<() => void>();
+ private readonly speechPause = new SpeechPauseDetector();
private readonly speechEndListeners = new Set<() => void>();
private controller: any | null = null;
private listenerProxy: any | null = null;
@@ -132,6 +136,12 @@ export class FaceclawVoiceControlBridge {
return () => this.speechEndListeners.delete(listener);
}
+ /** Pauses in on-device recognition, for Transcribe's presentation only. */
+ onSpeechPause(listener: () => void): () => void {
+ this.speechPauseListeners.add(listener);
+ return () => this.speechPauseListeners.delete(listener);
+ }
+
/** Begin push-to-talk capture (momentary; released with stopPushToTalk). */
startPushToTalk(options: PushToTalkOptions): void {
this.acquireCapture("ptt", options);
@@ -251,6 +261,9 @@ export class FaceclawVoiceControlBridge {
this.controller?.clearSpeakerVerification();
}
+ this.speechPause.reset();
+ // A previous push-to-talk commit may still be awaiting its final result.
+ this.cloudClient?.stop();
const cloudClient = this.createCloudClient(options);
if (cloudClient) {
this.cloudClient = cloudClient;
@@ -274,18 +287,20 @@ export class FaceclawVoiceControlBridge {
if (options.provider === "onboard") return null;
const sttOptions = {
apiKey: "",
- onTranscript: (event: { text: string; isFinal: boolean }) =>
- this.emitTranscript(event.text, event.isFinal),
+ onTranscript: (event: CloudSttTranscriptEvent) =>
+ this.emitTranscript(event.text, event.isFinal, event),
onStatus: (status: string) => this.setStatus(status),
onError: (message: string) => this.setStatus(message),
};
+ const reconnecting = (create: (options: CloudSttOptions) => CloudSttClient, apiKey: string) =>
+ new ReconnectingSttClient(create, { ...sttOptions, apiKey }, () => this.captureHolders.has("continuous"));
if (options.provider === "elevenlabs") {
const apiKey = options.elevenLabsApiKey.trim();
if (!apiKey) {
this.setStatus("No ElevenLabs key set; using on-device voice.");
return null;
}
- return new ElevenLabsSttClient({ ...sttOptions, apiKey });
+ return reconnecting((config) => new ElevenLabsSttClient(config), apiKey);
}
if (options.provider === "soniox") {
const apiKey = options.sonioxApiKey.trim();
@@ -293,14 +308,14 @@ export class FaceclawVoiceControlBridge {
this.setStatus("No Soniox key set; using on-device voice.");
return null;
}
- return new SonioxSttClient({ ...sttOptions, apiKey });
+ return reconnecting((config) => new SonioxSttClient(config), apiKey);
}
const apiKey = options.openAiApiKey.trim();
if (!apiKey) {
this.setStatus("No OpenAI key set; using on-device voice.");
return null;
}
- return new OpenAiRealtimeSttClient({ ...sttOptions, apiKey });
+ return reconnecting((config) => new OpenAiRealtimeSttClient(config), apiKey);
}
private releaseCapture(holder: CaptureHolder, commit: boolean): void {
@@ -432,6 +447,9 @@ export class FaceclawVoiceControlBridge {
onPcm: (pcm: any) => {
const bytes = toUint8Array(pcm);
this.cloudClient?.acceptPcm(bytes);
+ if (!this.cloudClient && this.captureHolders.has("continuous") && this.speechPause.accept(bytes)) {
+ for (const listener of this.speechPauseListeners) listener();
+ }
if (this.rawPcmListeners.size > 0) {
this.rawPcmListeners.forEach((listener) => listener(bytes));
}
@@ -459,15 +477,16 @@ export class FaceclawVoiceControlBridge {
this.controller.setListener(this.listenerProxy);
}
- private emitTranscript(text: string, isFinal: boolean): void {
+ private emitTranscript(text: string, isFinal: boolean, metadata?: CloudSttTranscriptEvent): void {
// "My voice only": a rejected session's final transcript is emptied so
// nothing downstream (assistant, dictation) acts on another speaker's
// words. The verification verdict is posted before the final, and cloud
// finals arrive over the network later still, so the flag is settled.
if (isFinal && this.verificationActive && this.verificationRejected) {
text = "";
+ metadata = undefined;
}
- const event = { text, isFinal };
+ const event = { ...metadata, text, isFinal };
for (const listener of this.transcriptListeners) {
listener(event);
}
diff --git a/app/phone-ui/main-page.ts b/app/phone-ui/main-page.ts
index 4298a5e7..244b6d05 100644
--- a/app/phone-ui/main-page.ts
+++ b/app/phone-ui/main-page.ts
@@ -1,4 +1,4 @@
-import { Application, Color, EventData, isAndroid, Observable, Page, TextField } from '@nativescript/core'
+import { Application, Color, EventData, isAndroid, Observable, Page, TextField, TextView } from '@nativescript/core'
import { MainViewModel } from './main-view-model'
import { dashboardController } from '../g2/dashboard-controller'
@@ -39,7 +39,12 @@ function cleanupPage(page: Page): void {
setPageState(page, undefined)
}
-function applySettingsTextFieldContrast(textField: TextField): void {
+/**
+ * Readable colours for the light editor panels in both themes. selectAllOnFocus
+ * suits replacing an existing setting value; a message being composed keeps
+ * its caret where the user taps.
+ */
+function applySettingsTextFieldContrast(textField: TextField | TextView, selectAllOnFocus = true): void {
textField.color = SETTINGS_TEXT_COLOR
textField.backgroundColor = SETTINGS_BACKGROUND_COLOR
textField.placeholderColor = SETTINGS_PLACEHOLDER_COLOR
@@ -48,7 +53,7 @@ function applySettingsTextFieldContrast(textField: TextField): void {
return
}
- const nativeTextField = (textField as TextField & { nativeView?: android.widget.EditText }).nativeView
+ const nativeTextField = (textField as (TextField | TextView) & { nativeView?: android.widget.EditText }).nativeView
if (!nativeTextField) {
return
}
@@ -57,7 +62,7 @@ function applySettingsTextFieldContrast(textField: TextField): void {
nativeTextField.setHintTextColor(android.graphics.Color.rgb(102, 102, 102))
// Editing an existing value usually means replacing it: select all on focus
// so typing starts fresh but the current value stays visible.
- nativeTextField.setSelectAllOnFocus(true)
+ nativeTextField.setSelectAllOnFocus(selectAllOnFocus)
}
/**
@@ -83,6 +88,22 @@ function focusTextEditor(page: Page): void {
}, 0)
}
+/** The keyboard dialog closed on the glasses (sent, discarded, or screen off). */
+function dismissKeyboardInputKeyboard(page: Page): void {
+ page.getViewById('keyboardInputField')?.dismissSoftInput()
+}
+
+/** The keyboard dialog opened: bring up the IME on its field right away. */
+function focusKeyboardInput(page: Page): void {
+ setTimeout(() => {
+ const textField = page.getViewById('keyboardInputField')
+ if (textField) {
+ applySettingsTextFieldContrast(textField, false)
+ textField.focus()
+ }
+ }, 0)
+}
+
export function loaded(args: EventData) {
const page = args.object as Page
cleanupPage(page)
@@ -121,6 +142,12 @@ export function loaded(args: EventData) {
} else {
dismissTextEditorKeyboard(page)
}
+ } else if (propertyArgs.propertyName === 'keyboardInputActive') {
+ if (model.keyboardInputActive) {
+ focusKeyboardInput(page)
+ } else {
+ dismissKeyboardInputKeyboard(page)
+ }
}
},
}
@@ -131,6 +158,9 @@ export function loaded(args: EventData) {
if (model.isTextSettingEditorActive) {
focusTextEditor(page)
}
+ if (model.keyboardInputActive) {
+ focusKeyboardInput(page)
+ }
}
export function unloaded(args: EventData) {
diff --git a/app/phone-ui/main-page.xml b/app/phone-ui/main-page.xml
index 7dc9a3d3..c10ee6a5 100644
--- a/app/phone-ui/main-page.xml
+++ b/app/phone-ui/main-page.xml
@@ -38,32 +38,41 @@
-
-
-
-
+
+
+
+
+
+
-
-
-
+ visibility="{{ displayPreviewMessageVisibility }}">
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
@@ -138,5 +151,29 @@
checkedChange="{{ onTextSettingToggleChange }}" />
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/phone-ui/main-view-model.ts b/app/phone-ui/main-view-model.ts
index a854727f..7a0768e4 100644
--- a/app/phone-ui/main-view-model.ts
+++ b/app/phone-ui/main-view-model.ts
@@ -19,9 +19,11 @@ import {
displayModeSetting,
mirrorTouchSetting,
onAnySettingChanged,
+ showBleBandwidthSetting,
type BrightnessSetting,
type DisplayModeSetting,
} from "../ui/dashboard-settings";
+import { sampleBleTraffic } from "../native/ble-traffic";
import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses";
import { isAutoReconnectSuppressed, resumeAutoReconnect } from "../g2/reconnect-policy";
import { formatErrorMessage } from "../util/format-error";
@@ -42,6 +44,9 @@ export class MainViewModel extends Observable {
private _displayPreview: ImageSource | null = null;
private _displayPreviewMessage = "";
private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation();
+ private _landscapePreviewWidth = 0;
+ private _landscapePreviewHeight = 0;
+ private _controlsContentHeight = 250;
private _activeTextSettingId: string | null = null;
private _activeTextEditorTitle = "";
private _activeTextSettingTitle = "";
@@ -54,6 +59,9 @@ export class MainViewModel extends Observable {
private _activeTextEditorToggleLabel = "";
private _activeTextEditorToggleValue = false;
private _activeTextEditorToggleVisible = false;
+ private _keyboardInputActive = false;
+ private _keyboardInputTargets: ReadonlyArray<{ id: string; label: string }> = [];
+ private _keyboardInputText = "";
private _evenAppConflictMessage = "";
private _evenAppConflictWarningVisible = false;
private _firmwareWarningMessage = "";
@@ -61,6 +69,7 @@ export class MainViewModel extends Observable {
private _screenRecordingActive = false;
private _batteryOptimizationWarningVisible = false;
private _fontsMissingWarningVisible = false;
+ private _alarmReliabilityMessage = "";
private _warningsModalVisible = false;
private _previewMode = false;
private _phase: "disconnected" | "connecting" | "connected" | "charging" | "disconnecting" = "disconnected";
@@ -101,6 +110,9 @@ export class MainViewModel extends Observable {
this.activeTextEditorToggleLabel = snapshot.activeTextEditorToggleLabel;
this.activeTextEditorToggleValue = snapshot.activeTextEditorToggleValue;
this.activeTextEditorToggleVisible = snapshot.activeTextEditorToggleVisible;
+ // Targets before active: the panel's buttons are labelled when it appears.
+ this.keyboardInputTargets = snapshot.keyboardInputTargets;
+ this.keyboardInputActive = snapshot.keyboardInputActive;
this.evenAppConflictMessage = snapshot.evenAppConflictMessage;
this.evenAppConflictWarningVisible = snapshot.evenAppConflictWarningVisible;
this.firmwareWarningMessage = snapshot.firmwareWarningMessage;
@@ -108,10 +120,16 @@ export class MainViewModel extends Observable {
this.screenRecordingActive = snapshot.screenRecordingActive;
this.batteryOptimizationWarningVisible = snapshot.batteryOptimizationWarningVisible;
this.fontsMissingWarningVisible = snapshot.fontsMissingWarningVisible;
+ this.alarmReliabilityMessage = snapshot.alarmReliabilityMessage;
this.refreshPadFocusLine();
}));
// Brightness / display mode can change from the glasses' Settings app too.
- this.unsubscribers.push(onAnySettingChanged(() => this.refreshDisplayControls()));
+ this.unsubscribers.push(onAnySettingChanged(() => {
+ this.refreshDisplayControls();
+ this.syncBleBandwidthPolling();
+ }));
+ this.syncBleBandwidthPolling();
+ this.unsubscribers.push(() => this.stopBleBandwidthPolling());
}
/** Detach from the controller and settings; the page calls this when it lets go of the model. */
@@ -221,18 +239,25 @@ export class MainViewModel extends Observable {
}
get landscapeDisplayPreviewWidth(): number {
- return Math.floor(this.landscapeDisplayPreviewHeight * LENS_ASPECT_RATIO);
+ return this._landscapePreviewWidth;
}
get landscapeDisplayPreviewHeight(): number {
- // Height keeps the vertical footprint the preview had at the old 2:1
- // aspect; the width is derived from it, so a wider lens aspect can't
- // grow the preview past the side panel.
- const screenWidth = Screen.mainScreen.widthDIPs;
- // Must match the landscape grid's fixed side-panel column in main-page.xml.
- const sidePanelWidth = 360;
- const availableWidth = Math.max(240, Math.floor(screenWidth - sidePanelWidth - 56));
- return Math.floor(availableWidth / 2);
+ return this._landscapePreviewHeight;
+ }
+
+ onLandscapePreviewLayoutChanged(args: { object: View }): void {
+ // Measure the actual content cell: excludes the action bar, system bars,
+ // and controls, and updates for rotation, split-screen, and the keyboard.
+ const { width, height } = args.object.getActualSize();
+ if (width <= 0 || height <= 0) return;
+ const previewHeight = Math.min(height, width / LENS_ASPECT_RATIO);
+ const previewWidth = previewHeight * LENS_ASPECT_RATIO;
+ if (previewWidth === this._landscapePreviewWidth && previewHeight === this._landscapePreviewHeight) return;
+ this._landscapePreviewWidth = previewWidth;
+ this._landscapePreviewHeight = previewHeight;
+ this.notifyPropertyChange("landscapeDisplayPreviewWidth", previewWidth);
+ this.notifyPropertyChange("landscapeDisplayPreviewHeight", previewHeight);
}
/** Near-full-width on phones, capped on tablets (the 32 clears the 16 margins). */
@@ -249,13 +274,27 @@ export class MainViewModel extends Observable {
const faceHeight = 230;
const available =
this._layoutOrientation === "landscape"
- ? // The landscape side panel column (see main-page.xml) minus its
- // m-l-16 margin and the controls' own 8+8 margins.
- 360 - 32
+ ? 345 // Matches the unpadded landscape controls column in main-page.xml.
: Screen.mainScreen.widthDIPs - 56; // p-20 padding + controls margins
return Math.min(available, Math.round(faceHeight * 1.5));
}
+ get watchFaceHeight(): number {
+ return Math.min(230, Math.max(0, this._controlsContentHeight - 2));
+ }
+
+ get ringTouchpadHeight(): number {
+ return Math.min(250, Math.max(0, this._controlsContentHeight - 2));
+ }
+
+ onControlsContentLayoutChanged(args: { object: View }): void {
+ const { height } = args.object.getActualSize();
+ if (height <= 0 || height === this._controlsContentHeight) return;
+ this._controlsContentHeight = height;
+ this.notifyPropertyChange("watchFaceHeight", this.watchFaceHeight);
+ this.notifyPropertyChange("ringTouchpadHeight", this.ringTouchpadHeight);
+ }
+
get portraitLayoutVisibility(): "visible" | "collapse" {
return this._layoutOrientation === "portrait" ? "visible" : "collapse";
}
@@ -459,6 +498,93 @@ export class MainViewModel extends Observable {
return this.isTextSettingEditorActive ? "visible" : "collapse";
}
+ // ---- keyboard-input panel (the keyboard button beside the mic button) ----
+ //
+ // The dialog lives on the glasses (ui/shell/keyboard-input.ts); this panel
+ // is the phone's end of it: the text field the IME types into and a send
+ // button per destination. The field's text is the panel's own state, never
+ // echoed back from the controller (see setActiveTextSettingValue for why);
+ // it is cleared whenever a dialog opens or closes.
+
+ get keyboardInputActive(): boolean {
+ return this._keyboardInputActive;
+ }
+
+ set keyboardInputActive(value: boolean) {
+ if (this._keyboardInputActive === value) return;
+ this._keyboardInputActive = value;
+ this.keyboardInputText = "";
+ this.notifyPropertyChange("keyboardInputActive", value);
+ this.notifyPropertyChange("keyboardInputVisibility", this.keyboardInputVisibility);
+ this.notifyPropertyChange("controlsVisibility", this.controlsVisibility);
+ }
+
+ get keyboardInputVisibility(): "visible" | "collapse" {
+ return this._keyboardInputActive ? "visible" : "collapse";
+ }
+
+ get keyboardInputText(): string {
+ return this._keyboardInputText;
+ }
+
+ set keyboardInputText(value: string) {
+ if (this._keyboardInputText === value) return;
+ this._keyboardInputText = value;
+ this.notifyPropertyChange("keyboardInputText", value);
+ }
+
+ set keyboardInputTargets(value: ReadonlyArray<{ id: string; label: string }>) {
+ this._keyboardInputTargets = value;
+ this.notifyPropertyChange("keyboardInputPrimaryTargetLabel", this.keyboardInputPrimaryTargetLabel);
+ this.notifyPropertyChange("keyboardInputPrimaryTargetVisibility", this.keyboardInputPrimaryTargetVisibility);
+ this.notifyPropertyChange("keyboardInputSecondaryTargetLabel", this.keyboardInputSecondaryTargetLabel);
+ this.notifyPropertyChange("keyboardInputSecondaryTargetVisibility", this.keyboardInputSecondaryTargetVisibility);
+ }
+
+ // The glasses menu has at most two destinations (assistant, app), so the
+ // panel has a fixed pair of buttons rather than a repeater.
+ get keyboardInputPrimaryTargetLabel(): string {
+ return this._keyboardInputTargets[0]?.label ?? "";
+ }
+
+ get keyboardInputPrimaryTargetVisibility(): "visible" | "collapse" {
+ return this._keyboardInputTargets[0] ? "visible" : "collapse";
+ }
+
+ get keyboardInputSecondaryTargetLabel(): string {
+ return this._keyboardInputTargets[1]?.label ?? "";
+ }
+
+ get keyboardInputSecondaryTargetVisibility(): "visible" | "collapse" {
+ return this._keyboardInputTargets[1] ? "visible" : "collapse";
+ }
+
+ onKeyboardTap(): void {
+ dashboardController.startKeyboardInput();
+ }
+
+ onKeyboardInputTextChange(args: { value?: string; object?: { text?: string } }): void {
+ const text = args.object?.text ?? args.value ?? "";
+ // Track the draft so closing the dialog emits a clear even when the
+ // binding hasn't updated the model. Avoid echoing edits into the IME.
+ this._keyboardInputText = text;
+ dashboardController.setKeyboardInputText(text);
+ }
+
+ onKeyboardInputPrimarySendTap(): void {
+ const target = this._keyboardInputTargets[0];
+ if (target) dashboardController.sendKeyboardInput(target.id);
+ }
+
+ onKeyboardInputSecondarySendTap(): void {
+ const target = this._keyboardInputTargets[1];
+ if (target) dashboardController.sendKeyboardInput(target.id);
+ }
+
+ onKeyboardInputDiscardTap(): void {
+ dashboardController.discardKeyboardInput();
+ }
+
get evenAppConflictMessage(): string {
return this._evenAppConflictMessage;
}
@@ -614,6 +740,28 @@ export class MainViewModel extends Observable {
dashboardController.requestBatteryOptimizationExemption();
}
+ get alarmReliabilityMessage(): string {
+ return this._alarmReliabilityMessage;
+ }
+
+ set alarmReliabilityMessage(value: string) {
+ if (this._alarmReliabilityMessage !== value) {
+ this._alarmReliabilityMessage = value;
+ this.notifyPropertyChange("alarmReliabilityMessage", value);
+ this.notifyPropertyChange("alarmReliabilityWarningVisibility", this.alarmReliabilityWarningVisibility);
+ this.refreshWarningIndicator();
+ }
+ }
+
+ get alarmReliabilityWarningVisibility(): "visible" | "collapse" {
+ return this._alarmReliabilityMessage ? "visible" : "collapse";
+ }
+
+ onFixAlarmReliabilityTap(): void {
+ this.setWarningsModalVisible(false);
+ dashboardController.openAlarmReliabilityFix();
+ }
+
// ---- the action bar's warning triangle and the modal behind it ----
get anyWarningVisible(): boolean {
@@ -621,7 +769,8 @@ export class MainViewModel extends Observable {
this._evenAppConflictWarningVisible ||
this._firmwareWarningVisible ||
this._batteryOptimizationWarningVisible ||
- this._fontsMissingWarningVisible
+ this._fontsMissingWarningVisible ||
+ this._alarmReliabilityMessage.length > 0
);
}
@@ -846,16 +995,36 @@ export class MainViewModel extends Observable {
dashboardController.openEvenAppSettings();
}
+ // Tap-then-hold on the simulated pads: NativeScript reports doubleTap on
+ // the second finger-down and still runs the long-press recognizer on that
+ // same press, so the sequence arrives as doubleTap followed by longPress.
+ // Each pad therefore defers its double-click until the finger-up (the touch
+ // handler) and converts the deferred pair into the G2 tap-then-hold gesture
+ // when a longPress lands first.
+
+ private ringPadDoubleTapPending = false;
+
async onRingPadTap(): Promise {
await dashboardController.injectSyntheticRingInput("click");
}
async onRingPadDoubleTap(): Promise {
- await dashboardController.injectSyntheticRingInput("double-click");
+ this.ringPadDoubleTapPending = true;
}
async onRingPadLongPress(): Promise {
- await dashboardController.injectSyntheticRingInput("long-press");
+ const kind = this.ringPadDoubleTapPending ? "short-then-long-press" : "long-press";
+ this.ringPadDoubleTapPending = false;
+ await dashboardController.injectSyntheticRingInput(kind);
+ }
+
+ async onRingPadTouch(args: TouchGestureEventData): Promise {
+ if (args.action !== "up" && args.action !== "cancel") return;
+ const pending = this.ringPadDoubleTapPending;
+ this.ringPadDoubleTapPending = false;
+ if (args.action === "up" && pending) {
+ await dashboardController.injectSyntheticRingInput("double-click");
+ }
}
/** The ring pad only has a vertical axis, so left/right swipes are ignored. */
@@ -878,6 +1047,9 @@ export class MainViewModel extends Observable {
// above stays on the ring's own scheme.
private padTwoFingerDown = false;
+ // See the ring pad above: defers the double-click so a longPress can turn
+ // the pair into tap-then-hold.
+ private padDoubleTapPending = false;
/** What the next gesture lands on, as the watch pad shows it. */
get padFocusLine(): string {
@@ -895,12 +1067,13 @@ export class MainViewModel extends Observable {
}
async onPadDoubleTap(): Promise {
- await dashboardController.injectSyntheticRingInput("double-click", "watch");
- this.refreshPadFocusLine();
+ this.padDoubleTapPending = true;
}
async onPadLongPress(): Promise {
- await dashboardController.injectSyntheticRingInput("long-press", "watch");
+ const kind = this.padDoubleTapPending ? "short-then-long-press" : "long-press";
+ this.padDoubleTapPending = false;
+ await dashboardController.injectSyntheticRingInput(kind, "watch");
this.refreshPadFocusLine();
}
@@ -917,6 +1090,8 @@ export class MainViewModel extends Observable {
return;
}
if (args.action === "up" || args.action === "cancel") {
+ const pendingDouble = this.padDoubleTapPending;
+ this.padDoubleTapPending = false;
const twoFinger = this.padTwoFingerDown;
if (twoFinger) {
// Let the single-tap recognizer's delayed tap see the flag first.
@@ -927,6 +1102,9 @@ export class MainViewModel extends Observable {
await dashboardController.injectSyntheticRingInput("double-click", "watch");
this.refreshPadFocusLine();
}
+ } else if (args.action === "up" && pendingDouble) {
+ await dashboardController.injectSyntheticRingInput("double-click", "watch");
+ this.refreshPadFocusLine();
}
}
}
@@ -980,7 +1158,7 @@ export class MainViewModel extends Observable {
private _controlsTab: ControlsTab = lastControlsTab;
get controlsVisibility(): "visible" | "collapse" {
- return this.isTextSettingEditorActive ? "collapse" : "visible";
+ return this.isTextSettingEditorActive || this._keyboardInputActive ? "collapse" : "visible";
}
get settingsTabVisibility(): "visible" | "collapse" {
@@ -1099,6 +1277,75 @@ export class MainViewModel extends Observable {
this.notifyPropertyChange("displayModeLabel", this.displayModeLabel);
}
+ // ---- BLE bandwidth indicator (Settings > Developer > Show BLE bandwidth usage) ----
+ //
+ // A running total of outbound BLE messages/bytes, overlaid at the bottom of
+ // the page on every tab. Polled from the Java-side counters while enabled.
+
+ private _bleBandwidthLabel = "";
+ private bleBandwidthTimer: ReturnType | null = null;
+ // Recent counter samples, one per poll tick, for the windowed rates.
+ private bleRateHistory: Array<{ atMs: number; bytes: number; frames: number }> = [];
+
+ get bleBandwidthVisibility(): "visible" | "collapse" {
+ return showBleBandwidthSetting.get() ? "visible" : "collapse";
+ }
+
+ get bleBandwidthLabel(): string {
+ return this._bleBandwidthLabel;
+ }
+
+ /** Start or stop the poll to match the setting; safe to call repeatedly. */
+ private syncBleBandwidthPolling(): void {
+ const enabled = showBleBandwidthSetting.get();
+ if (enabled && this.bleBandwidthTimer === null) {
+ this.refreshBleBandwidth();
+ this.bleBandwidthTimer = setInterval(() => this.refreshBleBandwidth(), 1000);
+ this.notifyPropertyChange("bleBandwidthVisibility", this.bleBandwidthVisibility);
+ } else if (!enabled && this.bleBandwidthTimer !== null) {
+ this.stopBleBandwidthPolling();
+ this.notifyPropertyChange("bleBandwidthVisibility", this.bleBandwidthVisibility);
+ }
+ }
+
+ private stopBleBandwidthPolling(): void {
+ if (this.bleBandwidthTimer !== null) {
+ clearInterval(this.bleBandwidthTimer);
+ this.bleBandwidthTimer = null;
+ }
+ // Don't let a later re-enable compute a rate across the disabled gap.
+ this.bleRateHistory = [];
+ }
+
+ private refreshBleBandwidth(): void {
+ let label: string;
+ try {
+ const sample = sampleBleTraffic();
+ const atMs = Date.now();
+ this.bleRateHistory.push({ atMs, bytes: sample.bytes, frames: sample.frames });
+ while (this.bleRateHistory.length > 0 && this.bleRateHistory[0]!.atMs < atMs - BLE_RATE_WINDOW_MS) {
+ this.bleRateHistory.shift();
+ }
+ label = `BLE sent: ${formatCount(sample.messages)} messages, ${formatCount(sample.bytes)} bytes`;
+ const oldest = this.bleRateHistory[0]!;
+ const elapsedSec = (atMs - oldest.atMs) / 1000;
+ if (elapsedSec > 0) {
+ const byteDelta = sample.bytes - oldest.bytes;
+ const frameDelta = sample.frames - oldest.frames;
+ label += ` · ${formatByteRate(byteDelta / elapsedSec)}, ${(frameDelta / elapsedSec).toFixed(1)} fps`;
+ if (frameDelta > 0) {
+ label += `, ${formatCount(byteDelta / frameDelta)} B/frame`;
+ }
+ }
+ } catch (error) {
+ label = `BLE sent: ${this.formatError(error)}`;
+ }
+ if (label !== this._bleBandwidthLabel) {
+ this._bleBandwidthLabel = label;
+ this.notifyPropertyChange("bleBandwidthLabel", label);
+ }
+ }
+
private readLayoutOrientation(): LayoutOrientation {
const applicationOrientation = Application.orientation();
if (applicationOrientation === "landscape" || applicationOrientation === "portrait") {
@@ -1112,6 +1359,20 @@ export class MainViewModel extends Observable {
}
}
+/** 1234567 -> "1,234,567"; kept exact rather than rounded so growth is visible at a glance. */
+function formatCount(value: number): string {
+ return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
+}
+
+/** How far back the BLE bandwidth indicator's rates look. */
+const BLE_RATE_WINDOW_MS = 5000;
+
+function formatByteRate(bytesPerSec: number): string {
+ if (bytesPerSec >= 1e6) return (bytesPerSec / 1e6).toFixed(2) + " MB/s";
+ if (bytesPerSec >= 1e3) return (bytesPerSec / 1e3).toFixed(1) + " kB/s";
+ return Math.round(bytesPerSec) + " B/s";
+}
+
/** NativeScript swipe direction -> the watch-scheme directional gesture. */
function swipeKind(direction: SwipeDirection): "swipe-up" | "swipe-down" | "swipe-left" | "swipe-right" {
switch (direction) {
diff --git a/app/phone-ui/onboarding-firmware-check-view-model.ts b/app/phone-ui/onboarding-firmware-check-view-model.ts
index 88850ced..446efe8b 100644
--- a/app/phone-ui/onboarding-firmware-check-view-model.ts
+++ b/app/phone-ui/onboarding-firmware-check-view-model.ts
@@ -7,12 +7,12 @@ import {
hasExtractedEvenHubFonts,
type FirmwareProgress,
} from "../g2/firmware-builder";
-import { classifyOnboardingFirmware, FLASHABLE_STOCK_VERSION_TEXT, type OnboardingFirmwareKind } from "../g2/firmware-compat";
+import { BASE_STOCK_VERSION_TEXT, classifyOnboardingFirmware, type OnboardingFirmwareKind } from "../g2/firmware-compat";
import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error";
-type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer" | "error";
+type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer-validated" | "newer" | "error";
export class OnboardingFirmwareCheckViewModel extends Observable {
private _phase: CheckPhase = "checking";
@@ -72,6 +72,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
case "custom":
return "Finish";
case "flashable":
+ case "newer-validated":
return "Install Firmware";
case "newer":
return "Proceed Anyway";
@@ -107,6 +108,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
this.finish();
return;
case "flashable":
+ case "newer-validated":
case "newer":
this.goToFlashing();
return;
@@ -196,8 +198,8 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
private applyClassification(kind: OnboardingFirmwareKind, version: string, capabilities: string): void {
this.busy = false;
// `kind` is classifyOnboardingFirmware's OnboardingFirmwareKind ("custom" |
- // "flashable-stock" | "newer-stock" | "unknown") -- NOT CheckPhase's shorter
- // "flashable"/"newer" (used below via setPhase for _phase/primaryLabel/etc).
+ // "flashable-stock" | "newer-stock-unvalidated" | "newer-stock-validated" | "unknown") -- NOT CheckPhase's shorter
+ // "flashable"/"newer-validated"/"newer" (used below via setPhase for _phase/primaryLabel/etc).
// The two types share two of four names, so a typo'd case label here type-checks
// fine as long as `kind` stays plain `string`, but silently falls through to
// `default` (the hard "couldn't read a firmware version" error) for every real
@@ -218,11 +220,22 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
`Your glasses run stock firmware ${version}. This is compatible — tap Install Firmware to flash ` +
"Faceclaw's custom firmware.";
break;
- case "newer-stock":
+ case "newer-stock-validated":
+ this.setPhase("newer-validated");
+ this.headline = "Newer Firmware";
+ this.status =
+ `Your glasses run stock firmware ${version}, which is compatible. This version is newer than the ` +
+ `${BASE_STOCK_VERSION_TEXT} release Faceclaw's custom image is built from. Applying custom ` +
+ `firmware will downgrade the firmware version, which may cause compatibility issues when using it ` +
+ `with the stock phone app. If you reconnect the stock phone app, it will offer an OTA update to ` +
+ `${version}; if you apply that update it will fully uninstall the custom firmware.`;
+ break;
+
+ case "newer-stock-unvalidated":
this.setPhase("newer");
this.headline = "Unrecognized Firmware";
this.status =
- `Your glasses run stock firmware ${version}, which is newer than the ${FLASHABLE_STOCK_VERSION_TEXT} ` +
+ `Your glasses run stock firmware ${version}, which is newer than the ${BASE_STOCK_VERSION_TEXT} ` +
"release Faceclaw's custom image is built from. Flashing may not work correctly and carries extra risk. " +
"You can proceed anyway, or go back.";
break;
diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts
index 7d29bdf1..2ce56ca2 100644
--- a/app/phone-ui/onboarding-flash-view-model.ts
+++ b/app/phone-ui/onboarding-flash-view-model.ts
@@ -14,7 +14,11 @@ import {
} from "../g2/firmware-builder";
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
import { FirmwareFlasher, FlashProgress, FlashState } from "../native/firmware-flasher";
-import { FlashPromptCommunicator, FlashPromptState } from "../native/flash-prompt-communicator";
+import {
+ FlashPromptBattery,
+ FlashPromptCommunicator,
+ FlashPromptState,
+} from "../native/flash-prompt-communicator";
import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error";
@@ -23,6 +27,10 @@ type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flas
export type FlashMode = "install" | "uninstall";
+// Flashing a lens takes minutes and the glasses reboot afterwards; refuse to
+// start when either arm is below this so a flat battery can't interrupt it.
+const MIN_FLASH_BATTERY_PERCENT = 30;
+
export class OnboardingFlashViewModel extends Observable {
private readonly mode: FlashMode;
private readonly fromOnboarding: boolean;
@@ -40,6 +48,7 @@ export class OnboardingFlashViewModel extends Observable {
private prompt: FlashPromptCommunicator | null = null;
private promptUnsubscribers: Array<() => void> = [];
+ private promptBattery: FlashPromptBattery | null = null;
private flasher: FirmwareFlasher | null = null;
private flasherUnsubscribers: Array<() => void> = [];
private retryAction: () => void = () => this.beginPrompt();
@@ -55,10 +64,10 @@ export class OnboardingFlashViewModel extends Observable {
this._headline = this.mode === "uninstall" ? "Uninstall Custom Firmware" : "Flash Custom Firmware";
this._status =
this.mode === "uninstall"
- ? "This connects to your glasses, asks for confirmation on the lens, then downloads and reflashes the " +
- "official firmware — removing Faceclaw's custom features."
- : "This connects to your glasses, asks for confirmation on the lens, then downloads, verifies, and flashes " +
- "Faceclaw's custom firmware.";
+ ? "This connects to your glasses, asks for confirmation on the lens, checks the battery, then downloads " +
+ "and reflashes the official firmware — removing Faceclaw's custom features."
+ : "This connects to your glasses, asks for confirmation on the lens, checks the battery, then downloads, " +
+ "verifies, and flashes Faceclaw's custom firmware.";
}
// Kept short to fit the glasses' ~50-column text grid.
@@ -219,15 +228,24 @@ export class OnboardingFlashViewModel extends Observable {
// --- prompt flow -----------------------------------------------------------
- private async beginPrompt(): Promise {
+ /**
+ * Connect to both arms, authenticate (this is where any Android pairing
+ * prompts appear), show the Yes/No confirmation on the lens, then read the
+ * battery. With `skipPrompt` (retrying after a low-battery refusal, when
+ * the user has already confirmed) the on-glasses confirmation is skipped
+ * and only the battery is re-checked.
+ */
+ private async beginPrompt(options?: { skipPrompt?: boolean }): Promise {
+ const skipPrompt = Boolean(options?.skipPrompt);
if (!global.isAndroid) {
- this.toError("Flashing is only available on Android.", () => this.beginPrompt());
+ this.toError("Flashing is only available on Android.", () => this.beginPrompt(options));
return;
}
this.setPhase("prompt");
- this.headline = "Confirm On Your Glasses";
+ this.headline = skipPrompt ? "Checking Battery" : "Confirm On Your Glasses";
this.log = "";
this.busy = true;
+ this.promptBattery = null;
this.status = "Preparing to connect. Make sure your glasses are on and the Even app is disconnected.";
try {
@@ -237,40 +255,50 @@ export class OnboardingFlashViewModel extends Observable {
this.busy = false;
this.toError(
"Couldn't find both glasses arms. Make sure the glasses are powered on and the Even app is disconnected, then retry.",
- () => this.beginPrompt(),
+ () => this.beginPrompt(options),
);
return;
}
this.addresses = addresses;
- this.status = "Connecting to your glasses. Watch the lens for a Yes/No prompt.";
- this.startCommunicator(addresses);
+ this.status = skipPrompt
+ ? "Connecting to your glasses to re-check the battery..."
+ : "Connecting to your glasses. Watch the lens for a Yes/No prompt.";
+ this.startCommunicator(addresses, skipPrompt);
} catch (error) {
this.busy = false;
- this.toError(this.formatError(error), () => this.beginPrompt());
+ this.toError(this.formatError(error), () => this.beginPrompt(options));
}
}
- private startCommunicator(addresses: { right: string; left: string }): void {
+ private startCommunicator(addresses: { right: string; left: string }, skipPrompt: boolean): void {
this.disposePrompt();
- const prompt = new FlashPromptCommunicator(addresses.right, this.glassesWarning);
+ const prompt = new FlashPromptCommunicator(addresses, this.glassesWarning, { skipPrompt });
this.prompt = prompt;
this.promptUnsubscribers.push(
prompt.onLog((line) => this.appendLog(line)),
- prompt.onStateChange((state, detail) => this.handlePromptState(state, detail)),
- prompt.onResult((approved) => this.handlePromptResult(approved)),
+ prompt.onStateChange((state, detail) => this.handlePromptState(state, detail, skipPrompt)),
+ prompt.onBattery((battery) => {
+ this.promptBattery = battery;
+ }),
+ prompt.onResult((approved) => this.handlePromptResult(approved, skipPrompt)),
);
prompt.start();
}
- private handlePromptState(state: FlashPromptState, detail: string): void {
+ private handlePromptState(state: FlashPromptState, detail: string, skipPrompt: boolean): void {
switch (state) {
case "connecting":
this.status = "Connecting to your glasses...";
break;
case "connected":
- this.status = "Connected. Showing the confirmation on the lens...";
+ this.status =
+ "Connected. Pairing with both lenses — if Android asks to pair, accept it (once per lens)." +
+ (skipPrompt ? "" : " Then watch the lens for the confirmation.");
+ break;
+ case "battery":
+ this.status = "Checking the glasses' battery level...";
break;
case "prompting":
this.status =
@@ -289,25 +317,57 @@ export class OnboardingFlashViewModel extends Observable {
break;
case "disconnected":
this.busy = false;
- this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt());
+ this.toError(detail || "Lost connection to the glasses.", () => this.beginPrompt({ skipPrompt }));
break;
case "error":
this.busy = false;
- this.toError(detail || "Connection failed.", () => this.beginPrompt());
+ this.toError(detail || "Connection failed.", () => this.beginPrompt({ skipPrompt }));
break;
}
}
- private handlePromptResult(approved: boolean): void {
+ private handlePromptResult(approved: boolean, skipPrompt: boolean): void {
this.disposePrompt();
if (!approved) {
this.busy = false;
this.toError("You declined on the glasses. No firmware was written.", () => this.beginPrompt());
return;
}
+ const lowBattery = this.describeLowBattery(this.promptBattery);
+ if (lowBattery) {
+ this.busy = false;
+ // The user already confirmed on the lens; a retry only re-checks the battery.
+ this.toError(lowBattery, () => this.beginPrompt({ skipPrompt: true }), "Charge Your Glasses");
+ return;
+ }
+ if (!this.promptBattery || (this.promptBattery.right === null && this.promptBattery.left === null)) {
+ this.appendLog("battery level unknown; proceeding");
+ }
+ this.appendLog(skipPrompt ? "battery ok; confirmed earlier on the lens" : "confirmed on the lens; battery ok");
void this.buildFirmware();
}
+ /** A "charge first" message when either arm is below the flashing threshold, else null. */
+ private describeLowBattery(battery: FlashPromptBattery | null): string | null {
+ if (!battery) {
+ return null;
+ }
+ const readings = [
+ { arm: "right", percent: battery.right },
+ { arm: "left", percent: battery.left },
+ ].filter((r): r is { arm: string; percent: number } => r.percent !== null);
+ const low = readings.filter((r) => r.percent < MIN_FLASH_BATTERY_PERCENT);
+ if (low.length === 0) {
+ return null;
+ }
+ const levels = readings.map((r) => `${r.arm} ${r.percent}%`).join(", ");
+ return (
+ `The glasses' battery is too low to flash safely (${levels}). ` +
+ `Charge both lenses to at least ${MIN_FLASH_BATTERY_PERCENT}%, then tap Retry to check again. ` +
+ "You won't need to confirm on the lens a second time."
+ );
+ }
+
private cancelPrompt(): void {
this.status = "Cancelling...";
try {
@@ -502,11 +562,11 @@ export class OnboardingFlashViewModel extends Observable {
});
}
- private toError(message: string, retry: () => void): void {
+ private toError(message: string, retry: () => void, headline = "Something Went Wrong"): void {
this.retryAction = retry;
this.status = message;
this.setPhase("error");
- this.headline = "Something Went Wrong";
+ this.headline = headline;
}
private setPhase(phase: FlashPhase): void {
diff --git a/app/phone-ui/remote-controls.xml b/app/phone-ui/remote-controls.xml
index 276df11a..a50d43d8 100644
--- a/app/phone-ui/remote-controls.xml
+++ b/app/phone-ui/remote-controls.xml
@@ -4,10 +4,12 @@
scheme as the watch pad - tap = select, double-tap or two fingers = back,
hold = menu, swipes navigate), and Ring (a touchpad on the ring's own
scheme: vertical swipes scroll, tap/double-tap/hold = click/double-click/
- long-press). The narrow mic button at the tab bar's right edge fires the
- wakeword without changing the selected tab. Used by main-page.xml in both
- orientations; binds to the page's MainViewModel, which collapses the whole
- area while a text setting is being edited (keyboard-input mode).
+ long-press). Tap-then-hold on either pad is the G2 system-menu gesture. The
+ narrow mic and keyboard buttons at the tab bar's right edge fire the
+ wakeword / open the keyboard dialog without changing the selected tab. Used
+ by main-page.xml in both orientations; binds to the page's MainViewModel,
+ which collapses the whole area while a text setting is being edited or the
+ keyboard dialog is up (keyboard-input mode).
The root is a rows="auto,*" grid so the active section can use the leftover
height (the Watch face centers in it); the three sections share the star
@@ -17,59 +19,62 @@
-
-
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts
index feca0e13..a233267e 100644
--- a/app/ui/dashboard-settings.ts
+++ b/app/ui/dashboard-settings.ts
@@ -1,3 +1,4 @@
+import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import {
getBooleanSetting,
@@ -24,7 +25,9 @@ export type NightscoutSettings = {
siteUrl: string;
apiToken: string;
};
-export type BatteryDisplayMode = "icon" | "percentage";
+export type BatteryDisplayMode = "icon" | "percentage" | "stacked" | "stacked-percentage";
+/** When a top-bar battery indicator is shown: always, only below 50%, or never. */
+export type BatteryIndicatorVisibility = "always" | "low" | "never";
export type TimeFormat = "24h" | "12h";
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "3m" | "never";
// "auto" lets the glasses' ambient-light sensor drive brightness; the numeric
@@ -205,14 +208,63 @@ export class ConfigSettingString extends ConfigSett
export const batteryDisplayModeSetting = new ConfigSettingEnum({
id: "batteryDisplayMode",
- label: "Battery display",
+ label: "Style",
storageKey: "dashboard.systemCard.batteryDisplayMode",
- defaultValue: "icon",
- values: ["icon", "percentage"],
+ defaultValue: "stacked",
+ values: ["icon", "percentage", "stacked", "stacked-percentage"],
formatValue: batteryDisplayModeLabel,
- description: "How the top bar shows the phone and glasses battery levels: a small gauge icon or an exact percentage.",
+ description: "How the top bar shows battery levels: a gauge icon or exact percentage beside the label, or a compact gauge or percentage with the label stacked above it.",
});
+/** Below this charge level a "Below 50%" indicator becomes visible. */
+export const BATTERY_LOW_VISIBILITY_THRESHOLD = 50;
+
+function batteryVisibilitySetting(
+ id: string,
+ device: string,
+ storageKey: string,
+): ConfigSettingEnum {
+ return new ConfigSettingEnum({
+ id,
+ label: device,
+ storageKey,
+ defaultValue: "always",
+ values: ["always", "low", "never"],
+ formatValue: batteryIndicatorVisibilityLabel,
+ description: `When the top bar shows the ${device} battery: always, only once it drops below ${BATTERY_LOW_VISIBILITY_THRESHOLD}%, or never.`,
+ });
+}
+
+export const phoneBatteryVisibilitySetting = batteryVisibilitySetting(
+ "phoneBatteryVisibility", "Phone", "display.battery.phoneVisibility",
+);
+export const glassesBatteryVisibilitySetting = batteryVisibilitySetting(
+ "glassesBatteryVisibility", "G2", "display.battery.glassesVisibility",
+);
+export const ringBatteryVisibilitySetting = batteryVisibilitySetting(
+ "ringBatteryVisibility", "R1", "display.battery.ringVisibility",
+);
+
+/** Whether an indicator with this visibility setting shows at the given charge. */
+export function batteryIndicatorVisible(visibility: BatteryIndicatorVisibility, percent: number): boolean {
+ if (visibility === "never") return false;
+ if (visibility === "always") return true;
+ return percent < BATTERY_LOW_VISIBILITY_THRESHOLD;
+}
+
+/**
+ * One string summarizing every setting the top-bar battery block reads, so
+ * the shell can cheaply tell whether a settings change needs a repaint.
+ */
+export function batteryIndicatorSettingsKey(): string {
+ return [
+ batteryDisplayModeSetting.get(),
+ phoneBatteryVisibilitySetting.get(),
+ glassesBatteryVisibilitySetting.get(),
+ ringBatteryVisibilitySetting.get(),
+ ].join("|");
+}
+
export const timeFormatSetting = new ConfigSettingEnum({
id: "timeFormat",
label: "Time format",
@@ -285,6 +337,17 @@ export const lockScreenEnabledSetting = new ConfigSettingBoolean({
// Phone display: the phone app's mirror of the glasses screen and the
// controls around it on the main page.
export type PreviewColor = "white" | "green";
+export type PhoneRotation = "auto" | "portrait" | "landscape";
+
+export const phoneRotationSetting = new ConfigSettingEnum({
+ id: "phone-rotation",
+ label: "Rotation",
+ storageKey: "phone.rotation",
+ defaultValue: "auto",
+ values: ["auto", "portrait", "landscape"],
+ formatValue: (value) => ({ auto: "Auto-Rotate", portrait: "Always Portrait", landscape: "Always Landscape" })[value],
+ description: "Automatically rotate with the phone, or keep the phone app in portrait or landscape. Auto-Rotate follows the phone's system rotation preference.",
+});
export const previewColorSetting = new ConfigSettingEnum({
id: "preview-color",
@@ -363,9 +426,43 @@ export const verticalPositionSetting = new ConfigSettingEnum({
values: ["top", "upper", "middle", "lower", "bottom"],
formatValue: (value) => VERTICAL_POSITION_LABELS[value] ?? value,
description:
- "Where standard (reduced-height) windows sit vertically within the display area, to position them within your field of view. Full-height windows such as terminal views always use the whole screen.",
+ "Where standard (reduced-height) windows sit vertically within the display area, to position them within your field of view. Full-height windows use the whole screen. Navigate and Terminal can override these display settings.",
});
+/** Per-app layouts can inherit the display preferences or choose their own size. */
+export type AppDisplayMode = "default" | "global" | DisplayModeSetting;
+
+function appDisplayModeSetting(appId: string, defaultValue: AppDisplayMode): ConfigSettingEnum {
+ return new ConfigSettingEnum({
+ id: `${appId}-display-mode`,
+ label: "Display mode",
+ storageKey: `${appId}.displayMode`,
+ defaultValue,
+ values: appId === "terminal" ? ["default", "global", ...DISPLAY_MODE_VALUES] : ["global", ...DISPLAY_MODE_VALUES],
+ formatValue: (value) => value === "default" ? "Tall sessions (default)" : value === "global" ? "Use global" : displayModeLabel(value),
+ description: appId === "terminal"
+ ? "Screen size for Terminal. The default keeps session windows tall and the terminals list at the global size. Use global follows Display settings for all Terminal windows. Resizing an open session reconnects its view at the new size."
+ : "Screen size for Navigate. Choose Band to leave more of your field of view clear, or Use global to follow Display settings. Applies to the current route too.",
+ });
+}
+
+function appVerticalPositionSetting(appId: string): ConfigSettingEnum<"global" | VerticalPosition> {
+ return new ConfigSettingEnum<"global" | VerticalPosition>({
+ id: `${appId}-vertical-position`,
+ label: "Vertical position",
+ storageKey: `${appId}.verticalPosition`,
+ defaultValue: "global",
+ values: ["global", "top", "upper", "middle", "lower", "bottom"],
+ formatValue: (value) => value === "global" ? "Use global" : VERTICAL_POSITION_LABELS[value],
+ description: "Where reduced-height windows for this app sit in your field of view. Use global follows Display settings. Full-height windows fill the display vertically.",
+ });
+}
+
+export const navigateDisplayModeSetting = appDisplayModeSetting("navigate", "global");
+export const navigateVerticalPositionSetting = appVerticalPositionSetting("navigate");
+export const terminalDisplayModeSetting = appDisplayModeSetting("terminal", "default");
+export const terminalVerticalPositionSetting = appVerticalPositionSetting("terminal");
+
export const voiceControlEnabledSetting = new ConfigSettingBoolean({
id: "voice-control-enabled",
label: "Enable",
@@ -399,6 +496,15 @@ export const useMicControlSetting = new ConfigSettingBoolean({
"Use the custom firmware's per-temple mic-control channel (caps token micctl) for the Microphones app's array capture. When off, behave as if the firmware doesn't have the feature and use the standard single mixed stream.",
});
+export const showBleBandwidthSetting = new ConfigSettingBoolean({
+ id: "show-ble-bandwidth",
+ label: "Show BLE bandwidth usage",
+ storageKey: "developer.showBleBandwidth",
+ defaultValue: false,
+ description:
+ "Show a running total of Bluetooth messages and bytes sent, at the bottom of the phone app's main screen.",
+});
+
export type RingConnectionMode = "glasses" | "direct";
export const ringConnectionModeSetting = new ConfigSettingEnum({
@@ -712,6 +818,138 @@ export const nightscoutApiTokenSetting = new ConfigSettingString({
description: "Access token for the Nightscout site's API.",
});
+function nightscoutThresholdSetting(id: string, label: string, unit: string, description: string): ConfigSettingString {
+ return new ConfigSettingString({
+ id: `nightscout-${id}`,
+ label,
+ storageKey: `integrations.nightscout.${id}`,
+ defaultValue: "0",
+ editorTitle: `${label} (${unit}; 0 = off)`,
+ normalize: normalizeNightscoutThreshold,
+ formatValue: (value) => Number(value) > 0 ? `${value} ${unit}` : "Off",
+ description: `${description} Enter 0 to disable.`,
+ });
+}
+
+export const nightscoutMaxCannulaAgeSetting = nightscoutThresholdSetting(
+ "max-cannula-age-hours", "Max cannula age", "h", "Warn when time since the last site change exceeds this many hours.",
+);
+export const nightscoutCartridgeLowSetting = nightscoutThresholdSetting(
+ "cartridge-low-units", "Cartridge low threshold", "U", "Warn when the pump reservoir falls below this many units.",
+);
+export const nightscoutBatteryLowSetting = nightscoutThresholdSetting(
+ "battery-low-voltage", "Battery voltage threshold", "V", "Warn when pump battery voltage falls below this value.",
+);
+export const nightscoutMaxLoopAgeSetting = nightscoutThresholdSetting(
+ "max-loop-age-minutes", "Max time since last loop", "min", "Warn when time since the last loop exceeds this many minutes.",
+);
+export const nightscoutAlwaysShowInTopBarSetting = new ConfigSettingBoolean({
+ id: "nightscout-always-show-in-top-bar",
+ label: "Always show in top bar",
+ storageKey: "integrations.nightscout.alwaysShowInTopBar",
+ defaultValue: false,
+ description: "Keep the Nightscout glucose graph and warnings in the top bar even when all Nightscout windows are closed.",
+});
+
+export function loadNightscoutThresholds(): NightscoutThresholds {
+ return {
+ maxCannulaAgeHours: Number(nightscoutMaxCannulaAgeSetting.get()),
+ cartridgeLowUnits: Number(nightscoutCartridgeLowSetting.get()),
+ batteryLowVoltage: Number(nightscoutBatteryLowSetting.get()),
+ maxLoopAgeMinutes: Number(nightscoutMaxLoopAgeSetting.get()),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Navigate app: saved and recent destinations.
+
+const stripControlChars = (value: string | null | undefined): string =>
+ (value ?? "").replace(/[\x00-\x1f]+/g, "").trim();
+
+export const navigateHomeAddressSetting = new ConfigSettingString({
+ id: "navigate-home-address",
+ label: "Home address",
+ storageKey: "navigate.homeAddress",
+ defaultValue: "",
+ editorTitle: "Home address",
+ glassesEditTitle: "Set Home address",
+ normalize: stripControlChars,
+ formatValue: emptySettingDisplay,
+ description: "Address (or place name) the Navigate app's Home destination routes to.",
+});
+
+export const navigateWorkAddressSetting = new ConfigSettingString({
+ id: "navigate-work-address",
+ label: "Work address",
+ storageKey: "navigate.workAddress",
+ defaultValue: "",
+ editorTitle: "Work address",
+ glassesEditTitle: "Set Work address",
+ normalize: stripControlChars,
+ formatValue: emptySettingDisplay,
+ description: "Address (or place name) the Navigate app's Work destination routes to.",
+});
+
+export const navigateRememberRecentSetting = new ConfigSettingBoolean({
+ id: "navigate-remember-recent",
+ label: "Remember recent destinations",
+ storageKey: "navigate.rememberRecent",
+ defaultValue: true,
+ description:
+ "Keep a short list of places you have navigated to, offered as destinations on the Navigate app's start page. Turning this off clears the list.",
+});
+
+/**
+ * Custom named destinations beyond Home and Work, as a JSON array of
+ * {id, name, address}. Managed inside the Navigate app (its context menu),
+ * not listed in the Settings app.
+ */
+export const navigateSavedDestinationsSetting = new ConfigSettingString({
+ id: "navigate-saved-destinations",
+ label: "Saved destinations",
+ storageKey: "navigate.savedDestinations",
+ defaultValue: "[]",
+});
+
+/**
+ * Recently navigated-to places, as a JSON array of {name, place, longitude,
+ * latitude, atMs}, most recent first. Written by the Navigate app when
+ * navigateRememberRecentSetting is on.
+ */
+export const navigateRecentDestinationsSetting = new ConfigSettingString({
+ id: "navigate-recent-destinations",
+ label: "Recent destinations",
+ storageKey: "navigate.recentDestinations",
+ defaultValue: "[]",
+});
+
+/**
+ * Staging buffers for the Navigate app's add/edit-destination flow: the
+ * worker asks the shell to open the phone text editor on one of these, the
+ * user types (or dictates) the name/address, and the worker reads the draft
+ * when the user confirms on the glasses. Deliberately not listed in the
+ * Settings app.
+ */
+export const navigateDestinationNameDraftSetting = new ConfigSettingString({
+ id: "navigate-destination-name-draft",
+ label: "Destination name",
+ storageKey: "navigate.destinationNameDraft",
+ defaultValue: "",
+ editorTitle: "Destination name (e.g. Gym)",
+ glassesEditTitle: "Destination name",
+ normalize: stripControlChars,
+});
+
+export const navigateDestinationAddressDraftSetting = new ConfigSettingString({
+ id: "navigate-destination-address-draft",
+ label: "Destination address",
+ storageKey: "navigate.destinationAddressDraft",
+ defaultValue: "",
+ editorTitle: "Destination address or place name",
+ glassesEditTitle: "Destination address",
+ normalize: stripControlChars,
+});
+
export function screenTimeoutSettingToMs(value: ScreenTimeoutSetting): number | null {
switch (value) {
@@ -742,7 +980,16 @@ export function screenTimeoutLabel(value: ScreenTimeoutSetting): string {
}
export function batteryDisplayModeLabel(value: BatteryDisplayMode): string {
- return value === "icon" ? "Icon" : "Percentage";
+ if (value === "percentage") return "Percentage";
+ if (value === "stacked") return "Stacked";
+ if (value === "stacked-percentage") return "Stacked percentage";
+ return "Icon";
+}
+
+export function batteryIndicatorVisibilityLabel(value: BatteryIndicatorVisibility): string {
+ if (value === "never") return "Never";
+ if (value === "low") return `Below ${BATTERY_LOW_VISIBILITY_THRESHOLD}%`;
+ return "Always";
}
export function timeFormatLabel(value: TimeFormat): string {
diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts
index 176bf28a..790941d3 100644
--- a/app/ui/dashboard/settings-menus.ts
+++ b/app/ui/dashboard/settings-menus.ts
@@ -35,18 +35,30 @@ import {
assistantSkipConfirmationSetting,
batteryDisplayModeSetting,
brightnessSetting,
+ glassesBatteryVisibilitySetting,
+ phoneBatteryVisibilitySetting,
+ ringBatteryVisibilitySetting,
displayModeSetting,
+ navigateDisplayModeSetting,
+ navigateVerticalPositionSetting,
+ terminalDisplayModeSetting,
+ terminalVerticalPositionSetting,
elevenLabsApiKeySetting,
mapboxApiKeySetting,
mirrorTouchSetting,
+ navigateHomeAddressSetting,
+ navigateRememberRecentSetting,
+ navigateWorkAddressSetting,
openAiApiKeySetting,
previewColorSetting,
+ phoneRotationSetting,
ringConnectionModeSetting,
sonioxApiKeySetting,
enumSettingMenuItem,
firmwareDebugFlagsSetting,
lockScreenEnabledSetting,
saveVoiceRecordingsSetting,
+ showBleBandwidthSetting,
suspendEvenHubWhenScreenOffSetting,
terminalAutoReconnectSetting,
terminalLaunchPresetsSetting,
@@ -64,8 +76,9 @@ import {
watchMirrorAssistantSetting,
watchRemoteEnabledSetting,
} from "../dashboard-settings";
+import { clearRecentDestinations } from "../../apps/navigate/destinations";
import { wearBridge } from "../../native/wear-bridge";
-import { SettingsPanelLayer, type SettingsSection } from "./settings-panel";
+import { openSettingsSubMenu, SettingsPanelLayer, type SettingsSection } from "./settings-panel";
import { terminalFontPickerMenuItem, uiFontPickerMenuItem } from "../font-picker";
/** The Settings app's master-detail panel (sections on the left, contents on the right). */
@@ -92,8 +105,8 @@ function settingsSections(): SettingsSection[] {
enumSettingMenuItem(verticalPositionSetting),
// Band / tall / full-panel; the dashboard controller reflows windows.
enumSettingMenuItem(displayModeSetting),
- // Controls the top-bar battery indicators (icon vs percentage).
- enumSettingMenuItem(batteryDisplayModeSetting),
+ // Submenu: top-bar battery indicator style plus per-device visibility.
+ batteryIndicatorsMenuItem(),
// Controls the top-bar clock (24-hour vs 12-hour).
enumSettingMenuItem(timeFormatSetting),
// Opens the modal font picker (face, weight, size) for UI text.
@@ -139,17 +152,36 @@ function settingsSections(): SettingsSection[] {
// Connections (g2mirror:// strings) are managed inside the Terminal
// app's Manage Connections section, not here.
items: [
+ enumSettingMenuItem(terminalDisplayModeSetting),
+ enumSettingMenuItem(terminalVerticalPositionSetting),
terminalFontPickerMenuItem(),
textSettingMenuItem(terminalLaunchPresetsSetting),
toggleSettingMenuItem(terminalAutoReconnectSetting),
toggleSettingMenuItem(terminalWakeOnBellSetting),
],
},
+ {
+ label: "Navigate",
+ // Home/Work are plain addresses; other named destinations (and the
+ // recent list) are managed inside the Navigate app's context menu.
+ items: [
+ enumSettingMenuItem(navigateDisplayModeSetting),
+ enumSettingMenuItem(navigateVerticalPositionSetting),
+ textSettingMenuItem(navigateHomeAddressSetting),
+ textSettingMenuItem(navigateWorkAddressSetting),
+ toggleSettingMenuItem(navigateRememberRecentSetting, {
+ onChange: (_ctx, enabled) => {
+ if (!enabled) clearRecentDestinations();
+ },
+ }),
+ ],
+ },
{
label: "Phone display",
// The phone app's mirror of the glasses screen and its controls
// (app/phone-ui/): all read live by the main page.
items: [
+ enumSettingMenuItem(phoneRotationSetting),
enumSettingMenuItem(previewColorSetting),
toggleSettingMenuItem(mirrorTouchSetting),
],
@@ -176,6 +208,7 @@ function settingsSections(): SettingsSection[] {
toggleSettingMenuItem(firmwareDebugFlagsSetting),
toggleSettingMenuItem(suspendEvenHubWhenScreenOffSetting),
toggleSettingMenuItem(useMicControlSetting),
+ toggleSettingMenuItem(showBleBandwidthSetting),
],
},
{
@@ -206,6 +239,38 @@ function settingsSections(): SettingsSection[] {
];
}
+/**
+ * The Display section's "Battery indicators" row: opens a modal submenu with
+ * the style (icon / percentage / stacked) and, per device, when its
+ * indicator is visible. The row itself shows the current style.
+ */
+function batteryIndicatorsMenuItem(): MenuItem {
+ return {
+ label: "Battery indicators",
+ description:
+ "Top-bar battery indicators for the phone, glasses, and ring: their style, and whether each shows always, only when low, or never.",
+ onSelect: (ctx) => {
+ openSettingsSubMenu(ctx, "Battery indicators", [
+ enumSettingMenuItem(batteryDisplayModeSetting),
+ enumSettingMenuItem(phoneBatteryVisibilitySetting),
+ enumSettingMenuItem(glassesBatteryVisibilitySetting),
+ enumSettingMenuItem(ringBatteryVisibilitySetting),
+ ]);
+ },
+ render: ({ image, x, y, width }) => {
+ drawRightValueMenuItem(
+ image,
+ getDefaultSmallFont(),
+ x,
+ y,
+ width,
+ "Battery indicators",
+ batteryDisplayModeSetting.displayValue(),
+ );
+ },
+ };
+}
+
const LOCAL_MODEL_GB = `${(LOCAL_MODEL.sizeBytes / 1e9).toFixed(1)}GB`;
// While a download is running, re-render on progress updates so the row's
diff --git a/app/ui/font-picker.ts b/app/ui/font-picker.ts
index 72b8adc4..70b113ca 100644
--- a/app/ui/font-picker.ts
+++ b/app/ui/font-picker.ts
@@ -27,7 +27,7 @@ import { drawRightValueMenuItem, drawSelectionHighlight, openModalMenu, type Men
import { LIST_ROW_TEXT_INSET, listRowHeight } from "./metrics";
import type { Layer, LayerContext } from "./layers";
-const SIZE_CHOICES = [12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
+const SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
const DEFAULT_TTF_SIZE = 16;
const PREVIEW_TEXT = "The quick brown fox jumps over 0123456789";
@@ -35,10 +35,10 @@ type FontPickerOptions = {
title: string;
/** Only offer faces where every style is monospace (terminal picker). */
monospaceOnly: boolean;
- /** When set, sizes where this returns false are disabled (and drafts are
+ /** When set, sizes where this returns false are hidden (and drafts are
* clamped to an allowed size on face/weight changes). The UI-font picker
* uses it to keep getDefaultSmallFont's line height within its guaranteed
- * 12..21px range; the terminal picker has no such bound. */
+ * 8..21px range; the terminal picker has no such bound. */
sizeAllowed?: (path: string, size: number) => boolean;
/** Bitmap faces offered ahead of the installed TTF families. */
bitmapFaces: readonly { face: BitmapFace; label: string }[];
@@ -217,10 +217,10 @@ export class FontPickerLayer implements Layer {
openModalMenu(ctx, "Font Face", items, Math.max(0, currentIndex));
}
- /** Switch families, carrying the weight (nearest available) and size over. */
+ /** Switch families, preferring Light (nearest available) and carrying the size over. */
private setFamily(family: FontFamily): void {
const previous = this.draft;
- const targetOrder = previous.kind === "ttf" ? previous.font.weightOrder : 400;
+ const targetOrder = 300;
const size = previous.kind === "ttf" ? previous.size : DEFAULT_TTF_SIZE;
let font = family.fonts[0]!;
for (const candidate of family.fonts) {
@@ -262,15 +262,17 @@ export class FontPickerLayer implements Layer {
private openSizeMenu(ctx: LayerContext): void {
if (this.draft.kind !== "ttf") return;
const draft = this.draft;
- const items = SIZE_CHOICES.map((size): MenuItem => ({
+ const sizes = SIZE_CHOICES.filter((size) =>
+ this.options.sizeAllowed === undefined || this.options.sizeAllowed(draft.font.path, size),
+ );
+ const items = sizes.map((size): MenuItem => ({
label: String(size),
- disabled: () => this.options.sizeAllowed !== undefined && !this.options.sizeAllowed(draft.font.path, size),
onSelect: (innerCtx) => {
this.draft = { ...draft, size };
innerCtx.stack.pop();
},
}));
- openModalMenu(ctx, "Size", items, Math.max(0, SIZE_CHOICES.indexOf(draft.size as (typeof SIZE_CHOICES)[number])));
+ openModalMenu(ctx, "Size", items, Math.max(0, sizes.indexOf(draft.size as (typeof SIZE_CHOICES)[number])));
}
}
diff --git a/app/ui/gestures.ts b/app/ui/gestures.ts
index 810d14a7..87bc99ab 100644
--- a/app/ui/gestures.ts
+++ b/app/ui/gestures.ts
@@ -25,6 +25,15 @@ export type InputEventPayload =
| { type: "scroll-down"; source?: InputSource }
| { type: "long-press"; source: InputSource }
| { type: "long-press-release"; source: InputSource }
+ /** G2 2.2.9 tap-then-hold gesture: the app context-menu gesture (long-press is the system menu's). */
+ | { type: "short-then-long-press"; source: InputSource }
+ /**
+ * Not a gesture: a shell -> foreground-window notification that the shell
+ * opened its system context menu over the window. An app with its own
+ * context menu up closes it in response, so the two menus never stack.
+ * Everything else ignores it.
+ */
+ | { type: "system-menu-opened" }
/**
* Spatial (four-way) input, which only a watch can produce: the ring's
* scroll is a one-dimensional cursor, these are directions. Components with
@@ -105,14 +114,17 @@ export function directionalFallback(event: InputEvent): InputEvent {
* click ● (U+00B7 middle dot)
* double-click ●● (twice)
* scroll ▲▼ (U+25B2 / U+25BC)
- * long-press - (hyphen-minus)
+ * long-press — (em dash)
+ * tap-then-hold ●— (click then long-press)
*/
export const GESTURE_CLICK = "\u25cf";
export const GESTURE_DOUBLE_CLICK = GESTURE_CLICK+GESTURE_CLICK;
export const GESTURE_SCROLL_UP = "▲";
export const GESTURE_SCROLL_DOWN = "▼";
export const GESTURE_SCROLL = "▲▼";
-export const GESTURE_LONG_PRESS = "-";
+export const GESTURE_LONG_PRESS = "—";
+/** The 2.2.9 tap-then-hold gesture (short-then-long-press): a click glyph then a hold. */
+export const GESTURE_SHORT_THEN_LONG_PRESS = GESTURE_CLICK + GESTURE_LONG_PRESS;
/**
* Join "glyph action" hint pairs into a single line, e.g.
diff --git a/app/ui/layers.ts b/app/ui/layers.ts
index 2e903387..50ad0473 100644
--- a/app/ui/layers.ts
+++ b/app/ui/layers.ts
@@ -1,5 +1,5 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
-import { type Plane } from "../graphics/plane";
+import { dimPlanes, type Plane } from "../graphics/plane";
import { spanCurrent } from "../native/frame-timings";
import { type ConfigSettingBoolean, type ConfigSettingString } from "./dashboard-settings";
import { directionalFallback, isDirectionalInput, type InputEvent } from "./gestures";
@@ -80,6 +80,15 @@ export interface LayerContext {
export interface Layer {
readonly paintOverBase?: boolean;
+ /**
+ * Dim everything painted beneath this layer: a 0..1 brightness factor
+ * applied to the pixels and glyphs of every plane below it in the stack
+ * (only meaningful for layers that call paintBelow). false, the default,
+ * leaves the planes below as painted. For the shell's stack the factor also
+ * reaches the window surfaces beneath the shell surface (see
+ * LayerStack.baseDim).
+ */
+ readonly dimUnderneath?: false | number;
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage;
handleInput(event: InputEvent, ctx: LayerContext): Promise | void;
/**
@@ -110,6 +119,7 @@ export class LayerStack {
private baseWidth: number;
private baseHeight: number;
private readonly focusedFn: () => boolean;
+ private lastBaseDim: number | false = 1;
constructor(
baseLayer: Layer,
@@ -203,7 +213,19 @@ export class LayerStack {
* PaintBelow). All planes share the stack's base size at offset (0, 0).
*/
paint(): Plane[] {
- return this.paintLayer(this.layers.length - 1);
+ this.lastBaseDim = false;
+ return this.paintLayer(this.layers.length - 1, 1);
+ }
+
+ /**
+ * The brightness factor the last paint applied to the base plane: 1 when
+ * nothing dims it, a smaller factor under a layer with dimUnderneath, and
+ * false when the base was not painted at all (a stacked layer replaced it).
+ * A stack whose base is transparent over something else (the shell chrome
+ * over the window surfaces) forwards this to what lies beneath.
+ */
+ baseDim(): number | false {
+ return this.lastBaseDim;
}
async handleInput(event: InputEvent): Promise {
@@ -235,7 +257,8 @@ export class LayerStack {
}
- private paintLayer(index: number): Plane[] {
+ /** Paint layer `index`; `dimSoFar` is the factor the layers above apply to it. */
+ private paintLayer(index: number, dimSoFar: number): Plane[] {
const layer = this.layers[index]!;
let canvas: GrayImage | null = null;
let belowRequested = false;
@@ -249,10 +272,15 @@ export class LayerStack {
}),
);
const ownPlane: Plane = { image, x: 0, y: 0 };
- if (index <= 0 || !belowRequested) {
+ if (index <= 0) {
+ this.lastBaseDim = dimSoFar;
return [ownPlane];
}
- const below = layer.paintOverBase ? this.paintLayer(0) : this.paintLayer(index - 1);
- return [...below, ownPlane];
+ if (!belowRequested) {
+ return [ownPlane];
+ }
+ const dim = layer.dimUnderneath || 1;
+ const below = this.paintLayer(layer.paintOverBase ? 0 : index - 1, dimSoFar * dim);
+ return [...(dim < 1 ? dimPlanes(below, dim) : below), ownPlane];
}
}
diff --git a/app/ui/menu.ts b/app/ui/menu.ts
index a4dfaff3..199b51a1 100644
--- a/app/ui/menu.ts
+++ b/app/ui/menu.ts
@@ -13,11 +13,14 @@ const DEFAULT_MENU_WIDTH = 272;
// fixed quarter-screen-era look) up to the full screen, then scroll.
const DEFAULT_MENU_MIN_HEIGHT = G2_LENS_HEIGHT / 2 - 2 * DEFAULT_MENU_Y;
const MENU_BODY_PADDING = 8;
+/** Gap between the last item row and a footer hint line. */
+const MENU_FOOTER_GAP = 8;
const MENU_HIGHLIGHT_SELECTED_BACKGROUND_FILL = 15;
const MENU_HIGHLIGHT_SELECTED_BORDER_STROKE = 45;
export type MenuLayout = {
- x: number;
+ /** Left edge, or "center" to center horizontally on the painted surface. */
+ x: number | "center";
y: number;
width: number;
/** Whether to draw the rounded outline around the menu. Default: true. */
@@ -26,6 +29,13 @@ export type MenuLayout = {
minHeight?: number;
/** Height cap before the menu starts scrolling. Default: the full screen. */
maxHeight?: number;
+ /**
+ * Dim hint line pinned to the bottom edge inside the box, below the items
+ * (gesture help such as "●— system menu"). Takes a line off the item area.
+ */
+ footer?: string;
+ /** Brightness factor for everything beneath the menu (see Layer.dimUnderneath). Default: none. */
+ dimUnderneath?: number;
/**
* Paint as a standalone page: the layers below stay in the stack for back
* navigation but are not composited underneath. Default: false — the menu
@@ -174,10 +184,17 @@ export function drawRightValueMenuItem(
image.drawText(font, valueX, y + LIST_ROW_TEXT_INSET, value, 220);
}
+/** How far context menus (window and system) dim the content beneath them. */
+export const CONTEXT_MENU_DIM = 0.25;
+
export class MenuLayer implements Layer {
private selectedIndex = 0;
private scrollRow = 0;
+ get dimUnderneath(): false | number {
+ return this.layout.dimUnderneath ?? false;
+ }
+
constructor(
private readonly title: string | null,
private readonly items: MenuItem[],
@@ -200,7 +217,8 @@ export class MenuLayer implements Layer {
const rowHeight = listRowHeight(font);
const base = ctx.stack.getBaseSize();
const image = this.layout.opaque ? new GrayImage(base.width, base.height, 0) : paintBelow();
- const { x, y, width } = this.layout;
+ const { y, width } = this.layout;
+ const x = this.layout.x === "center" ? ((image.width - width) / 2) | 0 : this.layout.x;
const chromeTop = (this.title ? menuTitleHeight(font) : 0) + MENU_BODY_PADDING;
const minHeight = this.layout.minHeight ?? DEFAULT_MENU_MIN_HEIGHT;
// Cap to the surface being painted on: a window's stack image may be much
@@ -209,9 +227,13 @@ export class MenuLayer implements Layer {
this.layout.maxHeight ?? image.height - y - DEFAULT_MENU_Y,
image.height - y,
);
- const contentHeight = chromeTop + this.items.length * rowHeight + MENU_BODY_PADDING;
+ const footerHeight = this.layout.footer ? MENU_FOOTER_GAP + lineStep(font) : 0;
+ const contentHeight = chromeTop + this.items.length * rowHeight + footerHeight + MENU_BODY_PADDING;
const height = clamp(contentHeight, Math.min(minHeight, maxHeight), maxHeight);
- const visibleRowCount = Math.max(1, ((height - chromeTop - MENU_BODY_PADDING) / rowHeight) | 0);
+ const visibleRowCount = Math.max(
+ 1,
+ ((height - chromeTop - footerHeight - MENU_BODY_PADDING) / rowHeight) | 0,
+ );
this.scrollRow = scrollToKeepSelectionVisible(
this.scrollRow,
this.selectedIndex,
@@ -228,6 +250,9 @@ export class MenuLayer implements Layer {
if (this.title) {
image.drawText(font, x + 12, y + 8, this.title, 220);
}
+ if (this.layout.footer) {
+ image.drawText(font, x + 22, y + height - MENU_BODY_PADDING - font.lineHeight, this.layout.footer, 110);
+ }
const bodyY = y + chromeTop;
const focused = ctx.stack.isFocused();
diff --git a/app/ui/metrics.ts b/app/ui/metrics.ts
index 2dc19a20..4c99f4d6 100644
--- a/app/ui/metrics.ts
+++ b/app/ui/metrics.ts
@@ -2,7 +2,7 @@
* Font-derived layout metrics for list-style UIs, so row spacing, selection
* highlights, and text line steps track the user's font size instead of
* assuming the 12px bitmap default. The font picker guarantees
- * getDefaultSmallFont's lineHeight is 12..21px (and getDefaultMediumFont's
+ * getDefaultSmallFont's lineHeight is 8..21px (and getDefaultMediumFont's
* 16..29px — see ui-fonts.ts), so layouts driven by these helpers have
* bounded growth.
*
diff --git a/app/ui/notification-filter.ts b/app/ui/notification-filter.ts
new file mode 100644
index 00000000..93bb9144
--- /dev/null
+++ b/app/ui/notification-filter.ts
@@ -0,0 +1,50 @@
+import { getDefaultSmallFont } from "../graphics/ui-fonts";
+import { GrayImage } from "../graphics/image";
+import { truncateText } from "../graphics/textwrap";
+import { ALL_NOTIFICATIONS, readActiveNotifications } from "../native/notification-icons";
+import { readNotificationSources, setNotificationSourceEnabled, shouldShowNotificationOnGlasses } from "../native/notification-sources";
+import { type InputEvent } from "./gestures";
+import { type Layer, type LayerContext, type PaintBelow } from "./layers";
+import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu";
+
+/** Rebuild rows when new sources arrive, keeping the current selection by package. */
+export class NotificationFilterLayer implements Layer {
+ private menu: MenuLayer | null = null;
+ private packages = "";
+ private selectedPackage = "";
+
+ private currentMenu(ctx: LayerContext): MenuLayer {
+ readActiveNotifications(ALL_NOTIFICATIONS);
+ const sources = readNotificationSources().sort((a, b) =>
+ a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
+ const signature = JSON.stringify([ctx.stack.getBaseSize().width, sources.map((source) => [source.packageName, source.appName])]);
+ if (!this.menu || signature !== this.packages) {
+ this.packages = signature;
+ const items: MenuItem[] = sources.map((source) => ({
+ label: source.appName,
+ onSelect: () => setNotificationSourceEnabled(source, !shouldShowNotificationOnGlasses(source.packageName)),
+ render: ({ image, x, y, width, selected }) => {
+ if (selected) this.selectedPackage = source.packageName;
+ const font = getDefaultSmallFont();
+ drawToggleMenuItem(image, font, x, y, width, truncateText(font, source.appName, width - 48),
+ shouldShowNotificationOnGlasses(source.packageName), selected);
+ },
+ }));
+ if (!items.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} });
+ this.menu = new MenuLayer("Notification filter", items, {
+ x: 8, y: 8, width: ctx.stack.getBaseSize().width - 16,
+ opaque: true, showBorder: false,
+ footer: "On = show popups on glasses",
+ }).selectItem(Math.max(0, sources.findIndex((source) => source.packageName === this.selectedPackage)));
+ }
+ return this.menu;
+ }
+
+ paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
+ return this.currentMenu(ctx).paint(ctx, paintBelow);
+ }
+
+ async handleInput(event: InputEvent, ctx: LayerContext): Promise {
+ await this.currentMenu(ctx).handleInput(event, ctx);
+ }
+}
diff --git a/app/ui/notifications.ts b/app/ui/notifications.ts
index d60602c3..647ffb58 100644
--- a/app/ui/notifications.ts
+++ b/app/ui/notifications.ts
@@ -6,6 +6,7 @@ import { GrayImage, type UiFont } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { lineStep, listRowHeight } from "./metrics";
import {
+ ALL_NOTIFICATIONS,
dismissNotification,
invokeNotificationAction,
readActiveNotifications,
@@ -13,10 +14,12 @@ import {
type AndroidNotification,
type AndroidNotificationAction,
} from "../native/notification-icons";
+import { setNotificationSourceEnabled } from "../native/notification-sources";
import { isNotificationListenerEnabled } from "../native/notification-access";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-freshness";
import { type InputEvent } from "./gestures";
import { type Layer, type LayerContext, type PaintBelow } from "./layers";
+import { MenuLayer } from "./menu";
const PAGE_X = 12;
const PAGE_Y = 12;
@@ -52,7 +55,8 @@ type CardLayout = {
type DetailMenuItem =
| { kind: "back"; label: string }
| { kind: "action"; label: string; action: AndroidNotificationAction }
- | { kind: "dismiss"; label: string };
+ | { kind: "dismiss"; label: string }
+ | { kind: "disable-source"; label: string };
export type SingleNotificationLayerOrigin = "notifications-list" | "new-notification-modal";
@@ -167,6 +171,7 @@ export class NotificationsListLayer implements Layer {
*/
export class SingleNotificationLayer implements Layer {
private selectedMenuIndex = 0;
+ private confirmation: { source: AndroidNotification; menu: MenuLayer } | null = null;
constructor(
private readonly notificationKey: string,
@@ -174,29 +179,36 @@ export class SingleNotificationLayer implements Layer {
) {}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
+ if (this.confirmation) return this.paintConfirmation(ctx);
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
- const notification = readActiveNotifications(MAX_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
+ const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
if (!notification) {
return this.closeUnavailableNotification(ctx, paintBelow);
}
- const menu = buildDetailMenu(notification);
+ const menu = buildDetailMenu(notification, this.options.origin);
this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, Math.max(0, menu.length - 1));
drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height);
drawDetailMenu(image, font, menu, this.selectedMenuIndex, width);
return image;
}
- handleInput(event: InputEvent, ctx: LayerContext): void {
- const notification = readActiveNotifications(MAX_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
+ async handleInput(event: InputEvent, ctx: LayerContext): Promise {
+ if (this.confirmation) {
+ if (event.type === "double-click") this.close(ctx);
+ else await this.confirmation.menu.handleInput(event, ctx);
+ return;
+ }
+ const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
if (!notification) {
this.closeUnavailableNotification(ctx);
return;
}
- const menu = buildDetailMenu(notification);
+ const menu = buildDetailMenu(notification, this.options.origin);
+ this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, menu.length - 1);
if (event.type === "double-click") {
this.close(ctx);
@@ -217,15 +229,47 @@ export class SingleNotificationLayer implements Layer {
this.close(ctx);
} else if (item.kind === "action") {
invokeNotificationAction(this.notificationKey, item.action.index);
- if (!readActiveNotifications(MAX_NOTIFICATIONS).some((item) => item.key === this.notificationKey)) {
+ if (!readActiveNotifications(ALL_NOTIFICATIONS).some((item) => item.key === this.notificationKey)) {
this.closeUnavailableNotification(ctx);
}
} else if (item.kind === "dismiss") {
dismissNotification(this.notificationKey);
this.closeUnavailableNotification(ctx);
+ } else if (item.kind === "disable-source") {
+ // Keep the modal alive for confirmation even after Android removes the notification.
+ this.confirmation = {
+ source: notification,
+ menu: new MenuLayer(null, [
+ { label: "Cancel", onSelect: () => this.close(ctx) },
+ { label: "Turn off popups", onSelect: () => {
+ setNotificationSourceEnabled(notification, false);
+ this.close(ctx);
+ } },
+ ], { x: 12, y: 0, width: ctx.stack.getBaseSize().width - 24, minHeight: 0, showBorder: false }),
+ };
+ dismissNotification(this.notificationKey);
}
}
+ private paintConfirmation(ctx: LayerContext): GrayImage {
+ const { source, menu } = this.confirmation!;
+ const font = getDefaultSmallFont();
+ const { width, height } = ctx.stack.getBaseSize();
+ const image = new GrayImage(width, height, 0);
+ // Put actions first so they remain reachable even with a large UI font.
+ menu.paint(ctx, () => image);
+ const top = 24 + 2 * listRowHeight(font);
+ const prompt = `Turn off notification popups from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`;
+ const lines = wrapText(font, prompt, width - 48);
+ const maxLines = Math.max(1, Math.floor((height - top - 12) / lineStep(font)));
+ for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
+ const text = index === maxLines - 1 && lines.length > maxLines
+ ? truncateText(font, lines[index] + "...", width - 48) : lines[index]!;
+ image.drawText(font, 24, top + index * lineStep(font), text, 210);
+ }
+ return image;
+ }
+
/** Leave the detail view, whatever hosts it. */
private close(ctx: LayerContext): void {
if (this.options.origin === "new-notification-modal") {
@@ -365,20 +409,35 @@ function drawDetailContent(
function drawDetailMenu(image: GrayImage, font: UiFont, menu: DetailMenuItem[], selectedIndex: number, width: number): void {
const menuX = width - DETAIL_MENU_WIDTH - 24;
const menuY = 24;
- const rowH = listRowHeight(font);
+ const rows = menu.map((item) => {
+ const lines = item.kind === "disable-source"
+ ? wrapText(font, item.label, DETAIL_MENU_WIDTH - 16)
+ : [truncateText(font, item.label, DETAIL_MENU_WIDTH - 16)];
+ return { lines, height: lines.length * lineStep(font) + 8 };
+ });
+ const selectedBottom = rows.slice(0, selectedIndex + 1).reduce((sum, row) => sum + row.height, 0);
+ const scrollY = Math.max(0, selectedBottom - (image.height - menuY - 12));
+ let y = menuY - scrollY;
for (let index = 0; index < menu.length; index++) {
- const y = menuY + index * (rowH + 2);
+ const row = rows[index]!;
+ if (y < menuY) {
+ y += row.height;
+ continue;
+ }
+ if (y + row.height > image.height - 12) break;
const selected = index === selectedIndex;
if (selected) {
- image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, rowH - 1, 18, 6);
- image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, rowH - 1, 60, 6);
+ image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 18, 6);
+ image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 60, 6);
}
- const label = truncateText(font, menu[index]!.label, DETAIL_MENU_WIDTH - 12);
- image.drawText(font, menuX, y + 2, label, selected ? 255 : 185);
+ for (let line = 0; line < row.lines.length; line++) {
+ image.drawText(font, menuX, y + 2 + line * lineStep(font), row.lines[line]!, selected ? 255 : 185);
+ }
+ y += row.height;
}
}
-function buildDetailMenu(notification: AndroidNotification): DetailMenuItem[] {
+function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] {
return [
{ kind: "back", label: "Back" },
...notification.actions.map((action): DetailMenuItem => ({
@@ -387,6 +446,8 @@ function buildDetailMenu(notification: AndroidNotification): DetailMenuItem[] {
action,
})),
{ kind: "dismiss", label: "Dismiss" },
+ ...(origin === "new-notification-modal" && notification.packageName
+ ? [{ kind: "disable-source" as const, label: "Don't show on glasses again" }] : []),
];
}
diff --git a/app/ui/shell/brightness-picker-layer.ts b/app/ui/shell/brightness-picker-layer.ts
new file mode 100644
index 00000000..6ff3108b
--- /dev/null
+++ b/app/ui/shell/brightness-picker-layer.ts
@@ -0,0 +1,66 @@
+import type { GrayImage } from "../../graphics/image";
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { clamp } from "../../util/numeric-util";
+import { brightnessSetting, brightnessSettingToLevel, type BrightnessSetting } from "../dashboard-settings";
+import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, gestureHints, type InputEvent } from "../gestures";
+import type { Layer, LayerContext, PaintBelow } from "../layers";
+import { appViewportRect, SHELL_OPAQUE_BLACK } from "./geometry";
+
+const DIALOG_WIDTH = 272;
+const BAR_WIDTH = 12;
+const BAR_HEIGHT = 100;
+
+/** Manual brightness changes apply immediately so the wearer can judge the level. */
+export class BrightnessPickerLayer implements Layer {
+ constructor(private readonly onClosed: () => void) {}
+
+ onRemoved(): void {
+ this.onClosed();
+ }
+
+ paint(_ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
+ const image = paintBelow();
+ const font = getDefaultSmallFont();
+ const viewport = appViewportRect("min");
+ const height = BAR_HEIGHT + 3 * font.lineHeight + 56;
+ const left = viewport.x + Math.round((viewport.width - DIALOG_WIDTH) / 2);
+ const top = viewport.y + Math.round((viewport.height - height) / 2);
+ image.fillRoundedRect(left, top, DIALOG_WIDTH, height, SHELL_OPAQUE_BLACK, 8);
+ image.drawRoundedRect(left, top, DIALOG_WIDTH, height, 110, 8);
+
+ const centeredText = (text: string, y: number, value: number) => {
+ image.drawText(font, left + Math.round((DIALOG_WIDTH - font.measureText(text)) / 2), y, text, value);
+ };
+ centeredText("Brightness", top + 12, 235);
+ const barX = left + Math.round((DIALOG_WIDTH - BAR_WIDTH) / 2);
+ const barY = top + font.lineHeight + 24;
+ const level = brightnessSettingToLevel(brightnessSetting.get());
+ image.drawRect(barX - 2, barY - 2, BAR_WIDTH + 4, BAR_HEIGHT + 4, 150);
+ const filledHeight = Math.round(BAR_HEIGHT * (level ?? 0) / 100);
+ image.fillRect(barX, barY + BAR_HEIGHT - filledHeight, BAR_WIDTH, filledHeight, 255);
+ image.drawText(font, barX + BAR_WIDTH + 12, barY + Math.round((BAR_HEIGHT - font.lineHeight) / 2),
+ level === null ? "Auto" : `${level}%`, 235);
+ centeredText(gestureHints([[GESTURE_SCROLL, "adjust"]]), barY + BAR_HEIGHT + 12, 150);
+ centeredText(gestureHints([[`${GESTURE_CLICK} / ${GESTURE_DOUBLE_CLICK}`, "confirm"]]),
+ barY + BAR_HEIGHT + font.lineHeight + 16, 150);
+ return image;
+ }
+
+ handleInput(event: InputEvent, ctx: LayerContext): void {
+ switch (event.type) {
+ case "scroll-up":
+ case "scroll-down": {
+ const level = brightnessSettingToLevel(brightnessSetting.get());
+ // Respect Auto if it was enabled on the phone while this dialog was open.
+ if (level === null) return;
+ const next = clamp(level + (event.type === "scroll-up" ? 10 : -10), 0, 100);
+ if (next !== level) brightnessSetting.set(String(next) as BrightnessSetting);
+ return;
+ }
+ case "click":
+ case "double-click":
+ ctx.stack.pop();
+ return;
+ }
+ }
+}
diff --git a/app/ui/shell/chrome-layer.ts b/app/ui/shell/chrome-layer.ts
index 14f5f835..5811997d 100644
--- a/app/ui/shell/chrome-layer.ts
+++ b/app/ui/shell/chrome-layer.ts
@@ -6,8 +6,17 @@ import { BATTERY_ICON_WIDTH, drawBattery } from "../../graphics/battery";
import { readActiveNotificationIcons } from "../../native/notification-icons";
import { readPhoneBatteryState } from "../../native/phone-battery";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
-import { renderIcon, renderIconWithGlyph, type IconName } from "../../graphics/icons";
-import { batteryDisplayModeSetting, timeFormatSetting } from "../dashboard-settings";
+import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons";
+import {
+ batteryDisplayModeSetting,
+ batteryIndicatorVisible,
+ glassesBatteryVisibilitySetting,
+ phoneBatteryVisibilitySetting,
+ ringBatteryVisibilitySetting,
+ timeFormatSetting,
+ type BatteryIndicatorVisibility,
+} from "../dashboard-settings";
+import { getFont } from "../../graphics/bdffont";
import { Layer } from "../layers";
import { scrollToKeepSelectionVisible } from "../menu";
import { lineStep } from "../metrics";
@@ -69,8 +78,8 @@ function slotPosition(variant: SidebarVariant, listTop: number, position: number
}
/** Top y of the sidebar's icon list (below the band's top bar). */
-function sidebarListTop(): number {
- return minWindowTop() + TOP_BAR_HEIGHT + LIST_MARGIN;
+function sidebarListTop(appId?: string): number {
+ return minWindowTop(appId) + TOP_BAR_HEIGHT + LIST_MARGIN;
}
/**
@@ -100,7 +109,8 @@ export type ShellChromeState = {
focus: "sidebar" | "window";
/** Height mode of the foreground window; decides where its top bar sits. */
foregroundHeightMode: WindowHeightMode;
- battery: { headset: number | null; headsetCharging: boolean | null };
+ foregroundAppId?: string;
+ battery: { headset: number | null; headsetCharging: boolean | null; ring: number | null; ringCharging: boolean | null };
/** App-provided tray images, drawn between notification icons and batteries. */
trayIcons: GrayImage[];
};
@@ -143,9 +153,9 @@ function invertedIcon(icon: GrayImage): GrayImage {
}
/** Window icon rendered from an SVG (Lucide), rendered once per size and cached. */
-export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWindow["drawIcon"] {
+export function makeSvgWindowIcon(name: IconName, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
return (image, x, y, size, inverted) => {
- const icon = glyph ? renderIconWithGlyph(name, glyph, size) : renderIcon(name, size);
+ const icon = glyph || activity ? renderIconWithGlyph(name, glyph ?? "", size, activity?.() ?? "idle") : renderIcon(name, size);
if (!icon) return;
const dx = x + Math.max(0, ((size - icon.width) / 2) | 0);
const dy = y + Math.max(0, ((size - icon.height) / 2) | 0);
@@ -154,8 +164,8 @@ export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWi
}
/** SVG icon when a name is given, else the letter placeholder. */
-export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string): ShellChromeWindow["drawIcon"] {
- return icon ? makeSvgWindowIcon(icon, glyph) : makeLetterWindowIcon(letter);
+export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
+ return icon ? makeSvgWindowIcon(icon, glyph, activity) : makeLetterWindowIcon(letter);
}
/** Window icon backed by an arbitrary cached grayscale image renderer. */
@@ -191,7 +201,7 @@ export class ShellChromeLayer implements Layer {
const state = this.getState();
// Full-panel mode: the strip is an overlay, present only while the user
// is in it (the window underneath keeps its full width the rest of the time).
- if (sidebarStripVisible(state.focus)) {
+ if (sidebarStripVisible(state.focus, state.foregroundAppId)) {
this.drawSidebar(image, state);
}
this.drawTopBar(image, state);
@@ -212,7 +222,7 @@ export class ShellChromeLayer implements Layer {
windowIndexAt(x: number, y: number, windowCount: number): number | null {
if (x < 0 || x >= SIDEBAR_WIDTH || windowCount === 0) return null;
const variant = sidebarVariant(windowCount);
- const listTop = sidebarListTop();
+ const listTop = sidebarListTop(this.getState().foregroundAppId);
const lastVisible = Math.min(windowCount, this.scrollRow + rowsPerColumn(variant) * variant.columns);
for (let index = this.scrollRow; index < lastVisible; index++) {
const { column, y: slotY } = slotPosition(variant, listTop, index - this.scrollRow);
@@ -225,10 +235,9 @@ export class ShellChromeLayer implements Layer {
}
private drawSidebar(image: GrayImage, state: ShellChromeState): void {
- // The sidebar always occupies the min-height window band at the preferred
- // vertical position: it never moves when the foreground window's height
- // changes, and it lines up exactly with a min-height window's chrome.
- const bandTop = minWindowTop();
+ // Align the sidebar with the app's preferred band. Legacy tall terminal
+ // sessions keep the sidebar at the global band position.
+ const bandTop = minWindowTop(state.foregroundAppId);
const bandBottom = bandTop + MIN_WINDOW_HEIGHT;
image.fillRect(0, bandTop, SIDEBAR_WIDTH, MIN_WINDOW_HEIGHT, SHELL_OPAQUE_BLACK);
@@ -242,7 +251,7 @@ export class ShellChromeLayer implements Layer {
const iconMarginX = ((variant.columnWidth - iconSize) / 2) | 0;
// Column index of the rightmost column (the one that fills first).
const firstColumn = variant.columns - 1;
- const listTop = sidebarListTop();
+ const listTop = sidebarListTop(state.foregroundAppId);
const visibleCount = rowsPerColumn(variant) * variant.columns;
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, state.selectedIndex, visibleCount, count);
const lastVisible = Math.min(count, this.scrollRow + visibleCount);
@@ -304,10 +313,10 @@ export class ShellChromeLayer implements Layer {
// The bar sits at the top edge of the foreground window's band, wherever
// its height mode puts that (screen top for max height). It moves when
// the foreground switches to a window of a different height.
- const barTop = windowTop(state.foregroundHeightMode);
+ const barTop = windowTop(state.foregroundHeightMode, state.foregroundAppId);
// The bar spans the app viewport; with the sidebar overlaid (full-panel
// mode, sidebar focused) it still starts past the strip.
- const barLeft = sidebarStripVisible(state.focus) ? SIDEBAR_WIDTH : 0;
+ const barLeft = sidebarStripVisible(state.focus, state.foregroundAppId) ? SIDEBAR_WIDTH : 0;
image.fillRect(barLeft, barTop, G2_LENS_WIDTH - barLeft, TOP_BAR_HEIGHT, SHELL_OPAQUE_BLACK);
image.drawLine(barLeft, barTop + TOP_BAR_HEIGHT - 1, G2_LENS_WIDTH - 1, barTop + TOP_BAR_HEIGHT - 1, BORDER_VALUE);
@@ -336,35 +345,46 @@ export class ShellChromeLayer implements Layer {
}
/**
- * Labelled battery indicators for the phone and the G2, right-aligned in
- * the top bar, following the dashboard card's icon/percentage setting.
- * Returns the left edge of the battery block.
+ * Labelled battery indicators for the phone, G2, and R1, right-aligned in
+ * the top bar. The Settings > Display > Battery indicators submenu picks
+ * the style (label beside a gauge icon or percentage, or stacked above
+ * either) and, per device, whether the indicator shows always, only below
+ * 50%, or never. Returns the left edge of the battery block.
*/
private drawTopBarBatteries(image: GrayImage, state: ShellChromeState, barTop: number): number {
- const font = getDefaultSmallFont();
- const percentageMode = batteryDisplayModeSetting.get() === "percentage";
- type BatteryItem = { label: string; percent: number; charging: boolean };
+ const mode = batteryDisplayModeSetting.get();
const items: BatteryItem[] = [];
const phone = readPhoneBatteryState();
if (phone.battery !== null && Number.isFinite(phone.battery)) {
- items.push({ label: "Phone", percent: phone.battery, charging: Boolean(phone.charging) });
+ pushBatteryItem(items, phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, Boolean(phone.charging));
}
if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) {
- items.push({ label: "G2", percent: state.battery.headset, charging: Boolean(state.battery.headsetCharging) });
+ pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", state.battery.headset,
+ Boolean(state.battery.headsetCharging));
+ }
+ if (state.battery.ring !== null && Number.isInteger(state.battery.ring)
+ && state.battery.ring >= 0 && state.battery.ring <= 100) {
+ pushBatteryItem(items, ringBatteryVisibilitySetting.get(), "R1", state.battery.ring,
+ Boolean(state.battery.ringCharging));
}
if (!items.length) return G2_LENS_WIDTH;
+ if (mode === "stacked" || mode === "stacked-percentage") {
+ return drawStackedBatteries(image, items, barTop, mode === "stacked-percentage");
+ }
+ const font = getDefaultSmallFont();
+ const percentageMode = mode === "percentage";
const labelGap = 5;
const itemGap = 12;
const textY = barTop + Math.max(0, ((TOP_BAR_HEIGHT - font.lineHeight) / 2) | 0);
- let x = G2_LENS_WIDTH - 8;
+ let x = G2_LENS_WIDTH - BATTERY_BLOCK_RIGHT_MARGIN;
for (let index = items.length - 1; index >= 0; index--) {
const item = items[index]!;
- const percentText = `${Math.max(0, Math.min(100, Math.round(item.percent)))}%`;
+ const percentText = `${item.percent}%`;
const valueWidth = percentageMode ? font.measureText(percentText) : BATTERY_ICON_WIDTH;
const labelWidth = font.measureText(item.label);
x -= labelWidth + labelGap + valueWidth;
- image.drawText(font, x, textY, item.label, 150);
+ image.drawText(font, x, textY, item.label, BATTERY_LABEL_VALUE);
const valueX = x + labelWidth + labelGap;
if (percentageMode) {
if (item.charging) {
@@ -386,6 +406,74 @@ export class ShellChromeLayer implements Layer {
}
}
+type BatteryItem = { label: string; percent: number; charging: boolean };
+
+const BATTERY_BLOCK_RIGHT_MARGIN = 8;
+const BATTERY_LABEL_VALUE = 150;
+
+/** Append an indicator if its visibility setting shows it at this charge. */
+function pushBatteryItem(
+ items: BatteryItem[],
+ visibility: BatteryIndicatorVisibility,
+ label: string,
+ percent: number,
+ charging: boolean,
+): void {
+ const clamped = Math.max(0, Math.min(100, Math.round(percent)));
+ if (!batteryIndicatorVisible(visibility, clamped)) return;
+ items.push({ label, percent: clamped, charging });
+}
+
+// Stacked style geometry, in rows below the bar's top edge. The bar has 27
+// usable rows above its bottom border line, too few for the user-sized UI
+// font (line height up to 21px) over a 10px gauge, so both stacked lines use
+// a fixed 12px bitmap face instead: TerminusV, proportional, with 8px
+// capitals and digits on a 10px ascent. Ink then spans rows 3..22: label
+// capitals at 3..10, a 2px gap, and the gauge at 13..22 (or the percentage
+// digits at 13..20, whose charging highlight box covers 12..21), leaving 3
+// rows above and 4 below (before the border) so the pair reads as one
+// centered unit.
+const STACKED_LABEL_BASELINE = 11;
+const STACKED_ICON_TOP = 13;
+const STACKED_PERCENT_BASELINE = 21;
+const STACKED_ITEM_GAP = 10;
+
+/**
+ * Stacked styles: each label centered above its gauge icon (or percentage
+ * text), right-aligned in the bar. Returns the left edge of the battery
+ * block.
+ */
+function drawStackedBatteries(image: GrayImage, items: BatteryItem[], barTop: number, percentage: boolean): number {
+ const font = getFont("terminusv12");
+ const labelTop = barTop + STACKED_LABEL_BASELINE - font.ascent;
+ const percentTop = barTop + STACKED_PERCENT_BASELINE - font.ascent;
+ let x = G2_LENS_WIDTH - BATTERY_BLOCK_RIGHT_MARGIN;
+ for (let index = items.length - 1; index >= 0; index--) {
+ const item = items[index]!;
+ const percentText = `${item.percent}%`;
+ const labelWidth = font.measureText(item.label);
+ const valueWidth = percentage ? font.measureText(percentText) : BATTERY_ICON_WIDTH;
+ const itemWidth = Math.max(labelWidth, valueWidth);
+ x -= itemWidth;
+ image.drawText(font, x + (((itemWidth - labelWidth) / 2) | 0), labelTop, item.label, BATTERY_LABEL_VALUE);
+ const valueX = x + (((itemWidth - valueWidth) / 2) | 0);
+ if (!percentage) {
+ const icon = drawBattery(item.percent, item.charging);
+ image.bitBlt(icon, valueX, barTop + STACKED_ICON_TOP, { transparentZero: true });
+ } else if (item.charging) {
+ // Inverted text marks charging, as in the side-by-side percentage style;
+ // the box hugs the digits' 8px ink rather than the full 12px line.
+ const inkTop = barTop + STACKED_PERCENT_BASELINE - 8;
+ image.fillRect(valueX - 2, inkTop - 1, valueWidth + 4, 10, 255);
+ image.drawText(font, valueX, percentTop, percentText, 1);
+ } else {
+ image.drawText(font, valueX, percentTop, percentText, 200);
+ }
+ x -= STACKED_ITEM_GAP;
+ }
+ return x + STACKED_ITEM_GAP;
+}
+
// Ambient cards (encounter popups): compact and deliberately unobtrusive,
// anchored to the bottom-right of the window band and stacking upward, clear
// of the caption area's left-aligned text. Never interactive.
diff --git a/app/ui/shell/geometry.ts b/app/ui/shell/geometry.ts
index d5ff437e..58454526 100644
--- a/app/ui/shell/geometry.ts
+++ b/app/ui/shell/geometry.ts
@@ -1,5 +1,13 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "../../graphics/image";
-import { displayModeSetting, type DisplayModeSetting, verticalPositionSetting } from "../dashboard-settings";
+import {
+ displayModeSetting,
+ type DisplayModeSetting,
+ verticalPositionSetting,
+ navigateDisplayModeSetting,
+ navigateVerticalPositionSetting,
+ terminalDisplayModeSetting,
+ terminalVerticalPositionSetting,
+} from "../dashboard-settings";
/** Top bar: 24px notification icons plus a little padding. */
export const TOP_BAR_HEIGHT = 28;
@@ -13,8 +21,14 @@ export const TOP_BAR_HEIGHT = 28;
export const SIDEBAR_WIDTH = 64;
/** The Display > Display mode setting (see dashboard-settings.ts). */
-export function displayMode(): DisplayModeSetting {
- return displayModeSetting.get();
+function appDisplayMode(appId?: string) {
+ return appId === "navigate" ? navigateDisplayModeSetting.get()
+ : appId === "terminal" ? terminalDisplayModeSetting.get() : "default";
+}
+
+export function displayMode(appId?: string): DisplayModeSetting {
+ const mode = appDisplayMode(appId);
+ return mode === "global" || mode === "default" ? displayModeSetting.get() : mode;
}
/**
@@ -22,24 +36,24 @@ export function displayMode(): DisplayModeSetting {
* the strip, or nothing in the full-panel mode (where the chrome paints the
* strip over the window while the sidebar has focus).
*/
-export function sidebarWidth(): number {
- return displayMode() === "640x480" ? 0 : SIDEBAR_WIDTH;
+export function sidebarWidth(appId?: string): number {
+ return displayMode(appId) === "640x480" ? 0 : SIDEBAR_WIDTH;
}
/**
* Whether the sidebar strip is on screen: always when it reserves width; in
* the full-panel mode (where it overlays the window) only while it has focus.
*/
-export function sidebarStripVisible(focus: "sidebar" | "window"): boolean {
- return sidebarWidth() > 0 || focus === "sidebar";
+export function sidebarStripVisible(focus: "sidebar" | "window", appId?: string): boolean {
+ return sidebarWidth(appId) > 0 || focus === "sidebar";
}
/**
- * The height an app's requested mode actually gets: the band mode honours
- * it, the taller modes give every window the whole screen.
+ * Explicit app sizes (including Use global) replace the requested height.
+ * The default keeps legacy per-window heights, such as tall terminal sessions.
*/
-export function effectiveHeightMode(mode: WindowHeightMode): WindowHeightMode {
- return displayMode() === "576x288" ? mode : "max";
+export function effectiveHeightMode(mode: WindowHeightMode, appId?: string): WindowHeightMode {
+ return displayMode(appId) === "576x288" ? (appDisplayMode(appId) === "default" ? mode : "min") : "max";
}
/**
@@ -74,8 +88,8 @@ export const MIN_WINDOW_HEIGHT = 288;
export const MIN_WINDOW_MAX_TOP = G2_LENS_HEIGHT - MIN_WINDOW_HEIGHT;
/** Total height (top bar + content) of a window's band in the given mode. */
-export function windowBandHeight(mode: WindowHeightMode): number {
- switch (effectiveHeightMode(mode)) {
+export function windowBandHeight(mode: WindowHeightMode, appId?: string): number {
+ switch (effectiveHeightMode(mode, appId)) {
case "max":
return G2_LENS_HEIGHT;
case "medium":
@@ -90,8 +104,10 @@ export function windowBandHeight(mode: WindowHeightMode): number {
* position setting: each band height distributes its own free space by the
* same fraction, so all heights sit consistently within the screen.
*/
-function verticalPositionFraction(): number {
- switch (verticalPositionSetting.get()) {
+function verticalPositionFraction(appId?: string): number {
+ const position = appId === "navigate" ? navigateVerticalPositionSetting.get()
+ : appId === "terminal" ? terminalVerticalPositionSetting.get() : "global";
+ switch (position === "global" ? verticalPositionSetting.get() : position) {
case "top":
return 0;
case "upper":
@@ -109,33 +125,33 @@ function verticalPositionFraction(): number {
* Top edge (y) of a min-height window. The sidebar and shell overlays always
* align to this band, even while a taller window is foreground.
*/
-export function minWindowTop(): number {
- return windowTop("min");
+export function minWindowTop(appId?: string): number {
+ return windowTop("min", appId);
}
/** Top edge (y) of a window's top bar; max-height windows pin to the screen top. */
-export function windowTop(mode: WindowHeightMode): number {
- return Math.round((G2_LENS_HEIGHT - windowBandHeight(mode)) * verticalPositionFraction());
+export function windowTop(mode: WindowHeightMode, appId?: string): number {
+ return Math.round((G2_LENS_HEIGHT - windowBandHeight(mode, appId)) * verticalPositionFraction(appId));
}
/** App-content viewport size for a height mode (independent of vertical position). */
-export function appViewportSize(mode: WindowHeightMode): { width: number; height: number } {
+export function appViewportSize(mode: WindowHeightMode, appId?: string): { width: number; height: number } {
return {
- width: G2_LENS_WIDTH - sidebarWidth(),
- height: windowBandHeight(mode) - TOP_BAR_HEIGHT,
+ width: G2_LENS_WIDTH - sidebarWidth(appId),
+ height: windowBandHeight(mode, appId) - TOP_BAR_HEIGHT,
};
}
/** Screen rect of a window's app-content viewport (below its top bar). */
-export function appViewportRect(mode: WindowHeightMode): {
+export function appViewportRect(mode: WindowHeightMode, appId?: string): {
x: number;
y: number;
width: number;
height: number;
} {
return {
- x: sidebarWidth(),
- y: windowTop(mode) + TOP_BAR_HEIGHT,
- ...appViewportSize(mode),
+ x: sidebarWidth(appId),
+ y: windowTop(mode, appId) + TOP_BAR_HEIGHT,
+ ...appViewportSize(mode, appId),
};
}
diff --git a/app/ui/shell/in-process-window.ts b/app/ui/shell/in-process-window.ts
index f6353f7e..a3ec71d5 100644
--- a/app/ui/shell/in-process-window.ts
+++ b/app/ui/shell/in-process-window.ts
@@ -31,11 +31,19 @@ export type InProcessWindowOptions = {
/** Window height: the standard 288px band ("min", default) or full screen ("max"). */
heightMode?: WindowHeightMode;
/**
- * App-specific entries for the window's long-press menu, listed ahead of
- * the default Voice input / Close window entries. Called at open time, so
- * the items can reflect current app state.
+ * The window's tap-then-hold context menu: app-specific entries only (the
+ * shared Focus app switcher / Voice input / Close window entries live in
+ * the shell's system menu, on long-press). Called at open time, so the
+ * items can reflect current app state. Omitted or empty means the window
+ * has no menu of its own, and tap-then-hold opens the system menu instead.
*/
menuItems?: () => MenuItem[];
+ /** Dedicated chat gestures: click menu, hold microphone, tap-hold system menu. */
+ holdToTalk?: boolean;
+ isVoiceCapturing?: () => boolean;
+ onSystemMenuOpened?: () => void;
+ onAppMenuOpened?: () => void;
+ setScreenOn?: ShellWindow["setScreenOn"];
/** Shared actions; requestRender is rebound to this window's render. */
actions: LayerActions;
/**
@@ -128,41 +136,19 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
}
}
- // The window's long-press menu: app-specific items, then the defaults every
- // window shares. In-process apps run on the main thread, so the default
- // items act on the shell directly (workers post messages instead).
+ const appMenuItems = () => options.menuItems?.() ?? [];
+
+ // The window's tap-then-hold menu: the app's own entries, or the shell's
+ // system menu when it has none (so both gestures land on the same menu).
const openWindowMenu = () => {
if (stack.topMatches((layer) => layer instanceof WindowMenuLayer)) return;
- // "Focus app switcher" first: long-press then tap defocuses the app
- // (hands focus to the sidebar) without closing it — the reliable way out
- // for apps that consume double-click.
- const items: MenuItem[] = [
- {
- label: "Focus app switcher",
- onSelect: (ctx) => {
- ctx.stack.pop();
- shell.yieldFocusToSidebar();
- },
- },
- ...(options.menuItems?.() ?? []),
- ];
- items.push({
- label: "Voice input",
- onSelect: (ctx) => {
- ctx.stack.pop();
- shell.startVoiceInput();
- },
- });
- if (options.closeable) {
- items.push({
- label: "Close window",
- onSelect: (ctx) => {
- ctx.stack.pop();
- shell.closeWindow(options.windowId);
- },
- });
+ const items = appMenuItems();
+ if (!items.length) {
+ shell.openSystemMenu(options.windowId);
+ return;
}
- stack.push(new WindowMenuLayer(items));
+ options.onAppMenuOpened?.();
+ stack.push(new WindowMenuLayer(options.title, items, options.holdToTalk));
};
const window: ShellWindow = {
@@ -174,7 +160,11 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
// The window's own LayerStack decides per layer whether a swipe is
// directional or falls back to click / double-click.
acceptsDirectional: true,
+ holdToTalk: options.holdToTalk,
+ isVoiceCapturing: options.isVoiceCapturing,
+ setScreenOn: options.setScreenOn,
heightMode,
+ hasAppMenu: () => appMenuItems().length > 0,
close: () => {
closed = true;
// Fire onRemoved for any pushed layers so they release resources (e.g. a
@@ -185,9 +175,22 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
},
drawIcon: options.drawIcon ?? windowIcon(options.icon, options.iconLetter),
handleInput: async (event, frameId) => {
- // The default long-press response: the window menu. Handled here (not
- // per-layer) so it works over submenus and app content alike.
- if (event.type === "long-press") {
+ // The shell opened its system menu over this window; close our own
+ // context menu so the two never stack. Never forwarded to app layers.
+ if (event.type === "system-menu-opened") {
+ options.onSystemMenuOpened?.();
+ if (stack.popIfTop((layer) => layer instanceof WindowMenuLayer)) {
+ requestRender();
+ }
+ return;
+ }
+ // The default tap-then-hold response: the window menu (or the system
+ // menu in its place). Handled here (not per-layer) so it works over
+ // submenus and app content alike. A plain long-press never arrives:
+ // the shell keeps it for the system menu (no in-process window claims
+ // it).
+ if ((!options.holdToTalk && event.type === "short-then-long-press") ||
+ (options.holdToTalk && event.type === "click" && stack.isAtBase())) {
openWindowMenu();
await render(frameId);
return;
diff --git a/app/ui/shell/input-dialog.ts b/app/ui/shell/input-dialog.ts
new file mode 100644
index 00000000..7b36d9d1
--- /dev/null
+++ b/app/ui/shell/input-dialog.ts
@@ -0,0 +1,90 @@
+import { G2_LENS_WIDTH, type GrayImage } from "../../graphics/image";
+import { wrapText, truncateText } from "../../graphics/textwrap";
+import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { drawSelectionHighlight } from "../menu";
+import { listRowHeight } from "../metrics";
+import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry";
+
+/**
+ * The shared look of the shell's text-entry dialogs (voice input and phone
+ * keyboard input): a solid box over whatever is on screen with a title line,
+ * a status line, the message so far, and either a menu of destinations at
+ * the bottom or a gesture hint.
+ */
+
+const DIALOG_X = 40;
+const DIALOG_W = G2_LENS_WIDTH - 80;
+// The dialog fits inside the min-height window band (like the other shell
+// overlays), wherever the vertical position setting puts it.
+const DIALOG_MARGIN_Y = 24;
+const DIALOG_H = MIN_WINDOW_HEIGHT - 2 * DIALOG_MARGIN_Y;
+const TEXT_MAX_WIDTH = DIALOG_W - 32;
+
+/** Dialog top edge; band-relative, so computed per paint. */
+function dialogY(): number {
+ return minWindowTop() + DIALOG_MARGIN_Y;
+}
+
+export type InputDialogRow = {
+ label: string;
+ /** Drawn faint: the row is not currently selectable (e.g. nothing to send). */
+ dim: boolean;
+};
+
+export type InputDialogContent = {
+ title: string;
+ status: string;
+ /** The message body (a placeholder when nothing has been captured yet). */
+ text: string;
+ /** Menu rows along the bottom edge; empty for no menu. */
+ rows: readonly InputDialogRow[];
+ selectedRow: number;
+ /** Gesture hint drawn along the bottom edge when there is no menu. */
+ hint?: string;
+};
+
+/** Paint the dialog onto `image` (an already-painted canvas of the layers below). */
+export function paintInputDialog(image: GrayImage, content: InputDialogContent): void {
+ const font = getDefaultSmallFont();
+ const menuRowH = listRowHeight(font);
+ const top = dialogY();
+
+ // Solid dialog box over the underlying UI. Fill 1, not 0: identical after
+ // 4bpp quantization, but 0 is transparent on the color-key shell surface.
+ image.fillRoundedRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 1, 10);
+ image.drawRoundedRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 90, 10);
+
+ const left = DIALOG_X + 16;
+ image.drawText(font, left, top + 12, content.title, 220);
+ image.drawText(font, left, top + 30, truncateText(font, content.status, TEXT_MAX_WIDTH), 130);
+
+ const rows = content.rows;
+ const hasMenu = rows.length > 0;
+ // Reserve space for the actual number of rows this menu has.
+ const textBottom = hasMenu ? top + DIALOG_H - rows.length * menuRowH - 8 : top + DIALOG_H - 8;
+ const textTop = top + 56;
+ const maxLines = Math.max(1, ((textBottom - textTop) / 16) | 0);
+
+ // The tail of a long message stays in view: it is what was said last (or
+ // where the phone keyboard is typing).
+ const wrapped = wrapText(font, content.text, TEXT_MAX_WIDTH);
+ const firstLine = Math.max(0, wrapped.length - maxLines);
+ for (let index = firstLine; index < wrapped.length; index++) {
+ image.drawText(font, left, textTop + (index - firstLine) * 16, wrapped[index]!, 235);
+ }
+
+ if (hasMenu) {
+ const menuTop = top + DIALOG_H - rows.length * menuRowH - 2;
+ for (let i = 0; i < rows.length; i++) {
+ const rowY = menuTop + i * menuRowH;
+ const selected = i === content.selectedRow;
+ if (selected) {
+ drawSelectionHighlight(image, left - 4, rowY - 2, DIALOG_W - 24, menuRowH - 2, true, 6);
+ }
+ const row = rows[i]!;
+ image.drawText(font, left + 4, rowY + 2, row.label, row.dim ? 90 : selected ? 255 : 200);
+ }
+ } else if (content.hint) {
+ image.drawText(font, left, top + DIALOG_H - 14, content.hint, 110 - font.lineHeight);
+ }
+}
diff --git a/app/ui/shell/keyboard-input.ts b/app/ui/shell/keyboard-input.ts
new file mode 100644
index 00000000..22f51014
--- /dev/null
+++ b/app/ui/shell/keyboard-input.ts
@@ -0,0 +1,159 @@
+import { type GrayImage } from "../../graphics/image";
+import { type InputEvent } from "../gestures";
+import { Layer, type LayerActions, type LayerContext } from "../layers";
+import { paintInputDialog } from "./input-dialog";
+import { type VoiceSendTarget } from "./voice-input";
+
+/**
+ * The phone side's handle on an open keyboard-input dialog: the phone types
+ * into it and picks where the text goes. The layer itself implements this;
+ * the controller hands it to the phone UI while the dialog is up.
+ */
+export type KeyboardInputSession = {
+ /** The send destinations, in the glasses menu's row order. */
+ readonly targets: ReadonlyArray<{ id: string; label: string }>;
+ /** Replace the message with what the phone's text field now holds. */
+ setText(text: string): void;
+ /**
+ * Send to the destination highlighted on the glasses (the entry point's
+ * default unless the user scrolled the menu). The IME's send key.
+ */
+ send(): void;
+ sendTo(targetId: string): void;
+ discard(): void;
+};
+
+export type KeyboardInputLayerOptions = {
+ actions: LayerActions;
+ /** Post-removal cleanup (also fires when the screen turns off). */
+ onClosed: () => void;
+ /** Pop this layer off the shell stack. */
+ dismiss: () => void;
+ /** Ordered send destinations shown as the first menu rows. */
+ sendTargets: VoiceSendTarget[];
+ /** Which send target is highlighted by default (entry-point dependent). */
+ defaultTargetIndex?: number;
+};
+
+/**
+ * The voice dialog's keyboard twin: the same box on the glasses, but the
+ * message is typed on the phone (its IME, opened by the keyboard button next
+ * to the mic button) instead of transcribed. The glasses mirror the text as
+ * it is typed and show the same send / discard menu, which works from either
+ * end: the ring or watch scrolls and clicks it, the phone has a button per
+ * row plus the IME's send key. There is no Continue row — the phone can
+ * simply edit the text.
+ */
+export class KeyboardInputLayer implements Layer, KeyboardInputSession {
+ private text = "";
+ private menuIndex: number;
+ private closed = false;
+
+ private readonly actions: LayerActions;
+ private readonly onClosed: () => void;
+ private readonly dismiss: () => void;
+ private readonly sendTargets: VoiceSendTarget[];
+ private readonly defaultTargetIndex: number;
+
+ constructor(options: KeyboardInputLayerOptions) {
+ this.actions = options.actions;
+ this.onClosed = options.onClosed;
+ this.dismiss = options.dismiss;
+ this.sendTargets = options.sendTargets;
+ const defaultIndex = options.defaultTargetIndex ?? 0;
+ this.defaultTargetIndex = Math.min(Math.max(0, defaultIndex), Math.max(0, this.sendTargets.length - 1));
+ this.menuIndex = this.defaultTargetIndex;
+ }
+
+ get targets(): ReadonlyArray<{ id: string; label: string }> {
+ return this.sendTargets.map((target) => ({ id: target.id, label: target.label }));
+ }
+
+ setText(text: string): void {
+ if (this.closed || this.text === text) return;
+ this.text = text;
+ this.actions.requestRender();
+ }
+
+ send(): void {
+ const row = this.menuRows()[this.menuIndex];
+ const target = row?.target ?? this.sendTargets[this.defaultTargetIndex];
+ if (target) this.sendToTarget(target);
+ }
+
+ sendTo(targetId: string): void {
+ const target = this.sendTargets.find((candidate) => candidate.id === targetId);
+ if (target) this.sendToTarget(target);
+ }
+
+ discard(): void {
+ if (!this.closed) this.dismiss();
+ }
+
+ private sendToTarget(target: VoiceSendTarget): void {
+ if (this.closed) return;
+ const text = this.text.trim();
+ // An empty message has nothing to deliver; the dialog stays up for the
+ // phone to keep typing (the glasses row is drawn dim for the same reason).
+ if (!text) return;
+ this.dismiss();
+ target.onSend(text);
+ }
+
+ /** The menu rows: one per send target, then Discard. */
+ private menuRows(): Array<{ label: string; dim: boolean; target?: VoiceSendTarget }> {
+ const hasText = this.text.trim().length > 0;
+ const rows: Array<{ label: string; dim: boolean; target?: VoiceSendTarget }> = [];
+ for (const target of this.sendTargets) {
+ rows.push({ label: target.label, dim: !hasText, target });
+ }
+ rows.push({ label: "Discard", dim: false });
+ return rows;
+ }
+
+ paint(_ctx: LayerContext, paintBelow: () => GrayImage): GrayImage {
+ const image = paintBelow();
+ paintInputDialog(image, {
+ title: "Keyboard",
+ status: "Type on the phone",
+ text: this.text || "(nothing typed yet)",
+ rows: this.menuRows(),
+ selectedRow: this.menuIndex,
+ });
+ return image;
+ }
+
+ handleInput(event: InputEvent, _ctx: LayerContext): void {
+ const rowCount = this.menuRows().length;
+ switch (event.type) {
+ case "scroll-up":
+ this.menuIndex = (this.menuIndex + rowCount - 1) % rowCount;
+ this.actions.requestRender();
+ return;
+ case "scroll-down":
+ this.menuIndex = (this.menuIndex + 1) % rowCount;
+ this.actions.requestRender();
+ return;
+ case "click": {
+ const row = this.menuRows()[this.menuIndex];
+ if (!row) return;
+ if (row.target) {
+ this.sendToTarget(row.target);
+ } else {
+ this.dismiss();
+ }
+ return;
+ }
+ case "double-click":
+ this.dismiss();
+ return;
+ default:
+ return;
+ }
+ }
+
+ onRemoved(): void {
+ this.closed = true;
+ this.onClosed();
+ }
+}
diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts
index 564fe45a..636f10b7 100644
--- a/app/ui/shell/shell.ts
+++ b/app/ui/shell/shell.ts
@@ -5,6 +5,8 @@ import { EvenAIStatus, EventSourceType, OsEventTypeList, WatchGestureType } from
import type { RawInputEvent } from "../../native/faceclaw-communicator";
import {
directionalFallback,
+ GESTURE_SHORT_THEN_LONG_PRESS,
+ gestureHints,
InputEvent,
type InputEventPayload,
type InputSource,
@@ -13,12 +15,15 @@ import {
makeInputEvent,
} from "../gestures";
import { Layer, LayerActions, LayerContext, LayerStack, noopLayerActions } from "../layers";
-import { MenuLayer, type MenuItem } from "../menu";
+import { CONTEXT_MENU_DIM, MenuLayer, type MenuItem } from "../menu";
import { VoiceInputLayer, type VoiceSendTarget } from "./voice-input";
+import { KeyboardInputLayer, type KeyboardInputSession } from "./keyboard-input";
import { voiceActivity } from "./voice-activity";
import { AssistantLayer } from "./assistant";
import { AssistantSession, type AssistantBackendConfig } from "../../assistant/session";
-import { resolveAssistantModel } from "../../assistant/models";
+import { resolveAssistantModel, type AssistantModel } from "../../assistant/models";
+import { AssistantConversations, type ReasoningLevel } from "../../assistant/conversations";
+import { getStringSetting, setStringSetting } from "../../native/settings-store";
import type { AssistantContext } from "../../assistant/types";
import { SingleNotificationLayer } from "../notifications";
import {
@@ -29,7 +34,8 @@ import {
assistantBridgeTokenSetting,
assistantModelSetting,
assistantSkipConfirmationSetting,
- batteryDisplayModeSetting,
+ batteryIndicatorSettingsKey,
+ brightnessSetting,
onAnySettingChanged,
openAiApiKeySetting,
timeFormatSetting,
@@ -39,6 +45,7 @@ import { onAmbientCardsChanged } from "./ambient-cards";
import { ShellChromeLayer, sidebarContentLeft, type ShellChromeState, type ShellChromeWindow } from "./chrome-layer";
import { ShellModalLayer } from "./modal-layer";
import { ToolDebugMenuLayer } from "./tool-debug-layer";
+import { BrightnessPickerLayer } from "./brightness-picker-layer";
import { toolRegistry } from "../../assistant/tool-registry";
import {
minWindowTop,
@@ -57,11 +64,14 @@ import {
*
* Input flow: every event enters via receiveInput. The shell consumes
* everything while the sidebar or a shell overlay has focus and forwards the
- * rest to the focused window. Long-press goes to the foreground window (from
- * the sidebar it focuses the window first); by convention apps answer it with
- * a window menu that ends in Voice input / Close window. Holding the press
- * past the escape threshold opens the shell's own escape menu, so the shell
- * keeps working when a window's handler hangs.
+ * rest to the focused window. Long-press opens the shell-owned system menu
+ * (Focus app switcher, Voice input, Brightness, Close window, Debug) without reaching the
+ * app, so the shell keeps working when a window's handler hangs; a window
+ * that claims long-press for a move of its own gets it forwarded instead, and
+ * holding the press past the escape threshold still opens the system menu.
+ * The 2.2.9 tap-then-hold gesture goes to the foreground window (from the
+ * sidebar it focuses the window first); by convention apps answer it with
+ * their own context menu, or ask for the system menu when they have none.
*/
export type ShellWindow = {
@@ -70,8 +80,25 @@ export type ShellWindow = {
title: string;
/** Compositor surface this window renders to; configured at connect / launch. */
surfaceId: string;
- /** Whether close menu entries (app menu default, shell escape menu) apply (the launcher is pinned). */
+ /** Whether the system menu offers Close window (the launcher is pinned). */
closeable: boolean;
+ /**
+ * True when tap-then-hold currently opens the window's own context menu
+ * (with at least one entry). While false, the system menu shows no
+ * app-menu hint and a tap-then-hold over the open system menu leaves it
+ * open instead of switching menus.
+ */
+ hasAppMenu?: () => boolean;
+ /**
+ * True while the window gives long-press a meaning of its own (a game
+ * move). The shell then forwards long-presses to it instead of opening the
+ * system menu; holding the press past the escape threshold still opens it.
+ */
+ claimsLongPress?: () => boolean;
+ /** Chat uses hold-to-talk and tap-then-hold for the system menu, without an escape timer. */
+ holdToTalk?: boolean;
+ /** A window owns microphone capture outside the shell voice dialog. */
+ isVoiceCapturing?: () => boolean;
/**
* True when the window gives swipe-left / swipe-right (watch directional
* input) a meaning; otherwise the shell forwards directionalFallback(event).
@@ -96,7 +123,7 @@ export type ShellWindow = {
requestRender: () => void;
/**
* Re-measure against the current display mode (viewport size / band) and
- * repaint. Windows without it (workers, whose canvas is fixed at open) are
+ * repaint. Windows without it (workers with a canvas fixed at open) are
* closed and relaunched by the controller instead.
*/
relayout?: () => void;
@@ -135,6 +162,11 @@ export type ShellConfig = {
* when RECORD_AUDIO isn't granted yet (the phone mic is the source there).
*/
prepareVoiceCapture?: () => Promise;
+ /**
+ * The keyboard dialog opened (with the session the phone types into) or
+ * closed (null) by any path; the phone UI shows/hides its typing panel.
+ */
+ onKeyboardInputChanged?: (session: KeyboardInputSession | null) => void;
/** Screen on/off changed: the controller blanks/unblanks the compositor. */
onScreenStateChanged: (on: boolean) => void;
/** Window registered/removed or foreground changed (persists the open-app list). */
@@ -160,28 +192,40 @@ export type FocusKind = "sidebar" | "window";
const noopActions: LayerActions = noopLayerActions;
/**
- * Hold a long-press this much past the long-press event (which the firmware
- * itself only fires after a shorter hold) and the shell opens its own escape
- * menu — the recovery path when an app ignores or mishandles the gesture.
+ * For a window that claims long-press: hold the press this much past the
+ * long-press event (which the firmware itself only fires after a shorter
+ * hold) and the shell opens the system menu anyway — the recovery path when
+ * the app ignores or mishandles the gesture.
*/
const LONG_PRESS_ESCAPE_MENU_MS = 4000;
-/** Shell-surface overlay menu (the escape menu); closing it returns focus to the sidebar. */
+/** Shell-surface overlay menu (the system menu); closing it returns focus to the sidebar. */
class ShellOverlayMenuLayer extends MenuLayer {
- constructor(items: MenuItem[], private readonly onClosed: () => void) {
+ /**
+ * Set before popping to keep focus on the window: an entry that acts on
+ * the window (Voice input aims its transcript at it) must not first hand
+ * focus to the sidebar.
+ */
+ keepWindowFocus = false;
+
+ constructor(items: MenuItem[], footer: string | undefined, private readonly onClosed: () => void) {
// Aligned to the min-height window band (like the sidebar), wherever the
- // vertical position setting currently puts it; past the sidebar strip
- // where one reserves width (none in the full-panel mode).
- super(null, items, {
- x: sidebarWidth() + 8,
+ // vertical position setting currently puts it; centered over the
+ // application area, i.e. the part of the screen past the sidebar strip
+ // (the whole screen in the full-panel mode, where the strip overlays).
+ const width = 272;
+ super("System", items, {
+ x: sidebarWidth() + (((G2_LENS_WIDTH - sidebarWidth() - width) / 2) | 0),
y: minWindowTop() + TOP_BAR_HEIGHT + 8,
- width: 272,
- minHeight: 0,
+ width,
+ minHeight: 150,
+ footer,
+ dimUnderneath: CONTEXT_MENU_DIM,
});
}
onRemoved(): void {
- this.onClosed();
+ if (!this.keepWindowFocus) this.onClosed();
}
}
@@ -245,6 +289,11 @@ class ShellAlertLayer implements Layer {
}
}
+/** Every setting the top bar paints from, as one comparable string. */
+function topBarSettingsKey(): string {
+ return `${batteryIndicatorSettingsKey()}|${timeFormatSetting.get()}`;
+}
+
class Shell {
private windows: ShellWindow[] = [];
private selectedIndex = 0;
@@ -255,13 +304,36 @@ class Shell {
private lastInputAtMs = Date.now();
/** The most recent input event received, for windows gaining focus (see ShellWindow.onFocus). */
private lastInput: InputEvent | null = null;
- private battery: ShellChromeState["battery"] = { headset: null, headsetCharging: null };
+ private battery: ShellChromeState["battery"] = { headset: null, headsetCharging: null, ring: null, ringCharging: null };
private attention = new Map();
// App-provided top-bar tray icons, keyed by owner id; drawn between the
// notification icons and the battery indicators.
private readonly trayIcons = new Map();
private activeVoiceLayer: VoiceInputLayer | null = null;
- private assistantSession: AssistantSession | null = null;
+ private activeKeyboardLayer: KeyboardInputLayer | null = null;
+ private conversations: AssistantConversations | null = null;
+ private get assistantSession(): AssistantSession | null {
+ return this.conversations?.current().session ?? null;
+ }
+
+ getAssistantConversations(): AssistantConversations {
+ if (!this.conversations) {
+ this.conversations = new AssistantConversations(
+ (model, reasoning) => this.resolveAssistantConfiguration(model, reasoning),
+ () => assistantModelSetting.get(),
+ (value) => setStringSetting("assistant.conversations", value),
+ getStringSetting("assistant.conversations", ""),
+ );
+ }
+ return this.conversations;
+ }
+
+ async prepareChatVoiceCapture(): Promise {
+ if (this.activeVoiceLayer || this.activeKeyboardLayer || this.voiceDialogPending) return false;
+ const ready = (await this.config.prepareVoiceCapture?.()) ?? true;
+ return ready && !this.activeVoiceLayer && !this.activeKeyboardLayer &&
+ this.stack.isAtBase() && this.isWindowFocused("ai-chat");
+ }
private assistantLayer: AssistantLayer | null = null;
private readonly assistantActivityListeners = new Set<(event: AssistantActivityEvent) => void>();
private readonly alertListeners = new Set<(text: string) => void>();
@@ -276,11 +348,10 @@ class Shell {
private readonly chrome = new ShellChromeLayer(() => this.chromeState());
private readonly stack = new LayerStack(this.chrome, this.actions);
- // Top-bar settings we mirror into the chrome; a change to either repaints
- // the shell surface so the top bar reflects it immediately.
+ // Top-bar settings we mirror into the chrome; a change to any of them
+ // repaints the shell surface so the top bar reflects it immediately.
private topBarSettingsSubscribed = false;
- private lastBatteryDisplayMode: string | null = null;
- private lastTimeFormat: string | null = null;
+ private lastTopBarSettingsKey: string | null = null;
configure(config: ShellConfig): void {
this.config = config;
@@ -306,16 +377,11 @@ class Shell {
private subscribeToTopBarSettings(): void {
if (this.topBarSettingsSubscribed) return;
this.topBarSettingsSubscribed = true;
- this.lastBatteryDisplayMode = batteryDisplayModeSetting.get();
- this.lastTimeFormat = timeFormatSetting.get();
+ this.lastTopBarSettingsKey = topBarSettingsKey();
onAnySettingChanged(() => {
- const batteryMode = batteryDisplayModeSetting.get();
- const timeFormat = timeFormatSetting.get();
- if (batteryMode === this.lastBatteryDisplayMode && timeFormat === this.lastTimeFormat) {
- return;
- }
- this.lastBatteryDisplayMode = batteryMode;
- this.lastTimeFormat = timeFormat;
+ const key = topBarSettingsKey();
+ if (key === this.lastTopBarSettingsKey) return;
+ this.lastTopBarSettingsKey = key;
this.config.requestShellRender();
});
}
@@ -518,10 +584,11 @@ class Shell {
// An open voice dialog suspends the timeout: a long dictation or refine
// has no button presses, but the screen must stay on for it. Sliding
// lastInputAtMs forward also restarts the full timeout when it closes.
- // An in-flight assistant turn suspends it for the same reason (a tool loop
- // can run for a while with no input); once the turn ends and the
- // Follow-up/Done menu is showing, the normal idle timeout resumes.
- if (this.activeVoiceLayer || this.assistantSession?.isTurnActive()) {
+ // The keyboard dialog likewise: typing happens on the phone, not the
+ // ring. An in-flight assistant turn suspends it for the same reason (a
+ // tool loop can run for a while with no input); once the turn ends and
+ // the Follow-up/Done menu is showing, the normal idle timeout resumes.
+ if (this.activeVoiceLayer || this.activeKeyboardLayer || this.assistantSession?.isTurnActive() || this.foregroundWindow()?.isVoiceCapturing?.()) {
this.lastInputAtMs = nowMs;
return false;
}
@@ -574,6 +641,17 @@ class Shell {
return this.stack.paint();
}
+ /**
+ * The brightness factor a shell overlay (a context menu) currently applies
+ * to what lies beneath the shell surface, i.e. the window surfaces: 1 when
+ * nothing dims them. Read after paintSurface; the controller forwards it to
+ * the compositor, which cannot see the shell's layer stack.
+ */
+ underlayDim(): number {
+ const dim = this.stack.baseDim();
+ return this.screenOn && dim !== false ? dim : 1;
+ }
+
async receiveInput(event: InputEvent, frameId = 0): Promise {
const previous = this.lastInput;
this.lastInput = event;
@@ -596,6 +674,7 @@ class Shell {
// Even AI app never launches, so the firmware does not power the display
// for us either -- actions that need it wake the screen themselves.
if (event.type === "wakeword") {
+ if (this.foregroundWindow()?.isVoiceCapturing?.()) return { shell: true, window: false };
const action = wakeWordActionSetting.get();
if (action === "off") {
return { shell: false, window: false };
@@ -603,7 +682,7 @@ class Shell {
this.lastInputAtMs = Date.now();
const wokeScreen = !this.screenOn && this.wake("sidebar");
- if (action === "voice-input" && !this.activeVoiceLayer) {
+ if (action === "voice-input" && !this.activeVoiceLayer && !this.activeKeyboardLayer) {
if (this.assistantLayer) {
// The assistant overlay is up; a wakeword continues that conversation.
this.startAssistantFollowUp(true);
@@ -631,12 +710,15 @@ class Shell {
return { shell: false, window: false };
}
- // Long-press goes to the foreground window (from the sidebar it focuses
- // the window first); apps conventionally answer it with their window
- // menu. The escape timer runs regardless of what the app does with it:
- // holding the press long enough opens the shell's own menu.
+ // Long-press is the shell's own gesture: it opens the system menu
+ // directly, never reaching the app — over the app's own context menu
+ // too (the window closes that on system-menu-opened), while an already
+ // open system menu just stays. Its later generic release is consumed
+ // while the shell overlay is active and therefore cannot leak into the
+ // app. The exception is a window that claims long-press for a move of
+ // its own: it gets the press forwarded, with the escape timer running
+ // so that holding the press long enough still opens the system menu.
if (event.type === "long-press") {
- this.startEscapeMenuTimer();
if (this.activeVoiceLayer || !this.stack.isAtBase()) {
return { shell: true, window: false };
}
@@ -644,6 +726,47 @@ class Shell {
if (!window) {
return { shell: true, window: false };
}
+ if (!window.holdToTalk && !window.claimsLongPress?.()) {
+ this.openEscapeMenu();
+ return { shell: true, window: false };
+ }
+ if (!window.holdToTalk) this.startEscapeMenuTimer();
+ if (this.focus === "sidebar") {
+ this.focus = "window";
+ window.onFocus?.(this.lastInput);
+ }
+ // The window owns frameId from here (render or explicit finish).
+ await window.handleInput(event, frameId);
+ return { shell: true, window: true };
+ }
+
+ // The 2.2.9 tap-then-hold gesture is the app's context-menu gesture: it
+ // goes to the foreground window (from the sidebar it focuses the window
+ // first), which answers with its own menu or asks for the system menu
+ // when it has none.
+ if (event.type === "short-then-long-press") {
+ const window = this.foregroundWindow();
+ if (window?.holdToTalk) {
+ this.openEscapeMenu();
+ return { shell: true, window: false };
+ }
+ // Over the open system menu it switches to the app's context menu:
+ // close the system menu and deliver the gesture to the window as
+ // usual. A window without a menu of its own would only ask for the
+ // system menu back, so for it the open menu stays.
+ if (
+ !this.activeVoiceLayer &&
+ window?.hasAppMenu?.() &&
+ this.stack.popIfTop((layer) => layer instanceof ShellOverlayMenuLayer)
+ ) {
+ this.config.requestShellRender();
+ }
+ if (this.activeVoiceLayer || !this.stack.isAtBase()) {
+ return { shell: true, window: false };
+ }
+ if (!window) {
+ return { shell: true, window: false };
+ }
if (this.focus === "sidebar") {
this.focus = "window";
window.onFocus?.(this.lastInput);
@@ -695,13 +818,14 @@ class Shell {
* strip left of the icon columns when the one-column variant is active.
*/
screenshotCropRect(): { x: number; y: number; width: number; height: number } {
+ const appId = this.foregroundWindow()?.appId;
const heightMode = this.foregroundWindow()?.heightMode ?? "min";
- const x = sidebarContentLeft(this.windows.length);
+ const x = sidebarWidth(appId) === 0 ? 0 : sidebarContentLeft(this.windows.length);
return {
x,
- y: windowTop(heightMode),
+ y: windowTop(heightMode, appId),
width: G2_LENS_WIDTH - x,
- height: windowBandHeight(heightMode),
+ height: windowBandHeight(heightMode, appId),
};
}
@@ -715,6 +839,7 @@ class Shell {
const foreground = this.foregroundWindow()?.windowId ?? "none";
if (!this.screenOn) return `fg=${foreground} target=screen-off`;
if (this.activeVoiceLayer) return `fg=${foreground} target=voice`;
+ if (this.activeKeyboardLayer) return `fg=${foreground} target=keyboard`;
if (!this.stack.isAtBase()) return `fg=${foreground} target=shell-overlay`;
return `fg=${foreground} target=${this.focus}`;
}
@@ -823,7 +948,7 @@ class Shell {
}
// Re-checked after the await: another path may have opened a dialog
// (or torn down the base state) while a permission prompt was up.
- if (!ready || this.activeVoiceLayer) return;
+ if (!ready || this.activeVoiceLayer || this.activeKeyboardLayer) return;
this.openVoiceDialogNow(options);
this.config.requestShellRender();
})();
@@ -909,9 +1034,9 @@ class Shell {
/**
* Open the voice dialog aimed at the foreground window. Called when the
- * user picks Voice input from a window's menu (in-process directly, worker
- * apps via a start-voice-input message). The menu click already ended the
- * press, so the dialog finishes on click instead of long-press-release.
+ * user picks Voice input from the system menu (or an app asks via a
+ * start-voice-input message). The menu click already ended the press, so
+ * the dialog finishes on click instead of long-press-release.
*/
startVoiceInput(): void {
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return;
@@ -922,8 +1047,64 @@ class Shell {
this.config.requestShellRender();
}
+ /**
+ * Open the keyboard dialog: the voice dialog's typed twin, driven by the
+ * phone's keyboard button (beside the mic button, whose wakeword this
+ * mirrors: it wakes a dark screen too). Over the assistant overlay the text
+ * continues that conversation; otherwise it goes to the usual destinations
+ * with Send to Assistant highlighted. Returns the session the phone types
+ * into (the already-open one if there is one), or null while a voice
+ * dialog is up.
+ */
+ startKeyboardInput(): KeyboardInputSession | null {
+ if (this.activeKeyboardLayer) return this.activeKeyboardLayer;
+ if (this.activeVoiceLayer || this.foregroundWindow()?.isVoiceCapturing?.()) return null;
+ if (!this.screenOn) this.wake("sidebar");
+ const assistantLayer = this.assistantLayer;
+ const assistantSession = this.assistantSession;
+ let targets: VoiceSendTarget[];
+ let defaultIndex = 0;
+ if (assistantLayer && assistantSession) {
+ targets = [
+ {
+ id: "assistant",
+ label: "Send",
+ onSend: (text) => this.runAssistantTurn(assistantSession, assistantLayer, text),
+ },
+ ];
+ } else {
+ targets = this.buildVoiceSendTargets();
+ defaultIndex = Math.max(0, targets.findIndex((target) => target.id === "assistant"));
+ }
+ const layer = new KeyboardInputLayer({
+ actions: this.config.actions,
+ onClosed: () => {
+ if (this.activeKeyboardLayer === layer) {
+ this.activeKeyboardLayer = null;
+ this.config.onKeyboardInputChanged?.(null);
+ // The idle countdown restarts in full once keyboard input ends.
+ this.noteUserActivity();
+ }
+ },
+ dismiss: () => {
+ this.stack.popIfTop((top) => top === layer);
+ // A send or discard from the phone side arrives outside the input
+ // path, so nothing else asks for the repaint.
+ this.config.requestShellRender();
+ },
+ sendTargets: targets,
+ defaultTargetIndex: defaultIndex,
+ });
+ this.activeKeyboardLayer = layer;
+ this.stack.push(layer);
+ this.config.onKeyboardInputChanged?.(layer);
+ this.config.requestShellRender();
+ return layer;
+ }
+
isAssistantAvailable(): boolean {
- return this.resolveAssistantConfiguration() !== null;
+ const current = this.getAssistantConversations().current();
+ return this.resolveAssistantConfiguration(current.model, current.reasoning) !== null;
}
/** Observe assistant turns (see AssistantActivityEvent). */
@@ -961,20 +1142,13 @@ class Shell {
}
private ensureAssistantSession(): AssistantSession | null {
- const config = this.resolveAssistantConfiguration();
- if (!config) return null;
- if (
- !this.assistantSession ||
- this.assistantSession.isExpired() ||
- !this.assistantSession.matchesConfiguration(config)
- ) {
- this.assistantSession?.cancel();
- this.assistantSession = new AssistantSession(config);
- }
- return this.assistantSession;
+ return this.getAssistantConversations().ensureSession();
}
- private resolveAssistantConfiguration(): AssistantBackendConfig | null {
+ private resolveAssistantConfiguration(
+ model: AssistantModel = this.conversations?.current().model ?? assistantModelSetting.get(),
+ reasoning: ReasoningLevel = this.conversations?.current().reasoning ?? "default",
+ ): AssistantBackendConfig | null {
if (assistantBackendSetting.get() === "external") {
const host = assistantBridgeHostSetting.get().trim();
const token = assistantBridgeTokenSetting.get();
@@ -982,10 +1156,11 @@ class Shell {
const port = parseInt(assistantBridgePortSetting.get(), 10) || 8790;
return { kind: "external", bridge: { host, port, token } };
}
- const llm = resolveAssistantModel(assistantModelSetting.get(), {
+ const llm = resolveAssistantModel(model, {
anthropic: anthropicApiKeySetting.get(),
openai: openAiApiKeySetting.get(),
});
+ if (llm && reasoning !== "default" && llm.effort) llm.effort = reasoning;
return llm ? { kind: "direct", llm } : null;
}
@@ -1005,7 +1180,9 @@ class Shell {
* Opens the assistant overlay if it isn't already up; a follow-up reuses the
* existing session and overlay.
*/
- sendToAssistant(text: string): void {
+ sendToAssistant(text: string, showOverlay = true): void {
+ text = text.trim();
+ if (!text) return;
const session = this.ensureAssistantSession();
if (!session) {
this.showAlert(
@@ -1015,7 +1192,15 @@ class Shell {
);
return;
}
+ if (session.isTurnActive()) {
+ this.showAlert("The assistant is still working on the previous request");
+ return;
+ }
if (!this.screenOn) this.wake("sidebar");
+ if (!showOverlay || this.foregroundWindow()?.appId === "ai-chat") {
+ this.runAssistantTurn(session, null, text);
+ return;
+ }
let layer = this.assistantLayer;
if (!layer) {
const created = new AssistantLayer(this.config.actions, {
@@ -1024,7 +1209,7 @@ class Shell {
onClose: () => this.closeAssistantLayer(),
onRemoved: () => {
// Removed by any path (Done, or the screen sleeping mid-conversation):
- // stop the turn and drop the reference so a later query starts clean.
+ // stop the turn and drop the overlay reference; keep shared history.
this.assistantSession?.cancel();
if (this.assistantLayer === created) this.assistantLayer = null;
this.emitAssistantActivity({ phase: "closed", text: "" });
@@ -1038,23 +1223,24 @@ class Shell {
this.config.requestShellRender();
}
- private runAssistantTurn(session: AssistantSession, layer: AssistantLayer, text: string): void {
- layer.startTurn();
+ private runAssistantTurn(session: AssistantSession, layer: AssistantLayer | null, text: string): void {
+ if (session.isTurnActive()) return;
+ layer?.startTurn();
let replySoFar = "";
this.emitAssistantActivity({ phase: "thinking", text: "" });
session.sendUtterance(text, this.buildAssistantContext(), {
onTextDelta: (delta, textSoFar) => {
replySoFar = textSoFar;
- layer.onTextDelta(delta, textSoFar);
+ layer?.onTextDelta(delta, textSoFar);
this.emitAssistantActivity({ phase: "streaming", text: textSoFar });
},
- onToolActivity: (label) => layer.onToolActivity(label),
+ onToolActivity: (label) => layer?.onToolActivity(label),
onTurnDone: () => {
- layer.onTurnDone();
+ layer?.onTurnDone();
this.emitAssistantActivity({ phase: "done", text: replySoFar });
},
onError: (message) => {
- layer.onError(message);
+ layer?.onError(message);
this.emitAssistantActivity({ phase: "error", text: message });
},
});
@@ -1068,7 +1254,7 @@ class Shell {
private startAssistantFollowUp(handsFree = false): void {
const layer = this.assistantLayer;
const session = this.assistantSession;
- if (!layer || !session || this.activeVoiceLayer) return;
+ if (!layer || !session || this.activeVoiceLayer || this.activeKeyboardLayer) return;
const voice = new VoiceInputLayer({
actions: this.config.actions,
onClosed: () => {
@@ -1141,14 +1327,28 @@ class Shell {
}
/**
- * The held-long-press safeguard menu. Shell-owned and shell-drawn (never
- * the app's), so an unresponsive app can always be closed. It opens over
- * whatever the app did with the long-press, including its own menu.
+ * A window's answer to tap-then-hold when it has no context menu of its
+ * own: open the system menu in its place, so both gestures land on the
+ * same menu. Ignored unless the window is still the foreground one.
+ */
+ openSystemMenu(windowId: string): void {
+ if (this.foregroundWindow()?.windowId !== windowId) return;
+ this.openEscapeMenu();
+ }
+
+ /**
+ * The system/escape menu: the entries every window shares (Focus app
+ * switcher, Voice input, Brightness, Close window) plus Debug. Shell-owned and
+ * shell-drawn (never the app's), so an unresponsive app can always be
+ * closed. It opens for long-press (over the app's own menu too), after an
+ * extended hold in a window that claims long-press, and on a window's
+ * request when tap-then-hold finds it has no menu of its own.
*/
private openEscapeMenu(): void {
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return;
const foreground = this.foregroundWindow();
if (!foreground) return;
+ let layer: ShellOverlayMenuLayer;
const items: MenuItem[] = [];
if (foreground.closeable) {
items.push({
@@ -1161,6 +1361,40 @@ class Shell {
},
});
}
+ // Close window sits first but the menu opens on Focus app switcher, so a
+ // reflexive tap never closes the window.
+ const initialSelection = items.length;
+ items.push(
+ {
+ // Defocus the app (hand focus to the sidebar) without closing it: the
+ // reliable way out of an app that consumes double-click. Closing the
+ // menu is what yields focus, so popping is the whole action.
+ label: "Focus app switcher",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ },
+ },
+ {
+ label: "Voice input",
+ onSelect: (ctx) => {
+ // The transcript is aimed at the foreground window, so keep focus
+ // there through the pop instead of yielding to the sidebar.
+ layer.keepWindowFocus = true;
+ ctx.stack.pop();
+ this.startVoiceInput();
+ },
+ },
+ );
+ if (brightnessSetting.get() !== "auto") {
+ items.push({
+ label: "Brightness",
+ onSelect: (ctx) => {
+ ctx.stack.pop();
+ ctx.stack.push(new BrightnessPickerLayer(() => this.yieldFocusToSidebar()));
+ this.config.requestShellRender();
+ },
+ });
+ }
items.push({
label: "Debug",
onSelect: (ctx) => {
@@ -1168,7 +1402,18 @@ class Shell {
this.openToolDebugDialog();
},
});
- this.stack.push(new ShellOverlayMenuLayer(items, () => this.yieldFocusToSidebar()));
+ // Gesture help: tap-then-hold switches to the app's own context menu,
+ // when the app has one (otherwise it opens this very menu, not worth a
+ // hint).
+ const footer = foreground.hasAppMenu?.()
+ ? (foreground.holdToTalk ? undefined : gestureHints([[GESTURE_SHORT_THEN_LONG_PRESS, "app menu"]]))
+ : undefined;
+ layer = new ShellOverlayMenuLayer(items, footer, () => this.yieldFocusToSidebar());
+ layer.selectItem(initialSelection);
+ this.stack.push(layer);
+ // Tell the window the system menu opened over it: an app with its own
+ // context menu up closes it, so the two context menus never stack.
+ void foreground.handleInput(makeInputEvent({ type: "system-menu-opened" }), 0);
this.config.requestShellRender();
}
@@ -1203,6 +1448,7 @@ class Shell {
selectedIndex: this.selectedIndex,
focus: this.focus,
foregroundHeightMode: this.foregroundWindow()?.heightMode ?? "min",
+ foregroundAppId: this.foregroundWindow()?.appId,
battery: this.battery,
trayIcons: Array.from(this.trayIcons.keys())
.sort()
@@ -1254,6 +1500,8 @@ function rawInputEventToPayload(event: RawInputEvent): InputEventPayload {
return { type: "long-press", source: eventSourceToString(event.eventSource) };
} else if (event.eventType === OsEventTypeList.RING_LONG_PRESS_RELEASE_EVENT) {
return { type: "long-press-release", source: eventSourceToString(event.eventSource) };
+ } else if (event.eventType === OsEventTypeList.SHORT_THEN_LONG_PRESS_EVENT) {
+ return { type: "short-then-long-press", source: eventSourceToString(event.eventSource) };
}
} else if (event.kind === "watch-gesture") {
// Synthetic, from the Wear OS remote (app/g2/wear-remote.ts); the glasses
@@ -1325,6 +1573,8 @@ export function inputEventToString(event: InputEvent): string {
return `Long press from ${event.source}`;
case "long-press-release":
return `Long press release from ${event.source}`;
+ case "short-then-long-press":
+ return `Short then long press from ${event.source}`;
case "swipe-left":
return `Swipe left from ${event.source}`;
case "swipe-right":
@@ -1337,6 +1587,8 @@ export function inputEventToString(event: InputEvent): string {
return `Display wake`;
case "wakeword":
return `Wakeword`;
+ case "system-menu-opened":
+ return `System menu opened`;
default:
case "unknown":
return `Unknown event: ${event.kind} ${event.eventSource} ${event.eventType}`;
diff --git a/app/ui/shell/voice-input.ts b/app/ui/shell/voice-input.ts
index bb0a16df..ed5f88c8 100644
--- a/app/ui/shell/voice-input.ts
+++ b/app/ui/shell/voice-input.ts
@@ -1,28 +1,10 @@
-import { G2_LENS_WIDTH, GrayImage } from "../../graphics/image";
-import { wrapText, truncateText } from "../../graphics/textwrap";
-import { type BdfFont } from "../../graphics/bdffont";
-import { getDefaultSmallFont } from "../../graphics/ui-fonts";
+import { type GrayImage } from "../../graphics/image";
import { voiceControlBridge, type VoiceTranscriptEvent } from "../../native/voice-control";
import { refineDictation, type AnthropicStreamHandle } from "../../native/anthropic";
import { anthropicApiKeySetting } from "../dashboard-settings";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, gestureHints, type InputEvent } from "../gestures";
-import { drawSelectionHighlight } from "../menu";
-import { listRowHeight } from "../metrics";
import { Layer, type LayerActions, type LayerContext } from "../layers";
-import { MIN_WINDOW_HEIGHT, minWindowTop } from "./geometry";
-
-const DIALOG_X = 40;
-const DIALOG_W = G2_LENS_WIDTH - 80;
-// The dialog fits inside the min-height window band (like the other shell
-// overlays), wherever the vertical position setting puts it.
-const DIALOG_MARGIN_Y = 24;
-const DIALOG_H = MIN_WINDOW_HEIGHT - 2 * DIALOG_MARGIN_Y;
-const TEXT_MAX_WIDTH = DIALOG_W - 32;
-
-/** Dialog top edge; band-relative, so computed per paint. */
-function dialogY(): number {
- return minWindowTop() + DIALOG_MARGIN_Y;
-}
+import { paintInputDialog } from "./input-dialog";
// After the mic stops, the provider's final transcript can trail in (cloud
// commit round-trip); wait this long for it before refining with what we have.
const FOLLOWUP_FINALIZE_TIMEOUT_MS = 1200;
@@ -228,48 +210,16 @@ export class VoiceInputLayer implements Layer {
}
paint(_ctx: LayerContext, paintBelow: () => GrayImage): GrayImage {
- const font = getDefaultSmallFont();
- const menuRowH = listRowHeight(font);
const image = paintBelow();
- const top = dialogY();
-
- // Solid dialog box over the underlying UI. Fill 1, not 0: identical after
- // 4bpp quantization, but 0 is transparent on the color-key shell surface.
- image.fillRoundedRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 1, 10);
- image.drawRoundedRect(DIALOG_X, top, DIALOG_W, DIALOG_H, 90, 10);
-
- const left = DIALOG_X + 16;
- image.drawText(font, left, top + 12, this.capturing ? "Voice ●" : "Voice", 220);
- image.drawText(font, left, top + 30, truncateText(font, this.status, TEXT_MAX_WIDTH), 130);
-
const inMenu = this.phase === "menu";
- const rows = inMenu ? this.menuRows() : [];
- // Reserve space for the actual number of rows this menu has.
- const textBottom = inMenu ? top + DIALOG_H - rows.length * menuRowH - 8 : top + DIALOG_H - 8;
- const textTop = top + 56;
- const maxLines = Math.max(1, ((textBottom - textTop) / 16) | 0);
-
- const text = this.displayText() || this.placeholderText();
- const wrapped = wrapText(font, text, TEXT_MAX_WIDTH);
- const firstLine = Math.max(0, wrapped.length - maxLines);
- for (let index = firstLine; index < wrapped.length; index++) {
- image.drawText(font, left, textTop + (index - firstLine) * 16, wrapped[index]!, 235);
- }
-
- if (inMenu) {
- const menuTop = top + DIALOG_H - rows.length * menuRowH - 2;
- for (let i = 0; i < rows.length; i++) {
- const rowY = menuTop + i * menuRowH;
- const selected = i === this.menuIndex;
- if (selected) {
- drawSelectionHighlight(image, left - 4, rowY - 2, DIALOG_W - 24, menuRowH - 2, true, 6);
- }
- const row = rows[i]!;
- image.drawText(font, left + 4, rowY + 2, row.label, row.dim ? 90 : selected ? 255 : 200);
- }
- } else {
- image.drawText(font, left, top + DIALOG_H - 14, this.hintText(), 110-font.lineHeight);
- }
+ paintInputDialog(image, {
+ title: this.capturing ? "Voice ●" : "Voice",
+ status: this.status,
+ text: this.displayText() || this.placeholderText(),
+ rows: inMenu ? this.menuRows() : [],
+ selectedRow: this.menuIndex,
+ hint: inMenu ? undefined : this.hintText(),
+ });
return image;
}
diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts
index a44bfbca..ce68989b 100644
--- a/app/ui/shell/worker-window.ts
+++ b/app/ui/shell/worker-window.ts
@@ -1,6 +1,6 @@
import { GrayImage } from "../../graphics/image";
import { windowIcon } from "./chrome-layer";
-import { type IconName } from "../../graphics/icons";
+import { type IconActivity, type IconName } from "../../graphics/icons";
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
import { appViewportSize, type WindowHeightMode } from "./geometry";
import * as frameTimings from "../../native/frame-timings";
@@ -13,7 +13,8 @@ import { shell, type ShellWindow } from "./shell";
* worker→Java directly.
*/
export type WorkerAppMessage =
- | { type: "open-window"; windowId: string; surfaceId: string; viewport: { width: number; height: number } }
+ | { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
+ | { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
| { type: "close-window"; windowId: string }
| { type: "input"; windowId: string; event: unknown; frameId: number; focused: boolean }
| { type: "text-input"; windowId: string; text: string }
@@ -61,16 +62,39 @@ export type WorkerAppReply =
}
| { type: "set-title"; windowId: string; title: string }
| { type: "set-attention"; windowId: string; attention: boolean }
+ /** App-driven animation phase for sidebar icons that support an activity cursor. */
+ | { type: "set-icon-activity"; windowId: string; activity: IconActivity }
| {
- /** Window-menu pick: open the shell's voice dialog aimed at this window. */
+ /** Open the shell's voice dialog aimed at this window (a menu pick). */
type: "start-voice-input";
windowId: string;
}
| {
- /** Window-menu pick: close this window (the shell owns the close path). */
+ /** Close this window (the shell owns the close path). */
type: "close-window-request";
windowId: string;
}
+ | {
+ /**
+ * The window's answer to tap-then-hold when it has no context menu of
+ * its own: open the shell's system menu in its place.
+ */
+ type: "open-system-menu";
+ windowId: string;
+ }
+ | {
+ /**
+ * The window's current gesture bindings, posted on change. hasAppMenu:
+ * tap-then-hold opens a context menu with something in it (the system
+ * menu shows its app-menu hint only then). claimsLongPress: the app
+ * gives long-press a meaning of its own, so the shell forwards it
+ * rather than opening the system menu (see ShellWindow).
+ */
+ type: "set-window-gestures";
+ windowId: string;
+ hasAppMenu: boolean;
+ claimsLongPress: boolean;
+ }
| {
/** Open or focus the Settings app, optionally jumping to a section. */
type: "open-settings";
@@ -172,6 +196,9 @@ const TOOL_CALL_HOST_TIMEOUT_MS = 15_000;
export class WorkerAppHost {
private readonly openWindows = new Set();
+ private readonly windowIconActivity = new Map();
+ /** Per-window gesture bindings, as last reported (see set-window-gestures). */
+ private readonly windowGestures = new Map();
private readonly pendingToolCalls = new Map();
private nextCallSerial = 1;
/**
@@ -241,6 +268,23 @@ export class WorkerAppHost {
this.options.requestShellRender();
}
break;
+ case "open-system-menu":
+ if (this.openWindows.has(message.windowId)) {
+ shell.openSystemMenu(message.windowId);
+ }
+ break;
+ case "set-icon-activity":
+ if (this.openWindows.has(message.windowId) && this.windowIconActivity.get(message.windowId) !== message.activity) {
+ this.windowIconActivity.set(message.windowId, message.activity);
+ this.options.requestShellRender();
+ }
+ break;
+ case "set-window-gestures":
+ this.windowGestures.set(message.windowId, {
+ hasAppMenu: message.hasAppMenu,
+ claimsLongPress: message.claimsLongPress,
+ });
+ break;
case "open-settings":
this.options.openSettings(message.section);
break;
@@ -303,7 +347,8 @@ export class WorkerAppHost {
type: "open-window",
windowId: spec.windowId,
surfaceId,
- viewport: appViewportSize(heightMode),
+ title: spec.title,
+ viewport: appViewportSize(heightMode, this.options.appId),
});
const window: ShellWindow = {
appId: this.options.appId,
@@ -313,15 +358,23 @@ export class WorkerAppHost {
closeable: true,
acceptsDirectional: spec.acceptsDirectional,
heightMode,
+ // These apps can resize their live content without losing route/session state.
+ relayout: this.options.appId === "navigate" || this.options.appId === "terminal"
+ ? () => this.post({ type: "resize-window", windowId: spec.windowId, viewport: appViewportSize(heightMode, this.options.appId) })
+ : undefined,
+ hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
+ claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
close: () => {
this.openWindows.delete(spec.windowId);
+ this.windowGestures.delete(spec.windowId);
+ this.windowIconActivity.delete(spec.windowId);
// Withdraw this window's tools and fail any in-flight calls to it.
toolRegistry.removeAppTools(spec.windowId);
this.failPendingToolCallsFor(spec.windowId);
this.post({ type: "close-window", windowId: spec.windowId });
this.options.removeSurface(surfaceId);
},
- drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph),
+ drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph, () => this.windowIconActivity.get(spec.windowId) ?? "idle"),
handleInput: (event, frameId) => {
frameTimings.logFrame(frameId, `input posted to the ${this.options.appId} worker`);
this.post({
diff --git a/app/ui/window-menu.ts b/app/ui/window-menu.ts
index fb1df546..f439bfb6 100644
--- a/app/ui/window-menu.ts
+++ b/app/ui/window-menu.ts
@@ -1,28 +1,57 @@
import { GrayImage } from "../graphics/image";
import { singlePlane, type Plane } from "../graphics/plane";
-import { type InputEvent } from "./gestures";
+import { GESTURE_LONG_PRESS, GESTURE_SHORT_THEN_LONG_PRESS, gestureHints, type InputEvent } from "./gestures";
import { type Layer, LayerStack, noopLayerActions } from "./layers";
-import { MenuLayer, type MenuItem, type MenuLayout } from "./menu";
+import { CONTEXT_MENU_DIM, MenuLayer, type MenuItem, type MenuLayout } from "./menu";
import type { WorkerAppReply } from "./shell/worker-window";
/**
- * The window long-press menu. By convention every app answers a long-press by
- * opening one of these: its app-specific actions followed by the default
- * entries (Voice input, Close window). This is a convenience path, not the
- * safety net — the shell separately opens its own escape menu when the press
- * is held long enough, so an unresponsive app can always be closed.
+ * The window context menu, opened by tap-then-hold: an app's own menu,
+ * holding its app-specific actions. The shell's system menu (long-press)
+ * carries the entries every window shares — Focus app switcher, Voice input,
+ * Close window — so an app with nothing of its own to offer has no menu of
+ * its own: tap-then-hold then opens the system menu in its place, so both
+ * gestures land on the same menu. The system menu is also the safety net:
+ * shell-owned, so an unresponsive app can always be closed (a window that
+ * claims long-press for a move of its own reaches it by holding the press).
*/
-/** Viewport-relative layout; visually matches the shell's escape menu position. */
-export const WINDOW_MENU_LAYOUT: MenuLayout = { x: 8, y: 8, width: 272, minHeight: 0 };
+/** Centered over the viewport; visually matches the shell's system menu position. */
+export const WINDOW_MENU_LAYOUT: MenuLayout = {
+ x: "center",
+ y: 8,
+ width: 272,
+ minHeight: 150,
+ footer: gestureHints([[GESTURE_LONG_PRESS, "system menu"]]),
+ dimUnderneath: CONTEXT_MENU_DIM,
+};
export class WindowMenuLayer extends MenuLayer {
- constructor(items: MenuItem[]) {
- super(null, items, WINDOW_MENU_LAYOUT);
+ constructor(title: string | null, items: MenuItem[], holdToTalk = false) {
+ super(title, items, holdToTalk
+ ? { ...WINDOW_MENU_LAYOUT, footer: gestureHints([[GESTURE_SHORT_THEN_LONG_PRESS, "system menu"]]) }
+ : WINDOW_MENU_LAYOUT);
}
}
export type WindowMenuOptions = {
+ windowId: string;
+ post: (reply: WorkerAppReply) => void;
+ /** Menu title: the window's title, read at open time. */
+ title: () => string;
+ /**
+ * The app's menu entries, built at open time so they reflect current
+ * state. Empty means the window has no context menu right now: open()
+ * asks the shell for the system menu instead.
+ */
+ items: () => MenuItem[];
+ /**
+ * True while the app gives long-press a meaning of its own (a game move).
+ * The shell then forwards long-presses to the window instead of opening
+ * the system menu on them; holding the press past the escape threshold
+ * still reaches the system menu. Default: never.
+ */
+ claimsLongPress?: () => boolean;
/** Paint the window content the menu draws over (a fresh, mutable image). */
paintBase: () => GrayImage;
size: { width: number; height: number };
@@ -34,76 +63,91 @@ export type WindowMenuOptions = {
* a persistent LayerStack. Wraps a short-lived stack so MenuLayer (and the
* ctx.stack.pop() convention in item callbacks) works unchanged.
*
- * Usage: route input to handleInput while isOpen(); paint() returns the
- * window content with the menu drawn over it.
+ * Usage: answer tap-then-hold with open(); route input to handleInput while
+ * isOpen(); paint every frame through paint(), which returns the window
+ * content with the menu drawn over it and keeps the shell told about the
+ * window's gesture bindings (whether it has a menu, whether it claims
+ * long-press).
*/
export class WindowMenu {
private stack: LayerStack | null = null;
+ private reported: { hasAppMenu: boolean; claimsLongPress: boolean } | null = null;
constructor(private readonly options: WindowMenuOptions) {}
+ resize(size: { width: number; height: number }): void {
+ this.options.size = size;
+ this.stack?.setBaseSize(size);
+ }
+
isOpen(): boolean {
return this.stack !== null;
}
- open(items: MenuItem[]): void {
+ /** True when tap-then-hold currently opens this menu with something in it. */
+ isAvailable(): boolean {
+ return this.options.items().length > 0;
+ }
+
+ /**
+ * Open the menu, or the shell's system menu when this window has no
+ * entries. `items` overrides the window's own entries for an app that
+ * reuses this host for another list (a per-row action menu).
+ */
+ open(items: MenuItem[] = this.options.items()): void {
if (this.stack) return;
+ if (!items.length) {
+ this.options.post({ type: "open-system-menu", windowId: this.options.windowId });
+ return;
+ }
const base: Layer = {
paint: () => this.options.paintBase(),
handleInput: () => {},
};
const stack = new LayerStack(base, { ...noopLayerActions }, this.options.size, this.options.isFocused);
- stack.push(new WindowMenuLayer(items));
+ stack.push(new WindowMenuLayer(this.options.title(), items));
this.stack = stack;
}
- /** Paint the window content with the menu over it (content alone if closed). */
- paint(): Plane[] {
- return this.stack ? this.stack.paint() : singlePlane(this.options.paintBase());
+ /**
+ * Paint the window content with the menu over it. `content` paints the
+ * closed-state content (default: paintBase alone), for windows whose
+ * ordinary frame has more planes than the menu needs beneath it.
+ */
+ paint(content?: () => Plane[]): Plane[] {
+ this.syncGestures();
+ if (this.stack) return this.stack.paint();
+ return content ? content() : singlePlane(this.options.paintBase());
+ }
+
+ /** Tell the shell when this window's gesture bindings change. */
+ private syncGestures(): void {
+ const hasAppMenu = this.isAvailable();
+ const claimsLongPress = this.options.claimsLongPress?.() ?? false;
+ if (this.reported?.hasAppMenu === hasAppMenu && this.reported.claimsLongPress === claimsLongPress) return;
+ this.reported = { hasAppMenu, claimsLongPress };
+ this.options.post({
+ type: "set-window-gestures",
+ windowId: this.options.windowId,
+ hasAppMenu,
+ claimsLongPress,
+ });
}
/** Route an input event to the menu; the menu closes by popping itself. */
async handleInput(event: InputEvent): Promise {
const stack = this.stack;
if (!stack) return;
+ // The shell opened its system menu over this window; close ours so the
+ // two context menus never stack.
+ if (event.type === "system-menu-opened") {
+ stack.clearToBase();
+ this.stack = null;
+ return;
+ }
await stack.handleInput(event);
if (stack.isAtBase()) {
this.stack = null;
}
}
}
-
-/**
- * The default entries every window menu ends with, in worker form: the
- * actions cross to the shell as WorkerAppReply messages. In-process windows
- * build the equivalent items against the shell directly (in-process-window.ts).
- */
-export function defaultWindowMenuItems(
- windowId: string,
- post: (reply: WorkerAppReply) => void,
-): MenuItem[] {
- return [
- {
- // Defocus the app (hand focus to the sidebar) without closing it.
- label: "Focus app switcher",
- onSelect: (ctx) => {
- ctx.stack.pop();
- post({ type: "yield-focus", windowId });
- },
- },
- {
- label: "Voice input",
- onSelect: (ctx) => {
- ctx.stack.pop();
- post({ type: "start-voice-input", windowId });
- },
- },
- {
- label: "Close window",
- onSelect: (ctx) => {
- ctx.stack.pop();
- post({ type: "close-window-request", windowId });
- },
- },
- ];
-}
diff --git a/app/version.ts b/app/version.ts
index 86fced96..0f8315fb 100644
--- a/app/version.ts
+++ b/app/version.ts
@@ -1,2 +1,2 @@
-export const FACECLAW_VERSION = "0.6.2";
+export const FACECLAW_VERSION = "0.6.5";
export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;
diff --git a/faceclaw-extensions/README.md b/faceclaw-extensions/README.md
index 3b33b520..b5abe31a 100644
--- a/faceclaw-extensions/README.md
+++ b/faceclaw-extensions/README.md
@@ -79,7 +79,7 @@ brief:
| `getConfiguredApiKeys(): Promise` | Which keys the user configured (names only). |
| `requestApiKeyAccess(services): Promise>>` | Prompt for and return key values. |
| `playBuzzer(steps): Promise` | Play a piezo tone sequence. |
-| `addCompassListener(fn): () => void` | Activate the magnetometer; receive heading samples. Uncalibrated (see note). |
+| `addCompassListener(fn): () => void` | Activate the magnetometer; receive heading samples (see note). |
| `createLayout(layout): Promise` | Build the initial page (extended layout: full 576×452, no count limit, `preserve`). |
| `replaceLayout(layout): Promise` | Replace the page; `preserve` containers inherit content by name. |
| `setAssistantTools(tools): void` | Contribute voice-assistant tools (namespaced by package name). |
@@ -88,9 +88,21 @@ brief:
### Compass
-`addCompassListener` is **not pre-calibrated**: the magnetometer is inside the
-right arm, which rests on the head with a slight curl that differs between
-wearers and wears. Treat the heading as relative — let the user zero it.
+Each `CompassReading` carries several headings, all degrees clockwise in
+[0, 360):
+
+- `headingDegrees` — the raw glasses reading. **Not pre-calibrated**: the
+ magnetometer is inside the right arm, which rests on the head with a slight
+ curl that differs between wearers and wears, so this is relative.
+- `magneticHeadingDegrees` — raw reading corrected by the wearer's calibration
+ offset from the host's Compass app. `wearerCalibrated` says whether they have
+ calibrated; until then it equals `headingDegrees`.
+- `declinationDegrees` / `trueHeadingDegrees` — local declination from the
+ phone's location, and the magnetic heading with it applied. Absent when the
+ host has no location (no permission, or no fix yet).
+
+Prefer `trueHeadingDegrees` when present, then `magneticHeadingDegrees`. If
+`wearerCalibrated` is false, treat them as relative or let the user zero them.
### Extended layout
diff --git a/faceclaw-extensions/dist/index.d.ts b/faceclaw-extensions/dist/index.d.ts
index 72806cb3..63a80290 100644
--- a/faceclaw-extensions/dist/index.d.ts
+++ b/faceclaw-extensions/dist/index.d.ts
@@ -62,10 +62,34 @@ export type WindowLifecycleEventType = "visible" | "hidden" | "focused" | "blurr
export interface WindowLifecycleEvent {
type: WindowLifecycleEventType;
}
-/** A magnetometer heading sample from {@link FaceclawExtensions.addCompassListener}. */
+/**
+ * A magnetometer heading sample from {@link FaceclawExtensions.addCompassListener}.
+ * All headings are degrees clockwise in [0, 360).
+ */
export interface CompassReading {
- /** Magnetic heading in degrees [0, 360). */
+ /**
+ * Raw magnetic heading as reported by the glasses, with no correction for
+ * how they sit on the wearer's head. Kept for apps that zero it themselves.
+ */
headingDegrees: number;
+ /**
+ * Magnetic heading corrected by the wearer's calibration offset from the
+ * host's Compass app. Equal to `headingDegrees` until they calibrate.
+ */
+ magneticHeadingDegrees: number;
+ /**
+ * Whether the wearer has been through the host's compass calibration, i.e.
+ * whether `magneticHeadingDegrees` and `trueHeadingDegrees` can be trusted
+ * as absolute rather than relative.
+ */
+ wearerCalibrated: boolean;
+ /**
+ * Local magnetic declination (east positive), from the phone's location and
+ * the World Magnetic Model. Absent when the host has no location.
+ */
+ declinationDegrees?: number;
+ /** `magneticHeadingDegrees` plus declination. Absent when declination is. */
+ trueHeadingDegrees?: number;
}
export interface FaceclawContainerCommon {
containerID: number;
@@ -172,10 +196,12 @@ export interface FaceclawExtensions {
* Returns an unsubscribe function; the sensor stays on while at least one
* listener is registered and the app is the foreground window.
*
- * NOT pre-calibrated: the magnetometer sits inside the right arm, which rests
- * against the wearer's head with a slight curl that differs between wearers
- * (and between wears). Treat `headingDegrees` as relative — let the user zero
- * it against a known direction rather than trusting it as true/magnetic north.
+ * The magnetometer sits inside the right arm, which rests against the
+ * wearer's head with a slight curl that differs between wearers (and between
+ * wears), so `headingDegrees` is relative. The host's Compass app lets the
+ * wearer calibrate that away and adds local declination: prefer
+ * `trueHeadingDegrees` when present, then `magneticHeadingDegrees`, and check
+ * `wearerCalibrated` before trusting either as absolute.
*/
addCompassListener(listener: (reading: CompassReading) => void): () => void;
/**
diff --git a/faceclaw-extensions/src/index.ts b/faceclaw-extensions/src/index.ts
index 4e5c4dff..d4706764 100644
--- a/faceclaw-extensions/src/index.ts
+++ b/faceclaw-extensions/src/index.ts
@@ -67,10 +67,34 @@ export interface WindowLifecycleEvent {
type: WindowLifecycleEventType;
}
-/** A magnetometer heading sample from {@link FaceclawExtensions.addCompassListener}. */
+/**
+ * A magnetometer heading sample from {@link FaceclawExtensions.addCompassListener}.
+ * All headings are degrees clockwise in [0, 360).
+ */
export interface CompassReading {
- /** Magnetic heading in degrees [0, 360). */
+ /**
+ * Raw magnetic heading as reported by the glasses, with no correction for
+ * how they sit on the wearer's head. Kept for apps that zero it themselves.
+ */
headingDegrees: number;
+ /**
+ * Magnetic heading corrected by the wearer's calibration offset from the
+ * host's Compass app. Equal to `headingDegrees` until they calibrate.
+ */
+ magneticHeadingDegrees: number;
+ /**
+ * Whether the wearer has been through the host's compass calibration, i.e.
+ * whether `magneticHeadingDegrees` and `trueHeadingDegrees` can be trusted
+ * as absolute rather than relative.
+ */
+ wearerCalibrated: boolean;
+ /**
+ * Local magnetic declination (east positive), from the phone's location and
+ * the World Magnetic Model. Absent when the host has no location.
+ */
+ declinationDegrees?: number;
+ /** `magneticHeadingDegrees` plus declination. Absent when declination is. */
+ trueHeadingDegrees?: number;
}
// ---- Extended layout (a superset of the stock EvenHub page containers) ----
@@ -207,10 +231,12 @@ export interface FaceclawExtensions {
* Returns an unsubscribe function; the sensor stays on while at least one
* listener is registered and the app is the foreground window.
*
- * NOT pre-calibrated: the magnetometer sits inside the right arm, which rests
- * against the wearer's head with a slight curl that differs between wearers
- * (and between wears). Treat `headingDegrees` as relative — let the user zero
- * it against a known direction rather than trusting it as true/magnetic north.
+ * The magnetometer sits inside the right arm, which rests against the
+ * wearer's head with a slight curl that differs between wearers (and between
+ * wears), so `headingDegrees` is relative. The host's Compass app lets the
+ * wearer calibrate that away and adds local declination: prefer
+ * `trueHeadingDegrees` when present, then `magneticHeadingDegrees`, and check
+ * `wearerCalibrated` before trusting either as absolute.
*/
addCompassListener(listener: (reading: CompassReading) => void): () => void;
diff --git a/scripts/pull-frame-timings.sh b/scripts/pull-frame-timings.sh
index 87ffbf66..5c249b18 100755
--- a/scripts/pull-frame-timings.sh
+++ b/scripts/pull-frame-timings.sh
@@ -1,3 +1,3 @@
#!/bin/bash
-adb pull /sdcard/Android/data/com.faceclaw.app/files/frame-timings.txt
+adb "$@" pull /sdcard/Android/data/com.faceclaw.app/files/frame-timings.txt
diff --git a/tests/README.md b/tests/README.md
index 89fd8a77..a9fe157f 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -14,3 +14,16 @@ That compiles the pure modules with the project's TypeScript into
`.test-build/` (git-ignored) and runs `node --test tests/`. No extra
dependencies are needed — the tests are plain `.test.cjs` files that use
`node:test` and `node:assert`.
+
+Compass diagnostics have focused UI and wire-format checks:
+
+ node --test tests/compass-debug.test.cjs tests/compass-protocol.test.cjs
+
+The protocol check also compiles the production Java parser, so it needs a
+JDK (`JAVA_HOME`, or `javac` and `java` on `PATH`). Its golden packet is shared
+with the firmware encoder test in `g2flash/tests/compass_diagnostics_test.c`.
+
+R1 battery field-106 decoding (valid zero, charging, unavailable/disconnected,
+legacy firmware, malformed messages) uses the same C/Java golden packet:
+
+ node --test tests/ring-battery-protocol.test.cjs
diff --git a/tests/app-layout.test.cjs b/tests/app-layout.test.cjs
new file mode 100644
index 00000000..38450863
--- /dev/null
+++ b/tests/app-layout.test.cjs
@@ -0,0 +1,169 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+const js = (source) => ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+}).outputText;
+
+function geometry() {
+ const settings = Object.fromEntries(Object.entries({
+ displayModeSetting: '576x288', verticalPositionSetting: 'middle',
+ navigateDisplayModeSetting: 'global', navigateVerticalPositionSetting: 'global',
+ terminalDisplayModeSetting: 'default', terminalVerticalPositionSetting: 'global',
+ }).map(([name, value]) => [name, { value, get() { return this.value; } }]));
+ const context = { exports: {}, require: (name) => {
+ if (name === '../../graphics/image') return { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 };
+ assert.equal(name, '../dashboard-settings');
+ return settings;
+ } };
+ vm.runInNewContext(js(read('app/ui/shell/geometry.ts')), context);
+ const rect = (mode, appId) => ({ ...context.exports.appViewportRect(mode, appId) });
+ return { ...context.exports, settings, rect };
+}
+
+test('defaults preserve normal windows, EvenHub height and tall terminal sessions', () => {
+ const g = geometry();
+ assert.deepEqual(g.rect('min', 'navigate'), { x: 64, y: 124, width: 576, height: 260 });
+ assert.deepEqual(g.rect('min', 'terminal'), g.rect('min'));
+ assert.deepEqual(g.rect('max', 'terminal'), { x: 64, y: 28, width: 576, height: 452 });
+ assert.equal(g.windowBandHeight('medium', 'evenhub'), 316);
+ g.settings.displayModeSetting.value = '640x480';
+ assert.deepEqual(g.rect('max', 'terminal'), { x: 0, y: 28, width: 640, height: 452 });
+});
+
+test('Navigate can use a small bottom band while other apps fill the panel', () => {
+ const g = geometry();
+ g.settings.displayModeSetting.value = '640x480';
+ g.settings.navigateDisplayModeSetting.value = '576x288';
+ g.settings.navigateVerticalPositionSetting.value = 'bottom';
+ assert.deepEqual(g.rect('min', 'navigate'), { x: 64, y: 220, width: 576, height: 260 });
+ assert.equal(g.minWindowTop('navigate'), 192);
+ assert.equal(g.sidebarStripVisible('window', 'navigate'), true);
+ assert.equal(g.sidebarStripVisible('window', 'other'), false);
+ assert.deepEqual(g.rect('min', 'other'), { x: 0, y: 28, width: 640, height: 452 });
+});
+
+test('Terminal can disable its tall default, inherit position or override both dimensions', () => {
+ const g = geometry();
+ g.settings.terminalDisplayModeSetting.value = 'global';
+ assert.deepEqual(g.rect('max', 'terminal'), g.rect('min'));
+ g.settings.verticalPositionSetting.value = 'top';
+ assert.equal(g.windowTop('max', 'terminal'), 0);
+ g.settings.terminalVerticalPositionSetting.value = 'lower';
+ assert.equal(g.windowTop('max', 'terminal'), 144);
+ g.settings.terminalDisplayModeSetting.value = '640x480';
+ assert.deepEqual(g.rect('max', 'terminal'), { x: 0, y: 28, width: 640, height: 452 });
+ assert.equal(g.sidebarStripVisible('window', 'terminal'), false);
+ assert.equal(g.sidebarStripVisible('sidebar', 'terminal'), true);
+ g.settings.terminalDisplayModeSetting.value = '576x480';
+ assert.deepEqual(g.rect('max', 'terminal'), { x: 64, y: 28, width: 576, height: 452 });
+});
+
+test('all explicit size/position combinations stay within the display and align content below the bar', () => {
+ const g = geometry();
+ for (const globalMode of ['576x288', '576x480', '640x480']) {
+ g.settings.displayModeSetting.value = globalMode;
+ for (const appId of ['navigate', 'terminal']) {
+ for (const mode of ['global', '576x288', '576x480', '640x480']) {
+ g.settings[`${appId}DisplayModeSetting`].value = mode;
+ for (const position of ['global', 'top', 'upper', 'middle', 'lower', 'bottom']) {
+ g.settings[`${appId}VerticalPositionSetting`].value = position;
+ const rect = g.rect('max', appId);
+ assert.equal(rect.x + rect.width, 640);
+ assert.equal(rect.y, g.windowTop('max', appId) + g.TOP_BAR_HEIGHT);
+ assert.ok(rect.y >= 28 && rect.y + rect.height <= 480);
+ }
+ }
+ }
+ }
+});
+
+// Exercise the real worker message handler with platform work stubbed out.
+function resizeHandler(file, globals) {
+ const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
+ const handler = source.statements.find((s) => ts.isExpressionStatement(s)
+ && ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage');
+ assert.ok(handler);
+ const context = { global: {}, ...globals };
+ vm.runInNewContext(js(handler.getText(source)), context);
+ return (viewport) => context.global.onmessage({ data: { type: 'resize-window', windowId: 'test', viewport } });
+}
+
+test('Navigate resize preserves its active route and window, and remeasures an open menu', () => {
+ let paints = 0;
+ let menuSize;
+ const window = { windowId: 'test', viewportWidth: 640, viewportHeight: 452,
+ menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' };
+ const route = { destination: 'Home' };
+ const resize = resizeHandler('app/apps/navigate/navigate-app.worker.ts', {
+ window, route, render: () => { paints++; },
+ });
+ resize({ width: 576, height: 260 });
+ assert.equal(window.viewportHeight, 260);
+ assert.equal(window.viewportWidth, 576);
+ assert.equal(window.lastSubmittedFingerprint, '');
+ assert.equal(route.destination, 'Home');
+ assert.deepEqual(menuSize, { width: 576, height: 260 });
+ resize({ width: 576, height: 260 });
+ assert.equal(paints, 1);
+});
+
+test('Terminal resize keeps the view identity, negotiates its grid and skips position-only changes', () => {
+ const calls = [];
+ const window = { kind: 'view', windowId: 'test', socket: 'session-1',
+ viewportWidth: 576, viewportHeight: 452, cellWidth: 8, cellHeight: 16,
+ menu: null, reconnectTimer: 42, emulator: { dispose: () => calls.push("dispose") },
+ client: { stop: () => calls.push('stop'), setViewport: (...size) => calls.push(size) },
+ };
+ const resize = resizeHandler('app/apps/terminal/terminal-app.worker.ts', {
+ windows: new Map([['test', window]]), clearTimeout: (timer) => calls.push(timer),
+ TerminalEmulator: class { constructor(cols, rows) { this.cols = cols; this.rows = rows; } },
+ reconnectView: (view) => { assert.equal(view, window); calls.push('reconnect'); },
+ scheduleRender: () => calls.push('paint'),
+ });
+ resize({ width: 576, height: 260 });
+ assert.equal(window.socket, 'session-1');
+ assert.equal(window.gridCols, 72);
+ assert.equal(window.gridRows, 16);
+ assert.equal(window.emulator.rows, 16);
+ assert.deepEqual(calls, [42, 'stop', [72, 16], 'dispose', 'reconnect', 'paint']);
+ resize({ width: 576, height: 260 });
+ assert.equal(calls.length, 6);
+});
+
+test('resizing a terminal reconnects with the new grid and ignores callbacks from the old socket', () => {
+ const sockets = [];
+ const context = {
+ exports: {}, require: () => ({}),
+ com: { faceclaw: { app: {
+ FaceclawWebSocketListener: class { constructor(callbacks) { return callbacks; } },
+ FaceclawWebSocket: class {
+ constructor(url, listener) { this.listener = listener; this.messages = []; sockets.push(this); }
+ sendText(text) { this.messages.push(JSON.parse(text)); }
+ close() {}
+ },
+ } } },
+ };
+ vm.runInNewContext(js(read('app/native/g2mirror-client.ts')), context);
+ const client = new context.exports.G2MirrorClient({ host: 'localhost', port: 1234, cols: 72, rows: 28 });
+ client.start();
+ const oldSocket = sockets[0];
+ oldSocket.listener.onOpen();
+ assert.equal(oldSocket.messages[0].height, 28);
+ client.stop();
+ client.setViewport(80, 16);
+ client.start();
+ const newSocket = sockets[1];
+ oldSocket.listener.onClosed(1000, 'bye');
+ oldSocket.listener.onFailure('late failure');
+ oldSocket.listener.onTextMessage('{"type":"error","message":"late error"}');
+ assert.equal(client.state().phase, 'connecting');
+ newSocket.listener.onOpen();
+ assert.equal(newSocket.messages[0].width, 80);
+ assert.equal(newSocket.messages[0].height, 16);
+ assert.equal(client.state().status, 'Authenticating...');
+});
diff --git a/tests/compass-debug.test.cjs b/tests/compass-debug.test.cjs
new file mode 100644
index 00000000..6df4cffe
--- /dev/null
+++ b/tests/compass-debug.test.cjs
@@ -0,0 +1,114 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+
+function load(file, modules = {}, globals = {}) {
+ const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+ const context = { exports: {}, require: (name) => {
+ assert.ok(name in modules, `Unexpected dependency: ${name}`);
+ return modules[name];
+ }, ...globals };
+ vm.runInNewContext(ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+ }).outputText, context, { filename: file });
+ return context.exports;
+}
+const textwrap = load('app/graphics/textwrap.ts');
+const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
+const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
+const font = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
+const small = font(18), large = font(32);
+const diagnostics = { magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 0x8c, sampleTimeMs: 1234 };
+
+function compass(width = 576, height = 260) {
+ const settings = new Map();
+ const debug = load('app/apps/compass/debug.ts', { '../../native/settings-store': {
+ getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback,
+ setBooleanSetting: (key, value) => settings.set(key, value),
+ } });
+ let listener, window, renders = 0, pops = 0;
+ class RecordingImage extends graphics.GrayImage {
+ texts = [];
+ drawText(font, x, y, text, value) {
+ this.texts.push({ x, y, text, width: font.measureText(text), height: font.lineHeight });
+ super.drawText(font, x, y, text, value);
+ }
+ }
+ // GrayImage.clone returns the base class; retain text recording for main-screen paints.
+ const baseClone = RecordingImage.prototype.clone;
+ RecordingImage.prototype.clone = function () {
+ const image = baseClone.call(this); Object.setPrototypeOf(image, RecordingImage.prototype); image.texts = []; return image;
+ };
+ const app = load('app/apps/compass/compass-app.ts', {
+ '../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
+ '../../graphics/image': { GrayImage: RecordingImage }, '../../graphics/textwrap': textwrap,
+ '../../native/compass': { COMPASS_CHANGED: 15, COMPASS_CALIBRATION_STARTED: 16, COMPASS_CALIBRATION_COMPLETE: 17,
+ addCompassListener: (fn) => { listener = fn; return () => {}; }, setCompassEnabled() {} },
+ '../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
+ '../../ui/shell/geometry': { screenCenterInViewportX: () => width / 2 - 32 },
+ '../../ui/shell/in-process-window': {
+ YieldAtRootLayer: class { constructor(layer) { return layer; } },
+ createInProcessWindow: (options) => { window = options; return { requestRender: () => ++renders }; },
+ },
+ '../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
+ '../../g2/android-permissions': { hasLocationPermission: () => false },
+ './calibration': { isCompassCalibrated: () => true, normalizeHeading: (v) => v },
+ './calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
+ './heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
+ './debug': debug,
+ }, { setInterval: () => 1, clearInterval() {} });
+ const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => ++pops } };
+ const open = () => app.createCompassAppWindow({ onClosed() {} }); open();
+ return { open, debug, settings, menu: () => window.menuItems(),
+ toggle: () => window.menuItems().find((item) => item.label.startsWith('Debug information:')).onSelect(ctx),
+ paint: () => window.baseLayer.paint(ctx),
+ heading: (info) => listener({ command: 15, headingDegrees: 359, diagnostics: info }),
+ renders: () => renders, pops: () => pops };
+}
+
+test('debug toggle defaults off, repaints, closes menu and survives reopening', () => {
+ const app = compass(); app.heading(diagnostics);
+ assert.equal(app.debug.isCompassDebugEnabled(), false);
+ assert.ok(!app.paint().texts.some((t) => t.text.startsWith('Mag:')));
+ const before = app.renders(); app.toggle();
+ assert.equal(app.debug.isCompassDebugEnabled(), true);
+ assert.ok(app.renders() > before && app.pops() === 1);
+ app.open(); assert.equal(app.debug.isCompassDebugEnabled(), true);
+ app.toggle(); assert.equal(app.debug.isCompassDebugEnabled(), false);
+});
+
+test('diagnostics sit to the right of the heading without overlap or clipping', () => {
+ for (const width of [240, 320, 576, 640]) {
+ const app = compass(width); app.toggle(); app.heading(diagnostics);
+ const image = app.paint();
+ const heading = image.texts.find((t) => t.text === '359° N');
+ for (const text of ['Mag: 3/3', 'Anom: 2', 'Src: RV']) {
+ const label = image.texts.find((t) => t.text === text);
+ assert.ok(label, text);
+ assert.ok(label.x > heading.x + heading.width);
+ assert.ok(label.x + label.width <= width && label.y + label.height <= image.height);
+ }
+ const status = image.texts.find((t) => t.text === 'Magnetic heading');
+ assert.ok(image.texts.filter((t) => t.text.startsWith('Src:')).every((t) => t.y + t.height < status.y));
+ if (process.env.COMPASS_PREVIEW && width === 576) {
+ fs.writeFileSync(process.env.COMPASS_PREVIEW, Buffer.concat([
+ Buffer.from(`P5\n${image.width} ${image.height}\n255\n`), Buffer.from(image.withDrawsBaked().pixels),
+ ]));
+ }
+ }
+});
+
+test('legacy and missing samples replace diagnostics instead of leaving stale values', () => {
+ const app = compass(); app.toggle(); app.heading(diagnostics);
+ assert.ok(app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
+ app.heading(undefined);
+ assert.ok(app.paint().texts.some((t) => t.text === 'unavailable'));
+ assert.ok(!app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
+ assert.deepEqual(Array.from(app.debug.compassDebugLines({ ...diagnostics, flags: 0 })), ['Sample data', 'unavailable']);
+ for (const [source, name] of [[1, 'GRV'], [2, 'GMRV'], [3, 'RV']]) {
+ assert.equal(app.debug.compassDebugLines({ ...diagnostics, orientationSource: source })[2], `Src: ${name}`);
+ }
+});
diff --git a/tests/compass-protocol.test.cjs b/tests/compass-protocol.test.cjs
new file mode 100644
index 00000000..feee8260
--- /dev/null
+++ b/tests/compass-protocol.test.cjs
@@ -0,0 +1,19 @@
+const test = require('node:test');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+
+test('compass diagnostics decode with legacy and malformed-extension fallback', () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-compass-java-'));
+ const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
+ try {
+ execFileSync(javaBin('javac'), ['-d', directory,
+ path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
+ path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
+ path.join(__dirname, 'fixtures/CompassProtocolTest.java')], { stdio: 'pipe' });
+ execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.CompassProtocolTest'], { stdio: 'pipe' });
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/tests/compass-style.test.cjs b/tests/compass-style.test.cjs
new file mode 100644
index 00000000..66d07a7b
--- /dev/null
+++ b/tests/compass-style.test.cjs
@@ -0,0 +1,150 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+
+function load(file, requireModule, globals = {}) {
+ const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+ const js = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+ }).outputText;
+ const context = { exports: {}, require: requireModule, ...globals };
+ vm.runInNewContext(js, context, { filename: file });
+ return context.exports;
+}
+
+const textwrap = load('app/graphics/textwrap.ts');
+const graphics = load('app/graphics/image.ts', () => textwrap);
+const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
+const font = (size) => BdfFont.parse(fs.readFileSync(
+ path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
+const small = font(12);
+const large = font(24);
+
+function compass({ style, width = 576, height = 260 } = {}) {
+ const settings = new Map(style === undefined ? [] : [['compass.style', style]]);
+ let listener;
+ let window;
+ let renders = 0;
+ let pops = 0;
+ class RecordingImage extends graphics.GrayImage {
+ lines = [];
+ texts = [];
+ drawLine(...args) { this.lines.push(args); super.drawLine(...args); }
+ drawText(font, x, y, text, value) {
+ this.texts.push({ x, y, text, value });
+ super.drawText(font, x, y, text, value);
+ }
+ }
+ const modules = {
+ '../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
+ '../../graphics/image': { ...graphics, GrayImage: RecordingImage },
+ '../../graphics/textwrap': textwrap,
+ '../../native/settings-store': {
+ getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
+ setStringSetting: (key, value) => settings.set(key, value),
+ },
+ '../../native/compass': {
+ COMPASS_CHANGED: 1, COMPASS_CALIBRATION_STARTED: 2, COMPASS_CALIBRATION_COMPLETE: 3,
+ addCompassListener: (fn) => { listener = fn; return () => {}; },
+ setCompassEnabled() {},
+ },
+ '../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
+ '../../ui/shell/geometry': { screenCenterInViewportX: () => width - 320 },
+ '../../ui/shell/in-process-window': {
+ YieldAtRootLayer: class { constructor(layer) { return layer; } },
+ createInProcessWindow: (options) => { window = options; return { requestRender: () => renders++ }; },
+ },
+ '../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
+ '../../g2/android-permissions': { hasLocationPermission: () => false },
+ './calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
+ './calibration-layer': {},
+ './declination': { onDeclinationChanged: () => () => {} },
+ './heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
+ };
+ const app = load('app/apps/compass/compass-app.ts', (name) => {
+ assert.ok(name in modules, `Unexpected dependency: ${name}`);
+ return modules[name];
+ }, { setInterval: () => 1, clearInterval() {} });
+ const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => pops++ } };
+ const open = () => app.createCompassAppWindow({ onClosed() {} });
+ open();
+ return {
+ settings, open,
+ menu: () => window.menuItems(),
+ toggle: () => window.menuItems().find((item) => item.label.startsWith('Style:')).onSelect(ctx),
+ paint: () => window.baseLayer.paint(ctx),
+ heading: (degrees) => listener({ command: 1, headingDegrees: degrees }),
+ renders: () => renders,
+ pops: () => pops,
+ };
+}
+
+test('Circle is the default; the context menu switches, repaints and remembers the style', () => {
+ const app = compass();
+ assert.equal(app.menu()[0].label, 'Style: Circle');
+ const before = app.renders();
+ app.toggle();
+ assert.equal(app.menu()[0].label, 'Style: Strip');
+ assert.equal(app.settings.get('compass.style'), 'strip');
+ assert.equal(app.renders(), before + 1);
+ assert.equal(app.pops(), 1);
+ app.open();
+ assert.equal(app.menu()[0].label, 'Style: Strip');
+ app.toggle();
+ assert.equal(app.menu()[0].label, 'Style: Circle');
+ assert.equal(compass({ style: 'unknown' }).menu()[0].label, 'Style: Circle');
+});
+
+test('switching styles preserves the numeric readout and status at every display size', () => {
+ for (const [width, height] of [[576, 260], [576, 452], [640, 452]]) {
+ const app = compass({ width, height });
+ app.heading(82);
+ const circle = app.paint();
+ app.toggle();
+ const strip = app.paint();
+ assert.deepEqual(strip.texts.slice(0, 2), circle.texts);
+ assert.deepEqual(circle.texts.map((item) => item.text), ['82° E', 'Magnetic heading']);
+ }
+});
+
+test('strip ticks are 5 degrees apart on the full-display 23 degree scale', () => {
+ for (const width of [576, 640]) {
+ const app = compass({ style: 'strip', width });
+ app.heading(90);
+ const image = app.paint();
+ const top = image.lines[0][1];
+ const ticks = image.lines.filter(([x0, y0, x1]) => x0 === x1 && y0 === top);
+ assert.deepEqual(ticks.map(([x]) => x), [80, 85, 90, 95, 100]
+ .map((bearing) => Math.round(width - 320 + (bearing - 90) * 640 / 23))
+ .filter((x) => x >= 0 && x < width));
+ assert.equal(image.lines[0][0], 0);
+ assert.equal(image.lines[0][2], width - 1);
+ assert.equal(image.lines[1][1], image.height - 4);
+ assert.ok(image.texts.some(({ text }) => text === 'E'));
+ }
+});
+
+test('bearings scroll continuously through north with wrapped labels', () => {
+ const app = compass({ style: 'strip' });
+ const northX = (heading) => {
+ app.heading(heading);
+ const image = app.paint();
+ const north = image.texts.find(({ text }) => text === 'N');
+ assert.ok(north);
+ assert.ok(image.texts.some(({ text }) => text === '355°'));
+ assert.ok(image.texts.some(({ text }) => text === '5°'));
+ return north.x;
+ };
+ assert.ok(Math.abs(northX(359.9) - northX(0.1) - 0.2 * 640 / 23) <= 1);
+});
+
+test('a strip waiting for sensor data shows the rails without invented bearings', () => {
+ const app = compass({ style: 'strip' });
+ const image = app.paint();
+ assert.deepEqual(image.texts.map(({ text }) => text), ['--°', 'Waiting for compass data…']);
+ assert.equal(image.lines.length, 2);
+ assert.ok(image.lines[0][4] < 105);
+});
diff --git a/tests/compass-texture-cache.test.cjs b/tests/compass-texture-cache.test.cjs
new file mode 100644
index 00000000..15828b99
--- /dev/null
+++ b/tests/compass-texture-cache.test.cjs
@@ -0,0 +1,154 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+
+function load(file, modules = {}, extra = '', globals = {}) {
+ const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8') + extra;
+ const context = { exports: {}, require: (name) => {
+ assert.ok(name in modules, `Unexpected dependency: ${name}`);
+ return modules[name];
+ }, ...globals };
+ vm.runInNewContext(ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+ }).outputText, context, { filename: file });
+ return context.exports;
+}
+
+const textwrap = load('app/graphics/textwrap.ts');
+const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
+const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
+const { GrayImage } = graphics;
+const font = (size) => BdfFont.parse(fs.readFileSync(
+ path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
+const small = font(12);
+const large = font(24);
+let viewportWidth = 576;
+const compass = load('app/apps/compass/compass-app.ts', {
+ '../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
+ '../../graphics/image': graphics,
+ '../../graphics/textwrap': textwrap,
+ '../../native/compass': {},
+ '../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
+ '../../ui/shell/geometry': { screenCenterInViewportX: () => viewportWidth - 320 },
+ '../../ui/shell/in-process-window': {},
+ '../../ui/shell/shell': {},
+ '../../g2/android-permissions': {},
+ './calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
+ './calibration-layer': {},
+ './declination': {},
+ './heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
+}, `
+export { CompassLayer, rotatingRoseBounds, createCompassBackground, drawCompassRose };
+export function referenceFrame(width, height, cx, cy, radius, clipY, heading) {
+ const image = new GrayImage(width, height, 0);
+ const fade = heading === null ? 0.45 : 1;
+ drawPlaneGrid(image, cx, cy, radius, clipY);
+ drawDiscWall(image, cx, cy, radius, fade);
+ drawTiltedRing(image, cx, cy, radius, 105 * fade);
+ drawCompassRose(image, cx, cy, radius, heading);
+ drawHeadingTick(image, cx, cy, radius, 255 * fade);
+ return image;
+}
+`);
+
+test('rotation bounds contain every painted point through a full turn', () => {
+ for (const radius of [24, 60, 98]) {
+ const cx = 120;
+ const cy = 70.25;
+ const bounds = compass.rotatingRoseBounds(cx, cy, radius);
+ assert.ok(bounds.width <= 255 && bounds.height <= 255, 'fits a cache image');
+ const image = new GrayImage(240, 160, 0);
+ // Accumulate the entire sweep, including fractional-degree orientations.
+ for (let heading = 0; heading < 360; heading += 0.5) {
+ compass.drawCompassRose(image, cx, cy, radius, heading);
+ }
+ let count = 0;
+ for (let y = 0; y < image.height; y++) {
+ for (let x = 0; x < image.width; x++) {
+ if (!image.getPixel(x, y)) continue;
+ count++;
+ assert.ok(x >= bounds.x && x < bounds.x + bounds.width
+ && y >= bounds.y && y < bounds.y + bounds.height, `point outside bounds at ${x},${y}`);
+ }
+ }
+ assert.ok(count > 0);
+ }
+});
+
+test('cached background preserves the raster and tick layering at every heading', () => {
+ for (const [width, height, radius] of [[576, 260, 98], [640, 452, 98], [240, 160, 24]]) {
+ const cx = width / 2;
+ const cy = height - 65.25;
+ for (const heading of [null, ...Array.from({ length: 72 }, (_, i) => i * 5)]) {
+ const background = compass.createCompassBackground(width, height, cx, cy, radius, 30, heading === null ? 0.45 : 1);
+ const image = background.clone();
+ compass.drawCompassRose(image, cx, cy, radius, heading);
+ const expected = compass.referenceFrame(width, height, cx, cy, radius, 30, heading);
+ assert.deepEqual(image.withDrawsBaked().pixels, expected.pixels, `heading ${heading}, radius ${radius}`);
+ assert.equal(image.draws.length, 1);
+ const draw = image.draws[0];
+ assert.equal(draw.kind, 'image');
+ assert.equal(draw.source.hasDeferredDraws(), false);
+ const bounds = compass.rotatingRoseBounds(cx, cy, radius);
+ assert.deepEqual({ x: draw.x, y: draw.y, width: draw.source.width, height: draw.source.height }, { ...bounds });
+ // Every nonzero texture pixel must match the final composite, as the
+ // wire planner requires before it can replay a cached image.
+ for (let y = 0; y < draw.source.height; y++) {
+ for (let x = 0; x < draw.source.width; x++) {
+ const value = draw.source.getPixel(x, y);
+ if (value) assert.equal(value, expected.getPixel(draw.x + x, draw.y + y));
+ }
+ }
+ }
+ }
+});
+
+test('heading updates reuse the texture; brightness, layout and clipping changes rebuild it', () => {
+ const layer = new compass.CompassLayer(() => {});
+ layer.enabled = true;
+ let height = 260;
+ const ctx = { stack: { getBaseSize: () => ({ width: viewportWidth, height }) } };
+ const texture = () => layer.paint(ctx).draws.find((draw) => draw.kind === 'image').source;
+ const waiting = texture();
+ layer.rawHeading = 0;
+ const initial = texture();
+ assert.notEqual(initial, waiting);
+ const snapshot = initial.pixels.slice();
+ for (const heading of [1, 45, 180, 359.9, 0]) {
+ layer.rawHeading = heading;
+ assert.equal(texture(), initial);
+ }
+ assert.deepEqual(initial.pixels, snapshot, 'shared texture remains immutable');
+ height = 452;
+ const tall = texture();
+ assert.notEqual(tall, initial);
+ viewportWidth = 640;
+ const wide = texture();
+ assert.notEqual(wide, tall);
+ layer.firmwareStatus = 'Calibration status '.repeat(12);
+ assert.notEqual(texture(), wide);
+ viewportWidth = 576;
+});
+
+test('the background registers once and uses a nine-byte image reference on later frames', () => {
+ const registered = [];
+ const { prepareFrameDraws } = load('app/graphics/glyph-wire.ts', {}, '', {
+ global: { isAndroid: true },
+ com: { faceclaw: { app: { ImageAtlas: { ensure: (...args) => {
+ registered.push(args);
+ return 1;
+ } } } } },
+ });
+ const background = compass.createCompassBackground(576, 260, 256, 193.25, 98, 140, 1);
+ for (const heading of [0, 1, 2, 45, 90]) {
+ const image = background.clone();
+ compass.drawCompassRose(image, 256, 193.25, 98, heading);
+ const buffer = prepareFrameDraws(image.draws);
+ assert.equal(buffer.byteLength, 9);
+ assert.equal(new DataView(buffer).getUint8(0), 1);
+ }
+ assert.equal(registered.length, 1);
+});
diff --git a/tests/evenhub-containers.test.cjs b/tests/evenhub-containers.test.cjs
new file mode 100644
index 00000000..366ee7f1
--- /dev/null
+++ b/tests/evenhub-containers.test.cjs
@@ -0,0 +1,91 @@
+// The SDK 0.0.14 additions to the page-container payload: the contextual menu
+// (`menuObject`) and text brightness (`textColor`).
+//
+// The payloads here were captured by running the real @evenrealities/
+// even_hub_sdk 0.0.14 against a stub `flutter_inappwebview.callHandler` and
+// recording what it sent, so they are the literal wire shapes, not a reading
+// of the docs. The rules the parser enforces are the ones the SDK enforces
+// app-side before it will call the host at all.
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { parsePage, declaredMenuItems } = require("../.test-build/app/apps/evenhub/containers.js");
+
+const menuItem = (itemID, itemName) => ({ itemName, itemID });
+
+test("a menuObject becomes the page's contextual menu", () => {
+ const page = parsePage({
+ containerTotalNum: 1,
+ textObject: [{ containerID: 1, containerName: "main", content: "hi" }],
+ menuObject: { menuItems: [menuItem(1, "Pause"), menuItem(2, "Resume")] },
+ });
+ assert.deepEqual(page.menuItems, [
+ { itemName: "Pause", itemID: 1 },
+ { itemName: "Resume", itemID: 2 },
+ ]);
+});
+
+test("a page with no menuObject has no menu, which is how rebuild clears one", () => {
+ const page = parsePage({ textObject: [{ containerID: 1, containerName: "main" }] });
+ assert.deepEqual(page.menuItems, []);
+});
+
+test("protobuf-style menu keys parse the same as camelCase", () => {
+ const page = parsePage({ Menu_Object: { Menu_Items: [{ Item_Name: "Go", Item_ID: 3 }] } });
+ assert.deepEqual(page.menuItems, [{ itemName: "Go", itemID: 3 }]);
+});
+
+test("menu entries the firmware cannot represent are dropped, not the whole page", () => {
+ const page = parsePage({
+ textObject: [{ containerID: 1, containerName: "main", content: "kept" }],
+ menuObject: {
+ menuItems: [
+ menuItem(0, "zero id"),
+ menuItem(1, "ok"),
+ menuItem(1, "duplicate id"),
+ menuItem(2, "x".repeat(33)),
+ menuItem(3, "x".repeat(32)),
+ ],
+ },
+ });
+ assert.deepEqual(page.menuItems, [
+ { itemName: "ok", itemID: 1 },
+ { itemName: "x".repeat(32), itemID: 3 },
+ ]);
+ assert.equal(page.containers.length, 1, "an invalid menu must not cost the app its containers");
+});
+
+test("itemName is measured in UTF-8 bytes, not characters", () => {
+ // 11 three-byte characters is 33 bytes: over the limit despite being short.
+ const overLimit = "あ".repeat(11);
+ const atLimit = "あ".repeat(10); // 30 bytes
+ const page = parsePage({ menuObject: { menuItems: [menuItem(1, overLimit), menuItem(2, atLimit)] } });
+ assert.deepEqual(page.menuItems, [{ itemName: atLimit, itemID: 2 }]);
+});
+
+test("a menu is capped at the firmware's ten entries", () => {
+ const menuItems = Array.from({ length: 12 }, (_, i) => menuItem(i + 1, `item ${i + 1}`));
+ const page = parsePage({ menuObject: { menuItems } });
+ assert.equal(page.menuItems.length, 10);
+ assert.equal(page.menuItems[9].itemID, 10);
+ assert.equal(declaredMenuItems({ menuObject: { menuItems } }).length, 12, "the raw count drives the dropped-items log");
+});
+
+test("textColor carries brightness levels 0 through 4", () => {
+ for (const level of [0, 1, 2, 3, 4]) {
+ const page = parsePage({ textObject: [{ containerID: 1, containerName: "t", textColor: level }] });
+ assert.equal(page.containers[0].textColor, level);
+ }
+});
+
+test("an omitted or out-of-range textColor falls back to the device default", () => {
+ for (const textObject of [
+ [{ containerID: 1, containerName: "t" }],
+ [{ containerID: 1, containerName: "t", textColor: 5 }],
+ [{ containerID: 1, containerName: "t", textColor: -1 }],
+ [{ containerID: 1, containerName: "t", textColor: 2.5 }],
+ ]) {
+ const page = parsePage({ textObject });
+ assert.equal(page.containers[0].textColor, undefined);
+ }
+});
diff --git a/tests/fixtures/CompassProtocolTest.java b/tests/fixtures/CompassProtocolTest.java
new file mode 100644
index 00000000..8b08eb92
--- /dev/null
+++ b/tests/fixtures/CompassProtocolTest.java
@@ -0,0 +1,52 @@
+package com.faceclaw.app;
+import java.util.Arrays;
+
+public class CompassProtocolTest {
+ private static byte[] hex(String value) {
+ byte[] bytes = new byte[value.length() / 2];
+ for (int i = 0; i < bytes.length; i++) bytes[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
+ return bytes;
+ }
+ private static BleProtocol.CompassEvent parse(byte[] payload) {
+ return parse(payload, BleProtocol.FLAG_NOTIFY);
+ }
+ private static BleProtocol.CompassEvent parse(byte[] payload, int flag) {
+ byte[] frame = BleProtocol.framePb(payload, 8, flag, 15).get(0);
+ return BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame));
+ }
+ public static void main(String[] args) {
+ // Golden packet also checked against the real C encoder in g2flash's host test.
+ byte[] packet = hex("080f1000520308e702a2060c434d010302038c0098badcfe");
+ BleProtocol.CompassEvent event = parse(packet);
+ assert event.headingDegrees == 359 && event.command == 15;
+ assert event.magneticAccuracy == 3 && event.magneticAnomalies == 2;
+ assert event.orientationSource == 3 && event.diagnosticFlags == 0x8c;
+ assert event.sampleTimeMs == 0xfedcba98L; // unsigned 32-bit timestamp through Java long
+ assert parse(packet, BleProtocol.FLAG_NOTIFY_ALT).headingDegrees == 359;
+ assert parse(packet, BleProtocol.FLAG_REQUEST) == null;
+ assert parse(packet, 0) == null;
+ byte[] legacy = Arrays.copyOf(packet, 9);
+ event = parse(legacy);
+ assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
+ for (int n = 9; n < packet.length; ++n) {
+ event = parse(Arrays.copyOf(packet, n));
+ assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
+ }
+ for (int offset : new int[] {12, 13, 14, 15, 16, 17, 19}) {
+ byte[] invalid = packet.clone(); invalid[offset] = 99;
+ event = parse(invalid);
+ assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
+ }
+ packet[15] = packet[16] = (byte)255; packet[17] = 0; packet[18] = 0;
+ event = parse(packet);
+ assert event.magneticAccuracy == -1 && event.magneticAnomalies == -1;
+ assert event.orientationSource == 0 && event.diagnosticFlags == 0;
+ event = parse(hex("08101000"));
+ assert event.command == 16 && event.headingDegrees == -1 && event.diagnosticFlags == -1;
+ event = parse(hex("08111000"));
+ assert event.command == 17 && event.diagnosticFlags == -1;
+ assert parse(hex("080f1000520308e802")) == null; // 360 isn't a heading
+ assert BleProtocol.parseCompassEvent(null) == null;
+ System.out.println("Compass protocol checks passed");
+ }
+}
diff --git a/tests/nightscout.test.cjs b/tests/nightscout.test.cjs
new file mode 100644
index 00000000..2e65706e
--- /dev/null
+++ b/tests/nightscout.test.cjs
@@ -0,0 +1,156 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const alerts = require('../.test-build/app/apps/nightscout/nightscout-alerts.js');
+const now = 1_800_000_000_000;
+const limits = { maxCannulaAgeHours: 72, cartridgeLowUnits: 20, batteryLowVoltage: 1.2, maxLoopAgeMinutes: 15 };
+const healthy = { cageTimestampMs: now, reservoirUnits: 100, batteryVoltage: 1.5, loopTimestampMs: now };
+
+function load(file, dependencies, globals = {}) {
+ const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+ const context = { exports: {}, require(name) { assert.ok(name in dependencies, name); return dependencies[name]; }, ...globals };
+ vm.runInNewContext(ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
+ }).outputText, context);
+ return context.exports;
+}
+
+test('each threshold breaches independently, with strict boundaries and zero disabling it', () => {
+ const cases = [
+ ['cageTimestampMs', 'maxCannulaAgeHours', 'cannula', now - 72 * 3_600_000, -1],
+ ['reservoirUnits', 'cartridgeLowUnits', 'cartridge', 20, -0.01],
+ ['batteryVoltage', 'batteryLowVoltage', 'battery', 1.2, -0.01],
+ ['loopTimestampMs', 'maxLoopAgeMinutes', 'loop', now - 15 * 60_000, -1],
+ ];
+ for (const [field, threshold, warning, boundary, delta] of cases) {
+ assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary }, limits, now).any, false);
+ const result = alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, limits, now);
+ assert.equal(result[warning], true);
+ assert.equal(result.any, true);
+ assert.equal(Object.values(result).filter(Boolean).length, 2);
+ assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, { ...limits, [threshold]: 0 }, now).any, false);
+ }
+});
+
+test('missing/invalid measurements do not alert; real empty reservoirs do', () => {
+ for (const value of [null, NaN, -1, Infinity]) {
+ const values = Object.fromEntries(Object.keys(healthy).map(key => [key, value]));
+ assert.equal(alerts.evaluateNightscoutAlerts(values, limits, now).any, false);
+ }
+ assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, reservoirUnits: 0 }, limits, now).cartridge, true);
+ assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, loopTimestampMs: now + 60_000 }, limits, now).loop, false);
+ for (const value of ['', '-2', 'NaN', 'Infinity', '12abc', null]) assert.equal(alerts.normalizeNightscoutThreshold(value), '0');
+ assert.equal(alerts.normalizeNightscoutThreshold(' 1.25 '), '1.25');
+ assert.equal(alerts.normalizeNightscoutThreshold('.5'), '0.5');
+});
+
+class Image {
+ constructor(width, height) { this.width = width; this.height = height; this.draws = []; }
+ drawText(font, ...args) { this.draws.push(['text', ...args]); }
+ drawLine(...args) { this.draws.push(['line', ...args]); }
+ fillRect(...args) { this.draws.push(['rect', ...args]); }
+}
+const font = { measureText: text => text.length * 6, lineHeight: 12, hasGlyph: () => true };
+function fixture(always = false) {
+ let time = now, icon, tick, changed, notify, renders = 0;
+ const state = { ...healthy, available: true, latest: { sgv: 100, timestampMs: now }, history: [], units: 'mg/dL', delta: 0, direction: '', iob: 1, cob: 0, pumpStatus: '0m ago', configurationMissing: false };
+ const bridge = { snapshot: () => state, onStateChange(fn) { notify = fn; fn(state); } };
+ const settings = { loadNightscoutThresholds: () => limits, nightscoutAlwaysShowInTopBarSetting: { get: () => always }, onAnySettingChanged(fn) { changed = fn; }, isNightscoutSettingsConfigured: () => true };
+ const deps = {
+ '../../graphics/image': { GrayImage: Image },
+ '../../graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultLargeFont: () => font },
+ '../../native/nightscout-bridge': { nightscoutBridge: bridge },
+ '../../ui/dashboard-settings': settings,
+ './nightscout-alerts': alerts,
+ };
+ const app = load('app/apps/nightscout/nightscout-app.ts', {
+ ...deps,
+ './nightscout': { NightscoutLayer: class {}, nightscoutMenuItems() {} },
+ '../../ui/shell/shell': { shell: { setTrayIcon(id, value) { icon = value; } } },
+ '../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: options => ({ close: options.onClosed, requestRender() { renders++; } }) },
+ }, { Date: { now: () => time }, setInterval(fn) { tick = fn; return 1; }, clearInterval() { tick = null; } });
+ return { app, deps, state, icon: () => icon, tick: () => tick?.(), advance(ms) { time += ms; }, notify: () => notify(), toggle(value) { always = value; changed(); }, renders: () => renders };
+}
+
+test('tray boots without a window, persists on close, and responds to settings and elapsed time', () => {
+ const f = fixture(true);
+ f.app.startNightscoutTrayIcon();
+ assert.ok(f.icon());
+ const width = f.icon().width;
+ f.advance(16 * 60_000); f.tick();
+ assert.equal(f.icon().width, width + 24);
+ const triangle = f.icon().draws.filter(d => d[0] === 'line' && d.at(-1) === 255);
+ assert.equal(triangle.length, 3);
+ assert.ok(triangle.every(d => d[1] > width && d[3] > width));
+ f.toggle(false); assert.equal(f.icon(), null);
+ const window = f.app.createNightscoutAppWindow({ onClosed() {} });
+ assert.ok(f.icon());
+ f.toggle(true); window.close(); assert.ok(f.icon());
+ const renders = f.renders(); f.notify(); assert.equal(f.renders(), renders);
+ f.toggle(false); assert.equal(f.icon(), null);
+ const reopened = f.app.createNightscoutAppWindow({ onClosed() {} });
+ reopened.close(); assert.equal(f.icon(), null);
+});
+
+test('tray is hidden by default and clears recovered measurement warnings immediately', () => {
+ const f = fixture();
+ f.app.startNightscoutTrayIcon();
+ assert.equal(f.icon(), null);
+ const first = f.app.createNightscoutAppWindow({ onClosed() {} });
+ const width = f.icon().width;
+ f.state.batteryVoltage = 1;
+ f.notify(); assert.equal(f.icon().width, width + 24);
+ f.state.batteryVoltage = 1.5;
+ f.notify(); assert.equal(f.icon().width, width);
+ const second = f.app.createNightscoutAppWindow({ onClosed() {} });
+ first.close(); assert.ok(f.icon());
+ second.close(); assert.equal(f.icon(), null);
+});
+
+test('main page highlights only the breached field and removes highlights on recovery', () => {
+ const f = fixture();
+ const page = load('app/apps/nightscout/nightscout.ts', {
+ ...f.deps,
+ '../../graphics/textwrap': { truncateText: (font, text) => text },
+ '../../ui/gestures': {}, '../../ui/layers': {}, '../../ui/menu': {},
+ '../../ui/dashboard/settings-panel': {}, '../../ui/metrics': { lineStep: () => 16 },
+ '~/util/date-util': { formatAgeShortFromTimestamp: () => '1m', formatTimestamp: () => '12:00' },
+ }, { Date: { now: () => now } });
+ const layer = new page.NightscoutLayer();
+ const paint = () => layer.paint({ stack: { getBaseSize: () => ({ width: 576, height: 260 }) } });
+ for (const [field, value, label] of [['reservoirUnits', 10, '10U'], ['batteryVoltage', 1, '1.00V'], ['cageTimestampMs', now - 73 * 3_600_000, 'CAGE 1m'], ['loopTimestampMs', now - 16 * 60_000, 'Loop 1m']]) {
+ f.state[field] = value;
+ const image = paint();
+ const highlighted = image.draws.filter(d => d[0] === 'text' && d.at(-1) === 0);
+ assert.equal(highlighted.length, 1);
+ assert.equal(highlighted[0][3], label);
+ f.state[field] = healthy[field];
+ assert.equal(paint().draws.filter(d => d[0] === 'text' && d.at(-1) === 0).length, 0);
+ }
+});
+
+test('bridge exposes numeric measurements and treats absent values as unknown', async () => {
+ let pump = { reservoir: '10.5', battery: { voltage: '1.15' } };
+ const module = load('app/native/nightscout-bridge.ts', {
+ '../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
+ '../util/http': { async fetchWithUserAgent(url) {
+ const body = url.includes('/entries.') ? [{ date: now, sgv: 100 }] : url.includes('/devicestatus.') ? [{ pump, openaps: { suggested: { mills: now - 60_000 } } }] : url.includes('/status.') ? {} : [];
+ return { ok: true, json: async () => body };
+ } },
+ }, { Date, console });
+ const bridge = new module.NightscoutBridge();
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().reservoirUnits, 10.5);
+ assert.equal(bridge.snapshot().batteryVoltage, 1.15);
+ assert.equal(bridge.snapshot().loopTimestampMs, now - 60_000);
+ pump = { reservoir: null, battery: { voltage: '' } };
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().reservoirUnits, null);
+ assert.equal(bridge.snapshot().batteryVoltage, null);
+ pump = { reservoir: 0, battery: { voltage: 0 } };
+ await bridge.refreshNow();
+ assert.equal(bridge.snapshot().reservoirUnits, 0);
+});
diff --git a/tests/notification-filter.test.cjs b/tests/notification-filter.test.cjs
new file mode 100644
index 00000000..3e77ac5d
--- /dev/null
+++ b/tests/notification-filter.test.cjs
@@ -0,0 +1,182 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+
+function evaluate(source, requireModule, globals = {}) {
+ const context = { exports: {}, require: requireModule, ...globals };
+ vm.runInNewContext(ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+ }).outputText, context);
+ return context.exports;
+}
+const source = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+const load = (file, requireModule) => evaluate(source(file), requireModule);
+
+function store(settings = new Map()) {
+ return load('app/native/notification-sources.ts', () => ({
+ getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
+ setStringSetting: (key, value) => settings.set(key, value),
+ }));
+}
+const mail = { packageName: 'com.mail', appName: 'Mail' };
+
+test('sources default on and retain per-package choices and names across restart and rediscovery', () => {
+ const settings = new Map();
+ let prefs = store(settings);
+ assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
+ prefs.rememberNotificationSources([mail, mail, { packageName: 'com.other', appName: 'Mail' }]);
+ assert.equal(prefs.readNotificationSources().length, 2);
+ prefs.setNotificationSourceEnabled({ ...mail, text: 'private notification content' }, false);
+ assert.ok(!Array.from(settings.values()).join('').includes('private notification content'));
+ prefs = store(settings);
+ prefs.rememberNotificationSources([{ ...mail, appName: 'Renamed Mail' }, { packageName: 'com.new', appName: '' }]);
+ assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
+ assert.equal(prefs.shouldShowNotificationOnGlasses('com.other'), true);
+ assert.equal(prefs.shouldShowNotificationOnGlasses('com.new'), true);
+ assert.equal(prefs.readNotificationSources().find((s) => s.packageName === mail.packageName).appName, 'Renamed Mail');
+ prefs.setNotificationSourceEnabled(mail, true);
+ assert.equal(store(settings).shouldShowNotificationOnGlasses(mail.packageName), true);
+});
+
+test('invalid saved source data falls back to enabled', () => {
+ for (const raw of ['invalid', '{}', '[null, {}, {"packageName": 1}]']) {
+ assert.equal(store(new Map([['notifications.sources', raw]])).shouldShowNotificationOnGlasses('com.mail'), true);
+ }
+});
+
+function ui(fontSize = 12) {
+ const prefs = store();
+ let active = [{ ...mail, key: 'key', title: 'Message', text: 'Hello', bigText: '', lines: [], actions: [], postTime: 0 }];
+ let dismissals = 0;
+ let closes = 0;
+ const textwrap = load('app/graphics/textwrap.ts');
+ const graphics = load('app/graphics/image.ts', () => textwrap);
+ const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
+ const font = BdfFont.parse(source(`app/fonts/terminus/ter-u${fontSize}n.bdf`));
+ class RecordingImage extends graphics.GrayImage {
+ texts = [];
+ drawText(font, x, y, text, value) {
+ this.texts.push({ x, y, text });
+ super.drawText(font, x, y, text, value);
+ }
+ }
+ const native = {
+ ALL_NOTIFICATIONS: 0x7fffffff,
+ readActiveNotifications: () => { prefs.rememberNotificationSources(active); return active; },
+ dismissNotification: () => { dismissals++; active = []; return true; },
+ readNotificationIconByKey: () => ({ icon: null, stale: false }),
+ };
+ const dependencies = {
+ '../graphics/image': { ...graphics, GrayImage: RecordingImage },
+ '../graphics/textwrap': textwrap,
+ '../graphics/ui-fonts': { getDefaultSmallFont: () => font },
+ '../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
+ '~/util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
+ '~/util/date-util': { formatRelativeTime: () => '' },
+ '../native/notification-icons': native,
+ '../native/notification-sources': prefs,
+ '../native/notification-access': { isNotificationListenerEnabled: () => true },
+ '../util/render-freshness': { renderPassAllowsStaleData: () => false },
+ './metrics': load('app/ui/metrics.ts'),
+ './gestures': {},
+ };
+ const requireModule = (name) => {
+ assert.ok(name in dependencies, `Unexpected dependency ${name}`);
+ return dependencies[name];
+ };
+ dependencies['./menu'] = load('app/ui/menu.ts', requireModule);
+ const { SingleNotificationLayer } = load('app/ui/notifications.ts', requireModule);
+ const { NotificationFilterLayer } = load('app/ui/notification-filter.ts', requireModule);
+ const ctx = { stack: { getBaseSize: () => ({ width: 540, height: 224 }), isFocused: () => true, pop: () => closes++ } };
+ const popup = new SingleNotificationLayer('key', { origin: 'new-notification-modal', closeModal: () => closes++ });
+ const filter = new NotificationFilterLayer();
+ const paint = (layer) => layer.paint(ctx, () => new RecordingImage(540, 224));
+ const input = (layer, type) => layer.handleInput({ type }, ctx);
+ return { prefs, popup, filter, paint, input, active: (value) => { active = value; },
+ dismissals: () => dismissals, closes: () => closes };
+}
+
+test('popup dismisses before confirmation; confirming disables the source even after the notification disappears', async () => {
+ const app = ui();
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'click');
+ assert.equal(app.dismissals(), 1);
+ assert.equal(app.closes(), 0);
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
+ assert.ok(app.paint(app.popup).texts.some(({ text }) => text.includes('Mail')));
+ assert.equal(app.closes(), 0);
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'click');
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
+ assert.equal(app.closes(), 1);
+});
+
+test('cancel and back dismiss the popup without changing source preferences', async () => {
+ for (const cancel of ['click', 'double-click']) {
+ const app = ui();
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'click');
+ await app.input(app.popup, cancel);
+ assert.equal(app.dismissals(), 1);
+ assert.equal(app.closes(), 1);
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
+ }
+});
+
+test('filter toggles persist after notifications disappear and discovers new sources while open', async () => {
+ const app = ui();
+ app.paint(app.filter);
+ await app.input(app.filter, 'click');
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
+ app.active([{ packageName: 'com.alpha', appName: 'Alpha' }]);
+ const image = app.paint(app.filter);
+ assert.ok(image.texts.some(({ text }) => text === 'Alpha'));
+ assert.ok(image.texts.some(({ text }) => text === 'Mail'));
+ // A source inserted before the selection must not move the toggle to another app.
+ await app.input(app.filter, 'click');
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
+ assert.equal(app.prefs.shouldShowNotificationOnGlasses('com.alpha'), true);
+});
+
+test('popup action wraps fully and stays visible with small and large fonts', async () => {
+ for (const size of [12, 20]) {
+ const app = ui(size);
+ await app.input(app.popup, 'scroll-down');
+ await app.input(app.popup, 'scroll-down');
+ const image = app.paint(app.popup);
+ assert.ok(image.texts.map(({ text }) => text).join(' ').includes("Don't show on glasses again"));
+ assert.ok(image.texts.every(({ y }) => y >= 0 && y < image.height));
+ }
+});
+
+test('controller filters before waking or opening a popup, and still refreshes the tray', async () => {
+ const file = ts.createSourceFile('controller.ts', source('app/g2/dashboard-controller.ts'), ts.ScriptTarget.Latest, true);
+ const controller = file.statements.find((node) => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
+ const handler = controller.members.find((node) => node.name?.getText(file) === 'handleAndroidNotificationPosted');
+ const prefs = store();
+ let wakes = 0, popups = 0, renders = 0;
+ const { Harness } = evaluate(`export class Harness { ${handler.getText(file)} }`, null, {
+ ALL_NOTIFICATIONS: 0x7fffffff,
+ readActiveNotifications: () => [{ ...mail, key: 'key' }],
+ shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
+ shell: { isScreenOn: () => false, wake: () => { wakes++; return true; }, openNotificationModal: () => popups++ },
+ });
+ const instance = new Harness();
+ instance.requestShellRender = () => renders++;
+ instance.appendLog = () => {};
+ prefs.setNotificationSourceEnabled(mail, false);
+ await instance.handleAndroidNotificationPosted('key');
+ await instance.handleAndroidNotificationPosted('gone');
+ assert.equal(wakes, 0);
+ assert.equal(popups, 0);
+ assert.equal(renders, 2);
+ prefs.setNotificationSourceEnabled(mail, true);
+ await instance.handleAndroidNotificationPosted('key');
+ assert.equal(wakes, 1);
+ assert.equal(popups, 1);
+});
diff --git a/tests/teleprompter-tracker.test.cjs b/tests/teleprompter-tracker.test.cjs
new file mode 100644
index 00000000..1891ed92
--- /dev/null
+++ b/tests/teleprompter-tracker.test.cjs
@@ -0,0 +1,132 @@
+// Pins the Teleprompter's speech-to-script tracker: tokenization, the fuzzy
+// word matcher, and the position tracking under realistic partial-transcript
+// streams (replace semantics), including misrecognitions, ad-libs, skipped
+// sentences and repeated phrases.
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const tracker = require("../.test-build/app/apps/teleprompter/script-tracker.js");
+
+const SCRIPT = `Good evening, everyone. Thank you for coming tonight.
+
+Four score and seven years ago our fathers brought forth on this continent
+a new nation, conceived in liberty, and dedicated to the proposition that
+all men are created equal.
+
+Now we are engaged in a great civil war, testing whether that nation, or any
+nation so conceived and so dedicated, can long endure. We are met on a great
+battle-field of that war.
+
+We have come to dedicate a portion of that field, as a final resting place
+for those who here gave their lives that that nation might live.`;
+
+/** Word index of the first occurrence of a normalized key, from `from`. */
+function wordAt(script, key, from = 0) {
+ const index = script.words.indexOf(key, from);
+ assert.notEqual(index, -1, `script has ${key}`);
+ return index;
+}
+
+/**
+ * Feed an utterance the way a streaming recognizer delivers it: a growing
+ * partial after every word, then the final. Returns the tracker position.
+ */
+function speak(t, utterance) {
+ const words = utterance.split(/\s+/);
+ for (let i = 1; i <= words.length; i++) {
+ t.feed(words.slice(0, i).join(" "));
+ }
+ t.feed(utterance);
+ return t.position;
+}
+
+test("tokenizeScript separates display tokens from trackable words", () => {
+ const script = tracker.tokenizeScript("Hello, world — it's 2026.\nNext line");
+ assert.deepEqual(
+ script.tokens.map((token) => token.text),
+ ["Hello,", "world", "—", "it's", "2026.", "Next", "line"],
+ );
+ assert.deepEqual(script.words, ["hello", "world", "its", "2026", "next", "line"]);
+ assert.equal(script.tokens[2].wordIndex, -1);
+ assert.equal(script.tokens[5].paragraph, 1);
+ assert.deepEqual(script.wordTokens, [0, 1, 3, 4, 5, 6]);
+});
+
+test("withinOneEdit accepts single slips and rejects more", () => {
+ assert.ok(tracker.withinOneEdit("conceived", "conceived"));
+ assert.ok(tracker.withinOneEdit("conceived", "concieved") === false, "transposition is two edits");
+ assert.ok(tracker.withinOneEdit("liberty", "libery"));
+ assert.ok(tracker.withinOneEdit("liberty", "libertyy"));
+ assert.ok(tracker.withinOneEdit("liberty", "libarty"));
+ assert.ok(!tracker.withinOneEdit("liberty", "library"));
+ assert.ok(tracker.withinOneEdit("nation", "notion"), "one substitution");
+});
+
+test("follows a clean read-through, word by word", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ assert.equal(t.position, 0);
+ // A lone first word is not enough evidence to move.
+ t.feed("Good");
+ assert.equal(t.position, 0);
+ t.feed("Good evening");
+ assert.equal(t.position, 2);
+ speak(t, "Good evening everyone thank you for coming tonight");
+ assert.equal(t.position, wordAt(script, "four"));
+ speak(t, "Four score and seven years ago our fathers brought forth on this continent");
+ assert.equal(t.position, wordAt(script, "a", wordAt(script, "continent")));
+});
+
+test("tolerates misrecognized and ad-libbed words", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ t.anchor(wordAt(script, "four"));
+ // "score" heard as "scored", "fathers" as "father's", plus an inserted "um".
+ speak(t, "for scored and seven years ago um our father's brought forth");
+ assert.equal(t.position, wordAt(script, "on"));
+});
+
+test("a partial last word counts as a prefix of the next script word", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ t.anchor(wordAt(script, "four"));
+ t.feed("four score and seven years ago our fath");
+ assert.equal(t.position, wordAt(script, "brought"));
+});
+
+test("catches up when the speaker skips a sentence", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ t.anchor(wordAt(script, "four"));
+ speak(t, "Now we are engaged in a great civil war");
+ assert.equal(t.position, wordAt(script, "testing"));
+});
+
+test("prefers the occurrence nearest the current position for repeated phrases", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ // "that nation" appears in paragraphs 3 and 4; anchored in paragraph 4 it
+ // should pick the later one.
+ const laterThat = wordAt(script, "gave");
+ t.anchor(laterThat);
+ speak(t, "their lives that that nation might live");
+ assert.equal(t.position, script.words.length);
+});
+
+test("does not move on transcripts that match nothing nearby", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words);
+ t.anchor(wordAt(script, "four"));
+ assert.equal(speak(t, "hang on let me find my glasses"), wordAt(script, "four"));
+});
+
+test("manual anchoring re-bases the search window", () => {
+ const script = tracker.tokenizeScript(SCRIPT);
+ const t = new tracker.ScriptTracker(script.words, { ahead: 10, back: 5 });
+ // Far outside the window from position 0.
+ speak(t, "final resting place for those who here gave");
+ assert.equal(t.position, 0);
+ t.anchor(wordAt(script, "final"));
+ speak(t, "final resting place for those who here gave");
+ assert.equal(t.position, wordAt(script, "their"));
+});
diff --git a/tests/terminal-activity.test.cjs b/tests/terminal-activity.test.cjs
new file mode 100644
index 00000000..b9910de7
--- /dev/null
+++ b/tests/terminal-activity.test.cjs
@@ -0,0 +1,163 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const read = file => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
+const js = source => ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+}).outputText;
+
+// Run the worker's actual activity and lifecycle code with platform work stubbed.
+function worker() {
+ let now = 100_000, timer, renderCount = 0;
+ const messages = [];
+ const file = 'app/apps/terminal/terminal-app.worker.ts';
+ const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
+ const functions = new Set(['recencyKey', 'post', 'renderHubWindows', 'isSessionActive', 'isWindowSessionActive', 'hubAnimationShouldRun', 'syncWindowIconActivity', 'updateHubAnimation', 'noteSessionActivity', 'openWindow', 'closeWindow']);
+ const variables = new Set(['windows', 'pendingViews', 'activeViewId', 'sessionRecency', 'sessionActivity', 'ACTIVITY_ACTIVE_MS', 'HUB_ANIMATION_STEP_MS', 'hubAnimationPhase', 'hubAnimationTimer', 'windowIconActivity', 'screenOn']);
+ const selected = source.statements.filter(s =>
+ ts.isFunctionDeclaration(s) && functions.has(s.name?.text) ||
+ ts.isVariableStatement(s) && s.declarationList.declarations.some(d => variables.has(d.name.getText(source))) ||
+ ts.isExpressionStatement(s) && ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage');
+ const context = {
+ exports: {}, Date: { now: () => now },
+ setInterval(fn, ms) { assert.equal(ms, 800); assert.equal(timer, undefined); timer = fn; return 1; },
+ clearInterval() { timer = undefined; },
+ global: { postMessage: message => messages.push(message) },
+ scheduleRender() { renderCount++; }, renderAndSubmit() {}, maybeReconnectView() {},
+ controlsInitialized: true, controls: new Map(), TERMINAL_TOOLS: [],
+ getTerminalFontConfig: () => ({ cellWidth: 6, cellHeight: 12 }),
+ };
+ vm.runInNewContext(js(selected.map(s => s.getText(source)).join('\n')) + '\nexports.windows = windows;', context);
+ const message = data => context.global.onmessage({ data });
+ return {
+ messages, windows: context.exports.windows,
+ activity: (connection = 'host1', socket = 'a') => context.noteSessionActivity(connection, socket),
+ openHub() { context.openWindow('hub', 'surface:hub', 'Terminal', { width: 576, height: 260 }); },
+ addView(id, connectionId = 'host1', socket = 'a') {
+ context.exports.windows.set(id, { windowId: id, kind: 'view', connectionId, socket, foreground: false, unsubscribers: [], client: { stop() {} } });
+ context.updateHubAnimation();
+ },
+ close: id => context.closeWindow(id),
+ screen: on => message({ type: 'screen', on }),
+ advance(ms) { now += ms; timer?.(); },
+ running: () => !!timer,
+ phase(id) { return messages.filter(m => m.type === 'set-icon-activity' && m.windowId === id).at(-1)?.activity ?? 'idle'; },
+ };
+}
+
+test('background hub aggregates activity; session icons match both host and socket', () => {
+ const w = worker();
+ w.openHub(); w.addView('a'); w.addView('b', 'host1', 'b'); w.addView('other-host', 'host2', 'a');
+ assert.equal(w.running(), false);
+ w.activity();
+ assert.equal(w.phase('hub'), 'on'); assert.equal(w.phase('a'), 'on');
+ assert.equal(w.phase('b'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
+ w.advance(800);
+ assert.equal(w.phase('hub'), 'off'); assert.equal(w.phase('a'), 'off');
+ w.advance(800); assert.equal(w.phase('a'), 'on');
+ w.activity('host2', 'a'); assert.equal(w.phase('other-host'), 'on');
+ w.advance(3400);
+ assert.equal(w.phase('a'), 'idle'); assert.notEqual(w.phase('hub'), 'idle');
+ w.advance(1600);
+ assert.equal(w.phase('hub'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
+ assert.equal(w.running(), false);
+});
+
+test('animation continues with hub closed and stops after the final window closes', () => {
+ const w = worker();
+ w.openHub(); w.addView('a'); w.activity(); w.close('hub');
+ w.advance(800); assert.equal(w.phase('a'), 'off'); assert.equal(w.running(), true);
+ w.close('a'); assert.equal(w.running(), false);
+ w.activity(); assert.equal(w.running(), false);
+ w.openHub(); assert.equal(w.phase('hub'), 'on'); assert.equal(w.running(), true);
+});
+
+test('screen off pauses animation; wake recalculates fresh and expired activity', () => {
+ const w = worker();
+ w.addView('a'); w.activity(); w.screen(false);
+ assert.equal(w.running(), false);
+ w.advance(1000); w.screen(true);
+ assert.equal(w.phase('a'), 'on'); assert.equal(w.running(), true);
+ w.screen(false); w.advance(5000); w.screen(true);
+ assert.equal(w.phase('a'), 'idle'); assert.equal(w.running(), false);
+});
+
+test('unopened sessions activate the hub and repeated pushes extend activity without duplicate messages', () => {
+ const w = worker();
+ w.openHub(); w.activity('host2', 'unopened');
+ assert.equal(w.phase('hub'), 'on');
+ const count = w.messages.length; w.activity('host2', 'unopened'); assert.equal(w.messages.length, count);
+ w.advance(4000); w.activity('host2', 'unopened'); w.advance(2000);
+ assert.notEqual(w.phase('hub'), 'idle');
+ w.advance(3000); assert.equal(w.phase('hub'), 'idle');
+});
+
+function load(file, deps, globals = {}) {
+ const context = { exports: {}, require(name) { assert.ok(name in deps, name); return deps[name]; }, ...globals };
+ vm.runInNewContext(js(read(file)), context);
+ return context.exports;
+}
+
+class Image {
+ constructor(width, height) { this.width = width; this.height = height; this.pixels = new Uint8Array(width * height); }
+}
+
+test('cursor replaces only the prompt; marker and frame persist across cached blink phases', () => {
+ const renders = [];
+ const icons = load('app/graphics/icons.ts', { './image': { GrayImage: Image } }, {
+ global: { isAndroid: true },
+ com: { faceclaw: { app: { IconRenderer: { renderSvgGray(svg, size, stroke) {
+ renders.push(svg); assert.equal(stroke, 2); return new Uint8Array(size * size).fill(255);
+ } } } } },
+ });
+ for (const glyph of ['', '1', '3', 'A']) {
+ const idle = icons.renderIconWithGlyph('terminal', glyph, 24, 'idle');
+ const idleSvg = renders.at(-1);
+ const on = icons.renderIconWithGlyph('terminal', glyph, 24, 'on');
+ const onSvg = renders.at(-1);
+ const off = icons.renderIconWithGlyph('terminal', glyph, 24, 'off');
+ const offSvg = renders.at(-1);
+ const prompt = '';
+ const cursor = '';
+ assert.ok(idleSvg.includes(prompt)); assert.ok(onSvg.includes(cursor));
+ assert.equal(onSvg.includes(prompt), false); assert.equal(offSvg.includes(prompt), false);
+ assert.equal(idleSvg.replace(prompt, ''), offSvg);
+ assert.equal(onSvg.replace(cursor, ''), offSvg);
+ assert.notEqual(on, off); assert.notEqual(idle, on);
+ const count = renders.length;
+ assert.equal(icons.renderIconWithGlyph('terminal', glyph, 24, 'on'), on);
+ assert.equal(renders.length, count);
+ }
+ assert.equal(icons.renderIconWithGlyph('timer', '', 24, 'on'), icons.renderIcon('timer', 24));
+});
+
+test('host applies activity only to its own open windows and cleans up on close', async () => {
+ let paints = 0;
+ const worker = { postMessage() {} };
+ const shellWindows = new Map();
+ const { WorkerAppHost } = load('app/ui/shell/worker-window.ts', {
+ '../../graphics/image': { GrayImage: Image },
+ './chrome-layer': { windowIcon: (icon, letter, glyph, phase) => phase },
+ '../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
+ './geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
+ '../../native/frame-timings': {},
+ './shell': { shell: { registerWindow: w => shellWindows.set(w.windowId, w) } },
+ });
+ const host = new WorkerAppHost({ appId: 'terminal', worker, configureSurface: async () => {}, requestShellRender() { paints++; }, removeSurface() {} });
+ const spec = { windowId: 'a', title: 'A', icon: 'terminal', iconGlyph: '1' };
+ const window = host.openWindow(spec);
+ await Promise.resolve();
+ const send = (windowId, activity) => worker.onmessage({ data: { type: 'set-icon-activity', windowId, activity } });
+ assert.equal(window.drawIcon(), 'idle');
+ let count = paints; send('unknown', 'on'); assert.equal(paints, count);
+ send('a', 'on'); assert.equal(window.drawIcon(), 'on'); assert.equal(paints, count + 1);
+ count = paints; send('a', 'on'); assert.equal(paints, count);
+ send('a', 'off'); assert.equal(window.drawIcon(), 'off');
+ send('a', 'idle'); assert.equal(window.drawIcon(), 'idle');
+ send('a', 'on'); window.close(); count = paints;
+ send('a', 'off'); assert.equal(paints, count);
+ const reopened = host.openWindow(spec); assert.equal(reopened.drawIcon(), 'idle');
+});
diff --git a/tests/timer-model.test.cjs b/tests/timer-model.test.cjs
new file mode 100644
index 00000000..b5e45527
--- /dev/null
+++ b/tests/timer-model.test.cjs
@@ -0,0 +1,151 @@
+// Pins the Timers app's clock arithmetic: the duration dial's ladder, the
+// countdown / stopwatch / span formatting the stage shows, alarm scheduling
+// across days and repeat masks, and the argument parsing the assistant
+// tools rely on.
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const model = require("../.test-build/app/apps/timer/timer-model.js");
+
+const MINUTE = 60_000;
+const HOUR = 60 * MINUTE;
+
+test("the duration ladder is strictly increasing and spans 10s to 24h", () => {
+ const ladder = model.DURATION_LADDER_MS;
+ assert.equal(ladder[0], 10_000);
+ assert.equal(ladder[ladder.length - 1], 24 * HOUR);
+ for (let index = 1; index < ladder.length; index++) {
+ assert.ok(ladder[index] > ladder[index - 1], `rung ${index} not increasing`);
+ }
+ assert.ok(ladder.includes(10 * MINUTE));
+ assert.ok(ladder.includes(25 * MINUTE));
+ assert.ok(ladder.includes(90 * MINUTE));
+});
+
+test("nearestLadderIndex snaps to the closest rung", () => {
+ assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(10 * MINUTE)], 10 * MINUTE);
+ assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(11 * MINUTE + 20_000)], 11 * MINUTE);
+ assert.equal(model.nearestLadderIndex(0), 0);
+ assert.equal(model.nearestLadderIndex(1000 * HOUR), model.DURATION_LADDER_MS.length - 1);
+});
+
+test("countdown rounds up so 0:00 means finished; elapsed rounds down", () => {
+ assert.equal(model.formatCountdown(59_001), "1:00");
+ assert.equal(model.formatCountdown(59_000), "0:59");
+ assert.equal(model.formatCountdown(0), "0:00");
+ assert.equal(model.formatCountdown(HOUR + 5 * MINUTE + 3000), "1:05:03");
+ assert.equal(model.formatElapsed(59_950, false), "0:59");
+ assert.equal(model.formatElapsed(59_950, true), "0:59.9");
+ assert.equal(model.formatElapsed(HOUR, true), "1:00:00.0");
+});
+
+test("durations and spans read naturally", () => {
+ assert.equal(model.formatDurationWords(20 * MINUTE), "20 min");
+ assert.equal(model.formatDurationWords(90 * MINUTE), "1h 30m");
+ assert.equal(model.formatDurationWords(45_000), "45s");
+ assert.equal(model.formatDurationWords(2 * MINUTE + 30_000), "2m 30s");
+ assert.equal(model.formatSpanWords(9 * HOUR + 12 * MINUTE), "9h 12m");
+ assert.equal(model.formatSpanWords(12 * MINUTE), "12m");
+ assert.equal(model.formatSpanWords(30 * HOUR), "1d 6h");
+});
+
+test("time of day honours the 12/24-hour choice", () => {
+ assert.equal(model.formatTimeOfDay(7, 5, false), "7:05");
+ assert.equal(model.formatTimeOfDay(19, 30, false), "19:30");
+ assert.equal(model.formatTimeOfDay(0, 0, true), "12:00 AM");
+ assert.equal(model.formatTimeOfDay(12, 0, true), "12:00 PM");
+ assert.equal(model.formatTimeOfDay(19, 30, true), "7:30 PM");
+});
+
+function alarm(hour, minute, days, extra = {}) {
+ return { id: 1, hour, minute, days, label: "", enabled: true, snoozedUntilMs: null, ringingSinceMs: null, lastFiredAtMs: null, ...extra };
+}
+
+/** Local-time constructor: Wednesday 2026-09-02 at hh:mm. */
+function wednesday(hour, minute) {
+ return new Date(2026, 8, 2, hour, minute, 0, 0).getTime();
+}
+
+test("a one-off alarm rings later today, else tomorrow", () => {
+ const now = wednesday(8, 0);
+ assert.equal(model.alarmNextRingMs(alarm(9, 30, 0), now), wednesday(9, 30));
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, 0), now), new Date(2026, 8, 3, 7, 0).getTime());
+ // Exactly now counts as passed.
+ assert.equal(model.alarmNextRingMs(alarm(8, 0, 0), now), new Date(2026, 8, 3, 8, 0).getTime());
+});
+
+test("a repeating alarm skips to its next enabled day", () => {
+ const now = wednesday(8, 0);
+ // Weekends only: Wednesday -> Saturday.
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKEND_MASK), now), new Date(2026, 8, 5, 7, 0).getTime());
+ // Weekdays, time already passed today: Thursday.
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKDAYS_MASK), now), new Date(2026, 8, 3, 7, 0).getTime());
+ // Only Wednesdays, time passed: a week from now.
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, model.DAY_BITS[2]), now), new Date(2026, 8, 9, 7, 0).getTime());
+});
+
+test("an alarm does not ring twice for the occurrence it last fired for", () => {
+ const now = wednesday(7, 0) + 20_000;
+ const fired = alarm(7, 0, model.EVERY_DAY_MASK, { lastFiredAtMs: wednesday(7, 0) });
+ assert.equal(model.alarmNextRingMs(fired, now - 5 * MINUTE), new Date(2026, 8, 3, 7, 0).getTime());
+});
+
+test("snooze and disabled override the schedule", () => {
+ const now = wednesday(8, 0);
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { snoozedUntilMs: now + 10 * MINUTE }), now), now + 10 * MINUTE);
+ assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { enabled: false }), now), null);
+});
+
+test("repeat masks have readable names", () => {
+ assert.equal(model.formatDays(0), "Once");
+ assert.equal(model.formatDays(model.WEEKDAYS_MASK), "Weekdays");
+ assert.equal(model.formatDays(model.WEEKEND_MASK), "Weekends");
+ assert.equal(model.formatDays(model.EVERY_DAY_MASK), "Every day");
+ assert.equal(model.formatDays(model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]), "Mon Wed Fri");
+});
+
+test("timers sort ringing first, then soonest running, then paused", () => {
+ const now = 1_000_000;
+ const running = { id: 1, label: "", durationMs: 600_000, endsAtMs: now + 300_000, pausedRemainingMs: null, rungAtMs: null, createdAtMs: 1 };
+ const sooner = { ...running, id: 2, endsAtMs: now + 60_000 };
+ const paused = { ...running, id: 3, endsAtMs: null, pausedRemainingMs: 10_000 };
+ const rung = { ...running, id: 4, endsAtMs: null, rungAtMs: now - 5000 };
+ assert.deepEqual(model.sortTimers([running, paused, rung, sooner], now).map((timer) => timer.id), [4, 2, 1, 3]);
+});
+
+test("tool arguments: times of day", () => {
+ assert.deepEqual(model.parseTimeOfDay("7:30"), { hour: 7, minute: 30 });
+ assert.deepEqual(model.parseTimeOfDay("7:30 pm"), { hour: 19, minute: 30 });
+ assert.deepEqual(model.parseTimeOfDay("12 am"), { hour: 0, minute: 0 });
+ assert.deepEqual(model.parseTimeOfDay("12:15PM"), { hour: 12, minute: 15 });
+ assert.deepEqual(model.parseTimeOfDay("19:30"), { hour: 19, minute: 30 });
+ assert.deepEqual(model.parseTimeOfDay("noon"), { hour: 12, minute: 0 });
+ assert.equal(model.parseTimeOfDay("25:00"), null);
+ assert.equal(model.parseTimeOfDay("13 pm"), null);
+ assert.equal(model.parseTimeOfDay("soon"), null);
+});
+
+test("tool arguments: repeat days", () => {
+ assert.equal(model.parseRepeatDays(undefined), 0);
+ assert.equal(model.parseRepeatDays(["weekdays"]), model.WEEKDAYS_MASK);
+ assert.equal(model.parseRepeatDays("every day"), model.EVERY_DAY_MASK);
+ assert.equal(model.parseRepeatDays(["mon", "Wednesday", "fri"]), model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]);
+ assert.equal(model.parseRepeatDays(["someday"]), null);
+});
+
+test("persisted state survives a round trip and shrugs off junk", () => {
+ const state = model.emptyTimersState();
+ state.timers.push(model.createTimer(5 * MINUTE, "tea", 1000));
+ state.alarms.push(model.createAlarm(7, 30, model.WEEKDAYS_MASK, "work", 1000));
+ state.stopwatch = { accumulatedMs: 1234, runningSinceMs: null, lapsMs: [500, 1000] };
+ state.recentDurationsMs = [5 * MINUTE];
+ const restored = model.parseTimersState(model.serializeTimersState(state));
+ assert.deepEqual(restored, state);
+ assert.deepEqual(model.parseTimersState("not json"), model.emptyTimersState());
+ assert.deepEqual(model.parseTimersState(JSON.stringify({ timers: [{ id: "x" }], alarms: [null] })), model.emptyTimersState());
+});
+
+test("recent durations stay short and deduplicated", () => {
+ assert.deepEqual(model.pushRecentDuration([1, 2, 3], 2), [2, 1, 3]);
+ assert.deepEqual(model.pushRecentDuration([1, 2, 3], 4), [4, 1, 2]);
+});
diff --git a/tests/touch-input.test.cjs b/tests/touch-input.test.cjs
new file mode 100644
index 00000000..8ddabb09
--- /dev/null
+++ b/tests/touch-input.test.cjs
@@ -0,0 +1,125 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const root = path.resolve(__dirname, '..');
+const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
+const js = (source) => ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
+}).outputText;
+
+// Run the actual decoder declarations without loading the Android shell.
+function decoder() {
+ const source = ts.createSourceFile('shell.ts', read('app/ui/shell/shell.ts'), ts.ScriptTarget.Latest, true);
+ const names = new Set(['rawInputEventToPayload', 'eventSourceToString', 'scrollEvent']);
+ const declarations = source.statements.filter((s) => ts.isFunctionDeclaration(s) && names.has(s.name?.text));
+ assert.equal(declarations.length, names.size);
+ const context = { exports: {} };
+ vm.createContext(context);
+ vm.runInContext(js(read('app/g2/events.ts')), context);
+ Object.assign(context, context.exports);
+ vm.runInContext(js(declarations.map((s) => s.getText(source)).join('\n')), context);
+ return context;
+}
+
+test('wire edges require explicit left/right temple provenance', () => {
+ const d = decoder();
+ for (const [key, source] of [['TOUCH_EVENT_FROM_GLASSES_L', 'left-arm'], ['TOUCH_EVENT_FROM_GLASSES_R', 'right-arm']]) {
+ const eventSource = d.EventSourceType[key];
+ for (const [eventType, type] of [[12, 'touch-press'], [13, 'touch-release']]) {
+ const event = d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType });
+ assert.equal(event.type, type);
+ assert.equal(event.source, source);
+ }
+ assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 0 }).type, 'click');
+ }
+ for (const eventSource of [undefined, -1, 99, d.EventSourceType.TOUCH_EVENT_FROM_RING]) {
+ assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventSource, eventType: 12 }).type, 'unknown');
+ }
+});
+
+function worker() {
+ const noop = () => {};
+ const modules = {
+ '@nativescript/core/globals': {},
+ '../../graphics/image': {}, '../../graphics/plane': {}, '../../graphics/glyph-wire': {},
+ '../../graphics/bdffont': { getFont: noop },
+ '../../graphics/ui-fonts': { getDefaultSmallFont: noop },
+ '../../native/frame-timings': { finishFrame: noop, logFrame: noop },
+ '../../native/active-display': {},
+ '../../native/settings-store': { getStringSetting: () => '0', setStringSetting: noop },
+ '../../ui/sound-effects': {}, '../../ui/window-menu': {},
+ '../../ui/gestures': { directionalFallback: (event) => event },
+ '../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) },
+ };
+ const context = {
+ exports: {}, console, Date, setInterval: () => 1, clearInterval: noop,
+ global: { postMessage: noop },
+ require: (name) => { assert.ok(name in modules, name); return modules[name]; },
+ };
+ vm.createContext(context);
+ vm.runInContext(js(read('app/apps/pinball/pinball-app.worker.ts')) + `
+ // Stub platform output only; exercise real worker input, physics and lifecycle.
+ renderAndSubmit = () => {};
+ playSfx = () => {};
+ exports.harness = { windows, stepFlippers, resetGame };
+ `, context);
+ const message = (data) => context.global.onmessage({ data });
+ message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: 'test', viewport: { width: 640, height: 480 } });
+ message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
+ const w = context.exports.harness.windows.get('test');
+ w.ballState = 'live';
+ const input = (type, source = 'left-arm') => message({ type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type, source, timestampMs: Date.now() } });
+ return { w, input, message, ...context.exports.harness };
+}
+
+test('pinball responds on contact, holds independently, and releases before tap', () => {
+ const h = worker();
+ h.input('touch-press');
+ assert.equal(h.w.flippers[0].state, 'rising');
+ assert.equal(h.w.flippers[1].state, 'rest');
+ h.stepFlippers(h.w, 1);
+ h.w.flippers[0].holdUntilMs = 0;
+ h.stepFlippers(h.w, 1);
+ assert.equal(h.w.flippers[0].state, 'hold');
+ h.input('touch-press', 'right-arm');
+ h.input('touch-release');
+ assert.equal(h.w.flippers[0].state, 'falling');
+ assert.equal(h.w.flippers[1].touchHeld, true);
+ h.input('click');
+ assert.equal(h.w.flippers[0].state, 'falling');
+ h.input('touch-release', 'right-arm');
+ assert.equal(h.w.flippers[1].state, 'falling');
+});
+
+test('pinball retains old firmware/ring controls and plunger click launch', () => {
+ const h = worker();
+ h.input('click');
+ assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
+ h.resetGame(h.w);
+ h.input('touch-press');
+ h.input('touch-release');
+ assert.equal(h.w.ballState, 'ready');
+ h.input('click');
+ assert.equal(h.w.ballState, 'live');
+ h.input('click', 'ring');
+ assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
+});
+
+test('pinball clears held contacts on pause, focus loss, screen-off and menus', () => {
+ for (const cancel of [
+ (h) => h.input('double-click', 'ring'),
+ (h) => h.input('system-menu-opened'),
+ (h) => h.message({ type: 'foreground', windowId: 'test', foreground: false, focused: false }),
+ (h) => h.message({ type: 'render', windowId: 'test', focused: false }),
+ (h) => h.message({ type: 'screen', on: false }),
+ ]) {
+ const h = worker();
+ h.input('touch-press');
+ cancel(h);
+ assert.equal(h.w.flippers[0].touchHeld, false);
+ assert.equal(h.w.flippers[0].state, 'falling');
+ }
+});
diff --git a/tests/tsconfig.json b/tests/tsconfig.json
index e554b339..a35f5c7b 100644
--- a/tests/tsconfig.json
+++ b/tests/tsconfig.json
@@ -23,6 +23,10 @@
"../app/apps/microphones/sentiment.ts",
"../app/apps/microphones/dsp.ts",
"../app/apps/microphones/radar-dots.ts",
- "../app/apps/microphones/name-guess.ts"
+ "../app/apps/microphones/name-guess.ts",
+ "../app/apps/evenhub/containers.ts",
+ "../app/apps/timer/timer-model.ts",
+ "../app/apps/teleprompter/script-tracker.ts",
+ "../app/apps/nightscout/nightscout-alerts.ts"
]
}
diff --git a/wear/PROTOCOL.md b/wear/PROTOCOL.md
index a94c2a4e..b67647b1 100644
--- a/wear/PROTOCOL.md
+++ b/wear/PROTOCOL.md
@@ -18,7 +18,7 @@ answered on `/faceclaw/ack`.
| Path | Payload | Effect |
| --- | --- | --- |
-| `/faceclaw/input` | `{gesture, steps?}` | A ring gesture through the same path as the phone UI's test buttons. `gesture` ∈ `click`, `double-click`, `scroll-up`, `scroll-down`, `long-press` (complete short hold), `long-press-start`, `long-press-release`, `wakeword` ("Hey Even"), `swipe-up`, `swipe-down`, `swipe-left`, `swipe-right` (spatial input only a watch can produce: delivered to the glasses UI as `swipe-*` events for components that navigate spatially — launcher grid, settings columns, sidebar, Music — with a scroll / click / double-click fallback elsewhere). `steps` (1–12) repeats a scroll. Refused while the glasses are disconnected. The lock screen is honoured exactly as for the ring. While the display is off, only a double-click is accepted and it wakes the display. |
+| `/faceclaw/input` | `{gesture, steps?}` | A ring gesture through the same path as the phone UI's test buttons. `gesture` ∈ `click`, `double-click`, `scroll-up`, `scroll-down`, `long-press` (complete short hold), `long-press-start`, `long-press-release`, `short-then-long-press` (tap then hold: the app's context menu; a plain `long-press` is the glasses' system menu), `wakeword` ("Hey Even"), `swipe-up`, `swipe-down`, `swipe-left`, `swipe-right` (spatial input only a watch can produce: delivered to the glasses UI as `swipe-*` events for components that navigate spatially — launcher grid, settings columns, sidebar, Music — with a scroll / click / double-click fallback elsewhere). `steps` (1–12) repeats a scroll. Refused while the glasses are disconnected. The lock screen is honoured exactly as for the ring. While the display is off, only a double-click is accepted and it wakes the display. |
| `/faceclaw/command` | `{command, …}` | `launch-app {appId}`, `focus-window {windowId}`, `close-window {windowId}`, `sidebar`, `wake`, `sleep`, `lock`, `unlock`, `connect`, `disconnect`, `close-assistant`, `display-mode {value}` (`value` ∈ `576x288`, `576x480`, `640x480`; sets the phone's Display > Display mode). Everything but connect/disconnect needs a connection; everything but lock/unlock is refused while locked; `unlock` also needs the phone's "Watch can unlock glasses" setting. |
| `/faceclaw/assistant` | `{text}` | Send a query to the assistant (`shell.sendToAssistant`) — the reply shows on the glasses and streams back to the watch as events. |
| `/faceclaw/text` | `{text}` | Type text into the foreground window (`receiveTextInput`, e.g. the terminal). Refused when the window doesn't take text. |
diff --git a/wear/README.md b/wear/README.md
index 04697424..1772f725 100644
--- a/wear/README.md
+++ b/wear/README.md
@@ -13,13 +13,12 @@ the phone it only tells you to install it.
| --- | --- |
| tap | select |
| double-tap, or a two-finger tap | **back**, everywhere: closes menus, leaves a settings column, leaves a folder or the launcher grid, returns to the sidebar (and from the sidebar turns the display off, as the ring does) |
-| press and hold | the app's context menu (a long press, held until you lift your finger) |
-| swipe ↑ ↓ ← → | **spatial navigation, with no mode to enter first**: the launcher highlights one app and the swipe moves it by a row or a column; the settings panel moves between its columns and down its lists; the sidebar moves up and down; Music skips to the previous / next track. Right goes *into* things (sidebar → window, section → items) and left comes back *out* (first column → sidebar). Anywhere without a spatial meaning, up/down scroll, right selects and left goes back. One step per swipe (long swipes used to repeat, which overshot lists whenever the display lagged); use repeated flicks, the crown, or a two-finger page swipe to cover distance. "Natural swipe" flips the vertical sense; left/right can be remapped in settings. |
+| press and hold | the system menu: Focus app switcher, Voice input, Close window (a long press, held until you lift your finger; games that use a long press as a move get it instead) |
+| tap, then press and hold | the app's context menu |
+| swipe ↑ ↓ ← → | **spatial navigation, with no mode to enter first**: the launcher highlights one app and the swipe moves it by a row or a column; the settings panel moves between its columns and down its lists; the sidebar moves up and down; Music skips to the previous / next track. Right goes *into* things (sidebar → window, section → items) and left comes back *out* (first column → sidebar). Anywhere without a spatial meaning, up/down scroll, right selects and left goes back. One step per swipe (long swipes used to repeat, which overshot lists whenever the display lagged); use repeated flicks, the crown, or a two-finger page swipe to cover distance. |
| rotate the crown | previous / next (one step per detent-ish, sensitivity adjustable) — clockwise is previous by default; reverse it in the on-glasses Settings > Watch section |
| two-finger swipe up / down | scroll a page (3 steps) |
-| **twist the wrist twice** (two brisk flicks, either direction) | back — from the gyroscope; on by default, sensitivity adjustable |
-| **tip taps** — tap your index finger against your thumb | select; two quick taps = back. From the accelerometer; **off by default** (experimental): on a wrist, ordinary hand movement produced phantom selects in testing. Turn on in Watch settings; needs ~¼ s of stillness before a tap counts, and both motion gestures are ignored while the watch is off the wrist or buzzing. |
-| **Tap zones** mode | tap the top / bottom third to scroll, the middle to select — for when swiping is awkward |
+| **tip taps** — tap your index finger against your thumb | select; two quick taps = back. From the accelerometer; **off by default** (experimental): on a wrist, ordinary hand movement produced phantom selects in testing. Turn on in Watch settings; needs ~¼ s of stillness before a tap counts, and taps are ignored while the watch is off the wrist or buzzing. |
The R1 ring's scheme is untouched: the ring only has up/down, tap, double-tap
and hold, so on the glasses it still works in the stock two-step way (pick a
@@ -46,13 +45,27 @@ down beginning in the button tray to hide them.
full launcher, including installed EvenHub apps.
- **Status** — connection and battery, display on/off, lock/unlock, connect /
disconnect, and whether Faceclaw is running on the phone; watch settings
- (haptics, keep screen on, swipe direction, tap zones, horizontal swipe
- actions, tip taps and their sensitivity, crown sensitivity).
+ (haptics, keep screen on, tip taps and their sensitivity, crown sensitivity).
The pad keeps the watch display awake while it is showing (Watch settings >
"Keep screen on", default on). Wear OS otherwise dozes within seconds of the
-wrist dropping and freezes the app, so the remote would need a wake-up tap
-before every gesture.
+wrist dropping, so the remote would need a wake-up tap before every gesture.
+
+When the watch does doze (wrist down, or "Keep screen on" off), the app stays
+in front as an always-on face: the pad's clock and status line on black,
+redrawn once a minute. Wear OS would otherwise blur a snapshot of the app
+under the system clock and, after its app timeout, drop back to the watch
+face; being ambient-aware avoids both. Motion and crown input pause in ambient.
+
+**Waking with a tap.** The system consumes the touch that wakes the watch, so
+the pad treats each wake as a first tap it never saw:
+
+- With the Wear OS "Always-on screen" setting on, the dozing pad is the same
+ screen, so a tap on it is a tap: one tap wakes the watch and sends *select*
+ to the glasses; a double-tap wakes it and sends *back*.
+- With "Always-on screen" off the display was dark, so a lone tap just turns
+ it on; a double-tap turns it on and sends *back*.
+- A wrist raise (the wrist-tilt gesture sensor) or a crown turn is not a tap.
Phone-side switches live in Faceclaw's Settings > Watch: turn watch control
off entirely, reverse the crown direction, forbid unlocking from the watch,
diff --git a/wear/app/build.gradle.kts b/wear/app/build.gradle.kts
index 71cd6049..963e22cf 100644
--- a/wear/app/build.gradle.kts
+++ b/wear/app/build.gradle.kts
@@ -68,6 +68,8 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.2")
// RemoteInputIntentHelper: the system keyboard / voice / emoji text entry.
implementation("androidx.wear:wear-input:1.1.0")
+ // AmbientLifecycleObserver: the always-on (ambient) display callbacks.
+ implementation("androidx.wear:wear:1.3.0")
implementation("com.google.android.gms:play-services-wearable:19.0.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.1")
diff --git a/wear/app/src/main/AndroidManifest.xml b/wear/app/src/main/AndroidManifest.xml
index 1f28264d..1a700075 100644
--- a/wear/app/src/main/AndroidManifest.xml
+++ b/wear/app/src/main/AndroidManifest.xml
@@ -4,6 +4,8 @@
+
+
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/AmbientMode.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/AmbientMode.kt
new file mode 100644
index 00000000..bb1fefef
--- /dev/null
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/AmbientMode.kt
@@ -0,0 +1,20 @@
+package com.faceclaw.wear
+
+/**
+ * The watch's ambient (always-on, low-power) display state, as reported by
+ * the system through [androidx.wear.ambient.AmbientLifecycleObserver].
+ */
+data class AmbientMode(
+ /** The display is in ambient: draw black, still, and as few pixels as possible. */
+ val active: Boolean = false,
+ /** The panel burns in: nudge the content between redraws. */
+ val burnInProtectionRequired: Boolean = false,
+ /** The panel is 1-bit in ambient: no greys, no anti-aliasing worth relying on. */
+ val lowBit: Boolean = false,
+ /**
+ * Bumped on entering ambient and on every ambient update (about once a
+ * minute), so the clock redraws: the CPU may be suspended in between, so
+ * no timer can be relied on for that.
+ */
+ val tick: Long = 0,
+)
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/MainActivity.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/MainActivity.kt
index b5c1e6b9..41274bd9 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/MainActivity.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/MainActivity.kt
@@ -3,18 +3,56 @@ package com.faceclaw.wear
import android.os.Bundle
import android.os.Handler
import android.os.Looper
+import android.os.PowerManager
+import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
+import androidx.wear.ambient.AmbientLifecycleObserver
import com.faceclaw.wear.ui.FaceclawWearApp
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.update
class MainActivity : ComponentActivity() {
private lateinit var link: PhoneLink
private lateinit var prefs: WatchPrefs
private lateinit var haptics: Haptics
+ private lateinit var wakeTracker: WakeTracker
+ private val ambient = MutableStateFlow(AmbientMode())
+ /** The last stop was the display turning off (not the user leaving). */
+ private var stoppedForScreenOff = false
+
+ // Always-on support: with these callbacks Wear OS keeps the activity in
+ // front in ambient (we draw the clock) instead of blurring a snapshot of
+ // it under the system clock and, after a timeout, dropping back to the
+ // watch face.
+ private val ambientCallback = object : AmbientLifecycleObserver.AmbientLifecycleCallback {
+ override fun onEnterAmbient(ambientDetails: AmbientLifecycleObserver.AmbientDetails) {
+ Log.d(TAG, "enter ambient (burnIn=${ambientDetails.burnInProtectionRequired} lowBit=${ambientDetails.deviceHasLowBitAmbient})")
+ ambient.update {
+ AmbientMode(
+ active = true,
+ burnInProtectionRequired = ambientDetails.burnInProtectionRequired,
+ lowBit = ambientDetails.deviceHasLowBitAmbient,
+ tick = it.tick + 1,
+ )
+ }
+ }
+
+ override fun onUpdateAmbient() {
+ Log.d(TAG, "update ambient")
+ ambient.update { it.copy(tick = it.tick + 1) }
+ }
+
+ override fun onExitAmbient() {
+ Log.d(TAG, "exit ambient")
+ ambient.update { it.copy(active = false) }
+ wakeTracker.onWake(fromScreenOff = false)
+ }
+ }
// Side (stem) buttons: button 1 is click / hold, 2 double-click, 3 "Hey Even".
private val stemHandler = Handler(Looper.getMainLooper())
@@ -27,8 +65,17 @@ class MainActivity : ComponentActivity() {
link = PhoneLink(this)
prefs = WatchPrefs(this)
haptics = Haptics(this) { prefs.prefs.value.haptics }
+ wakeTracker = WakeTracker(this)
+ wakeTracker.start()
+ lifecycle.addObserver(AmbientLifecycleObserver(this, ambientCallback))
setContent {
- FaceclawWearApp(link = link, prefsStore = prefs, haptics = haptics)
+ FaceclawWearApp(
+ link = link,
+ prefsStore = prefs,
+ haptics = haptics,
+ ambient = ambient,
+ wakes = wakeTracker.wakes,
+ )
}
// A remote that dozes mid-gesture is no remote: hold the display while
// the app is in front (every screen, not just the pad), unless the
@@ -46,10 +93,29 @@ class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
+ Log.d(TAG, "onStart")
link.start()
}
+ override fun onResume() {
+ super.onResume()
+ Log.d(TAG, "onResume")
+ if (stoppedForScreenOff) {
+ stoppedForScreenOff = false
+ wakeTracker.onWake(fromScreenOff = true)
+ }
+ }
+
+ override fun onPause() {
+ Log.d(TAG, "onPause")
+ super.onPause()
+ }
+
override fun onStop() {
+ // With always-on off the display going dark stops the activity; the
+ // next resume is then a wake, and its tap deserves the wake treatment.
+ stoppedForScreenOff = getSystemService(PowerManager::class.java)?.isInteractive == false
+ Log.d(TAG, "onStop (screenOff=$stoppedForScreenOff)")
cancelStemHold()
// A stopped activity never sees the key-up, and the phone keeps the
// hold (and its escape-menu countdown) running until it hears the
@@ -62,6 +128,11 @@ class MainActivity : ComponentActivity() {
super.onStop()
}
+ override fun onDestroy() {
+ wakeTracker.stop()
+ super.onDestroy()
+ }
+
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_STEM_1 -> {
@@ -132,6 +203,7 @@ class MainActivity : ComponentActivity() {
link.state.value?.let { it.connected && !it.screenOn } == true
private companion object {
+ const val TAG = "FaceclawWear"
const val STEM_HOLD_MS = 450L
}
}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/OnBodyMonitor.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/OnBodyMonitor.kt
index 609d888b..c77cd41a 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/OnBodyMonitor.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/OnBodyMonitor.kt
@@ -11,7 +11,7 @@ import android.util.Log
/**
* Whether the watch is on a wrist, from the low-latency off-body sensor.
- * The motion-sensor gestures (tip taps, wrist twists) only make sense on a
+ * The motion-sensor gestures (tip taps) only make sense on a
* wrist: on a desk, a buzzing phone next to the watch reads as a fingertip
* tap. Watches without the sensor are assumed worn.
*/
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt
index f2d0903a..7e430742 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/Protocol.kt
@@ -34,6 +34,8 @@ enum class Gesture(val wire: String) {
/** Finger down: the hold lasts until LONG_PRESS_RELEASE. */
LONG_PRESS_START("long-press-start"),
LONG_PRESS_RELEASE("long-press-release"),
+ /** Tap then hold: opens the app's context menu on the glasses (G2 2.2.9 gesture). */
+ SHORT_THEN_LONG_PRESS("short-then-long-press"),
/** The spoken "Hey Even": opens the glasses' own voice dialog. */
WAKEWORD("wakeword"),
/**
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/WakeTracker.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/WakeTracker.kt
new file mode 100644
index 00000000..2a7ffac6
--- /dev/null
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/WakeTracker.kt
@@ -0,0 +1,98 @@
+package com.faceclaw.wear
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.util.Log
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/** A wake of the watch display that a tap on the pad may have caused. */
+data class Wake(
+ val id: Long,
+ /** SystemClock.uptimeMillis when the app learned of the wake. */
+ val uptimeMillis: Long,
+ /**
+ * The display was fully off (always-on disabled), so the activity was
+ * stopped and the tap's job was to turn the screen on; a lone tap should
+ * not also reach the glasses. False for an exit from ambient, where the
+ * pad was already showing and a tap on it means a tap.
+ */
+ val fromScreenOff: Boolean,
+)
+
+/**
+ * Which display wakes were taps. The system consumes the touch that wakes
+ * the watch (from ambient or from off), so the pad never sees it; this
+ * reports each wake so the pad can treat it as a virtual first tap. Wakes by
+ * wrist raise are filtered out with the wrist-tilt gesture sensor, the same
+ * signal tilt-to-wake uses. Rotary and button wakes are left to the pad to
+ * cancel (a crown event follows straight away; a button wake leaves the app).
+ * Lives for the activity's lifetime (start()/stop() from onCreate/onDestroy):
+ * the sensor is a wake-up one, so a tilt is seen even while the activity sits
+ * stopped behind an off display.
+ */
+class WakeTracker(context: Context) : SensorEventListener {
+ private val sensorManager: SensorManager? = context.getSystemService(SensorManager::class.java)
+ private val sensor: Sensor? = sensorManager?.getDefaultSensor(TYPE_WRIST_TILT_GESTURE, true)
+ ?: sensorManager?.getDefaultSensor(TYPE_WRIST_TILT_GESTURE)
+ private val handler = Handler(Looper.getMainLooper())
+ private var running = false
+ private var lastTiltAt = Long.MIN_VALUE / 2
+ private var nextId = 1L
+
+ private val _wakes = MutableStateFlow(null)
+ /** The latest wake, or null once it was attributed to a wrist raise. */
+ val wakes: StateFlow = _wakes.asStateFlow()
+
+ fun start() {
+ val manager = sensorManager ?: return
+ val target = sensor ?: run { Log.i(TAG, "no wrist-tilt sensor: wakes are all taken for taps"); return }
+ if (running) return
+ running = manager.registerListener(this, target, SensorManager.SENSOR_DELAY_NORMAL, handler)
+ }
+
+ fun stop() {
+ if (!running) return
+ running = false
+ sensorManager?.unregisterListener(this)
+ }
+
+ /** The display just woke with the app in front. Main thread. */
+ fun onWake(fromScreenOff: Boolean) {
+ val now = SystemClock.uptimeMillis()
+ if (now - lastTiltAt <= TILT_GRACE_MS) {
+ Log.d(TAG, "wake (fromScreenOff=$fromScreenOff): wrist raise, ignored")
+ return
+ }
+ Log.d(TAG, "wake (fromScreenOff=$fromScreenOff): possible tap")
+ _wakes.value = Wake(id = nextId++, uptimeMillis = now, fromScreenOff = fromScreenOff)
+ }
+
+ override fun onSensorChanged(event: SensorEvent) {
+ lastTiltAt = SystemClock.uptimeMillis()
+ val pending = _wakes.value
+ if (pending != null && lastTiltAt - pending.uptimeMillis <= TILT_GRACE_MS) {
+ Log.d(TAG, "wrist tilt: wake ${pending.id} was a wrist raise")
+ _wakes.value = null
+ } else {
+ Log.d(TAG, "wrist tilt")
+ }
+ }
+
+ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
+
+ private companion object {
+ const val TAG = "FaceclawWear"
+ /** Sensor.TYPE_WRIST_TILT_GESTURE ("android.sensor.wrist_tilt_gesture"): hidden in the SDK. */
+ const val TYPE_WRIST_TILT_GESTURE = 26
+ /** A tilt this close to a wake (either side) means the tilt caused it. */
+ const val TILT_GRACE_MS = 500L
+ }
+}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/WatchPrefs.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/WatchPrefs.kt
index 2cb19e25..b53483c1 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/WatchPrefs.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/WatchPrefs.kt
@@ -13,20 +13,6 @@ enum class CrownSensitivity(val label: String, val pixelsPerStep: Float) {
fun next(): CrownSensitivity = entries[(ordinal + 1) % entries.size]
}
-/** What a horizontal swipe on the pad does. */
-enum class SwipeAction(val label: String) {
- /** Sent as directional input; the glasses UI decides (see Gesture.SWIPE_LEFT). */
- NAVIGATE("Navigate"),
- SIDEBAR("Sidebar"),
- DOUBLE_CLICK("Double-click"),
- CLICK("Click"),
- LONG_PRESS("Long press"),
- WAKEWORD("“Hey Even”"),
- NONE("Nothing");
-
- fun next(): SwipeAction = entries[(ordinal + 1) % entries.size]
-}
-
/** Watch-local preferences (nothing here is synced to the phone). */
data class Prefs(
/** Buzz on every gesture sent. */
@@ -37,13 +23,7 @@ data class Prefs(
* exactly when a remote wants to stay ready.
*/
val keepScreenOn: Boolean = true,
- /** Swipe direction follows the content (touch-scroll style) instead of the ring. */
- val naturalScroll: Boolean = false,
- /** Tap the top/bottom of the pad to scroll instead of swiping. */
- val tapZones: Boolean = false,
val crownSensitivity: CrownSensitivity = CrownSensitivity.NORMAL,
- val swipeLeft: SwipeAction = SwipeAction.NAVIGATE,
- val swipeRight: SwipeAction = SwipeAction.NAVIGATE,
/**
* Fingertip (pinch) taps from the motion sensors; see FingerTapDetector.
* Off by default: on a wrist, ordinary hand movement produced phantom
@@ -51,9 +31,6 @@ data class Prefs(
*/
val fingerTaps: Boolean = false,
val tapSensitivity: TapSensitivity = TapSensitivity.NORMAL,
- /** Two quick wrist twists = back (double-click); see WristTwistDetector. */
- val wristTwist: Boolean = true,
- val twistSensitivity: TwistSensitivity = TwistSensitivity.NORMAL,
)
class WatchPrefs(context: Context) {
@@ -64,25 +41,13 @@ class WatchPrefs(context: Context) {
private fun load(): Prefs = Prefs(
haptics = store.getBoolean(KEY_HAPTICS, true),
keepScreenOn = store.getBoolean(KEY_KEEP_SCREEN_ON, true),
- naturalScroll = store.getBoolean(KEY_NATURAL_SCROLL, false),
- tapZones = store.getBoolean(KEY_TAP_ZONES, false),
crownSensitivity = store.getString(KEY_CROWN, null)
?.let { stored -> CrownSensitivity.entries.firstOrNull { it.name == stored } }
?: CrownSensitivity.NORMAL,
- swipeLeft = store.getString(KEY_SWIPE_LEFT, null)
- ?.let { stored -> SwipeAction.entries.firstOrNull { it.name == stored } }
- ?: SwipeAction.NAVIGATE,
- swipeRight = store.getString(KEY_SWIPE_RIGHT, null)
- ?.let { stored -> SwipeAction.entries.firstOrNull { it.name == stored } }
- ?: SwipeAction.NAVIGATE,
fingerTaps = store.getBoolean(KEY_FINGER_TAPS, false),
tapSensitivity = store.getString(KEY_TAP_SENSITIVITY, null)
?.let { stored -> TapSensitivity.entries.firstOrNull { it.name == stored } }
?: TapSensitivity.NORMAL,
- wristTwist = store.getBoolean(KEY_WRIST_TWIST, true),
- twistSensitivity = store.getString(KEY_TWIST_SENSITIVITY, null)
- ?.let { stored -> TwistSensitivity.entries.firstOrNull { it.name == stored } }
- ?: TwistSensitivity.NORMAL,
)
fun update(transform: (Prefs) -> Prefs) {
@@ -91,29 +56,17 @@ class WatchPrefs(context: Context) {
store.edit()
.putBoolean(KEY_HAPTICS, next.haptics)
.putBoolean(KEY_KEEP_SCREEN_ON, next.keepScreenOn)
- .putBoolean(KEY_NATURAL_SCROLL, next.naturalScroll)
- .putBoolean(KEY_TAP_ZONES, next.tapZones)
.putString(KEY_CROWN, next.crownSensitivity.name)
- .putString(KEY_SWIPE_LEFT, next.swipeLeft.name)
- .putString(KEY_SWIPE_RIGHT, next.swipeRight.name)
.putBoolean(KEY_FINGER_TAPS, next.fingerTaps)
.putString(KEY_TAP_SENSITIVITY, next.tapSensitivity.name)
- .putBoolean(KEY_WRIST_TWIST, next.wristTwist)
- .putString(KEY_TWIST_SENSITIVITY, next.twistSensitivity.name)
.apply()
}
private companion object {
const val KEY_HAPTICS = "haptics"
const val KEY_KEEP_SCREEN_ON = "keepScreenOn"
- const val KEY_NATURAL_SCROLL = "naturalScroll"
- const val KEY_TAP_ZONES = "tapZones"
const val KEY_CROWN = "crownSensitivity"
- const val KEY_SWIPE_LEFT = "swipeLeft"
- const val KEY_SWIPE_RIGHT = "swipeRight"
const val KEY_FINGER_TAPS = "fingerTaps"
const val KEY_TAP_SENSITIVITY = "tapSensitivity"
- const val KEY_WRIST_TWIST = "wristTwist"
- const val KEY_TWIST_SENSITIVITY = "twistSensitivity"
}
}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/WristTwistDetector.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/WristTwistDetector.kt
deleted file mode 100644
index 82d134df..00000000
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/WristTwistDetector.kt
+++ /dev/null
@@ -1,137 +0,0 @@
-package com.faceclaw.wear
-
-import android.content.Context
-import android.hardware.Sensor
-import android.hardware.SensorEvent
-import android.hardware.SensorEventListener
-import android.hardware.SensorManager
-import android.os.Handler
-import android.os.Looper
-import android.os.SystemClock
-import android.util.Log
-import kotlin.math.abs
-
-/** How fast the wrist has to turn before a twist counts. */
-enum class TwistSensitivity(val label: String, val threshold: Float) {
- /** Only a brisk flick; rad/s about the forearm. */
- LOW("Low", 5.0f),
- NORMAL("Normal", 3.6f),
- HIGH("High", 2.6f);
-
- fun next(): TwistSensitivity = entries[(ordinal + 1) % entries.size]
-}
-
-/**
- * "Twist the wrist twice" = back. The gyroscope's x axis runs along the
- * forearm on a watch, so a wrist twist (pronation / supination) is a burst of
- * angular velocity about x. Two brisk twists in the same direction, each
- * short and separated by 120–900 ms, fire the gesture; the wrist coming back
- * between them spins the other way and is ignored. The direction is not
- * fixed (away or toward), so it works on either wrist, and the twists must be
- * quick: a slow arm rotation never crosses the rate threshold.
- *
- * Same status as FingerTapDetector: a heuristic with a toggle, not a
- * classifier.
- */
-class WristTwistDetector(
- context: Context,
- private val sensitivity: () -> TwistSensitivity,
- /** elapsedRealtime before which samples are ignored (the watch's own haptics). */
- private val quietUntil: () -> Long,
- /** False while the watch is off the wrist; twists then never fire. */
- private val onBody: () -> Boolean,
- private val onDoubleTwist: () -> Unit,
-) : SensorEventListener {
- private val sensorManager: SensorManager? = context.getSystemService(SensorManager::class.java)
- private val sensor: Sensor? = sensorManager?.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
- private val handler = Handler(Looper.getMainLooper())
-
- private var inBurst = false
- /** Slow average of |rate| outside bursts: how much the arm is rotating anyway. */
- private var activity = 0f
- private var lastMotionNs = 0L
- private var burstStartNs = 0L
- private var burstSign = 0
- private var firstTwistNs = 0L
- private var firstTwistSign = 0
- private var running = false
-
- val available: Boolean get() = sensor != null
-
- fun start(): Boolean {
- val manager = sensorManager ?: return false
- val target = sensor ?: return false
- if (running) return true
- running = manager.registerListener(this, target, SAMPLING_PERIOD_US, handler)
- Log.i(TAG, "wrist-twist detector ${if (running) "started" else "failed to start"}")
- return running
- }
-
- fun stop() {
- if (!running) return
- running = false
- sensorManager?.unregisterListener(this)
- inBurst = false
- firstTwistNs = 0L
- }
-
- override fun onSensorChanged(event: SensorEvent) {
- val rate = event.values[0]
- val now = event.timestamp
- if (SystemClock.elapsedRealtime() < quietUntil() || !onBody()) {
- inBurst = false
- firstTwistNs = 0L
- return
- }
- val threshold = sensitivity().threshold
-
- if (!inBurst) {
- val magnitude = abs(rate)
- // A twist pair only starts from a still-ish wrist: general arm
- // rotation (reaching, gesturing) produced same-sign burst pairs
- // that read as the gesture.
- val still = activity < threshold * ACTIVITY_FRACTION && now - lastMotionNs > STILLNESS_BEFORE_TWIST_NS
- if (magnitude > threshold && (still || firstTwistNs != 0L)) {
- inBurst = true
- burstStartNs = now
- burstSign = if (rate > 0) 1 else -1
- } else {
- activity += (magnitude - activity) * ACTIVITY_ALPHA
- if (magnitude > threshold * ACTIVITY_FRACTION) lastMotionNs = now
- }
- return
- }
- // In a burst: wait for the rate to drop back under the threshold.
- if (abs(rate) > threshold * BURST_END_FRACTION && (if (rate > 0) 1 else -1) == burstSign) return
- inBurst = false
- val duration = now - burstStartNs
- if (duration > MAX_BURST_NS) return // a slow sweep, not a flick
-
- val sinceFirst = now - firstTwistNs
- if (firstTwistNs != 0L && burstSign == firstTwistSign && sinceFirst in MIN_GAP_NS..MAX_GAP_NS) {
- firstTwistNs = 0L
- onDoubleTwist()
- } else if (firstTwistNs == 0L || sinceFirst > MAX_GAP_NS || burstSign != firstTwistSign) {
- // The return twist (opposite sign) does not start a new pair; a
- // fresh same-direction twist does.
- if (firstTwistNs == 0L || sinceFirst > MAX_GAP_NS) {
- firstTwistNs = now
- firstTwistSign = burstSign
- }
- }
- }
-
- override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
-
- private companion object {
- const val TAG = "FaceclawWear"
- const val SAMPLING_PERIOD_US = 10_000
- const val MAX_BURST_NS = 350_000_000L
- const val MIN_GAP_NS = 120_000_000L
- const val MAX_GAP_NS = 900_000_000L
- const val BURST_END_FRACTION = 0.5f
- const val ACTIVITY_ALPHA = 0.04f
- const val ACTIVITY_FRACTION = 0.35f
- const val STILLNESS_BEFORE_TWIST_NS = 300_000_000L
- }
-}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/AmbientScreen.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/AmbientScreen.kt
new file mode 100644
index 00000000..7e3cc278
--- /dev/null
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/AmbientScreen.kt
@@ -0,0 +1,80 @@
+package com.faceclaw.wear.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.wear.compose.material.MaterialTheme
+import androidx.wear.compose.material.Text
+import com.faceclaw.wear.AmbientMode
+import com.faceclaw.wear.PhoneLink
+import java.util.Date
+import kotlin.random.Random
+
+/** Burn-in protection shifts the content by up to this many pixels each way. */
+private const val BURN_IN_SHIFT_PX = 8
+
+/**
+ * The always-on face: the pad's clock and its status line on black, nothing
+ * else and nothing moving. Redraws when [AmbientMode.tick] changes (the
+ * system's once-a-minute ambient update) and when the phone's state does.
+ */
+@Composable
+fun AmbientScreen(link: PhoneLink, ambient: AmbientMode) {
+ val state by link.state.collectAsStateWithLifecycle()
+ val linkStatus by link.link.collectAsStateWithLifecycle()
+ val formatter = rememberClockFormatter()
+ val time = remember(ambient.tick, formatter) { formatter.format(Date()) }
+ val shift = remember(ambient.tick, ambient.burnInProtectionRequired) {
+ if (!ambient.burnInProtectionRequired) IntOffset.Zero else {
+ val random = Random(ambient.tick)
+ IntOffset(
+ random.nextInt(-BURN_IN_SHIFT_PX, BURN_IN_SHIFT_PX + 1),
+ random.nextInt(-BURN_IN_SHIFT_PX, BURN_IN_SHIFT_PX + 1),
+ )
+ }
+ }
+ // A 1-bit panel renders grey as noise: everything white there.
+ val statusColor = if (ambient.lowBit) Color.White else Color(0xFF8A8A8A)
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black)
+ .offset { shift },
+ ) {
+ Text(
+ text = time,
+ color = Color.White,
+ fontSize = 42.sp,
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ modifier = Modifier.align(Alignment.Center),
+ )
+ Text(
+ text = padLine(state, linkStatus).text,
+ style = MaterialTheme.typography.title3,
+ color = statusColor,
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier
+ .align(Alignment.Center)
+ .offset(y = 46.dp)
+ .padding(horizontal = 42.dp),
+ )
+ }
+}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/Common.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/Common.kt
index e571e861..1e3b3232 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/Common.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/Common.kt
@@ -3,15 +3,18 @@ package com.faceclaw.wear.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
+import android.text.format.DateFormat
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -20,6 +23,16 @@ import androidx.wear.compose.material.Text
import com.faceclaw.wear.LinkStatus
import com.faceclaw.wear.Notice
import com.faceclaw.wear.PhoneState
+import java.text.SimpleDateFormat
+import java.util.Locale
+
+/** Hours and minutes in the watch's 12/24-hour preference, for the pad's clock. */
+@Composable
+fun rememberClockFormatter(): SimpleDateFormat {
+ val context = LocalContext.current
+ val pattern = remember(context) { if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm" }
+ return remember(pattern) { SimpleDateFormat(pattern, Locale.getDefault()) }
+}
/** A transient pill at the bottom of the screen: ack failures and confirmations. */
@Composable
@@ -72,7 +85,7 @@ fun padLine(state: PhoneState?, link: LinkStatus): StatusLine = when {
}
state.phase == "connecting" -> StatusLine("Connecting…", StatusTone.BUSY)
state.phase == "disconnecting" -> StatusLine("Disconnecting…", StatusTone.BUSY)
- else -> StatusLine("Glasses disconnected", StatusTone.OFF)
+ else -> StatusLine("Disconnected", StatusTone.OFF)
}
private fun chargingLine(battery: Int?): String =
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/FaceclawWearApp.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/FaceclawWearApp.kt
index dbeb36b0..4b0209d3 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/FaceclawWearApp.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/FaceclawWearApp.kt
@@ -1,17 +1,26 @@
package com.faceclaw.wear.ui
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
+import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.navigation.NavHostController
import androidx.wear.compose.material.Colors
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
+import com.faceclaw.wear.AmbientMode
import com.faceclaw.wear.Haptics
import com.faceclaw.wear.PhoneLink
+import com.faceclaw.wear.Wake
import com.faceclaw.wear.WatchPrefs
+import kotlinx.coroutines.flow.StateFlow
object Routes {
const val REMOTE = "remote"
@@ -30,36 +39,73 @@ private val FaceclawColors = Colors(
onSecondary = Color(0xFF101010),
)
-/** Root: the remote pad, with every other screen a swipe-back away. */
+/** The watch's ambient state, for screens that pause work while it is on. */
+val LocalAmbientMode = compositionLocalOf { AmbientMode() }
+
+/**
+ * Root: the remote pad, with every other screen a swipe-back away. In ambient
+ * [AmbientScreen] is laid over the lot. The screens stay composed underneath
+ * (the nav host animates any destination it composes, which on every wake
+ * was a visible flicker between two identical frames) and read
+ * [LocalAmbientMode] to pause their sensors.
+ */
@Composable
-fun FaceclawWearApp(link: PhoneLink, prefsStore: WatchPrefs, haptics: Haptics) {
- val prefs by prefsStore.prefs.collectAsStateWithLifecycle()
+fun FaceclawWearApp(
+ link: PhoneLink,
+ prefsStore: WatchPrefs,
+ haptics: Haptics,
+ ambient: StateFlow,
+ wakes: StateFlow,
+) {
+ val ambientMode by ambient.collectAsStateWithLifecycle()
val navController = rememberSwipeDismissableNavController()
MaterialTheme(colors = FaceclawColors) {
- SwipeDismissableNavHost(navController = navController, startDestination = Routes.REMOTE) {
- composable(Routes.REMOTE) {
- RemoteScreen(
- link = link,
- prefs = prefs,
- haptics = haptics,
- onOpenApps = { navController.navigate(Routes.APPS) },
- onOpenAssistant = { navController.navigate(Routes.ASSISTANT) },
- onOpenStatus = { navController.navigate(Routes.STATUS) },
- )
- }
- composable(Routes.APPS) {
- AppsScreen(link = link, haptics = haptics, onDone = { navController.popBackStack() })
- }
- composable(Routes.ASSISTANT) {
- AssistantScreen(link = link, haptics = haptics)
- }
- composable(Routes.STATUS) {
- StatusScreen(link = link, haptics = haptics, onOpenSettings = { navController.navigate(Routes.SETTINGS) })
- }
- composable(Routes.SETTINGS) {
- SettingsScreen(prefs = prefs, store = prefsStore)
+ CompositionLocalProvider(LocalAmbientMode provides ambientMode) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ Screens(navController, link, prefsStore, haptics, wakes)
+ if (ambientMode.active) AmbientScreen(link = link, ambient = ambientMode)
}
}
}
}
+
+@Composable
+private fun Screens(
+ navController: NavHostController,
+ link: PhoneLink,
+ prefsStore: WatchPrefs,
+ haptics: Haptics,
+ wakes: StateFlow,
+) {
+ // Prefs are collected inside each destination rather than passed in as a
+ // value: the nav host keeps the content lambda it composed, so a value
+ // captured by the builder would stay stale until the screen is re-entered.
+ SwipeDismissableNavHost(navController = navController, startDestination = Routes.REMOTE) {
+ composable(Routes.REMOTE) {
+ val prefs by prefsStore.prefs.collectAsStateWithLifecycle()
+ RemoteScreen(
+ link = link,
+ prefs = prefs,
+ haptics = haptics,
+ wakes = wakes,
+ onOpenApps = { navController.navigate(Routes.APPS) },
+ onOpenAssistant = { navController.navigate(Routes.ASSISTANT) },
+ onOpenStatus = { navController.navigate(Routes.STATUS) },
+ )
+ }
+ composable(Routes.APPS) {
+ AppsScreen(link = link, haptics = haptics, onDone = { navController.popBackStack() })
+ }
+ composable(Routes.ASSISTANT) {
+ AssistantScreen(link = link, haptics = haptics)
+ }
+ composable(Routes.STATUS) {
+ StatusScreen(link = link, haptics = haptics, onOpenSettings = { navController.navigate(Routes.SETTINGS) })
+ }
+ composable(Routes.SETTINGS) {
+ val prefs by prefsStore.prefs.collectAsStateWithLifecycle()
+ SettingsScreen(prefs = prefs, store = prefsStore)
+ }
+ }
+}
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/RemoteScreen.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/RemoteScreen.kt
index f836832f..471fd45c 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/RemoteScreen.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/RemoteScreen.kt
@@ -1,6 +1,6 @@
package com.faceclaw.wear.ui
-import android.text.format.DateFormat
+import android.os.SystemClock
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -30,9 +30,9 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.layout.onSizeChanged
-import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
@@ -50,7 +50,6 @@ import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
-import com.faceclaw.wear.Command
import com.faceclaw.wear.FingerTapDetector
import com.faceclaw.wear.Gesture
import com.faceclaw.wear.Haptics
@@ -58,27 +57,38 @@ import com.faceclaw.wear.OnBodyMonitor
import com.faceclaw.wear.PhoneLink
import com.faceclaw.wear.Prefs
import com.faceclaw.wear.R
-import com.faceclaw.wear.SwipeAction
-import com.faceclaw.wear.WristTwistDetector
+import com.faceclaw.wear.Wake
import kotlinx.coroutines.delay
-import java.text.SimpleDateFormat
+import kotlinx.coroutines.flow.StateFlow
import java.util.Date
-import java.util.Locale
import kotlin.math.abs
/** A two-finger swipe scrolls this many steps: a "page". */
private const val TWO_FINGER_SWIPE_STEPS = 3
private val EDGE_REVEAL_ZONE = 24.dp
private val BUTTON_TRAY_HEIGHT = 62.dp
+/**
+ * After a wake from an off display, how long a press still counts as the
+ * second tap of the double-tap that woke it. Longer than the double-tap
+ * timeout because the window only gets input focus ~300 ms into such a wake
+ * and the press queues behind that.
+ */
+private const val SCREEN_ON_SECOND_TAP_WINDOW_MS = 600L
/**
* The touchpad. The whole screen is the pad: tap = select, double-tap =
* back, hold = long press (released when the finger lifts), two-finger tap =
- * the hold menu ("right click"), swipes in four directions = spatial
+ * back as well, swipes in four directions = spatial
* navigation (crown and two-finger vertical swipes = plain scrolling, a page
* at a time for the latter). Fingertip pinch-taps from the motion sensors
- * select / go back, and two quick wrist twists go back. An upward swipe that
+ * select / go back. An upward swipe that
* begins at the bottom edge reveals the otherwise-hidden action buttons.
+ *
+ * A tap that wakes the display never reaches the pad (the system eats it),
+ * so each wake in [wakes] stands in for a first tap: a press inside the
+ * double-tap window makes the pair a double-tap, and a lone wake from ambient
+ * (where the pad was already showing) becomes a tap once the window closes.
+ * A lone wake from an off display just turned the screen on.
*/
// rememberActiveFocusRequester (rotary focus) is still experimental in Wear Compose 1.4.
@OptIn(ExperimentalWearFoundationApi::class)
@@ -87,6 +97,7 @@ fun RemoteScreen(
link: PhoneLink,
prefs: Prefs,
haptics: Haptics,
+ wakes: StateFlow,
onOpenApps: () -> Unit,
onOpenAssistant: () -> Unit,
onOpenStatus: () -> Unit,
@@ -94,6 +105,10 @@ fun RemoteScreen(
val state by link.state.collectAsStateWithLifecycle()
val linkStatus by link.link.collectAsStateWithLifecycle()
val notice by link.notice.collectAsStateWithLifecycle()
+ val wake by wakes.collectAsStateWithLifecycle()
+ val ambientActive = LocalAmbientMode.current.active
+ val doubleTapTimeout = LocalViewConfiguration.current.doubleTapTimeoutMillis
+ val pendingTap = remember { PendingTap() }
val currentPrefs by rememberUpdatedState(prefs)
val currentState by rememberUpdatedState(state)
val view = LocalView.current
@@ -116,7 +131,7 @@ fun RemoteScreen(
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var crownAccumulator by remember { mutableStateOf(0f) }
- // Pad height in px, for the tap zones; written by onSizeChanged, read by
+ // Pad height in px, for the edge-reveal zone; written by onSizeChanged, read by
// the gesture callbacks (plain holder: the callbacks are remembered once).
val padHeight = remember { floatArrayOf(1f) }
@@ -148,55 +163,26 @@ fun RemoteScreen(
link.sendGesture(Gesture.DOUBLE_CLICK)
}
- /** Run a horizontal-swipe action; `left` says which way the finger went. */
- fun perform(action: SwipeAction, left: Boolean) {
- when (action) {
- SwipeAction.NAVIGATE -> {
- val gesture = if (left) Gesture.SWIPE_LEFT else Gesture.SWIPE_RIGHT
- if (gestureAllowed(gesture)) { haptics.click(); link.sendGesture(gesture) }
- }
- SwipeAction.SIDEBAR -> if (!glassesScreenIsOff()) {
- haptics.click()
- link.sendCommand(Command.SIDEBAR, "source" to "gesture")
- }
- SwipeAction.DOUBLE_CLICK -> doubleClick()
- SwipeAction.CLICK -> click()
- SwipeAction.LONG_PRESS -> if (!glassesScreenIsOff()) { haptics.heavy(); link.sendGesture(Gesture.LONG_PRESS) }
- SwipeAction.WAKEWORD -> if (!glassesScreenIsOff()) { haptics.click(); link.sendGesture(Gesture.WAKEWORD) }
- SwipeAction.NONE -> Unit
- }
- }
-
- /** Whether a vertical swipe means "up", honouring the natural-scroll preference. */
- fun swipeIsUp(dy: Float): Boolean {
- // Ring convention: swiping up means up. "Natural" flips it so the
- // content follows the finger like a touch screen.
- return if (currentPrefs.naturalScroll) dy > 0 else dy < 0
+ /** A horizontal swipe is spatial input; the glasses UI decides what it means. */
+ fun navigate(left: Boolean) {
+ val gesture = if (left) Gesture.SWIPE_LEFT else Gesture.SWIPE_RIGHT
+ if (gestureAllowed(gesture)) { haptics.click(); link.sendGesture(gesture) }
}
val callbacks = remember(link, haptics) {
TouchpadCallbacks(
- onTap = { position ->
- if (currentPrefs.tapZones) {
- // Top third scrolls up, bottom third down, the middle clicks.
- val zone = position.y / padHeight[0].coerceAtLeast(1f)
- when {
- zone < 1f / 3f -> scroll(Gesture.SCROLL_UP, 1)
- zone > 2f / 3f -> scroll(Gesture.SCROLL_DOWN, 1)
- else -> click()
- }
- } else {
- click()
- }
- },
+ onTap = { _ -> click() },
onDoubleTap = { _ -> doubleClick() },
+ onShortThenLongPress = {
+ if (!glassesScreenIsOff()) { haptics.heavy(); link.sendGesture(Gesture.SHORT_THEN_LONG_PRESS) }
+ },
// Two fingers = back as well: easier than timing a double-tap.
onTwoFingerTap = { doubleClick() },
onTwoFingerSwipe = { dx, dy ->
if (abs(dy) >= abs(dx)) {
- scroll(if (swipeIsUp(dy)) Gesture.SCROLL_UP else Gesture.SCROLL_DOWN, TWO_FINGER_SWIPE_STEPS)
+ scroll(if (dy < 0) Gesture.SCROLL_UP else Gesture.SCROLL_DOWN, TWO_FINGER_SWIPE_STEPS)
} else {
- perform(if (dx < 0) currentPrefs.swipeLeft else currentPrefs.swipeRight, left = dx < 0)
+ navigate(left = dx < 0)
}
},
onLongPressStart = {
@@ -231,18 +217,33 @@ fun RemoteScreen(
// whenever the display lagged the finger. Fast repeated
// swiping, the crown, or a two-finger page swipe cover
// long distances instead.
- val up = swipeIsUp(dy)
- scroll(if (up) Gesture.SWIPE_UP else Gesture.SWIPE_DOWN, 1)
+ scroll(if (dy < 0) Gesture.SWIPE_UP else Gesture.SWIPE_DOWN, 1)
}
- else -> perform(if (dx < 0) currentPrefs.swipeLeft else currentPrefs.swipeRight, left = dx < 0)
+ else -> navigate(left = dx < 0)
}
},
)
}
- // Motion-sensor gestures only count on a wrist (see OnBodyMonitor).
+ // The wake-tap: arm the detector for a second press, and when none comes
+ // decide what the lone tap meant. A wake the tracker re-attributes to a
+ // wrist raise arrives as null and cancels all of it.
+ LaunchedEffect(wake) {
+ val current = wake
+ if (current == null) {
+ pendingTap.disarm()
+ return@LaunchedEffect
+ }
+ val window = if (current.fromScreenOff) SCREEN_ON_SECOND_TAP_WINDOW_MS else doubleTapTimeout
+ pendingTap.arm(current.uptimeMillis, window)
+ delay((current.uptimeMillis + window - SystemClock.uptimeMillis()).coerceAtLeast(0L))
+ if (pendingTap.expire() && !current.fromScreenOff) click()
+ }
+
+ // Motion-sensor gestures only count on a wrist (see OnBodyMonitor); none
+ // of the sensors run in ambient.
val onBody = remember { OnBodyMonitor(view.context) }
- WhileStartedEffect(onBody, start = onBody::start, stop = onBody::stop)
+ WhileStartedEffect(onBody, enabled = !ambientActive, start = onBody::start, stop = onBody::stop)
// Fingertip (pinch) taps from the motion sensors, only while the pad is up.
val fingerTapsEnabled = prefs.fingerTaps
@@ -256,19 +257,7 @@ fun RemoteScreen(
onDoubleTap = { doubleClick() },
)
}
- WhileStartedEffect(fingerTapDetector, start = { fingerTapDetector?.start() }, stop = { fingerTapDetector?.stop() })
- // Two quick wrist twists = back, from the gyroscope, only while the pad is up.
- val wristTwistEnabled = prefs.wristTwist
- val wristTwistDetector = remember(wristTwistEnabled, link, haptics) {
- if (!wristTwistEnabled) null else WristTwistDetector(
- context = view.context,
- sensitivity = { currentPrefs.twistSensitivity },
- quietUntil = { haptics.quietUntil() },
- onBody = { onBody.onBody },
- onDoubleTwist = { doubleClick() },
- )
- }
- WhileStartedEffect(wristTwistDetector, start = { wristTwistDetector?.start() }, stop = { wristTwistDetector?.stop() })
+ WhileStartedEffect(fingerTapDetector, enabled = !ambientActive, start = { fingerTapDetector?.start() }, stop = { fingerTapDetector?.stop() })
// A refused or unanswered gesture gets a distinct buzz, so the wrist knows
// without looking (the notice pill says why).
@@ -281,6 +270,8 @@ fun RemoteScreen(
modifier = Modifier
.fillMaxSize()
.onRotaryScrollEvent { event ->
+ // A crown turn can be what woke the display: not a tap, then.
+ pendingTap.disarm()
crownAccumulator += event.verticalScrollPixels
val threshold = currentPrefs.crownSensitivity.pixelsPerStep
var steps = 0
@@ -296,7 +287,7 @@ fun RemoteScreen(
.focusRequester(focusRequester)
.focusable()
.onSizeChanged { padHeight[0] = it.height.toFloat() }
- .pointerInput(callbacks) { detectTouchpadGestures(callbacks) },
+ .pointerInput(callbacks) { detectTouchpadGestures(callbacks, pendingTap) },
) {
StraightTime(modifier = Modifier.align(Alignment.Center))
@@ -359,11 +350,14 @@ fun RemoteScreen(
* leaving the composition. A plain DisposableEffect keeps sensors registered
* while the activity sits stopped-but-cached (palmed screen, back on the watch
* face), which at gyroscope/accelerometer rates is a real battery drain.
+ * [enabled] false holds it stopped regardless (ambient, where the activity
+ * stays started for the clock).
*/
@Composable
-private fun WhileStartedEffect(key: Any?, start: () -> Unit, stop: () -> Unit) {
+private fun WhileStartedEffect(key: Any?, enabled: Boolean = true, start: () -> Unit, stop: () -> Unit) {
val lifecycleOwner = LocalLifecycleOwner.current
- DisposableEffect(lifecycleOwner, key) {
+ DisposableEffect(lifecycleOwner, key, enabled) {
+ if (!enabled) return@DisposableEffect onDispose { }
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_START -> start()
@@ -379,14 +373,18 @@ private fun WhileStartedEffect(key: Any?, start: () -> Unit, stop: () -> Unit) {
}
}
-/** A large, straight clock fixed on the vertical centre of the touchpad. */
+/**
+ * A large, straight clock fixed on the vertical centre of the touchpad. The
+ * minute timer cannot run while the watch dozes, so the clock also resyncs
+ * on every ambient tick and on the way out of ambient: the first frame after
+ * a wake would otherwise show the minute the watch dozed off at.
+ */
@Composable
private fun StraightTime(modifier: Modifier = Modifier) {
- val context = LocalContext.current
var now by remember { mutableStateOf(System.currentTimeMillis()) }
- val pattern = remember(context) { if (DateFormat.is24HourFormat(context)) "HH:mm" else "h:mm" }
- val formatter = remember(pattern) { SimpleDateFormat(pattern, Locale.getDefault()) }
- LaunchedEffect(Unit) {
+ val formatter = rememberClockFormatter()
+ val ambient = LocalAmbientMode.current
+ LaunchedEffect(ambient.tick, ambient.active) {
while (true) {
val current = System.currentTimeMillis()
now = current
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/SettingsScreen.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/SettingsScreen.kt
index 60a9283d..c7b33464 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/SettingsScreen.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/SettingsScreen.kt
@@ -50,44 +50,6 @@ fun SettingsScreen(prefs: Prefs, store: WatchPrefs) {
modifier = Modifier.fillMaxWidth(),
)
}
- item {
- ToggleChip(
- checked = prefs.naturalScroll,
- onCheckedChange = { on -> store.update { it.copy(naturalScroll = on) } },
- label = { Text("Natural swipe") },
- secondaryLabel = { Text(if (prefs.naturalScroll) "content follows finger" else "swipe up = scroll up (ring)") },
- toggleControl = { Switch(checked = prefs.naturalScroll) },
- modifier = Modifier.fillMaxWidth(),
- )
- }
- item {
- ToggleChip(
- checked = prefs.tapZones,
- onCheckedChange = { on -> store.update { it.copy(tapZones = on) } },
- label = { Text("Tap zones") },
- secondaryLabel = { Text("tap top/bottom to scroll") },
- toggleControl = { Switch(checked = prefs.tapZones) },
- modifier = Modifier.fillMaxWidth(),
- )
- }
- item {
- Chip(
- onClick = { store.update { it.copy(swipeLeft = it.swipeLeft.next()) } },
- label = { Text("Swipe left") },
- secondaryLabel = { Text(prefs.swipeLeft.label) },
- colors = ChipDefaults.secondaryChipColors(),
- modifier = Modifier.fillMaxWidth(),
- )
- }
- item {
- Chip(
- onClick = { store.update { it.copy(swipeRight = it.swipeRight.next()) } },
- label = { Text("Swipe right") },
- secondaryLabel = { Text(prefs.swipeRight.label) },
- colors = ChipDefaults.secondaryChipColors(),
- modifier = Modifier.fillMaxWidth(),
- )
- }
item { ListHeader { Text("Tip taps") } }
item {
ToggleChip(
@@ -117,27 +79,6 @@ fun SettingsScreen(prefs: Prefs, store: WatchPrefs) {
textAlign = TextAlign.Center,
)
}
- item { ListHeader { Text("Wrist twist") } }
- item {
- ToggleChip(
- checked = prefs.wristTwist,
- onCheckedChange = { on -> store.update { it.copy(wristTwist = on) } },
- label = { Text("Twist twice = back") },
- secondaryLabel = { Text("two quick wrist flicks") },
- toggleControl = { Switch(checked = prefs.wristTwist) },
- modifier = Modifier.fillMaxWidth(),
- )
- }
- item {
- Chip(
- onClick = { store.update { it.copy(twistSensitivity = it.twistSensitivity.next()) } },
- label = { Text("Twist sensitivity") },
- secondaryLabel = { Text(prefs.twistSensitivity.label) },
- colors = ChipDefaults.secondaryChipColors(),
- modifier = Modifier.fillMaxWidth(),
- enabled = prefs.wristTwist,
- )
- }
item { ListHeader { Text("Crown") } }
item {
Chip(
diff --git a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/TouchpadGestures.kt b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/TouchpadGestures.kt
index 3698af99..7cf837e4 100644
--- a/wear/app/src/main/kotlin/com/faceclaw/wear/ui/TouchpadGestures.kt
+++ b/wear/app/src/main/kotlin/com/faceclaw/wear/ui/TouchpadGestures.kt
@@ -2,9 +2,10 @@ package com.faceclaw.wear.ui
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
-import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.pointer.AwaitPointerEventScope
import androidx.compose.ui.input.pointer.PointerEventPass
+import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.positionChanged
import kotlin.math.abs
@@ -13,6 +14,8 @@ import kotlin.math.abs
class TouchpadCallbacks(
val onTap: (position: Offset) -> Unit,
val onDoubleTap: (position: Offset) -> Unit,
+ /** A tap whose immediate second press was held: the G2 tap-then-hold gesture. */
+ val onShortThenLongPress: () -> Unit,
val onTwoFingerTap: () -> Unit,
/** Two fingers travelled past touch slop; dx/dy are the primary finger's displacement. */
val onTwoFingerSwipe: (dx: Float, dy: Float) -> Unit,
@@ -22,14 +25,51 @@ class TouchpadCallbacks(
val onSwipe: (start: Offset, dx: Float, dy: Float, durationMs: Long) -> Unit,
)
+/**
+ * A first tap the pad never saw: the touch that woke the display, which the
+ * system consumes. Armed by the pad on a wake; the next press inside the
+ * window is then the second tap of a pair (a double-tap, or tap-then-hold),
+ * and if no press comes the pad decides what a lone wake-tap meant. Main
+ * thread only.
+ */
+class PendingTap {
+ private var armedAt = -1L
+ private var windowMs = 0L
+
+ fun arm(uptimeMillis: Long, windowMs: Long) {
+ armedAt = uptimeMillis
+ this.windowMs = windowMs
+ }
+
+ fun disarm() {
+ armedAt = -1L
+ }
+
+ /** A press just landed: whether it pairs with the pending tap (which is spent either way). */
+ fun claim(downUptimeMillis: Long): Boolean {
+ val at = armedAt
+ armedAt = -1L
+ return at >= 0 && downUptimeMillis - at in 0..windowMs
+ }
+
+ /** The window closed: whether the tap was still pending (it is spent now). */
+ fun expire(): Boolean {
+ val pending = armedAt >= 0
+ armedAt = -1L
+ return pending
+ }
+}
+
/**
* One detector for everything the pad does, so a gesture is reported exactly
* once: tap, double-tap (a second tap inside the double-tap timeout), a hold
- * (reported at the long-press timeout and again on release), a swipe, and a
- * two-finger tap or swipe. Written as a single awaitEachGesture loop because the
- * stock detectors would each claim the same finger.
+ * (reported at the long-press timeout and again on release), tap-then-hold (a
+ * second tap held past the long-press timeout), a swipe, and a two-finger tap
+ * or swipe. Written as a single awaitEachGesture loop because the stock
+ * detectors would each claim the same finger. A press that pairs with
+ * [pendingTap] skips straight to the second-tap handling.
*/
-suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallbacks) {
+suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallbacks, pendingTap: PendingTap) {
val longPressTimeout = viewConfiguration.longPressTimeoutMillis
val doubleTapTimeout = viewConfiguration.doubleTapTimeoutMillis
val slop = viewConfiguration.touchSlop
@@ -38,6 +78,10 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
val down = awaitFirstDown()
down.consume()
val downTime = down.uptimeMillis
+ if (pendingTap.claim(downTime)) {
+ secondTap(callbacks, longPressTimeout, down.position, down)
+ return@awaitEachGesture
+ }
var maxPointers = 1
var moved = false
var longPressed = false
@@ -95,10 +139,7 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
if (second == null) {
callbacks.onTap(down.position)
} else {
- second.consume()
- val up = waitForUpOrCancellation()
- if (up != null) up.consume()
- callbacks.onDoubleTap(down.position)
+ secondTap(callbacks, longPressTimeout, down.position, second)
}
}
}
@@ -110,6 +151,42 @@ suspend fun PointerInputScope.detectTouchpadGestures(callbacks: TouchpadCallback
}
}
+/**
+ * The second press of a pair. Released within the long-press timeout it's a
+ * double-tap; held past it, the G2 tap-then-hold gesture (reported once at
+ * the timeout, movement tolerated, the rest of the hold swallowed).
+ */
+private suspend fun AwaitPointerEventScope.secondTap(
+ callbacks: TouchpadCallbacks,
+ longPressTimeout: Long,
+ first: Offset,
+ second: PointerInputChange,
+) {
+ second.consume()
+ var held = false
+ while (true) {
+ val remaining = if (held) {
+ HOLD_POLL_MS
+ } else {
+ longPressTimeout - (System.currentTimeMillis() - wallClockAt(second.uptimeMillis))
+ }
+ val event = withTimeoutOrNull(remaining.coerceAtLeast(1L)) { awaitPointerEvent() }
+ if (event == null) {
+ if (!held) {
+ held = true
+ callbacks.onShortThenLongPress()
+ }
+ continue
+ }
+ if (event.changes.any { it.isConsumed }) break
+ for (change in event.changes) change.consume()
+ if (event.changes.none { it.pressed }) {
+ if (!held) callbacks.onDoubleTap(first)
+ break
+ }
+ }
+}
+
/**
* Observe the button tray before its child buttons consume a pointer. A
* downward drag claims the gesture and dismisses the tray; a tap remains
diff --git a/website/index.html b/website/index.html
index 755c4dfb..baa2a341 100644
--- a/website/index.html
+++ b/website/index.html
@@ -69,7 +69,11 @@
- Display settings, including height and vertical position.
+ Display settings, including screen size and font.
+
+
+
+ Compass app.
diff --git a/website/screenshots/compass.png b/website/screenshots/compass.png
new file mode 100644
index 00000000..a4fc51f5
Binary files /dev/null and b/website/screenshots/compass.png differ
diff --git a/website/screenshots/screenshot-launcher.png b/website/screenshots/screenshot-launcher.png
new file mode 100644
index 00000000..79e060f5
Binary files /dev/null and b/website/screenshots/screenshot-launcher.png differ
diff --git a/website/screenshots/settings-display.png b/website/screenshots/settings-display.png
index 7c7da123..ec36a09d 100644
Binary files a/website/screenshots/settings-display.png and b/website/screenshots/settings-display.png differ