forked from Blendman974/faceclaw
Merge branch 'main' of https://github.com/jimrandomh/faceclaw into ring-health-fixes
This commit is contained in:
commit
a2166c6a6c
822 files changed
+79614
-30124
No files matched your search
+2
-134
@@ -1,5 +1,6 @@
|
||||
@import '@nativescript/theme/css/core.css';
|
||||
@import '@nativescript/theme/css/core.css';
|
||||
@import '@nativescript/theme/css/default.css';
|
||||
@import './phone-ui/remote-controls.css';
|
||||
|
||||
Page {
|
||||
background-color: #ffffff;
|
||||
@@ -171,139 +172,6 @@ Button.-primary {
|
||||
margin-bottom: 12;
|
||||
}
|
||||
|
||||
/* The phone's controller for the glasses (phone-ui/remote-controls.xml). */
|
||||
.remote-controls {
|
||||
margin: 0 8 0 8;
|
||||
}
|
||||
/* The Settings / Watch / Ring tab bar above the controls. */
|
||||
.controls-tab-bar {
|
||||
margin-bottom: 8;
|
||||
}
|
||||
.tab-button {
|
||||
font-size: 14;
|
||||
padding: 8 0;
|
||||
margin: 0 2;
|
||||
border-radius: 6;
|
||||
background-color: #e2e2e2;
|
||||
color: #333333;
|
||||
}
|
||||
.tab-button-selected {
|
||||
background-color: #424242;
|
||||
color: #ffffff;
|
||||
}
|
||||
/* 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.
|
||||
* The height also bounds the tile's measure, without which its star row
|
||||
* would collapse to content and pin the icon to the top. */
|
||||
height: 48;
|
||||
margin: 6 2;
|
||||
android-elevation: 2;
|
||||
}
|
||||
.tab-icon {
|
||||
height: 20;
|
||||
tint-color: #333333;
|
||||
}
|
||||
/* 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 {
|
||||
background-color: #333333;
|
||||
color: #cccccc;
|
||||
}
|
||||
.ns-dark .tab-button-selected {
|
||||
background-color: #e2e2e2;
|
||||
color: #222222;
|
||||
}
|
||||
/* Settings tab rows. */
|
||||
.settings-row {
|
||||
margin-bottom: 8;
|
||||
}
|
||||
.settings-row-label {
|
||||
font-size: 14;
|
||||
margin-right: 10;
|
||||
}
|
||||
.mode-button {
|
||||
font-size: 13;
|
||||
padding: 6 10;
|
||||
margin-right: 6;
|
||||
}
|
||||
.brightness-icon {
|
||||
font-size: 16;
|
||||
margin: 0 4 0 4;
|
||||
color: #444444;
|
||||
}
|
||||
.auto-toggle Label {
|
||||
font-size: 13;
|
||||
margin-right: 2;
|
||||
}
|
||||
.touchpad {
|
||||
height: 230;
|
||||
background-color: #1f1f1f;
|
||||
border-radius: 14;
|
||||
border-width: 1;
|
||||
border-color: #3a3a3a;
|
||||
color: #f0f0f0;
|
||||
margin-top: 2;
|
||||
}
|
||||
.pad-focus {
|
||||
font-size: 20;
|
||||
color: #ffffff;
|
||||
}
|
||||
.pad-legend {
|
||||
font-size: 11;
|
||||
color: #8a8a8a;
|
||||
margin-bottom: 8;
|
||||
}
|
||||
.action-row {
|
||||
margin-top: 6;
|
||||
}
|
||||
.action-button {
|
||||
margin: 2;
|
||||
font-size: 14;
|
||||
}
|
||||
/* Ring tab: the same touchpad, but portrait like the ring's own pad. */
|
||||
.ring-touchpad {
|
||||
width: 150;
|
||||
height: 250;
|
||||
}
|
||||
/* Cosmetic marks mirroring the six rectangles on the physical ring's touch
|
||||
strip; barely lighter than the pad so they read as texture, not buttons. */
|
||||
.ring-pad-marking {
|
||||
width: 18;
|
||||
height: 5;
|
||||
border-radius: 2;
|
||||
background-color: #2a2a2a;
|
||||
horizontal-align: center;
|
||||
vertical-align: center;
|
||||
}
|
||||
/*
|
||||
* Pairing scan list (phone-ui/pairing-page). Rows are Repeater items: product
|
||||
* art (or a colourway swatch) on the left, decoded SKU + proximity + serial in
|
||||
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
@import '@nativescript/theme/css/core.css';
|
||||
@import './phone-ui/remote-controls.css';
|
||||
|
||||
.pairing-instructions {
|
||||
color: #555555;
|
||||
font-size: 14;
|
||||
}
|
||||
|
||||
.pairing-status {
|
||||
font-size: 14;
|
||||
margin-left: 8;
|
||||
}
|
||||
|
||||
.pairing-section {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
margin-bottom: 4;
|
||||
}
|
||||
|
||||
.pairing-empty {
|
||||
color: #777777;
|
||||
font-size: 14;
|
||||
padding: 8 0;
|
||||
}
|
||||
|
||||
.pairing-row {
|
||||
background-color: #f4f4f4;
|
||||
border-color: #dddddd;
|
||||
border-width: 1;
|
||||
border-radius: 10;
|
||||
padding: 10;
|
||||
margin-bottom: 8;
|
||||
}
|
||||
|
||||
.pairing-row-selected {
|
||||
background-color: #e6f0ff;
|
||||
border-color: #3b6fd6;
|
||||
}
|
||||
|
||||
.pairing-row-incomplete {
|
||||
background-color: #fafafa;
|
||||
border-color: #e6e6e6;
|
||||
}
|
||||
|
||||
.pairing-art {
|
||||
vertical-align: center;
|
||||
}
|
||||
|
||||
.pairing-title {
|
||||
font-size: 16;
|
||||
font-weight: bold;
|
||||
color: #222222;
|
||||
}
|
||||
|
||||
.pairing-badge {
|
||||
font-size: 11;
|
||||
font-weight: bold;
|
||||
color: #2a5bc4;
|
||||
background-color: #dbe6fb;
|
||||
border-radius: 9;
|
||||
padding: 1 7;
|
||||
}
|
||||
|
||||
.pairing-variant {
|
||||
font-size: 13;
|
||||
font-weight: bold;
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.pairing-proximity {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
.pairing-proximity-immediate {
|
||||
color: #2a5bc4;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.pairing-serial {
|
||||
font-size: 12;
|
||||
color: #666666;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.pairing-arms {
|
||||
font-size: 12;
|
||||
color: #444444;
|
||||
}
|
||||
|
||||
.pairing-warning {
|
||||
font-size: 12;
|
||||
color: #a33a1f;
|
||||
margin-top: 4;
|
||||
}
|
||||
|
||||
.pairing-swatch-label {
|
||||
font-size: 11;
|
||||
color: #555555;
|
||||
}
|
||||
|
||||
.pairing-chevron {
|
||||
font-size: 22;
|
||||
color: #444444;
|
||||
margin-left: 6;
|
||||
}
|
||||
|
||||
.pairing-selection {
|
||||
background-color: #eef4ff;
|
||||
border-radius: 10;
|
||||
padding: 10;
|
||||
}
|
||||
|
||||
Button.pairing-link {
|
||||
background-color: transparent;
|
||||
color: #2a5bc4;
|
||||
font-size: 14;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Permissions screen (phone-ui/permissions-page). Cards reuse the pairing-row
|
||||
* / pairing-title / pairing-badge look above; these add the explanation body
|
||||
* and the already-granted checkmark.
|
||||
*/
|
||||
.permissions-description {
|
||||
font-size: 13;
|
||||
color: #555555;
|
||||
margin-top: 2;
|
||||
}
|
||||
|
||||
.permissions-check {
|
||||
font-size: 24;
|
||||
color: #2e7d32;
|
||||
margin-left: 10;
|
||||
}
|
||||
|
||||
/* Continue with required permissions still missing: looks disabled but stays
|
||||
* tappable (the tap raises an are-you-sure prompt instead of being ignored). */
|
||||
Button.permissions-primary-dimmed {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
|
||||
.body-text { font-size: 18; }
|
||||
.h1 { font-size: 28; font-weight: bold; }
|
||||
.footer-link { color: #285c45; padding: 4 8; text-decoration: underline; }
|
||||
|
||||
Page {
|
||||
background-color: #f5f5f2;
|
||||
color: #202820;
|
||||
}
|
||||
|
||||
Button {
|
||||
background-color: #285c45;
|
||||
color: #ffffff;
|
||||
border-radius: 12;
|
||||
padding: 12 8;
|
||||
margin-left: 4;
|
||||
margin-right: 4;
|
||||
font-size: 15;
|
||||
}
|
||||
|
||||
|
||||
Page.main-page {
|
||||
background-color: #ffffff;
|
||||
color: #222222;
|
||||
}
|
||||
.main-page .main-header {
|
||||
background-color: #424242;
|
||||
color: #ffffff;
|
||||
padding: 0 0 0 16;
|
||||
height: 56;
|
||||
}
|
||||
.main-page .action-bar-title { font-size: 18; font-weight: bold; color: #ffffff; }
|
||||
.main-page .action-bar-status { font-size: 14; color: #ffffff; margin-right: 12; }
|
||||
.main-page .overflow-button {
|
||||
background-color: transparent;
|
||||
color: #ffffff;
|
||||
font-size: 24;
|
||||
width: 44;
|
||||
height: 48;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
/* Match Android's button layout boxes, including the inset around each tile. */
|
||||
.main-page Button.tab-button { height: 48; margin-top: 6; margin-bottom: 6; }
|
||||
.main-page .mode-button { background-color: #e2e2e2; color: #333333; border-radius: 6; }
|
||||
.main-page .ble-bandwidth-indicator { color: #777777; font-size: 12; padding: 2 8; }
|
||||
|
||||
.main-page .system-name-modal {
|
||||
background-color: #eeeeee;
|
||||
color: #222222;
|
||||
padding: 16;
|
||||
}
|
||||
.main-page .system-name-modal TextView {
|
||||
margin: 0;
|
||||
padding: 4;
|
||||
background-color: #ffffff;
|
||||
color: #222222;
|
||||
placeholder-color: #666666;
|
||||
}
|
||||
|
||||
.main-landscape .system-name-modal { padding: 6 12; }
|
||||
.main-landscape .system-name-modal .h2 { visibility: collapse; }
|
||||
.main-landscape .system-name-modal Button { padding: 6 8; margin-top: 0; margin-bottom: 0; }
|
||||
+2
-22
@@ -4,27 +4,7 @@ You can use this file to perform app-level initialization, but the primary
|
||||
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'
|
||||
import { startLiveHealthSync, startAlignedRingPull } from './health/health-live'
|
||||
|
||||
installNativeUserAgent()
|
||||
registerShareIntentHandler()
|
||||
registerPhoneRotation()
|
||||
|
||||
// Ring health records live only in the communicator's memory until something
|
||||
// stores them. Both health surfaces store on open, but a pull that lands while
|
||||
// they are closed would be lost if the process restarted first, so this keeps
|
||||
// them reaching disk regardless. No-op when there is nothing new.
|
||||
startLiveHealthSync()
|
||||
|
||||
// Collect from the ring on a wall-clock cadence (:01 and :31). Without this
|
||||
// nothing drives a pull on a timer at all - only onRingReady() on reconnect -
|
||||
// so a ring that stays connected is never read.
|
||||
startAlignedRingPull()
|
||||
|
||||
Application.run({ moduleName: 'app-root' })
|
||||
// NativeScript resolves the matching .android.ts or .ios.ts implementation.
|
||||
import './bootstrap'
|
||||
|
||||
// Don't place any code after the application has been started
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { ASSISTANT_MODEL_CHOICES, 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";
|
||||
@@ -102,7 +102,7 @@ class AiChatLayer implements Layer {
|
||||
}
|
||||
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; }
|
||||
if (!shell.isAssistantAvailable()) { shell.showAlert(global.isIOS ? "Set an OpenAI or Anthropic API key in Settings." : "Set an API key or download the on-phone model in Settings."); return; }
|
||||
void this.draft.start();
|
||||
}
|
||||
return;
|
||||
@@ -126,7 +126,7 @@ class AiChatLayer implements Layer {
|
||||
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) => ({
|
||||
ASSISTANT_MODEL_CHOICES.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(); },
|
||||
|
||||
@@ -54,6 +54,8 @@ export type GlanceboardProvider = {
|
||||
showOnLongPress: () => boolean;
|
||||
/** Whether the head-tilt wake goes to the board rather than the regular UI. */
|
||||
showOnHeadTilt: () => boolean;
|
||||
/** Stereo depth (firmware units; positive is nearer) while the board covers the screen. */
|
||||
depth: () => number;
|
||||
/** A fresh board; requestRender asks the host to repaint it. */
|
||||
createBoard: (requestRender: () => void) => GlanceBoardInstance;
|
||||
};
|
||||
|
||||
@@ -11,12 +11,14 @@
|
||||
* focus, tap-then-hold opens the window menu.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
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 { playWorkerBuzzerSequence } from "../../native/worker-buzzer";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
|
||||
import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting";
|
||||
@@ -33,7 +35,6 @@ import {
|
||||
} from "../../ui/gestures";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
@@ -187,6 +188,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: BlocksWindow = {
|
||||
windowId: message.windowId,
|
||||
@@ -295,16 +302,13 @@ function inferForeground(window: BlocksWindow, focused: boolean): void {
|
||||
|
||||
/**
|
||||
* Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the
|
||||
* steps on its own timer, and the Java call is safe from the worker thread
|
||||
* (same path as frame submission). Effects never exceed one message, so no
|
||||
* phrase pacing is needed.
|
||||
* steps on its own timer; the platform bridge routes it from the worker.
|
||||
* Effects never exceed one message, so no phrase pacing is needed.
|
||||
*/
|
||||
function playSfx(window: BlocksWindow, steps: Step[]): void {
|
||||
if (!window.soundOn || steps.length === 0) return;
|
||||
try {
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) return;
|
||||
communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer);
|
||||
playWorkerBuzzerSequence(buildSoundSequencePayload(steps));
|
||||
} catch (error) {
|
||||
console.warn(`blocks sfx failed: ${error}`);
|
||||
}
|
||||
|
||||
@@ -82,10 +82,11 @@ export class CalculatorLayer implements Layer {
|
||||
constructor(
|
||||
private readonly coordinator: MathCoordinator,
|
||||
private readonly actions: LayerActions,
|
||||
private readonly textInput?: () => Promise<void>,
|
||||
) {
|
||||
this.coordinator.setUsesDegrees(calculatorDegreesSetting.get());
|
||||
this.coordinator.onChanged = () => this.handleCoordinatorChanged();
|
||||
this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => this.onTranscript(event));
|
||||
if (!this.textInput) this.unsubscribeTranscript = voiceControlBridge.onTranscript((event) => this.onTranscript(event));
|
||||
}
|
||||
|
||||
private get mode(): CalculatorMode {
|
||||
@@ -125,6 +126,7 @@ export class CalculatorLayer implements Layer {
|
||||
}
|
||||
|
||||
private refreshListening(): void {
|
||||
if (this.textInput) return;
|
||||
if (!this.foreground) return;
|
||||
if (this.listening === "continuous") {
|
||||
if (!this.continuousActive) {
|
||||
@@ -244,6 +246,7 @@ export class CalculatorLayer implements Layer {
|
||||
* that did not.
|
||||
*/
|
||||
beginDictation(): void {
|
||||
if (this.textInput) { void this.textInput(); return; }
|
||||
if (this.dictating) return;
|
||||
this.dictating = true;
|
||||
void this.actions.startVoiceCapture(true);
|
||||
@@ -513,7 +516,8 @@ export class CalculatorLayer implements Layer {
|
||||
bodyBottom: number,
|
||||
): void {
|
||||
const prompt =
|
||||
this.listening === "continuous"
|
||||
this.textInput ? "Tap to type a problem on your phone"
|
||||
: this.listening === "continuous"
|
||||
? `Say a problem, then "${modeLabel(this.mode).toLowerCase()} it"`
|
||||
: "Tap to say a problem — or use Voice input to type one";
|
||||
const lines = wrapText(font, prompt, width - 96);
|
||||
@@ -527,7 +531,7 @@ export class CalculatorLayer implements Layer {
|
||||
|
||||
private paintHeardLine(image: GrayImage, font: UiFont, width: number, y: number): void {
|
||||
if (!this.lastInput) return;
|
||||
const label = "Heard";
|
||||
const label = this.textInput ? "Entered" : "Heard";
|
||||
image.drawText(font, 24, y, label, 110);
|
||||
const x = 24 + font.measureText(label) + 10;
|
||||
image.drawText(font, x, y, truncateText(font, this.lastInput, width - x - 24), 160);
|
||||
@@ -579,7 +583,7 @@ export class CalculatorLayer implements Layer {
|
||||
this.mode === "explain" && this.coordinator.stepPosition !== null ? "steps" : "mode";
|
||||
return gestureHints([
|
||||
[GESTURE_SCROLL, scrollTarget],
|
||||
[GESTURE_CLICK, "mic"],
|
||||
[GESTURE_CLICK, this.textInput ? "type" : "mic"],
|
||||
[GESTURE_DOUBLE_CLICK, "back"],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { invalidateCalendarCache } from "../../native/calendar";
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../../native/calendar-permissions";
|
||||
import { invalidateCalendarCache, onCalendarChanged } from "../../native/calendar";
|
||||
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
|
||||
import { CalendarLayer } from "./calendar";
|
||||
import { renderCalendarDateIcon } from "./calendar-icon";
|
||||
@@ -14,25 +14,27 @@ export const CALENDAR_WINDOW_ID = "calendar";
|
||||
export const CALENDAR_SURFACE_ID = "window:calendar";
|
||||
|
||||
/**
|
||||
* The Calendar app: a single screen listing upcoming events from the Android
|
||||
* Calendar provider. If calendar permission is missing it shows a prompt and
|
||||
* The Calendar app: a single screen listing upcoming events from the phone's
|
||||
* calendars. If calendar permission is missing it shows a prompt and
|
||||
* fires the system permission dialog (on launch and on any tap); once granted
|
||||
* it re-renders with the event list.
|
||||
*/
|
||||
export function createCalendarAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
let requesting = false;
|
||||
let app: InProcessWindow;
|
||||
let unsubscribe = () => {};
|
||||
let tick: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const requestPermission = () => {
|
||||
if (requesting || hasCalendarPermission()) return;
|
||||
requesting = true;
|
||||
void ensureCalendarPermission().then((granted) => {
|
||||
requesting = false;
|
||||
if (granted) {
|
||||
invalidateCalendarCache();
|
||||
app.requestRender();
|
||||
}
|
||||
});
|
||||
}).catch(error => console.warn("Calendar permission failed", error))
|
||||
.finally(() => { requesting = false; });
|
||||
};
|
||||
|
||||
app = createInProcessWindow({
|
||||
@@ -48,9 +50,15 @@ export function createCalendarAppWindow(options: InProcessAppOptions): InProcess
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: options.onClosed,
|
||||
onClosed: () => {
|
||||
unsubscribe();
|
||||
if (tick !== null) clearInterval(tick);
|
||||
options.onClosed();
|
||||
},
|
||||
});
|
||||
|
||||
unsubscribe = onCalendarChanged(app.requestRender);
|
||||
tick = setInterval(app.requestRender, 30_000);
|
||||
// Prompt immediately on launch so the user doesn't have to discover the tap.
|
||||
requestPermission();
|
||||
return app;
|
||||
|
||||
@@ -2,10 +2,10 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
|
||||
import { getCalendarReadState, readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
|
||||
import { timeFormatSetting } from "../../ui/dashboard-settings";
|
||||
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { hasCalendarPermission } from "../../native/calendar-permissions";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
|
||||
@@ -58,7 +58,9 @@ export class CalendarLayer implements Layer {
|
||||
const events = readUpcomingEvents(MAX_EVENTS);
|
||||
if (!events.length) {
|
||||
image.drawText(font, TITLE_X, TITLE_Y, "Calendar", 220);
|
||||
image.drawText(font, 24, 72, "No upcoming events.", 190);
|
||||
const state = getCalendarReadState();
|
||||
image.drawText(font, 24, 72, state === "loading" ? "Loading calendar..."
|
||||
: state === "error" ? "Calendar unavailable. Try again shortly." : "No upcoming events.", 190);
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,13 +21,12 @@ import {
|
||||
type InProcessWindow,
|
||||
} from "../../ui/shell/in-process-window";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
|
||||
import { ensureLocationPermission, hasLocationPermission } from "../../native/location-permissions";
|
||||
import { isCompassCalibrated, normalizeHeading } from "./calibration";
|
||||
import { cardinalDirection, createCompassBackground, drawCompassRose, layoutCompassRose, TICK_HEIGHT } from "./compass-rose";
|
||||
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,11 +91,6 @@ class CompassLayer implements Layer {
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
toggleDebugInfo(): void {
|
||||
setCompassDebugEnabled(!isCompassDebugEnabled());
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.removed) return;
|
||||
this.removed = true;
|
||||
@@ -162,17 +156,9 @@ class CompassLayer implements Layer {
|
||||
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);
|
||||
const headingFont = large.measureText(headingText) <= width - EDGE_PAD * 2 ? large : small;
|
||||
const readoutWidth = headingFont.measureText(headingText);
|
||||
const readoutHeight = headingFont.lineHeight;
|
||||
|
||||
// One column centred on the display's true centre, so the rose sits where
|
||||
// the wearer is looking rather than 32px right of it.
|
||||
@@ -204,17 +190,14 @@ class CompassLayer implements Layer {
|
||||
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);
|
||||
}
|
||||
image.drawText(headingFont, readoutX, y, headingText, heading === null ? 150 : 255);
|
||||
y += readoutHeight + 4;
|
||||
for (const line of statusLines) {
|
||||
image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125);
|
||||
y += smallStep;
|
||||
}
|
||||
const accuracyText = magneticAccuracyText(this.diagnostics);
|
||||
image.drawText(small, width - EDGE_PAD - small.measureText(accuracyText), TOP_PAD, accuracyText, 175);
|
||||
|
||||
return image;
|
||||
}
|
||||
@@ -255,19 +238,12 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
|
||||
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,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
reconfigureSurface: options.reconfigureSurface,
|
||||
onClosed: () => {
|
||||
layer.stop();
|
||||
options.onClosed();
|
||||
@@ -298,3 +274,15 @@ function frameStatusText(): string {
|
||||
return "Magnetic heading - waiting for location";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The firmware's magnetometer calibration readiness (0-3) as filled/empty
|
||||
* dots, e.g. "Calibration: ●●○" for 2/3. This is the glasses' own sensor
|
||||
* calibration, not the wearer-fit offset set on the calibration screen.
|
||||
*/
|
||||
function magneticAccuracyText(diagnostics: CompassDiagnostics | null): string {
|
||||
const accuracy = diagnostics && (diagnostics.flags & 0x80) ? diagnostics.magneticAccuracy : -1;
|
||||
if (accuracy < 0) return "Calibration: --";
|
||||
const filled = Math.min(3, accuracy);
|
||||
return `Calibration: ${"●".repeat(filled)}${"○".repeat(3 - filled)}`;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
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}`];
|
||||
}
|
||||
@@ -2,16 +2,16 @@
|
||||
* 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.
|
||||
* whatever the phone can cheaply produce, refreshed no more than daily. The
|
||||
* last fix is persisted so a fresh start has a usable correction immediately.
|
||||
* Android re-evaluates its magnetic model; iOS caches the correction supplied
|
||||
* by Core Location (true heading minus magnetic heading).
|
||||
*/
|
||||
import { hasLocationPermission } from "../../g2/android-permissions";
|
||||
import { magneticDeclinationDegrees } from "../../native/geomagnetic";
|
||||
import { getCurrentLocation } from "../../native/location";
|
||||
import { hasLocationPermission } from "../../native/location-permissions";
|
||||
import { getCurrentDeclination, restoreDeclination } from "../../native/declination";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
|
||||
const DEGREES_KEY = "compass.declination.degrees";
|
||||
const LATITUDE_KEY = "compass.declination.latitude";
|
||||
const LONGITUDE_KEY = "compass.declination.longitude";
|
||||
const LOCATED_AT_KEY = "compass.declination.locatedAtMs";
|
||||
@@ -40,7 +40,7 @@ function loadStoredFix(): void {
|
||||
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 = restoreDeclination(latitude, longitude, parseFloat(getStringSetting(DEGREES_KEY, "")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,16 +73,17 @@ 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 (declination !== null && fix !== null && now - fix.locatedAtMs < FIX_MAX_AGE_MS) return;
|
||||
if (now - lastAttemptMs < RETRY_INTERVAL_MS) return;
|
||||
lastAttemptMs = now;
|
||||
refreshing = true;
|
||||
getCurrentLocation()
|
||||
getCurrentDeclination()
|
||||
.then((location) => {
|
||||
const value = magneticDeclinationDegrees(location.latitude, location.longitude);
|
||||
if (value === null) return;
|
||||
const value = location.degrees;
|
||||
if (!Number.isFinite(value)) return;
|
||||
fix = { latitude: location.latitude, longitude: location.longitude, locatedAtMs: now };
|
||||
declination = value;
|
||||
setStringSetting(DEGREES_KEY, String(value));
|
||||
setStringSetting(LATITUDE_KEY, String(location.latitude));
|
||||
setStringSetting(LONGITUDE_KEY, String(location.longitude));
|
||||
setStringSetting(LOCATED_AT_KEY, String(now));
|
||||
|
||||
@@ -2,8 +2,8 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { Layer, type LayerContext } from "../../ui/layers";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
import { drawSelectionHighlight } from "../../ui/menu";
|
||||
import { tightRowHeight } from "../../ui/metrics";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { centeredTextY, tightRowHeight } from "../../ui/metrics";
|
||||
import {
|
||||
cancelBandwidthBenchmark,
|
||||
getBandwidthBenchmarkStatus,
|
||||
@@ -29,6 +29,7 @@ const LIST_X = 20;
|
||||
const VALUE_X = 150;
|
||||
|
||||
type Phase = "config" | "arming" | "running" | "done";
|
||||
type ConfigRow = "size" | "window" | "link" | "start";
|
||||
|
||||
/**
|
||||
* BLE bandwidth benchmark: pick a message size and pipeline window, stream
|
||||
@@ -38,7 +39,14 @@ type Phase = "config" | "arming" | "running" | "done";
|
||||
*/
|
||||
export class BandwidthBenchmarkLayer implements Layer {
|
||||
private phase: Phase = "config";
|
||||
private selectedRow = 0; // size, window, link preference, start
|
||||
private readonly menu = new Menu<ConfigRow>({
|
||||
items: ["size", "window", "link", "start"],
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()) + 4,
|
||||
draw: (args) => this.drawRow(args),
|
||||
});
|
||||
private sizeIndex = 2;
|
||||
private windowIndex = 2;
|
||||
private linkModeIndex = 0;
|
||||
@@ -134,26 +142,14 @@ export class BandwidthBenchmarkLayer implements Layer {
|
||||
}
|
||||
|
||||
const rowH = tightRowHeight(font) + 4;
|
||||
const rows: Array<[string, string]> = [
|
||||
["Message size", `${MESSAGE_SIZES[this.sizeIndex]} B`],
|
||||
["Window size", `${WINDOW_SIZES[this.windowIndex]}`],
|
||||
["Link request", LINK_MODES[this.linkModeIndex]!],
|
||||
[this.phase === "done" ? "Run again" : "Start", ""],
|
||||
];
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const [label, value] = rows[index]!;
|
||||
const y = HEADER_HEIGHT + index * rowH;
|
||||
const selected = index === this.selectedRow;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4);
|
||||
}
|
||||
image.drawText(font, LIST_X, y + 2, label, selected ? 255 : 200);
|
||||
if (value) {
|
||||
image.drawText(font, VALUE_X, y + 2, value, selected ? 235 : 160);
|
||||
}
|
||||
}
|
||||
const rowCount = this.menu.items.length;
|
||||
this.menu.paint(
|
||||
image,
|
||||
{ x: LIST_X - 6, y: HEADER_HEIGHT - 1, width: width - 2 * LIST_X + 12, height: rowCount * rowH },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
|
||||
let y = HEADER_HEIGHT + rows.length * rowH + 10;
|
||||
let y = HEADER_HEIGHT + rowCount * rowH + 10;
|
||||
if (this.error) {
|
||||
image.drawText(font, LIST_X, y, this.error, 180);
|
||||
} else if (this.result) {
|
||||
@@ -176,6 +172,21 @@ export class BandwidthBenchmarkLayer implements Layer {
|
||||
return image;
|
||||
}
|
||||
|
||||
private drawRow({ image, item, x, y, height, selected }: MenuDrawArgs<ConfigRow>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const [label, value]: [string, string] =
|
||||
item === "size" ? ["Message size", `${MESSAGE_SIZES[this.sizeIndex]} B`]
|
||||
: item === "window" ? ["Window size", `${WINDOW_SIZES[this.windowIndex]}`]
|
||||
: item === "link" ? ["Link request", LINK_MODES[this.linkModeIndex]!]
|
||||
: [this.phase === "done" ? "Run again" : "Start", ""];
|
||||
const textY = centeredTextY(font, y, height);
|
||||
// Text sits 6px in from the row box (LIST_X), values at VALUE_X.
|
||||
image.drawText(font, x + 6, textY, label, selected ? 255 : 200);
|
||||
if (value) {
|
||||
image.drawText(font, x + 6 + VALUE_X - LIST_X, textY, value, selected ? 235 : 160);
|
||||
}
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
if (this.phase === "arming" || this.phase === "running") {
|
||||
// A static screen during the run: only allow bailing out.
|
||||
@@ -186,22 +197,22 @@ export class BandwidthBenchmarkLayer implements Layer {
|
||||
}
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.selectedRow = Math.max(0, this.selectedRow - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.selectedRow = Math.min(3, this.selectedRow + 1);
|
||||
await this.menu.handleInput(event);
|
||||
return;
|
||||
case "click":
|
||||
if (this.selectedRow === 0) {
|
||||
case "click": {
|
||||
const row = this.menu.selectedItem;
|
||||
if (row === "size") {
|
||||
this.sizeIndex = (this.sizeIndex + 1) % MESSAGE_SIZES.length;
|
||||
} else if (this.selectedRow === 1) {
|
||||
} else if (row === "window") {
|
||||
this.windowIndex = (this.windowIndex + 1) % WINDOW_SIZES.length;
|
||||
} else if (this.selectedRow === 2) {
|
||||
} else if (row === "link") {
|
||||
this.linkModeIndex = (this.linkModeIndex + 1) % LINK_MODES.length;
|
||||
} else {
|
||||
} else if (row === "start") {
|
||||
this.startRun();
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { Layer, type LayerActions, type LayerContext } from "../../ui/layers";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures";
|
||||
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../../ui/menu";
|
||||
import { tightRowHeight } from "../../ui/metrics";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { centeredTextY, tightRowHeight } from "../../ui/metrics";
|
||||
import {
|
||||
buildSoundSequencePayload,
|
||||
CFW_SEQ_MAX,
|
||||
@@ -28,8 +27,14 @@ function sleep(ms: number): Promise<void> {
|
||||
* sequencer message lands as the previous phrase finishes.
|
||||
*/
|
||||
export class BuzzerDemoLayer implements Layer {
|
||||
private selectedIndex = 0;
|
||||
private scrollRow = 0;
|
||||
private readonly menu = new Menu<SoundEffect>({
|
||||
items: SOUND_EFFECTS,
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => drawEffectRow(args),
|
||||
});
|
||||
private playing: string | null = null;
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
@@ -42,21 +47,11 @@ export class BuzzerDemoLayer implements Layer {
|
||||
image.drawText(font, width - 24 - font.measureText(status), 8, status, 140);
|
||||
|
||||
const listHeight = height - HEADER_HEIGHT - FOOTER_HEIGHT;
|
||||
const rowH = tightRowHeight(font);
|
||||
const visibleRows = Math.max(1, (listHeight / rowH) | 0);
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, SOUND_EFFECTS.length);
|
||||
|
||||
const lastVisible = Math.min(SOUND_EFFECTS.length, this.scrollRow + visibleRows);
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const effect = SOUND_EFFECTS[index]!;
|
||||
const y = HEADER_HEIGHT + (index - this.scrollRow) * rowH;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4);
|
||||
}
|
||||
image.drawText(font, LIST_X, y + 1, effect.name, selected ? 255 : 200);
|
||||
image.drawText(font, LIST_X + 110, y + 1, effect.desc, selected ? 180 : 120);
|
||||
}
|
||||
this.menu.paint(
|
||||
image,
|
||||
{ x: LIST_X - 6, y: HEADER_HEIGHT - 1, width: width - 2 * LIST_X + 12, height: listHeight },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
|
||||
return image;
|
||||
}
|
||||
@@ -64,13 +59,11 @@ export class BuzzerDemoLayer implements Layer {
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.selectedIndex = Math.min(SOUND_EFFECTS.length - 1, this.selectedIndex + 1);
|
||||
await this.menu.handleInput(event);
|
||||
return;
|
||||
case "click": {
|
||||
const effect = SOUND_EFFECTS[clamp(this.selectedIndex, 0, SOUND_EFFECTS.length - 1)];
|
||||
const effect = this.menu.selectedItem;
|
||||
if (effect && !this.playing) {
|
||||
// Fire-and-forget: playback paces itself with sleeps between
|
||||
// phrases; awaiting it here would stall input for seconds.
|
||||
@@ -106,3 +99,11 @@ export class BuzzerDemoLayer implements Layer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Effect name, then its description in a second column 110px to the right. */
|
||||
function drawEffectRow({ image, item: effect, x, y, height, selected }: MenuDrawArgs<SoundEffect>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const textY = centeredTextY(font, y, height);
|
||||
image.drawText(font, x + 6, textY, effect.name, selected ? 255 : 200);
|
||||
image.drawText(font, x + 6 + 110, textY, effect.desc, selected ? 180 : 120);
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { MenuLayer, drawSubmenuIndicator, type MenuItem } from "../../ui/menu";
|
||||
import { ScreenTestLayer } from "./screen-test";
|
||||
import { InputEventsLayer } from "./input-events";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
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 { unicodeTestMenu } from "./unicode-test";
|
||||
import { type AppContext } from "../app-definition";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { appViewportSize } from "../../ui/shell/geometry";
|
||||
@@ -47,10 +50,11 @@ function submenuItem(label: string, onSelect: MenuItem["onSelect"]): MenuItem {
|
||||
}
|
||||
|
||||
/** The diagnostic demos, one level down from the root menu. */
|
||||
function debugTestsMenu(): MenuLayer {
|
||||
function debugTestsMenu(openInputEvents: (ctx: Parameters<MenuItem["onSelect"]>[0]) => void): MenuLayer {
|
||||
return new MenuLayer(
|
||||
"Debug tests",
|
||||
[
|
||||
{ label: "Input events", onSelect: openInputEvents },
|
||||
{
|
||||
label: "Dither test",
|
||||
onSelect: (ctx) => {
|
||||
@@ -59,18 +63,24 @@ function debugTestsMenu(): MenuLayer {
|
||||
},
|
||||
{
|
||||
label: "Buzzer demo",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Glasses sound playback is not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new BuzzerDemoLayer());
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Accelerometer demo",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new AccelerometerDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Light sensor",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new LightSensorDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
@@ -81,6 +91,9 @@ function debugTestsMenu(): MenuLayer {
|
||||
ctx.stack.push(new BandwidthBenchmarkLayer(ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
submenuItem("Unicode test", (ctx) => {
|
||||
ctx.stack.push(unicodeTestMenu(MENU_LAYOUT));
|
||||
}),
|
||||
],
|
||||
MENU_LAYOUT,
|
||||
);
|
||||
@@ -93,6 +106,7 @@ function debugTestsMenu(): MenuLayer {
|
||||
* under "Debug tests".
|
||||
*/
|
||||
export function createDeveloperAppWindow(appContext: AppContext, options: InProcessAppOptions): InProcessWindow {
|
||||
let inputEvents: InputEventsLayer | null = null;
|
||||
const menu = new MenuLayer(
|
||||
"Developer",
|
||||
[
|
||||
@@ -114,12 +128,20 @@ export function createDeveloperAppWindow(appContext: AppContext, options: InProc
|
||||
},
|
||||
{
|
||||
label: "Show resource usage",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new ResourceUsageLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
submenuItem("Debug tests", (ctx) => {
|
||||
ctx.stack.push(debugTestsMenu());
|
||||
ctx.stack.push(debugTestsMenu((inputCtx) => {
|
||||
const page = new InputEventsLayer(inputCtx.actions.requestRender,
|
||||
() => shell.isWindowVisible(DEVELOPER_WINDOW_ID),
|
||||
() => { if (inputEvents === page) inputEvents = null; });
|
||||
inputEvents = page;
|
||||
inputCtx.stack.push(page);
|
||||
}));
|
||||
}),
|
||||
],
|
||||
MENU_LAYOUT,
|
||||
@@ -133,6 +155,7 @@ export function createDeveloperAppWindow(appContext: AppContext, options: InProc
|
||||
icon: "wrench",
|
||||
closeable: true,
|
||||
actions: options.actions,
|
||||
menuItems: () => inputEvents?.menuItems() ?? [],
|
||||
// Dictating a URL is the one thing worth speaking at in this app; the
|
||||
// load pages take the text and every other page ignores it.
|
||||
receiveTextInput: (text) => {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
import type { InputEvent } from "../../ui/gestures";
|
||||
import { addInputListener, InputEventLog, inputTimestamp } from "../../ui/input-monitor";
|
||||
import type { Layer, LayerContext } from "../../ui/layers";
|
||||
import { drawListScrollbar, type MenuItem } from "../../ui/menu";
|
||||
|
||||
/** Gestures are samples here; back/clear/pause live in the tap-then-hold menu. */
|
||||
export class InputEventsLayer implements Layer {
|
||||
readonly acceptsDirectional = true;
|
||||
readonly log = new InputEventLog();
|
||||
private scrollRow = 0;
|
||||
private phoneTime = false;
|
||||
private visibleRows = 1;
|
||||
private readonly unsubscribe: () => void;
|
||||
|
||||
constructor(requestRender: () => void, isVisible: () => boolean,
|
||||
private readonly removed: () => void = () => {}) {
|
||||
this.unsubscribe = addInputListener((event, filtered) => {
|
||||
if (!isVisible() || this.log.paused) return;
|
||||
this.log.add(event, filtered);
|
||||
this.scrollRow = 0;
|
||||
requestRender();
|
||||
});
|
||||
}
|
||||
|
||||
onRemoved(): void { this.unsubscribe(); this.removed(); }
|
||||
|
||||
menuItems(): MenuItem[] {
|
||||
return [
|
||||
{ label: this.log.paused ? "Resume capture" : "Pause capture", onSelect: (ctx) => {
|
||||
this.log.paused = !this.log.paused;
|
||||
this.scrollRow = 0;
|
||||
ctx.stack.pop();
|
||||
} },
|
||||
{ label: "Clear history", onSelect: (ctx) => {
|
||||
this.log.clear();
|
||||
this.scrollRow = 0;
|
||||
ctx.stack.pop();
|
||||
} },
|
||||
{ label: this.phoneTime ? "Show ring timestamps" : "Show phone receive time", onSelect: (ctx) => {
|
||||
this.phoneTime = !this.phoneTime;
|
||||
ctx.stack.pop();
|
||||
} },
|
||||
{ label: "Back to Debug tests", onSelect: (ctx) => { ctx.stack.popThrough(this); } },
|
||||
];
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const font = getDefaultSmallFont();
|
||||
image.drawText(font, 12, 8, "Input events", 230);
|
||||
const status = `${this.log.paused ? "Paused" : "Live"} ${this.log.count} events`;
|
||||
image.drawText(font, width - 12 - font.measureText(status), 8, status, 180);
|
||||
image.drawText(font, 12, 28, this.phoneTime ? "Phone receive time | gap ms | source | event" : "Time (R=ring tick) | gap | source | event", 140);
|
||||
const lineHeight = Math.max(18, font.lineHeight + 2);
|
||||
const rowHeight = lineHeight * 2 + 4;
|
||||
this.visibleRows = Math.max(1, Math.floor((height - 76) / rowHeight));
|
||||
this.scrollRow = Math.min(this.scrollRow, Math.max(0, this.log.entries.length - this.visibleRows));
|
||||
const timeX = 12;
|
||||
const gapX = timeX + font.measureText("00:00:00.000") + 12;
|
||||
const sourceX = gapX + font.measureText("+99999") + 12;
|
||||
const eventX = sourceX + font.measureText("right-arm") + 12;
|
||||
if (!this.log.entries.length) {
|
||||
image.drawText(font, 12, 62, "Touch, tap, double-tap, hold, or swipe the ring.", 210);
|
||||
image.drawText(font, 12, 82, "Press arrives before an interpreted gesture.", 150);
|
||||
}
|
||||
for (const [index, entry] of this.log.entries.slice(this.scrollRow, this.scrollRow + this.visibleRows).entries()) {
|
||||
const { event } = entry;
|
||||
const ringTime = !this.phoneTime && event.ringInput;
|
||||
const gapMs = ringTime ? entry.ringGapTicks : entry.gapMs;
|
||||
const y = 50 + index * rowHeight;
|
||||
const gap = gapMs === null ? "-" : `${gapMs >= 0 ? "+" : ""}${gapMs}`;
|
||||
const source = "source" in event ? event.source ?? "-" : "-";
|
||||
const label = (entry.filtered ? "*" : "") + (event.type === "unknown"
|
||||
? event.ringInput ? `ring type ${event.ringInput.type}` : `${event.kind} ${event.eventSource}/${event.eventType}`
|
||||
: event.type);
|
||||
image.drawText(font, timeX, y, ringTime ? `R${ringTime.tick}` : inputTimestamp(event.timestampMs), 170);
|
||||
image.drawText(font, gapX, y, truncateText(font, gap, sourceX - gapX - 4), 160);
|
||||
image.drawText(font, sourceX, y, source, 180);
|
||||
image.drawText(font, eventX, y, truncateText(font, label, width - eventX - 12), event.type === "ring-press" ? 255 : 200);
|
||||
if (event.ringInput) {
|
||||
const { type, aux, speed } = event.ringInput;
|
||||
// These are the original report bytes, not physical distance/speed units.
|
||||
const details = `Raw ring: type ${type} AUX ${aux} speed ${speed}`;
|
||||
image.drawText(font, timeX + 12, y + lineHeight,
|
||||
truncateText(font, details, width - timeX - 36), 170);
|
||||
}
|
||||
}
|
||||
if (this.log.paused) drawListScrollbar(image, width - 5, 50, height - 78,
|
||||
this.scrollRow, this.visibleRows, this.log.entries.length);
|
||||
image.drawText(font, 12, height - 20,
|
||||
this.log.paused ? "Scroll: history Tap-hold: controls" : "Unfiltered (*=dedup) Tap-hold: controls", 140);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: InputEvent): void {
|
||||
// Live gestures, including double-click, must remain on this page.
|
||||
if (!this.log.paused) return;
|
||||
if (event.type === "scroll-up" || event.type === "swipe-up") {
|
||||
this.scrollRow = Math.max(0, this.scrollRow - 1);
|
||||
} else if (event.type === "scroll-down" || event.type === "swipe-down") {
|
||||
this.scrollRow = Math.min(Math.max(0, this.log.entries.length - this.visibleRows), this.scrollRow + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/g
|
||||
import { Layer, type LayerContext } from "../../ui/layers";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
import { developerAppUrlSetting } from "../../ui/dashboard-settings";
|
||||
import { isQrScannerAvailable, scanQrCode } from "../../native/qr-scan";
|
||||
import { cancelQrScan, isQrScannerAvailable, scanQrCode } from "../../native/qr-scan";
|
||||
|
||||
const MARGIN = 20;
|
||||
|
||||
@@ -114,20 +114,23 @@ export class LoadAppFromUrlLayer implements Layer {
|
||||
}
|
||||
|
||||
/**
|
||||
* "Load app from QR code": hand off to an installed scanner app, then launch
|
||||
* "Load app from QR code": open the phone's scanner, then launch
|
||||
* whatever URL it decodes. The scanned URL is kept in developerAppUrlSetting so
|
||||
* the URL page can reload it later without rescanning.
|
||||
*/
|
||||
export class LoadAppFromQrLayer implements Layer {
|
||||
private status = "Starting scanner...";
|
||||
private busy = false;
|
||||
private removed = false;
|
||||
|
||||
constructor(private readonly ctx: AppContext) {}
|
||||
|
||||
/** Launches the scanner; call right after pushing the layer. */
|
||||
open(ctx: LayerContext): void {
|
||||
if (this.busy || this.removed) return;
|
||||
if (!isQrScannerAvailable()) {
|
||||
this.status = "No QR scanner on this phone (needs Play Services or a scanner app).";
|
||||
this.status = global.isIOS ? "No camera available. Scan using a physical iPhone."
|
||||
: "No QR scanner on this phone (needs Play Services or a scanner app).";
|
||||
ctx.actions.requestRender();
|
||||
return;
|
||||
}
|
||||
@@ -135,6 +138,11 @@ export class LoadAppFromQrLayer implements Layer {
|
||||
void this.scan(ctx);
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.removed = true;
|
||||
if (this.busy) cancelQrScan();
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
@@ -156,12 +164,7 @@ export class LoadAppFromQrLayer implements Layer {
|
||||
handleInput(event: InputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "click":
|
||||
if (!this.busy && isQrScannerAvailable()) {
|
||||
this.busy = true;
|
||||
this.status = "Starting scanner...";
|
||||
ctx.actions.requestRender();
|
||||
void this.scan(ctx);
|
||||
}
|
||||
this.open(ctx);
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
@@ -176,6 +179,7 @@ export class LoadAppFromQrLayer implements Layer {
|
||||
this.status = "Point the phone camera at the QR code.";
|
||||
ctx.actions.requestRender();
|
||||
const scanned = await scanQrCode();
|
||||
if (this.removed) return;
|
||||
if (scanned === null) {
|
||||
this.status = "Scan cancelled.";
|
||||
return;
|
||||
@@ -184,17 +188,18 @@ export class LoadAppFromQrLayer implements Layer {
|
||||
this.status = `Not a URL: ${scanned}`;
|
||||
return;
|
||||
}
|
||||
developerAppUrlSetting.set(scanned);
|
||||
developerAppUrlSetting.set(scanned.trim());
|
||||
this.status = `Loading ${scanned}`;
|
||||
ctx.actions.requestRender();
|
||||
await openEvenHubUrl(this.ctx, scanned);
|
||||
ctx.stack.pop();
|
||||
if (!this.removed) ctx.stack.pop();
|
||||
} catch (error) {
|
||||
if (this.removed) return;
|
||||
this.status = cleanError(error);
|
||||
this.ctx.appendLog(`evenhub qr launch failed: ${this.status}`);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
ctx.actions.requestRender();
|
||||
if (!this.removed) ctx.actions.requestRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { fontSelectionLabel, getDefaultSmallFont, getUiFontSelection } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
import { Layer, type LayerContext } from "../../ui/layers";
|
||||
import { MenuLayer, type MenuLayout } from "../../ui/menu";
|
||||
|
||||
/**
|
||||
* Unicode test: sample texts chosen to exercise text-rendering features that
|
||||
* need special support beyond one-glyph-per-codepoint left-to-right layout.
|
||||
* Each sample is rendered with the user's configured UI font so gaps (tofu,
|
||||
* unshaped Arabic, misplaced combining marks, reversed RTL runs, missing CJK
|
||||
* coverage) show up the way they would in real app content.
|
||||
*
|
||||
* Every sample lists what it exercises so a tester knows what "correct" looks
|
||||
* like without reading this file.
|
||||
*/
|
||||
export type UnicodeSample = {
|
||||
/** Menu label: the language, with the feature in parentheses. */
|
||||
label: string;
|
||||
/** What a correct rendering has to get right, shown under the title. */
|
||||
exercises: string;
|
||||
/** The text itself; paragraphs separated by "\n". */
|
||||
text: string;
|
||||
};
|
||||
|
||||
// Sentences are mostly Article 1 of the Universal Declaration of Human Rights
|
||||
// (the same passage in every language, so a tester who knows one can compare
|
||||
// line lengths and shapes across scripts), plus a pangram or two.
|
||||
export const UNICODE_SAMPLES: readonly UnicodeSample[] = [
|
||||
{
|
||||
label: "English (ligatures)",
|
||||
exercises: "fi/fl/ff pairs stay separate glyphs; kerning (AV, To, Wa)",
|
||||
text:
|
||||
"All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.\n" +
|
||||
"Ligature pairs: office affluent waffle fjord shuffle difficult\n" +
|
||||
"Kerning pairs: AVATAR Toward Wavy LTA. Yo Te Ty\n" +
|
||||
"The quick brown fox jumps over the lazy dog. 0123456789",
|
||||
},
|
||||
{
|
||||
label: "French (precomposed accents)",
|
||||
exercises: "é è ê ç œ æ ù as single precomposed codepoints",
|
||||
text:
|
||||
"Tous les êtres humains naissent libres et égaux en dignité et en droits. Ils sont doués de raison et de conscience et doivent agir les uns envers les autres dans un esprit de fraternité.\n" +
|
||||
"Portez ce vieux whisky au juge blond qui fume. Œuvre, cœur, æther, à côté, où, naïve, Noël.",
|
||||
},
|
||||
{
|
||||
label: "German / Polish / Turkish",
|
||||
exercises: "ß ä ö ü; ą ę ł ń ś ź ż; dotted İ and dotless ı",
|
||||
text:
|
||||
"Falsches Üben von Xylophonmusik quält jeden größeren Zwerg. Straße, Fußgänger, Ärger, Öl, Übung.\n" +
|
||||
"Pchnąć w tę łódź jeża lub ośm skrzyń fig. Zażółć gęślą jaźń.\n" +
|
||||
"Pijamalı hasta yağız şoföre çabucak güvendi. İstanbul, ılık, Iğdır, iyi.",
|
||||
},
|
||||
{
|
||||
label: "Vietnamese (stacked marks)",
|
||||
exercises: "tone mark above a vowel that already has a diacritic (ấ ệ ở ữ)",
|
||||
text:
|
||||
"Tất cả mọi người sinh ra đều được tự do và bình đẳng về nhân phẩm và quyền lợi. Mọi con người đều được tạo hóa ban cho lý trí và lương tâm và cần phải đối xử với nhau trong tình bằng hữu.\n" +
|
||||
"Tiếng Việt: Hà Nội, Huế, Đà Nẵng, Sài Gòn. ấ ầ ẩ ẫ ậ ế ề ể ễ ệ ố ồ ổ ỗ ộ ớ ờ ở ỡ ợ ứ ừ ử ữ ự",
|
||||
},
|
||||
{
|
||||
label: "Combining marks (decomposed)",
|
||||
exercises: "base letter + separate combining accent must overlay, not advance",
|
||||
text:
|
||||
// Written with explicit combining codepoints (no String.normalize, so
|
||||
// the sample is the same on every JS engine).
|
||||
"Decomposed: café naïve résumé Việt Nam Saõ Paulo\n" +
|
||||
"Precomposed: café naïve résumé Việt Nam São Paulo\n" +
|
||||
"Both lines should look identical.\n" +
|
||||
"Stacked: à́̂ ë̄ ô̧ ñ́ ů̈\n" +
|
||||
"Marks with no base: ́ ̈ ̧ (should attach to nothing, or a dotted circle)",
|
||||
},
|
||||
{
|
||||
label: "Greek",
|
||||
exercises: "Greek alphabet with tonos/dialytika; final sigma ς vs σ",
|
||||
text:
|
||||
"Όλοι οι άνθρωποι γεννιούνται ελεύθεροι και ίσοι στην αξιοπρέπεια και τα δικαιώματα. Είναι προικισμένοι με λογική και συνείδηση, και οφείλουν να συμπεριφέρονται μεταξύ τους με πνεύμα αδελφοσύνης.\n" +
|
||||
"Ξεσκεπάζω την ψυχοφθόρα βδελυγμία. ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ αβγδεζηθικλμνξοπρσςτυφχψω",
|
||||
},
|
||||
{
|
||||
label: "Russian (Cyrillic)",
|
||||
exercises: "Cyrillic coverage incl. й ё ъ ь; italic-free shapes",
|
||||
text:
|
||||
"Все люди рождаются свободными и равными в своем достоинстве и правах. Они наделены разумом и совестью и должны поступать в отношении друг друга в духе братства.\n" +
|
||||
"Съешь же ещё этих мягких французских булок, да выпей чаю. АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
|
||||
},
|
||||
{
|
||||
label: "Arabic (RTL, joining)",
|
||||
exercises: "right-to-left; letters take initial/medial/final forms; lam-alef لا ligature",
|
||||
text:
|
||||
"يولد جميع الناس أحرارًا متساوين في الكرامة والحقوق. وقد وهبوا عقلاً وضميرًا وعليهم أن يعامل بعضهم بعضًا بروح الإخاء.\n" +
|
||||
"السلام عليكم. العربية لغة جميلة.\n" +
|
||||
"Arabic-Indic digits: ٠١٢٣٤٥٦٧٨٩ and Persian: پ چ ژ گ",
|
||||
},
|
||||
{
|
||||
label: "Hebrew (RTL, niqqud)",
|
||||
exercises: "right-to-left; vowel points (niqqud) below/inside letters; final forms ך ם ן ף ץ",
|
||||
text:
|
||||
"כל בני אדם נולדו בני חורין ושווים בערכם ובזכויותיהם. כולם חוננו בתבונה ובמצפון, לפיכך חובה עליהם לנהוג איש ברעהו ברוח של אחוה.\n" +
|
||||
"With niqqud: שָׁלוֹם עוֹלָם. בְּרֵאשִׁית בָּרָא אֱלֹהִים\n" +
|
||||
"Final forms: מלך שלום דין סוף ארץ",
|
||||
},
|
||||
{
|
||||
label: "Bidirectional (mixed)",
|
||||
exercises: "RTL runs inside LTR lines and vice versa; numbers and punctuation keep their side",
|
||||
text:
|
||||
"The Hebrew word שלום means peace, and the Arabic word سلام means the same.\n" +
|
||||
"Price: 120 ש\"ח (about $32) — call 555-1234.\n" +
|
||||
"מספר הטלפון שלי הוא 052-1234567, ואני גר ב-Tel Aviv.\n" +
|
||||
"أعيش في London منذ 5 سنوات.\n" +
|
||||
"Nested: he said \"مرحبا (hello) بكم\" and left.",
|
||||
},
|
||||
{
|
||||
label: "Hindi (Devanagari)",
|
||||
exercises: "conjuncts (क्ष त्र ज्ञ), vowel sign ि drawn BEFORE its consonant, headline bar",
|
||||
text:
|
||||
"सभी मनुष्यों को गौरव और अधिकारों के मामले में जन्मजात स्वतन्त्रता और समानता प्राप्त है। उन्हें बुद्धि और अन्तरात्मा की देन प्राप्त है और परस्पर उन्हें भाईचारे के भाव से बर्ताव करना चाहिए।\n" +
|
||||
"Reordering: कि (ka + i) की (ka + ii) दिल्ली हिन्दी\n" +
|
||||
"Conjuncts: क्ष त्र ज्ञ द्ध श्र प्र स्त्री",
|
||||
},
|
||||
{
|
||||
label: "Thai (no spaces, stacked)",
|
||||
exercises: "no inter-word spaces (wrap by syllable); vowels and tone marks stack above/below",
|
||||
text:
|
||||
"มนุษย์ทั้งหลายเกิดมามีอิสระและเสมอภาคกันในเกียรติศักดิ์และสิทธิ ต่างมีเหตุผลและมโนธรรม และควรปฏิบัติต่อกันด้วยเจตนารมณ์แห่งภราดรภาพ\n" +
|
||||
"สวัสดีครับ ภาษาไทย กรุงเทพมหานคร\n" +
|
||||
"Stacked marks: ปั้น ที่ กี้ น้ำ ป์ ฐ์",
|
||||
},
|
||||
{
|
||||
label: "Chinese (Simplified)",
|
||||
exercises: "CJK coverage; full-width punctuation ,。;wrapping between any two characters",
|
||||
text:
|
||||
"人人生而自由,在尊严和权利上一律平等。他们赋有理性和良心,并应以兄弟关系的精神相对待。\n" +
|
||||
"你好,世界!中文测试。繁體:臺灣、香港、澳門。\n" +
|
||||
"Mixed: 我有 3 个 apples 和 2 个 oranges。",
|
||||
},
|
||||
{
|
||||
label: "Japanese (kana + kanji)",
|
||||
exercises: "hiragana, katakana, kanji, half-width katakana カタカナ, long vowel mark ー",
|
||||
text:
|
||||
"すべての人間は、生れながらにして自由であり、かつ、尊厳と権利とについて平等である。人間は、理性と良心とを授けられており、互いに同胞の精神をもって行動しなければならない。\n" +
|
||||
"いろはにほへと ちりぬるを。コンピューター、テレビ、ゲーム。\n" +
|
||||
"半角カナ: コンピューター 全角英数: ABC123",
|
||||
},
|
||||
{
|
||||
label: "Korean (Hangul)",
|
||||
exercises: "precomposed syllables; conjoining jamo (ㅎㅏㄴ) should compose to 한",
|
||||
text:
|
||||
"모든 인간은 태어날 때부터 자유로우며 그 존엄과 권리에 있어 동등하다. 인간은 천부적으로 이성과 양심을 부여받았으며 서로 형제애의 정신으로 행동하여야 한다.\n" +
|
||||
"안녕하세요, 세계! 한국어 테스트.\n" +
|
||||
"Jamo: 한 (= 한) Compatibility jamo: ㅎ ㅏ ㄴ",
|
||||
},
|
||||
{
|
||||
label: "Emoji (ZWJ, modifiers)",
|
||||
exercises: "color emoji as monochrome; skin-tone modifiers, ZWJ families, flag pairs, VS16 render as ONE glyph",
|
||||
text:
|
||||
"Basic: 😀 👍 ❤ ☀ ★\n" +
|
||||
"Variation selector: ❤️ ☀️ ✈️ (same as above but VS16)\n" +
|
||||
"Skin tone: 👍🏻 👍🏽 👍🏿 👋🏾\n" +
|
||||
"ZWJ: 👨👩👧👦 👩💻 🏳️🌈\n" +
|
||||
"Flags: 🇯🇵 🇺🇸 🇩🇪 🇧🇷\n" +
|
||||
"Keycaps: 1️⃣ #️⃣",
|
||||
},
|
||||
{
|
||||
label: "Symbols & misc",
|
||||
exercises: "math, arrows, box drawing, currency, non-BMP (astral) codepoints",
|
||||
text:
|
||||
"Math: ∑ ∫ √ ∞ ≠ ≤ ≥ ± × ÷ π θ λ\n" +
|
||||
"Arrows: ← ↑ → ↓ ↔ ⇒ ⇔\n" +
|
||||
"Box: ┌─┬─┐ │ │ │ ├─┼─┤ └─┴─┘ ▲▼● ░▒▓█\n" +
|
||||
"Currency: $ € £ ¥ ₹ ₩ ₪ ¢\n" +
|
||||
"Astral: 𝔘𝔫𝔦𝔠𝔬𝔡𝔢 𝕳𝖊𝖑𝖑𝖔 𐐀𐐁 🜁🜂\n" +
|
||||
"Zero-width: ab (ZWSP) cd (ZWJ) ef (WJ) should read as ab cd ef",
|
||||
},
|
||||
];
|
||||
|
||||
const MARGIN_X = 18;
|
||||
const TITLE_Y = 8;
|
||||
const FOOTER_MARGIN = 20;
|
||||
const BODY_GAP = 6;
|
||||
|
||||
/**
|
||||
* Shows one Unicode sample wrapped to the page, with the feature under test
|
||||
* under the title and the current font in the footer. Scroll pages through
|
||||
* the text; double-click goes back to the language list.
|
||||
*/
|
||||
export class UnicodeSampleLayer implements Layer {
|
||||
private lines: string[] | null = null;
|
||||
private wrappedForWidth = 0;
|
||||
private wrappedWithFont = 0;
|
||||
private firstLine = 0;
|
||||
private bodyLineCount = 1;
|
||||
|
||||
constructor(private readonly sample: UnicodeSample) {}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const textWidth = width - 2 * MARGIN_X;
|
||||
|
||||
image.drawText(font, MARGIN_X, TITLE_Y, truncateText(font, this.sample.label, textWidth), 220);
|
||||
const noteY = TITLE_Y + font.lineHeight;
|
||||
const noteLines = wrapText(font, this.sample.exercises, textWidth);
|
||||
for (let i = 0; i < noteLines.length; i++) {
|
||||
image.drawText(font, MARGIN_X, noteY + i * font.lineHeight, noteLines[i]!, 120);
|
||||
}
|
||||
|
||||
const bodyY = noteY + noteLines.length * font.lineHeight + BODY_GAP;
|
||||
const footerY = height - FOOTER_MARGIN;
|
||||
this.bodyLineCount = Math.max(1, Math.floor((footerY - bodyY) / font.lineHeight));
|
||||
|
||||
const lines = this.getLines(font, textWidth);
|
||||
this.clampScroll(lines.length);
|
||||
const visible = lines.slice(this.firstLine, this.firstLine + this.bodyLineCount);
|
||||
for (let i = 0; i < visible.length; i++) {
|
||||
image.drawText(font, MARGIN_X, bodyY + i * font.lineHeight, visible[i]!, 235);
|
||||
}
|
||||
|
||||
const page = Math.floor(this.firstLine / this.pageStep()) + 1;
|
||||
image.drawText(font, MARGIN_X, footerY, `Page ${page}/${this.pageCount(lines.length)}`, 110);
|
||||
const fontLabel = fontSelectionLabel(getUiFontSelection());
|
||||
image.drawText(font, width - MARGIN_X - font.measureText(fontLabel), footerY, fontLabel, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: InputEvent, ctx: LayerContext): void {
|
||||
switch (event.type) {
|
||||
case "scroll-down":
|
||||
this.firstLine += this.pageStep();
|
||||
return;
|
||||
case "scroll-up":
|
||||
this.firstLine = Math.max(0, this.firstLine - this.pageStep());
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private pageStep(): number {
|
||||
return Math.max(1, this.bodyLineCount - 1);
|
||||
}
|
||||
|
||||
private clampScroll(lineCount: number): void {
|
||||
if (lineCount <= this.bodyLineCount) {
|
||||
this.firstLine = 0;
|
||||
return;
|
||||
}
|
||||
const lastPageStart = (this.pageCount(lineCount) - 1) * this.pageStep();
|
||||
this.firstLine = Math.max(0, Math.min(lastPageStart, this.firstLine));
|
||||
}
|
||||
|
||||
private pageCount(lineCount: number): number {
|
||||
if (lineCount <= this.bodyLineCount) return 1;
|
||||
return Math.ceil((lineCount - this.bodyLineCount) / this.pageStep()) + 1;
|
||||
}
|
||||
|
||||
private getLines(font: UiFont, width: number): string[] {
|
||||
if (this.lines === null || this.wrappedForWidth !== width || this.wrappedWithFont !== font.fingerprintId) {
|
||||
// breakLongWords: CJK and Thai have no spaces to wrap at.
|
||||
this.lines = wrapText(font, this.sample.text, width, { breakLongWords: true });
|
||||
this.wrappedForWidth = width;
|
||||
this.wrappedWithFont = font.fingerprintId;
|
||||
}
|
||||
return this.lines;
|
||||
}
|
||||
}
|
||||
|
||||
/** The language list; selecting a row opens its sample. */
|
||||
export function unicodeTestMenu(layout: MenuLayout): MenuLayer {
|
||||
return new MenuLayer(
|
||||
"Unicode test",
|
||||
UNICODE_SAMPLES.map((sample) => ({
|
||||
label: sample.label,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new UnicodeSampleLayer(sample));
|
||||
},
|
||||
})),
|
||||
layout,
|
||||
);
|
||||
}
|
||||
@@ -3,8 +3,8 @@ 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 { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { lineStep, listRowHeight } from "../../ui/metrics";
|
||||
|
||||
const DIALOG_X = 8;
|
||||
const DIALOG_Y = 8;
|
||||
@@ -21,6 +21,8 @@ const SERVICE_LABELS: Record<string, string> = {
|
||||
|
||||
export type ApiKeyRequestItem = { id: string; configured: boolean };
|
||||
|
||||
type ConsentAction = "Allow" | "Deny";
|
||||
|
||||
/**
|
||||
* Consent dialog shown when an EvenHub app calls requestApiKeyAccess: lists the
|
||||
* requested API-key services (marking any the user hasn't configured) and asks
|
||||
@@ -28,8 +30,14 @@ export type ApiKeyRequestItem = { id: string; configured: boolean };
|
||||
* double-click) shares nothing.
|
||||
*/
|
||||
export class EvenHubApiKeyDialogLayer implements Layer {
|
||||
/** 0 = Allow, 1 = Deny. */
|
||||
private selectedIndex = 0;
|
||||
private readonly menu = new Menu<ConsentAction>({
|
||||
items: ["Allow", "Deny"],
|
||||
wrap: true,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 8 },
|
||||
getHeight: () => listRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => drawActionRow(args),
|
||||
});
|
||||
private resolved = false;
|
||||
|
||||
constructor(
|
||||
@@ -67,16 +75,11 @@ export class EvenHubApiKeyDialogLayer implements Layer {
|
||||
}
|
||||
y += 4;
|
||||
|
||||
const focused = ctx.stack.isFocused();
|
||||
const actions = ["Allow", "Deny"];
|
||||
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);
|
||||
}
|
||||
this.menu.paint(
|
||||
image,
|
||||
{ x: DIALOG_X + 12, y, width: DIALOG_WIDTH - 24, height: Math.max(0, DIALOG_Y + height - PADDING - y) },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
return image;
|
||||
}
|
||||
|
||||
@@ -84,10 +87,10 @@ export class EvenHubApiKeyDialogLayer implements Layer {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
case "scroll-down":
|
||||
this.selectedIndex = (this.selectedIndex + 1) % 2;
|
||||
void this.menu.handleInput(event);
|
||||
return;
|
||||
case "click":
|
||||
this.resolve(ctx, this.selectedIndex === 0);
|
||||
this.resolve(ctx, this.menu.selectedItem === "Allow");
|
||||
return;
|
||||
case "double-click":
|
||||
this.resolve(ctx, false);
|
||||
@@ -113,3 +116,7 @@ export class EvenHubApiKeyDialogLayer implements Layer {
|
||||
else this.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
function drawActionRow({ image, item, x, y, selected }: MenuDrawArgs<ConsentAction>): void {
|
||||
image.drawText(getDefaultSmallFont(), x + 10, y + 3, item, selected ? 255 : 200);
|
||||
}
|
||||
@@ -80,7 +80,7 @@ class EvenHubCompassRouter {
|
||||
});
|
||||
}
|
||||
if (!this.enabled) {
|
||||
setCompassEnabled(true);
|
||||
setCompassEnabled(true, "evenhub");
|
||||
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.
|
||||
@@ -88,7 +88,7 @@ class EvenHubCompassRouter {
|
||||
}
|
||||
} else {
|
||||
if (this.enabled) {
|
||||
setCompassEnabled(false);
|
||||
setCompassEnabled(false, "evenhub");
|
||||
this.enabled = false;
|
||||
}
|
||||
this.unsubscribe?.();
|
||||
|
||||
+45
-25
@@ -18,6 +18,11 @@ const RECORD_FILE = 0xe4;
|
||||
const RECORD_DIR = 0xe5;
|
||||
const RECORD_FOOTER = 0xe3;
|
||||
|
||||
/** Archive paths are relative to one package, never to the phone container. */
|
||||
export function safeEhpkPath(value: string): boolean {
|
||||
return !!value && !/[\\\u0000:]/.test(value) && value.split('/').every(part => !!part && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
export type EhpkArchive = {
|
||||
/** Relative path (e.g. "app.json", "dist/index.html") to contents. */
|
||||
files: Map<string, Uint8Array>;
|
||||
@@ -71,41 +76,55 @@ export function utf8Decode(bytes: Uint8Array): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function parseEhpk(data: Uint8Array): EhpkArchive {
|
||||
if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b) {
|
||||
/** Index compressed records without expanding assets merely to read app.json. */
|
||||
export function openEhpk(data: Uint8Array) {
|
||||
if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b)
|
||||
throw new Error("not an EHPK file");
|
||||
}
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
const firstRecord = view.getUint32(8, true);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
|
||||
let p = firstRecord;
|
||||
const records = new Map<string, { offset: number; compressed: number; size: number }>();
|
||||
const requireBytes = (offset: number, length: number) => {
|
||||
if (offset < 20 || length < 0 || offset + length > data.length) throw new Error("ehpk: truncated record");
|
||||
};
|
||||
let p = view.getUint32(8, true);
|
||||
requireBytes(p, 0);
|
||||
while (p < data.length) {
|
||||
requireBytes(p, 4);
|
||||
const type = data[p]!;
|
||||
if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba) {
|
||||
if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba)
|
||||
throw new Error(`ehpk: bad record magic at ${p}`);
|
||||
}
|
||||
if (type === RECORD_FILE) {
|
||||
const compressedLength = view.getUint32(p + 4, true);
|
||||
const uncompressedLength = view.getUint32(p + 8, true);
|
||||
requireBytes(p, 16);
|
||||
const compressed = view.getUint32(p + 4, true), size = view.getUint32(p + 8, true);
|
||||
const nameLength = view.getUint16(p + 14, true);
|
||||
requireBytes(p + 16, nameLength + compressed);
|
||||
const name = utf8Decode(unxor(data, p + 16, nameLength));
|
||||
const blob = unxor(data, p + 16 + nameLength, compressedLength);
|
||||
const content = decompress(blob, new Uint8Array(uncompressedLength));
|
||||
if (content.length !== uncompressedLength) {
|
||||
throw new Error(`ehpk: ${name}: expected ${uncompressedLength} bytes, got ${content.length}`);
|
||||
}
|
||||
files.set(name, content);
|
||||
p += 16 + nameLength + compressedLength;
|
||||
if (!safeEhpkPath(name)) throw new Error(`ehpk: invalid file path ${name}`);
|
||||
records.set(name, { offset: p + 16 + nameLength, compressed, size });
|
||||
p += 16 + nameLength + compressed;
|
||||
} else if (type === RECORD_DIR) {
|
||||
const nameLength = view.getUint16(p + 6, true);
|
||||
p += 8 + nameLength;
|
||||
} else if (type === RECORD_FOOTER) {
|
||||
break;
|
||||
} else {
|
||||
throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`);
|
||||
}
|
||||
requireBytes(p, 8);
|
||||
const length = view.getUint16(p + 6, true);
|
||||
requireBytes(p + 8, length); p += 8 + length;
|
||||
} else if (type === RECORD_FOOTER) break;
|
||||
else throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`);
|
||||
}
|
||||
return { files: {
|
||||
keys: () => records.keys(),
|
||||
has: (name: string) => records.has(name),
|
||||
get: (name: string): Uint8Array | undefined => {
|
||||
const record = records.get(name);
|
||||
if (!record) return undefined;
|
||||
const content = decompress(unxor(data, record.offset, record.compressed), new Uint8Array(record.size));
|
||||
if (content.length !== record.size) throw new Error(`ehpk: ${name}: expected ${record.size} bytes, got ${content.length}`);
|
||||
return content;
|
||||
},
|
||||
} };
|
||||
}
|
||||
export type EhpkIndex = ReturnType<typeof openEhpk>;
|
||||
|
||||
export function parseEhpk(data: Uint8Array): EhpkArchive {
|
||||
const index = openEhpk(data), files = new Map<string, Uint8Array>();
|
||||
for (const name of index.files.keys()) files.set(name, index.files.get(name)!);
|
||||
return { files };
|
||||
}
|
||||
|
||||
@@ -119,6 +138,7 @@ export function parseManifest(appJsonText: string): EvenHubManifest {
|
||||
const name = String(raw.name ?? packageId);
|
||||
const version = String(raw.version ?? "0");
|
||||
const entrypoint = String(raw.entrypoint ?? "index.html");
|
||||
if (!safeEhpkPath(entrypoint)) throw new Error('Invalid EHPK entrypoint');
|
||||
|
||||
const permissions = parsePermissions(raw.permissions);
|
||||
const privacyPolicyUrl = firstSafeHttpsUrl(
|
||||
|
||||
@@ -5,16 +5,17 @@
|
||||
* it only discovers and downloads public .ehpk packages. Authentication is
|
||||
* the same signed-header scheme used by the firmware API.
|
||||
*/
|
||||
import { Application } from "@nativescript/core";
|
||||
import { hmacSha256Base64, getPhoneOpenUdid } from "./even-platform";
|
||||
export { getPhoneOpenUdid } from "./even-platform";
|
||||
import {
|
||||
getEvenHubToken,
|
||||
hasEvenHubCredentials,
|
||||
invalidateEvenHubToken,
|
||||
saveEvenHubSession,
|
||||
} from "./credentials";
|
||||
import { downloadBinary } from "../../native/binary-http";
|
||||
import { fetchWithUserAgent } from "../../util/http";
|
||||
|
||||
declare const android: any;
|
||||
|
||||
const API_HOST = "https://api.evenrealities.com";
|
||||
const PUBLIC_CDN_HOST = "https://cdn-pub.evenhub.evenrealities.com";
|
||||
@@ -128,9 +129,9 @@ export class EvenHubApiClient {
|
||||
const url = typeof metadata.url === "string" ? metadata.url : "";
|
||||
if (!url.startsWith("https://")) throw new Error("EvenHub returned no package download URL.");
|
||||
|
||||
const response = await fetchWithTimeout(url, {}, 60_000);
|
||||
if (!response.ok) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
const response = await downloadBinary(url, 60_000);
|
||||
if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`);
|
||||
const bytes = response.bytes;
|
||||
const expectedSize = finiteNumber(metadata.size);
|
||||
if (expectedSize > 0 && bytes.length !== expectedSize) {
|
||||
throw new Error(`EvenHub package was truncated (${bytes.length} of ${expectedSize} bytes).`);
|
||||
@@ -156,11 +157,11 @@ export class EvenHubApiClient {
|
||||
if (!/^prod\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+\.(?:svg|png|webp|jpe?g)$/i.test(cleanPath) || cleanPath.includes("..")) {
|
||||
throw new Error("EvenHub returned an invalid public asset path.");
|
||||
}
|
||||
const response = await fetchWithTimeout(`${PUBLIC_CDN_HOST}/${cleanPath}`, {}, 30_000);
|
||||
if (!response.ok) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`);
|
||||
const contentLength = Number(response.headers.get("Content-Length") ?? 0);
|
||||
const response = await downloadBinary(`${PUBLIC_CDN_HOST}/${cleanPath}`, 30_000);
|
||||
if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`);
|
||||
const contentLength = response.contentLength;
|
||||
if (contentLength > 1_000_000) throw new Error("EvenHub icon is unexpectedly large.");
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
const bytes = response.bytes;
|
||||
if (bytes.length === 0 || bytes.length > 1_000_000) throw new Error("EvenHub icon is empty or too large.");
|
||||
const extension = cleanPath.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? "";
|
||||
return { bytes, extension: extension === "jpeg" ? "jpg" : extension };
|
||||
@@ -180,12 +181,18 @@ export class EvenHubApiClient {
|
||||
path: string,
|
||||
options: { query?: Record<string, string | number>; body?: Record<string, unknown> } = {},
|
||||
): Promise<unknown> {
|
||||
let token = await this.ensureLogin();
|
||||
const token = await this.ensureLogin();
|
||||
const response = await this.request(method, path, { ...options, token, commonVersion: 3 });
|
||||
if (response.httpStatus === 401) {
|
||||
invalidateEvenHubToken();
|
||||
try {
|
||||
return unwrap(response.envelope, response.httpStatus, path);
|
||||
} catch (error) {
|
||||
// A rejected session fails every later request too, so drop the token
|
||||
// (unless a fresh sign-in replaced it while this request was in flight).
|
||||
if (error instanceof EvenHubAuthenticationError && getEvenHubToken() === token) {
|
||||
invalidateEvenHubToken();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return unwrap(response.envelope, response.httpStatus, path);
|
||||
}
|
||||
|
||||
private ensureLogin(): Promise<string> {
|
||||
@@ -287,9 +294,9 @@ function buildCommon(version: 1 | 3): string {
|
||||
buildTime: "26060821",
|
||||
appId: "1001",
|
||||
v: version,
|
||||
// This is Android's app-scoped SSAID. Even's login endpoint registers a
|
||||
// previously unseen value as a terminal, so Faceclaw does not need the
|
||||
// official Even app's differently-scoped ID.
|
||||
// Keep the established wire profile on both platforms. Even registers
|
||||
// this installation-scoped terminal ID at login (SSAID on Android,
|
||||
// a persisted random ID on iOS).
|
||||
openUdid: getPhoneOpenUdid(),
|
||||
os: "1",
|
||||
sn: "",
|
||||
@@ -333,13 +340,7 @@ function formEncode(value: string): string {
|
||||
}
|
||||
|
||||
function hmacSign(message: string): string {
|
||||
if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android.");
|
||||
const charset = java.nio.charset.StandardCharsets.UTF_8;
|
||||
const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(SIGN_KEY).getBytes(charset), "HmacSHA256");
|
||||
const mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(key);
|
||||
const digest = mac.doFinal(new java.lang.String(message).getBytes(charset));
|
||||
return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP));
|
||||
return hmacSha256Base64(SIGN_KEY, message);
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQUEST_TIMEOUT_MS): Promise<Response> {
|
||||
@@ -355,30 +356,21 @@ async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQU
|
||||
}
|
||||
|
||||
function unwrap(envelope: ApiEnvelope, httpStatus: number, path: string): unknown {
|
||||
if (httpStatus === 401) {
|
||||
throw new EvenHubAuthenticationError("Even rejected the login session.");
|
||||
const message = typeof envelope.msg === "string" ? envelope.msg.trim() : "";
|
||||
// An expired session can come back as HTTP 401, or as HTTP 200 with code
|
||||
// 401 in the envelope ("Your login is expired").
|
||||
if (httpStatus === 401 || Number(envelope.code) === 401) {
|
||||
throw new EvenHubAuthenticationError(message || "Even rejected the login session.");
|
||||
}
|
||||
if (httpStatus < 200 || httpStatus >= 300) {
|
||||
throw new Error(`EvenHub request failed (HTTP ${httpStatus}, ${path}).`);
|
||||
}
|
||||
if (envelope.code !== 0) {
|
||||
const detail = typeof envelope.msg === "string" && envelope.msg ? `: ${envelope.msg}` : "";
|
||||
throw new Error(`EvenHub API error ${envelope.code ?? "unknown"}${detail}`);
|
||||
throw new Error(`EvenHub API error ${envelope.code ?? "unknown"}${message ? `: ${message}` : ""}`);
|
||||
}
|
||||
return envelope.data;
|
||||
}
|
||||
|
||||
/** Return this installation's Android ID, which Even calls `openUdid`. */
|
||||
export function getPhoneOpenUdid(): string {
|
||||
if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android.");
|
||||
const resolver = Application.android.context?.getContentResolver();
|
||||
const openUdid = resolver
|
||||
? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "")
|
||||
: "";
|
||||
if (!openUdid) throw new Error("Android did not provide a device ID for EvenHub authentication.");
|
||||
return openUdid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a list response. The leaderboard returns `{list, total, page,
|
||||
* page_size}`; the ranking/search endpoints were only recovered from the
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
declare const FaceclawCrypto: any;
|
||||
|
||||
export function hmacSha256Base64(secret: string, message: string): string {
|
||||
return FaceclawCrypto.hmacSha256Message(secret, message);
|
||||
}
|
||||
|
||||
/** A stable random terminal ID, independent of phone hardware identifiers. */
|
||||
export function getPhoneOpenUdid(): string {
|
||||
const key = "integrations.evenhub.terminalId";
|
||||
let id = getStringSetting(key, "");
|
||||
if (!id) {
|
||||
id = NSUUID.UUID().UUIDString.replace(/-/g, "").slice(0, 16).toLowerCase();
|
||||
setStringSetting(key, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Application } from "@nativescript/core";
|
||||
|
||||
export function hmacSha256Base64(secret: string, message: string): string {
|
||||
const charset = java.nio.charset.StandardCharsets.UTF_8;
|
||||
const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(secret).getBytes(charset), "HmacSHA256");
|
||||
const mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(key);
|
||||
const digest = mac.doFinal(new java.lang.String(message).getBytes(charset));
|
||||
return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP));
|
||||
}
|
||||
|
||||
export function getPhoneOpenUdid(): string {
|
||||
const resolver = Application.android.context?.getContentResolver();
|
||||
const id = resolver ? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "") : "";
|
||||
if (!id) throw new Error("Android did not provide a device ID for EvenHub authentication.");
|
||||
return id;
|
||||
}
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
writeBinaryFile,
|
||||
} from "../../native/file-access";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import { loadImageFileAsGray } from "../../native/image-files";
|
||||
import { loadIconImage } from "../../native/icon-image";
|
||||
import { renderSvgIcon } from "../../graphics/icons";
|
||||
import { type GrayImage } from "../../graphics/image";
|
||||
import { parseEhpk, parseManifest, utf8Decode, type EhpkArchive, type EvenHubManifest } from "./ehpk";
|
||||
import { openEhpk, parseManifest, utf8Decode, type EhpkIndex, type EvenHubManifest } from "./ehpk";
|
||||
|
||||
const STORAGE_KEY = "evenhub.installedApps.v1";
|
||||
const APP_ID_PREFIX = "evenhub-installed:";
|
||||
@@ -209,7 +209,7 @@ export function renderInstalledEvenHubIcon(
|
||||
const svg = readTextFile(path);
|
||||
if (svg) image = renderSvgIcon(cacheKey, svg, size);
|
||||
} else {
|
||||
image = loadImageFileAsGray(path, size, size);
|
||||
image = loadIconImage(path, size, size);
|
||||
}
|
||||
renderedIconCache.set(cacheKey, image);
|
||||
return image;
|
||||
@@ -220,8 +220,8 @@ export function getInstalledEvenHubFingerprint(): string {
|
||||
return getStringSetting(STORAGE_KEY, "");
|
||||
}
|
||||
|
||||
function inspectEhpk(bytes: Uint8Array): { archive: EhpkArchive; manifest: EvenHubManifest } {
|
||||
const archive = parseEhpk(bytes);
|
||||
function inspectEhpk(bytes: Uint8Array): { archive: EhpkIndex; manifest: EvenHubManifest } {
|
||||
const archive = openEhpk(bytes);
|
||||
const appJson = archive.files.get("app.json");
|
||||
if (!appJson) throw new Error("The EHPK package has no app.json manifest.");
|
||||
return { archive, manifest: parseManifest(utf8Decode(appJson)) };
|
||||
@@ -242,7 +242,7 @@ function saveInstalledApps(apps: InstalledEvenHubApp[]): void {
|
||||
);
|
||||
}
|
||||
|
||||
function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): EvenHubInstallIcon | null {
|
||||
function findEmbeddedIcon(archive: EhpkIndex, manifest: EvenHubManifest): EvenHubInstallIcon | null {
|
||||
const candidates: string[] = [];
|
||||
for (const key of ["icon", "icon_path", "iconPath", "app_icon", "appIcon"]) {
|
||||
const value = manifest.raw[key];
|
||||
@@ -270,11 +270,11 @@ function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): Even
|
||||
if (content && extension) return { bytes: content, extension };
|
||||
}
|
||||
}
|
||||
const fallback = Array.from(archive.files.entries()).find(([path]) =>
|
||||
const fallback = Array.from(archive.files.keys()).find((path) =>
|
||||
/(?:^|\/)(?:app-?)?(?:icon|favicon)\.(?:svg|png|webp|jpe?g)$/i.test(path),
|
||||
);
|
||||
const extension = fallback ? iconExtension(fallback[0]) : null;
|
||||
return fallback && extension ? { bytes: fallback[1], extension } : null;
|
||||
const extension = fallback ? iconExtension(fallback) : null;
|
||||
return fallback && extension ? { bytes: archive.files.get(fallback)!, extension } : null;
|
||||
}
|
||||
|
||||
function normalizeInstallIcon(icon: EvenHubInstallIcon | undefined): EvenHubInstallIcon | null {
|
||||
|
||||
+25
-30
@@ -15,16 +15,16 @@ import { type AppContext } from "../app-definition";
|
||||
import {
|
||||
appFilesDirPath,
|
||||
deletePathRecursively,
|
||||
readBinaryFile,
|
||||
writeBinaryFile,
|
||||
} from "../../native/file-access";
|
||||
import { parseEhpk, parseManifest, utf8Decode, type EvenHubManifest } from "./ehpk";
|
||||
import { type EvenHubManifest } from "./ehpk";
|
||||
import { unpackRuntime } from "./unpack-runtime";
|
||||
import { type EvenHubPermission } from "./permissions";
|
||||
import { EvenHubSession } from "./session";
|
||||
import { createEvenHubWindow } from "./evenhub-window";
|
||||
import { createEvenHubWebView, type EvenHubWebView } from "./webview";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
import {
|
||||
readEvenHubPackageManifest,
|
||||
installedEvenHubAppId,
|
||||
installedEvenHubPackagePath,
|
||||
type InstalledEvenHubApp,
|
||||
@@ -64,18 +64,6 @@ export async function launchPackage(
|
||||
ehpkPath: string,
|
||||
options: { appId?: string; singleton?: boolean } = {},
|
||||
): Promise<void> {
|
||||
const data = readBinaryFile(ehpkPath);
|
||||
if (!data) {
|
||||
ctx.appendLog(`evenhub: could not read ${ehpkPath}`);
|
||||
return;
|
||||
}
|
||||
const archive = parseEhpk(data);
|
||||
const appJson = archive.files.get("app.json");
|
||||
if (!appJson) {
|
||||
ctx.appendLog("evenhub: package has no app.json");
|
||||
return;
|
||||
}
|
||||
const manifest = parseManifest(utf8Decode(appJson));
|
||||
const appId = options.appId ?? "evenhub";
|
||||
if (options.singleton) {
|
||||
const existing = Array.from(running.values()).find((app) => app.appId === appId);
|
||||
@@ -86,18 +74,19 @@ export async function launchPackage(
|
||||
}
|
||||
}
|
||||
|
||||
// Unpack fresh into app-private storage, keyed by package id.
|
||||
const manifest = readEvenHubPackageManifest(ehpkPath);
|
||||
if (!manifest) throw new Error('Could not read the EHPK manifest.');
|
||||
// Unpack off the iOS UI thread; reserve a unique directory before awaiting.
|
||||
const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_");
|
||||
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}`;
|
||||
deletePathRecursively(baseDir);
|
||||
for (const [name, content] of Array.from(archive.files)) {
|
||||
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
|
||||
ctx.appendLog(`evenhub: failed to write ${name}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await startApp(ctx, manifest, `${baseDir}/dist`, "", appId);
|
||||
if (!safeId || safeId === '.' || safeId === '..') throw new Error('Invalid EHPK package ID');
|
||||
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial++}` : ''}`;
|
||||
const started = Date.now();
|
||||
ctx.appendLog(`evenhub: unpacking ${manifest.name}`);
|
||||
try {
|
||||
const loadedManifest = await unpackRuntime(ehpkPath, baseDir);
|
||||
ctx.appendLog(`evenhub: unpacked ${loadedManifest.name} in ${Date.now() - started} ms`);
|
||||
await startApp(ctx, loadedManifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined);
|
||||
} catch (error) { deletePathRecursively(baseDir); throw error; }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,9 +100,11 @@ async function startApp(
|
||||
distDir: string,
|
||||
remoteUrl: string,
|
||||
appId: string,
|
||||
cleanup?: () => void,
|
||||
): Promise<void> {
|
||||
const windowId = `evenhub:app:${nextSerial++}`;
|
||||
const session = new EvenHubSession(manifest, distDir, ctx.appendLog, remoteUrl);
|
||||
const session = new EvenHubSession(manifest, distDir, ctx.appendLog, remoteUrl,
|
||||
payload => ctx.actions.playBuzzerSequence(payload));
|
||||
const webView = createEvenHubWebView(session);
|
||||
session.attachWebView({
|
||||
evaluateJs: webView.evaluateJs,
|
||||
@@ -123,6 +114,7 @@ async function startApp(
|
||||
phoneShownWindowId = null;
|
||||
}
|
||||
webView.destroy();
|
||||
cleanup?.();
|
||||
running.delete(windowId);
|
||||
},
|
||||
});
|
||||
@@ -130,9 +122,11 @@ async function startApp(
|
||||
ensureBackHandler();
|
||||
ctx.appendLog(`evenhub: launching ${manifest.name} ${manifest.version} (${manifest.packageId})`);
|
||||
|
||||
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
|
||||
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
|
||||
);
|
||||
try {
|
||||
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
|
||||
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
|
||||
);
|
||||
} catch (error) { session.close(); throw error; }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,6 +204,7 @@ export function closeRunningPackage(packageId: string): void {
|
||||
export function showOnPhone(windowId: string): void {
|
||||
const app = running.get(windowId);
|
||||
if (!app) return;
|
||||
if (phoneShownWindowId && phoneShownWindowId !== windowId) hidePhone();
|
||||
app.webView.showOnPhone();
|
||||
phoneShownWindowId = windowId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { deletePathRecursively, readBinaryFile, writeBinaryFile } from '../../native/file-access';
|
||||
import { openEhpk, parseManifest, utf8Decode, type EvenHubManifest } from './ehpk';
|
||||
|
||||
/** Called on a worker on iOS. Hold only one expanded asset at a time. */
|
||||
export function extractPackage(path: string, directory: string): EvenHubManifest {
|
||||
try {
|
||||
const bytes = readBinaryFile(path);
|
||||
if (!bytes) throw new Error('Could not read the EHPK file.');
|
||||
const archive = openEhpk(bytes);
|
||||
const json = archive.files.get('app.json');
|
||||
if (!json) throw new Error('The EHPK package has no app.json.');
|
||||
const manifest = parseManifest(utf8Decode(json));
|
||||
if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.');
|
||||
deletePathRecursively(directory);
|
||||
for (const name of archive.files.keys()) {
|
||||
if (!writeBinaryFile(`${directory}/${name}`, archive.files.get(name)!)) throw new Error(`Could not unpack ${name}.`);
|
||||
}
|
||||
return manifest;
|
||||
} catch (error) { deletePathRecursively(directory); throw error; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import '@nativescript/core/globals';
|
||||
import { extractPackage } from './package-extraction';
|
||||
|
||||
global.onmessage = (event: { data: { path: string; directory: string } }) => {
|
||||
try {
|
||||
const manifest = extractPackage(event.data.path, event.data.directory);
|
||||
global.postMessage({ manifest });
|
||||
} catch (error) { global.postMessage({ error: String((error as Error)?.message ?? error) }); }
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Utils } from '@nativescript/core'
|
||||
/** Open outside the app runtime; this page has no EvenHub bridge. */
|
||||
export function openPrivacyPolicyOnPhone(url: string, _appName: string): void {
|
||||
if (/^https:\/\//i.test(url)) Utils.openUrl(url)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Application } from "@nativescript/core";
|
||||
import { fetchWithUserAgent } from "../../util/http";
|
||||
import { copyToJavaByteBuffer } from "../../native/java-direct-buffer";
|
||||
|
||||
declare const android: any;
|
||||
declare const androidx: any;
|
||||
@@ -93,8 +94,7 @@ async function downloadAndOpenPdf(url: string, appName: string, activity: any):
|
||||
const file = new java.io.File(directory, `policy-${hash.toString(16)}.pdf`);
|
||||
const stream = new java.io.FileOutputStream(file);
|
||||
try {
|
||||
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
||||
stream.getChannel().write(buffer);
|
||||
stream.getChannel().write(copyToJavaByteBuffer(bytes));
|
||||
} finally {
|
||||
stream.close();
|
||||
}
|
||||
|
||||
+15
-18
@@ -61,12 +61,10 @@ import { type ImuReading } from "../../native/imu";
|
||||
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
|
||||
import { getCurrentLocation } from "../../native/location";
|
||||
import { LocationTracker, type TrackedLocation } from "../../native/location-tracker";
|
||||
import { ensureFineLocationPermission } from "../../g2/android-permissions";
|
||||
import { ensureFineLocationPermission } from "../../native/location-permissions";
|
||||
|
||||
const UPNG = require("upng-js");
|
||||
|
||||
declare const com: any;
|
||||
|
||||
/** OsEventTypeList values (PB ordinals). */
|
||||
const CLICK_EVENT = 0;
|
||||
const SCROLL_TOP_EVENT = 1;
|
||||
@@ -334,6 +332,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
private windowHooks: EvenHubWindowHooks | null = null;
|
||||
private closed = false;
|
||||
private launchContextPushed = false;
|
||||
private loadError = '';
|
||||
private systemExitSent = false;
|
||||
/** The one-shot launch FOREGROUND_ENTER has been delivered (page exists). */
|
||||
private launchEnterSent = false;
|
||||
@@ -370,6 +369,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
distDir: string,
|
||||
log: (message: string) => void,
|
||||
remoteUrl = "",
|
||||
private readonly sendBuzzerSequence: (payload: Uint8Array) => Promise<void> | void = () => {},
|
||||
) {
|
||||
this.manifest = manifest;
|
||||
this.distDir = distDir;
|
||||
@@ -383,6 +383,11 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
this.webViewHandle = handle;
|
||||
}
|
||||
|
||||
webViewFailed(message: string): void {
|
||||
if (this.closed) return;
|
||||
this.loadError = message; this.log(`evenhub: ${message}`); this.windowHooks?.requestRender();
|
||||
}
|
||||
|
||||
/** The WebView finished loading the app: push the one-shot launch context. */
|
||||
webViewLoaded(): void {
|
||||
if (this.launchContextPushed) return;
|
||||
@@ -416,11 +421,12 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
// Focus changes always trigger a repaint of the foreground window, so paint
|
||||
// is a reliable place to sample shell input-focus for lifecycle events.
|
||||
this.updateShellFocus(focused);
|
||||
if (!this.pageCreated || !this.page) {
|
||||
if (this.loadError || !this.pageCreated || !this.page) {
|
||||
const image = new GrayImage(size.width, size.height, 0);
|
||||
const font = EvenHubFont.get();
|
||||
font.drawText(image, 16, 16, `Loading ${this.manifest.name}...`, 255);
|
||||
font.drawText(image, 16, 16 + 2 * font.lineHeight, "(waiting for the app to build its page)", 120);
|
||||
font.drawText(image, 16, 16, `${this.loadError ? 'Could not run' : 'Loading'} ${this.manifest.name}...`, 255);
|
||||
font.drawTextWrapped(image, 16, 16 + 2 * font.lineHeight, Math.max(1, size.width - 32),
|
||||
this.loadError || "(waiting for the app to build its page)", 120);
|
||||
return image;
|
||||
}
|
||||
return compositePage(this.page, size, focused);
|
||||
@@ -604,6 +610,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
* flows (foreground + screen on + no assistant modal).
|
||||
*/
|
||||
private audioControl(data: Record<string, unknown>): boolean {
|
||||
if (global.isIOS) return false; // EvenHub PCM routing is not ported yet.
|
||||
if (!permissionsIncludeMicrophone(this.manifest.permissions)) {
|
||||
this.log("evenhub: audioControl denied (app declares no microphone permission)");
|
||||
return false;
|
||||
@@ -697,6 +704,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
* to the foreground app. reportFrq is one of 100..1000 (step 100).
|
||||
*/
|
||||
private imuControl(data: Record<string, unknown>): boolean {
|
||||
if (global.isIOS) return false;
|
||||
const enable = readEnableFlag(data);
|
||||
const freq = clampImuFreq(readOptionalNumber(data, "reportFrq") ?? readOptionalNumber(data, "reportFreq") ?? 100);
|
||||
// Payload field spelling isn't fully captured; log once per toggle.
|
||||
@@ -1155,13 +1163,11 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
private async playBuzzer(rawSteps: unknown[]): Promise<void> {
|
||||
const steps = normalizeBuzzerSteps(rawSteps);
|
||||
if (steps.length === 0) return;
|
||||
const communicator = activeCommunicator();
|
||||
if (!communicator) return;
|
||||
for (let i = 0; i < steps.length; i += CFW_SEQ_MAX) {
|
||||
const chunk = steps.slice(i, i + CFW_SEQ_MAX);
|
||||
const payload = buildSoundSequencePayload(chunk);
|
||||
try {
|
||||
communicator.playBuzzerSequence(payload.buffer);
|
||||
await this.sendBuzzerSequence(payload);
|
||||
} catch (error) {
|
||||
this.log(`evenhub: playBuzzer failed: ${error}`);
|
||||
return;
|
||||
@@ -1265,15 +1271,6 @@ function clampImuFreq(freq: number): number {
|
||||
return Math.min(1000, Math.max(100, snapped));
|
||||
}
|
||||
|
||||
function activeCommunicator(): any {
|
||||
if (!global.isAndroid) return null;
|
||||
try {
|
||||
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy content into a `preserve` container from the same-named, same-kind
|
||||
* container in the previous page (if any), so a replaceLayout keeps its pixels /
|
||||
|
||||
@@ -3,7 +3,7 @@ import { GrayImage } from "../../graphics/image";
|
||||
import { truncateText, wrapText } from "../../graphics/textwrap";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { drawSelectionHighlight } from "../../ui/menu";
|
||||
import { Menu } from "../../ui/menu-core";
|
||||
import { TextViewerLayer } from "../files/text-viewer";
|
||||
import { evenHubApi, type EvenHubStoreApp } from "./even-api";
|
||||
import {
|
||||
@@ -18,17 +18,36 @@ import { lineStep, listRowHeight } from "../../ui/metrics";
|
||||
|
||||
const X = 18;
|
||||
|
||||
type DetailAction = "about" | "whats-new" | "primary";
|
||||
const ACTIONS: readonly DetailAction[] = ["about", "whats-new", "primary"];
|
||||
|
||||
export type EvenHubStoreDetailOptions = {
|
||||
launchApp: (appId: string) => Promise<void> | void;
|
||||
appendLog: (message: string) => void;
|
||||
/** A package was installed, updated, or reinstalled from this page. */
|
||||
onInstalled?: (app: InstalledEvenHubApp) => void;
|
||||
/** Offered every failure first; returns true if it was a rejected session (and was dealt with). */
|
||||
onAuthError?: (ctx: LayerContext, error: unknown) => boolean;
|
||||
};
|
||||
|
||||
/** Storefront metadata and the Install/Launch action for one public app. */
|
||||
export class EvenHubStoreDetailLayer implements Layer {
|
||||
/** About, What's New, Install/Launch. */
|
||||
private selectedIndex = 2;
|
||||
/** About, What's New, Install/Launch; starts on the primary action. */
|
||||
private readonly actions = new Menu<DetailAction>({
|
||||
items: ACTIONS,
|
||||
selectedIndex: 2,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 8 },
|
||||
getHeight: () => listRowHeight(getDefaultSmallFont()) + 4,
|
||||
draw: ({ image, item, x, y, width, selected }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
const label = item === "about" ? "About" : item === "whats-new" ? "What's New" : this.primaryLabel;
|
||||
const value = this.working && item === "primary" ? 145 : selected ? 245 : 190;
|
||||
image.drawText(font, x + 11, y + 5, truncateText(font, label, width - 18), value);
|
||||
},
|
||||
});
|
||||
/** The primary action's label for the paint in progress. */
|
||||
private primaryLabel = "";
|
||||
private working = false;
|
||||
private detailPromise: Promise<void> | null = null;
|
||||
private status = "";
|
||||
@@ -47,7 +66,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..." : this.primaryActionLabel(installed)];
|
||||
this.primaryLabel = 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.
|
||||
@@ -90,7 +109,7 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
// Stacked layout (details full-width, actions at the bottom) when it
|
||||
// fits; otherwise the actions become a narrow top-right menu and the
|
||||
// details flow down a left column beside it.
|
||||
const stackedActionTop = height - 6 - actions.length * actionRowH;
|
||||
const stackedActionTop = height - 6 - ACTIONS.length * actionRowH;
|
||||
const stacked = 8 + linesHeight(buildLines(width - X * 2)) + 6 <= stackedActionTop;
|
||||
const menuW = 150;
|
||||
const menuX = width - menuW - 12;
|
||||
@@ -105,15 +124,11 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
const actionX = stacked ? X : menuX;
|
||||
const actionW = stacked ? textWidth : menuW;
|
||||
const actionTop = stacked ? stackedActionTop : 8;
|
||||
for (let index = 0; index < actions.length; index++) {
|
||||
const actionY = actionTop + index * actionRowH;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, actionX - 5, actionY, actionW + 10, actionRowH - 1, ctx.stack.isFocused(), 8);
|
||||
}
|
||||
const value = this.working && index === 2 ? 145 : selected ? 245 : 190;
|
||||
image.drawText(font, actionX + 6, actionY + 5, truncateText(font, actions[index]!, actionW - 8), value);
|
||||
}
|
||||
this.actions.paint(
|
||||
image,
|
||||
{ x: actionX - 5, y: actionTop, width: actionW + 10, height: ACTIONS.length * actionRowH - 1 },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
return image;
|
||||
}
|
||||
|
||||
@@ -123,34 +138,44 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
return;
|
||||
}
|
||||
if (this.working) return;
|
||||
if (event.type === "scroll-up") {
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
return;
|
||||
}
|
||||
if (event.type === "scroll-down") {
|
||||
this.selectedIndex = Math.min(2, this.selectedIndex + 1);
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
await this.actions.handleInput(event);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "click") return;
|
||||
|
||||
await this.ensureDetail(ctx);
|
||||
// Never hold the serialized input queue across network work or a dialog
|
||||
// that needs a subsequent input to resolve.
|
||||
void this.activate(ctx);
|
||||
}
|
||||
|
||||
if (this.selectedIndex === 0) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About"));
|
||||
return;
|
||||
}
|
||||
if (this.selectedIndex === 1) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New"));
|
||||
return;
|
||||
}
|
||||
private async activate(ctx: LayerContext): Promise<void> {
|
||||
this.working = true;
|
||||
try {
|
||||
await this.ensureDetail(ctx);
|
||||
|
||||
const installed = getInstalledEvenHubApp(this.app.packageId);
|
||||
if (installed && this.primaryActionLabel(installed) === "Launch") {
|
||||
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
|
||||
return;
|
||||
}
|
||||
const action = this.actions.selectedItem;
|
||||
if (action === "about") {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About"));
|
||||
return;
|
||||
}
|
||||
if (action === "whats-new") {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New"));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.install(ctx);
|
||||
const installed = getInstalledEvenHubApp(this.app.packageId);
|
||||
if (installed && this.primaryActionLabel(installed) === "Launch") {
|
||||
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.install(ctx);
|
||||
} catch (error) {
|
||||
if (this.options.onAuthError?.(ctx, error)) return;
|
||||
this.status = cleanError(error);
|
||||
this.options.appendLog(`evenhub store: ${this.status}`);
|
||||
} finally { this.working = false; ctx.actions.requestRender(); }
|
||||
}
|
||||
|
||||
/** Install for a new app; Update / Reinstall when the installed copy is stale or gone. */
|
||||
@@ -181,6 +206,7 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
ctx.actions.requestRender();
|
||||
await this.options.launchApp(installedEvenHubAppId(result.packageId));
|
||||
} catch (error) {
|
||||
if (this.options.onAuthError?.(ctx, error)) return;
|
||||
this.status = cleanError(error);
|
||||
this.options.appendLog(`evenhub store: ${this.status}`);
|
||||
} finally {
|
||||
@@ -204,6 +230,7 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (this.options.onAuthError?.(ctx, error)) return;
|
||||
this.options.appendLog(`evenhub store: app details unavailable: ${cleanError(error)}`);
|
||||
})
|
||||
.finally(() => ctx.actions.requestRender());
|
||||
|
||||
@@ -53,8 +53,6 @@ export async function installStoreApp(
|
||||
const needsPrompt = (manifest.permissions.length > 0 || privacyPolicyUrl)
|
||||
&& !alreadyGranted(app.packageId, manifest);
|
||||
if (needsPrompt) {
|
||||
options.onStatus("");
|
||||
ctx.actions.requestRender();
|
||||
const accepted = await new Promise<boolean>((resolve) => {
|
||||
ctx.stack.push(
|
||||
new EvenHubPermissionDialogLayer(
|
||||
@@ -65,6 +63,10 @@ export async function installStoreApp(
|
||||
() => resolve(false),
|
||||
),
|
||||
);
|
||||
// Only once the dialog is stacked: an in-process window's requestRender
|
||||
// paints synchronously, and nothing else repaints after a download.
|
||||
options.onStatus("");
|
||||
ctx.actions.requestRender();
|
||||
});
|
||||
if (!accepted) return null;
|
||||
}
|
||||
|
||||
+137
-92
@@ -1,16 +1,16 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
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, type LayerStack } from "../../ui/layers";
|
||||
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
|
||||
import { drawSelectionHighlight, type MenuItem } from "../../ui/menu";
|
||||
import { Menu } from "../../ui/menu-core";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
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 { EvenHubStoreDetailLayer, type EvenHubStoreDetailOptions } from "./store-detail-layer";
|
||||
import { cleanError, installStoreApp } from "./store-install";
|
||||
import { checkForEvenHubUpdates, describeUpdate, type EvenHubAppUpdate } from "./updates";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
@@ -24,6 +24,11 @@ function headerHeight(font: UiFont): number {
|
||||
return 8 + lineStep(font) + font.lineHeight + 6;
|
||||
}
|
||||
|
||||
/** Row pitch of the two-line app list (title + detail), including the 2px gap between highlights. */
|
||||
function storeRowHeight(font: UiFont): number {
|
||||
return Math.max(30, 2 * lineStep(font) + 4);
|
||||
}
|
||||
|
||||
/** Last search typed on the phone; kept so reopening the store shows it again. */
|
||||
export const evenHubSearchQuerySetting = new ConfigSettingString({
|
||||
id: "evenhub-search-query",
|
||||
@@ -64,27 +69,46 @@ type TabState = {
|
||||
loading: boolean;
|
||||
/** Progress or error text for the subtitle line. */
|
||||
status: string;
|
||||
selectedIndex: number;
|
||||
scrollRow: number;
|
||||
/** Selection and scroll over `rows` (resynced before each paint and input). */
|
||||
menu: Menu<StoreRow>;
|
||||
/** Search only: the query the rows belong to. */
|
||||
query: string;
|
||||
};
|
||||
|
||||
function emptyTab(): TabState {
|
||||
const rows: StoreRow[] = [];
|
||||
return {
|
||||
rows: [],
|
||||
rows,
|
||||
total: 0,
|
||||
nextPage: 1,
|
||||
exhausted: false,
|
||||
loaded: false,
|
||||
loading: false,
|
||||
status: "",
|
||||
selectedIndex: 0,
|
||||
scrollRow: 0,
|
||||
menu: new Menu<StoreRow>({
|
||||
items: rows,
|
||||
rowGap: 2,
|
||||
highlight: { radius: 5 },
|
||||
getHeight: () => storeRowHeight(getDefaultSmallFont()),
|
||||
draw: ({ image, item, x, y, width }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
const { title, detail, titleValue } = rowText(item);
|
||||
const textX = x + 6;
|
||||
const textW = width - 12;
|
||||
image.drawText(font, textX, y + 2, truncateText(font, title, textW), titleValue);
|
||||
image.drawText(font, textX, y + 2 + lineStep(font), truncateText(font, detail, textW), 115);
|
||||
},
|
||||
}),
|
||||
query: "",
|
||||
};
|
||||
}
|
||||
|
||||
/** The tab's menu, with its items brought up to date with `rows` (which loads replace or extend). */
|
||||
function tabMenu(tab: TabState): Menu<StoreRow> {
|
||||
if (tab.menu.items !== tab.rows) tab.menu.setItems(tab.rows);
|
||||
return tab.menu;
|
||||
}
|
||||
|
||||
export type EvenHubStoreLayerOptions = {
|
||||
launchApp: (appId: string) => Promise<void> | void;
|
||||
appendLog: (message: string) => void;
|
||||
@@ -124,9 +148,14 @@ export class EvenHubStoreLayer implements Layer {
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
if (!this.started) {
|
||||
this.started = true;
|
||||
if (this.showingLogin) {
|
||||
this.openCredentialEditor(ctx);
|
||||
} else {
|
||||
// Do NOT open the phone credential editor here. This runs on the first
|
||||
// paint, which includes the restore of a still-open EvenHub at app
|
||||
// startup -- so an unfinished sign-in re-opened the form on every
|
||||
// launch, unasked. The login pane already says "Enter your Even account
|
||||
// email and password in the phone app" and already opens the editor on
|
||||
// click (handleInput), so the editor is still one tap away for someone
|
||||
// who actually wants it.
|
||||
if (!this.showingLogin) {
|
||||
void this.ensureTabLoaded(ctx, this.activeTab);
|
||||
}
|
||||
}
|
||||
@@ -163,25 +192,16 @@ export class EvenHubStoreLayer implements Layer {
|
||||
return image;
|
||||
}
|
||||
|
||||
tab.selectedIndex = clamp(tab.selectedIndex, 0, tab.rows.length - 1);
|
||||
const rowH = Math.max(30, 2 * lineStep(font) + 4);
|
||||
const rowH = storeRowHeight(font);
|
||||
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);
|
||||
}
|
||||
const menu = tabMenu(tab);
|
||||
menu.paint(
|
||||
image,
|
||||
{ x: LIST_X - 6, y: headerH, width: width - LIST_X * 2 + 12, height: visibleRows * rowH - 2 },
|
||||
listFocused,
|
||||
);
|
||||
menu.drawScrollbar(image, width - 5, headerH, visibleRows * rowH - 3);
|
||||
return image;
|
||||
}
|
||||
|
||||
@@ -243,41 +263,6 @@ export class EvenHubStoreLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
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<void> {
|
||||
if (this.showingLogin) {
|
||||
if (event.type === "click" && !this.loginBusy) {
|
||||
@@ -292,16 +277,17 @@ export class EvenHubStoreLayer implements Layer {
|
||||
return;
|
||||
}
|
||||
const tab = this.tabs[this.activeTab];
|
||||
const menu = tabMenu(tab);
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
tab.selectedIndex = Math.max(0, tab.selectedIndex - 1);
|
||||
await menu.handleInput(event);
|
||||
return;
|
||||
case "scroll-down":
|
||||
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);
|
||||
await menu.handleInput(event);
|
||||
if ((menu.selectedIndex ?? 0) >= tab.rows.length - 4) void this.loadNextPage(ctx, this.activeTab);
|
||||
return;
|
||||
case "click":
|
||||
await this.activateRow(ctx, tab.rows[tab.selectedIndex]);
|
||||
await this.activateRow(ctx, menu.selectedItem ?? undefined);
|
||||
return;
|
||||
case "double-click":
|
||||
this.focus = "tabs";
|
||||
@@ -360,13 +346,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
}
|
||||
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),
|
||||
}),
|
||||
);
|
||||
ctx.stack.push(new EvenHubStoreDetailLayer(row.app, this.detailOptions()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -384,13 +364,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
}
|
||||
this.pendingPackage = null;
|
||||
stack.clearToBase();
|
||||
stack.push(
|
||||
new EvenHubStoreDetailLayer(placeholderStoreApp(installed), {
|
||||
launchApp: this.options.launchApp,
|
||||
appendLog: this.options.appendLog,
|
||||
onInstalled: (result) => this.onInstalled(result),
|
||||
}),
|
||||
);
|
||||
stack.push(new EvenHubStoreDetailLayer(placeholderStoreApp(installed), this.detailOptions()));
|
||||
}
|
||||
|
||||
/** Dictated text becomes a search (the shell's "Type Into App" / voice input). */
|
||||
@@ -533,7 +507,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
state.rows = [{ kind: "search-query" }];
|
||||
state.loaded = !query;
|
||||
// Keep the cursor on the first result once there are some.
|
||||
state.selectedIndex = query ? 1 : 0;
|
||||
state.menu.setItems(state.rows, query ? 1 : 0);
|
||||
this.tabs.search = state;
|
||||
ctx.actions.requestRender();
|
||||
if (query) await this.loadNextPage(ctx, "search");
|
||||
@@ -559,8 +533,8 @@ export class EvenHubStoreLayer implements Layer {
|
||||
update.latest ? { kind: "app", app: update.latest, update } : { kind: "orphan", update },
|
||||
);
|
||||
state.rows = rows;
|
||||
state.selectedIndex = 0;
|
||||
state.scrollRow = 0;
|
||||
state.menu.setItems(rows, 0);
|
||||
state.menu.scrollTop = 0;
|
||||
state.status = "";
|
||||
state.exhausted = true;
|
||||
} catch (error) {
|
||||
@@ -607,6 +581,8 @@ export class EvenHubStoreLayer implements Layer {
|
||||
failures.push(`${row.app.name} (declined)`);
|
||||
}
|
||||
} catch (error) {
|
||||
// An expired session fails every remaining update the same way.
|
||||
if (this.handleAuthError(ctx, error)) return;
|
||||
const message = cleanError(error);
|
||||
this.options.appendLog(`evenhub store: update of ${row.app.packageId} failed: ${message}`);
|
||||
failures.push(row.app.name);
|
||||
@@ -636,21 +612,43 @@ export class EvenHubStoreLayer implements Layer {
|
||||
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));
|
||||
state.menu.setItems(state.rows);
|
||||
}
|
||||
|
||||
// ---- login and phone editors --------------------------------------------
|
||||
|
||||
/** Route a rejected session back to the login form; true if it was one. */
|
||||
/**
|
||||
* Drop back to the logged-out pane when Even rejects the session (an
|
||||
* expired login); true if the error was one. Anything open above the list
|
||||
* (an app page, a permission dialog) needed the session too, so it goes.
|
||||
* The phone form is not opened: this can happen on the first load of a
|
||||
* store window restored at startup (see paint), and the pane's click
|
||||
* opens it.
|
||||
*/
|
||||
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}`);
|
||||
this.options.appendLog(`evenhub store: session rejected: ${message}`);
|
||||
if (this.closed) return true;
|
||||
ctx.stack.clearToBase();
|
||||
this.enterLogin(ctx, `Signed out: ${message}`, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private enterLogin(ctx: LayerContext, status = "Sign in to browse public apps."): void {
|
||||
private detailOptions(): EvenHubStoreDetailOptions {
|
||||
return {
|
||||
launchApp: this.options.launchApp,
|
||||
appendLog: this.options.appendLog,
|
||||
onInstalled: (installed) => this.onInstalled(installed),
|
||||
onAuthError: (ctx, error) => this.handleAuthError(ctx, error),
|
||||
};
|
||||
}
|
||||
|
||||
private enterLogin(
|
||||
ctx: LayerContext,
|
||||
status = "Sign in to browse public apps.",
|
||||
openEditor = true,
|
||||
): void {
|
||||
const wasShowingLogin = this.showingLogin;
|
||||
this.closePhoneEditor(ctx.actions, "search");
|
||||
this.showingLogin = true;
|
||||
@@ -659,7 +657,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
for (const tab of TABS) this.tabs[tab.id] = emptyTab();
|
||||
this.focus = "list";
|
||||
if (!wasShowingLogin) resetEvenHubLoginForm();
|
||||
this.openCredentialEditor(ctx);
|
||||
if (openEditor) this.openCredentialEditor(ctx);
|
||||
ctx.actions.requestRender();
|
||||
}
|
||||
|
||||
@@ -674,6 +672,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
void this.submitCredentials(ctx);
|
||||
},
|
||||
{ setting: evenHubRememberMeSetting, label: "Remember me" },
|
||||
() => { this.phoneEditor = "none"; clearEvenHubLoginForm(); },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -684,7 +683,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
this.phoneEditor = "none";
|
||||
if (this.closed) return;
|
||||
void this.runSearch(ctx, evenHubSearchQuerySetting.get());
|
||||
});
|
||||
}, undefined, () => { this.phoneEditor = "none"; });
|
||||
}
|
||||
|
||||
/** Close the phone editor if one is open (optionally only a given kind). */
|
||||
@@ -698,7 +697,17 @@ export class EvenHubStoreLayer implements Layer {
|
||||
const email = evenHubLoginEmailSetting.get();
|
||||
const password = evenHubLoginPasswordSetting.get();
|
||||
if (!email.trim() || !password) {
|
||||
this.enterLogin(ctx, "Email and password are required.");
|
||||
// A wholly empty submission (the keyboard's Done key on an untouched
|
||||
// form) is treated as a cancel and leaves the editor closed -- the login
|
||||
// pane still says how to get back in, and a click reopens the editor.
|
||||
// A half-filled form is a real mistake, so that still reopens with the
|
||||
// message.
|
||||
const cancelled = !email.trim() && !password;
|
||||
this.enterLogin(
|
||||
ctx,
|
||||
cancelled ? "Sign in to browse public apps." : "Email and password are required.",
|
||||
!cancelled,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.loginBusy = true;
|
||||
@@ -731,6 +740,42 @@ export class EvenHubStoreLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
/** A list row's title (with its shade) and dim detail line. */
|
||||
function 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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A registry entry dressed as a store record, for pages opened before the store record arrives. */
|
||||
function placeholderStoreApp(installed: InstalledEvenHubApp): EvenHubStoreApp {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { EvenHubManifest } from './ehpk';
|
||||
|
||||
/** Paths and a small manifest cross isolates; package bytes never become JSON. */
|
||||
export function unpackRuntime(path: string, directory: string): Promise<EvenHubManifest> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker('./package-extraction.worker');
|
||||
let settled = false;
|
||||
const finish = (error?: string, manifest?: EvenHubManifest) => {
|
||||
if (settled) return;
|
||||
settled = true; clearTimeout(timeout); worker.terminate();
|
||||
if (error) reject(new Error(error));
|
||||
else if (manifest) resolve(manifest);
|
||||
else reject(new Error('The package worker returned no manifest.'));
|
||||
};
|
||||
const timeout = setTimeout(() => finish('Unpacking the EvenHub app timed out.'), 180_000);
|
||||
worker.onmessage = (event: MessageEvent) => finish(event.data.error, event.data.manifest);
|
||||
worker.onerror = event => { finish(String(event.message ?? event)); return true; };
|
||||
try { worker.postMessage({ path, directory }); }
|
||||
catch (error) { finish(String(error)); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { extractPackage } from './package-extraction';
|
||||
import type { EvenHubManifest } from './ehpk';
|
||||
export async function unpackRuntime(path: string, directory: string): Promise<EvenHubManifest> {
|
||||
return extractPackage(path, directory);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { EVENHUB_BRIDGE_INJECT_SCRIPT, buildFaceclawExtensionsScript, type EvenHubSession } from './session'
|
||||
import { FACECLAW_VERSION } from '../../version'
|
||||
import type { EvenHubWebView } from './webview'
|
||||
declare const FaceclawEvenHubWebView: any
|
||||
|
||||
export const IOS_EVENHUB_TRANSPORT_SCRIPT = `
|
||||
window.__faceclawEvenHub = { postMessage: function(name, args, id) {
|
||||
window.webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:name, args:args, id:id});
|
||||
}};
|
||||
(function() {
|
||||
['log','warn','error'].forEach(function(level) {
|
||||
var original = console[level];
|
||||
console[level] = function() {
|
||||
original.apply(console, arguments);
|
||||
window.webkit.messageHandlers.faceclaw.postMessage({kind:'console', message:Array.prototype.map.call(arguments, String).join(' ').slice(0,4000)});
|
||||
};
|
||||
});
|
||||
window.addEventListener('error', function(e) { console.error(e.message); });
|
||||
window.addEventListener('unhandledrejection', function(e) { console.error(String(e.reason)); });
|
||||
})();
|
||||
`
|
||||
|
||||
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
|
||||
const host = FaceclawEvenHubWebView.new()
|
||||
host.packageIdentifier = session.manifest.packageId
|
||||
host.eventHandler = (json: string) => {
|
||||
try {
|
||||
const event = JSON.parse(json)
|
||||
if (event.kind === 'call' && typeof event.name === 'string' && typeof event.args === 'string' && Number.isSafeInteger(event.id))
|
||||
session.handleBridgeCall(event.name, event.args, event.id)
|
||||
else if (event.kind === 'loaded') session.webViewLoaded()
|
||||
else if (event.kind === 'error') session.webViewFailed(String(event.message))
|
||||
else if (event.kind === 'console') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
|
||||
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
|
||||
}
|
||||
// Defer loading until manager.ts has attached the session/window handles.
|
||||
const script = IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)
|
||||
const loading = setTimeout(() => {
|
||||
if (session.remoteUrl) host.startURLScript(session.remoteUrl, script)
|
||||
else host.startEntrypointScript(session.distDir, session.manifest.entrypoint, script)
|
||||
}, 0)
|
||||
return { native: host, evaluateJs: js => host.evaluate(js),
|
||||
destroy: () => { clearTimeout(loading); host.destroy() },
|
||||
showOnPhone: () => host.showOnPhone(), hideOnPhone: () => host.hideOnPhone() }
|
||||
}
|
||||
+88
-341
@@ -2,9 +2,10 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { truncateText, truncateLeft } from "../../graphics/textwrap";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { renderIcon, type IconName } from "../../graphics/icons";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
|
||||
import { iconGridMinRowHeight, tightRowHeight } from "../../ui/metrics";
|
||||
import { type MenuItem } from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { IconGrid, ICON_GRID_ICON_SIZE } from "../../ui/icon-grid";
|
||||
import { centeredTextY, tightRowHeight } from "../../ui/metrics";
|
||||
import { ConfigSettingEnum } from "../../ui/dashboard-settings";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import {
|
||||
@@ -15,21 +16,18 @@ import {
|
||||
statPath,
|
||||
type DirectoryEntry,
|
||||
} from "../../native/file-access";
|
||||
import { directionalFallback, isWatchInput, type InputEvent } from "../../ui/gestures";
|
||||
import { directionalFallback, type InputEvent } from "../../ui/gestures";
|
||||
import { Layer, type LayerContext } from "../../ui/layers";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
|
||||
const LIST_X = 20;
|
||||
/** List view: the selection box extends this far left and right of the row text. */
|
||||
const LIST_HIGHLIGHT_PAD = 6;
|
||||
|
||||
/** Header: one line holding both the title and the current path. */
|
||||
function headerHeight(font: UiFont): number {
|
||||
return 10 + font.lineHeight;
|
||||
}
|
||||
|
||||
const GRID_COLS = 5;
|
||||
const ICON_SIZE = 44;
|
||||
const LABEL_GAP = 2;
|
||||
|
||||
export type FilesViewMode = "icons" | "list";
|
||||
|
||||
export const filesViewModeSetting = new ConfigSettingEnum<FilesViewMode>({
|
||||
@@ -102,23 +100,14 @@ type EntryItem = {
|
||||
|
||||
type BrowserItem = { kind: "grant"; label: string } | { kind: "info"; label: string } | EntryItem;
|
||||
|
||||
type IconRow =
|
||||
| { kind: "special"; item: BrowserItem; flatIndex: number }
|
||||
| { kind: "grid"; items: EntryItem[]; firstIndex: number };
|
||||
|
||||
type IconMode = "row" | "item";
|
||||
|
||||
/**
|
||||
* Filesystem browser with two views. The top "Places" level lists bookmarks
|
||||
* and the storage roots; descending browses real directories. Icons view is a
|
||||
* 5-column grid with launcher-style two-level selection (scroll picks a row,
|
||||
* click drops into the row, scroll picks the item); list view is a flat list.
|
||||
* and the storage roots; descending browses real directories. Icons view is
|
||||
* the launcher's IconGrid (two-level ring selection, four-way watch
|
||||
* selection; notice rows span the full width); list view is a flat list.
|
||||
* Click descends into a directory or picks a supported file; double-click
|
||||
* backs out one level (item selection, then parent directory, then Places,
|
||||
* then leaving the browser). That is the ring's scheme; in icons view the
|
||||
* watch (see handleIconsWatchInput) skips row mode and moves one cell at a
|
||||
* time in four directions, exactly as in the launcher. Sized to its hosting
|
||||
* stack.
|
||||
* then leaving the browser). Sized to its hosting stack.
|
||||
*/
|
||||
export class FileBrowserLayer implements Layer {
|
||||
// Watch swipes are spatial in icons view: up/down move between rows,
|
||||
@@ -133,11 +122,26 @@ export class FileBrowserLayer implements Layer {
|
||||
private entries: DirectoryEntry[] | null = null;
|
||||
private listingFailed = false;
|
||||
|
||||
private listIndex = 0;
|
||||
private selectedRow = 0;
|
||||
private selectedCol = 0;
|
||||
private iconMode: IconMode = "row";
|
||||
private scrollRow = 0;
|
||||
/** List view. Both views index the same flatRows(), which is how setViewMode carries the selection across. */
|
||||
private readonly listMenu = new Menu<BrowserItem>({
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => this.drawListRow(args),
|
||||
});
|
||||
/** Icons view. */
|
||||
private readonly grid = new IconGrid<BrowserItem>({
|
||||
items: () => this.flatRows(),
|
||||
isWide: (item) => item.kind !== "entry",
|
||||
describe: (item, selected) =>
|
||||
item.kind === "entry"
|
||||
? { label: item.label, icon: gridIcon(item), labelValue: item.supported ? 210 : 100 }
|
||||
: { label: item.label, labelValue: itemValue(item, selected) },
|
||||
onActivate: (item, _index, ctx) => this.activateItem(item, ctx),
|
||||
onBack: () => this.navigateUp(),
|
||||
scrollbar: true,
|
||||
});
|
||||
|
||||
constructor(private readonly options: FileBrowserOptions) {}
|
||||
|
||||
@@ -145,7 +149,6 @@ export class FileBrowserLayer implements Layer {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const rows = this.flatRows();
|
||||
|
||||
image.drawText(font, 20, 8, "Files", 220);
|
||||
const pathLabel = this.location === null ? "Places" : this.location;
|
||||
@@ -153,97 +156,30 @@ export class FileBrowserLayer implements Layer {
|
||||
image.drawText(font, pathX, 8, truncateLeft(font, pathLabel, width - pathX - 20), 130);
|
||||
|
||||
if (filesViewModeSetting.get() === "list") {
|
||||
this.paintList(image, font, rows, ctx);
|
||||
this.paintList(image, font, ctx);
|
||||
} else {
|
||||
this.paintIcons(image, font, rows, ctx);
|
||||
const headerH = headerHeight(font);
|
||||
this.grid.paint(image, { x: 0, y: headerH, width, height: height - headerH - 6 }, ctx.stack.isFocused());
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private paintList(image: GrayImage, font: UiFont, rows: BrowserItem[], ctx: LayerContext): void {
|
||||
private paintList(image: GrayImage, font: UiFont, ctx: LayerContext): void {
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1));
|
||||
|
||||
const rowH = tightRowHeight(font);
|
||||
const headerH = headerHeight(font);
|
||||
const listHeight = height - headerH - 4;
|
||||
const visibleRows = Math.max(1, (listHeight / rowH) | 0);
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.listIndex, visibleRows, rows.length);
|
||||
|
||||
const lastVisible = Math.min(rows.length, this.scrollRow + visibleRows);
|
||||
for (let index = this.scrollRow; index < lastVisible; index++) {
|
||||
const row = rows[index]!;
|
||||
const y = headerH + (index - this.scrollRow) * rowH;
|
||||
const selected = index === this.listIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, LIST_X - 6, y - 1, width - 2 * LIST_X + 12, rowH - 1, ctx.stack.isFocused(), 4);
|
||||
}
|
||||
const value = itemValue(row, selected);
|
||||
image.drawText(font, LIST_X, y + 1, truncateText(font, row.label, width - 2 * LIST_X), value);
|
||||
}
|
||||
this.listMenu.setItems(this.flatRows());
|
||||
// Row boxes start one pixel above the header's bottom edge.
|
||||
this.listMenu.paint(
|
||||
image,
|
||||
{ x: LIST_X - LIST_HIGHLIGHT_PAD, y: headerH - 1, width: width - 2 * LIST_X + 2 * LIST_HIGHLIGHT_PAD, height: height - headerH - 4 },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
}
|
||||
|
||||
private paintIcons(image: GrayImage, font: UiFont, rows: BrowserItem[], ctx: LayerContext): void {
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const focused = ctx.stack.isFocused();
|
||||
const iconRows = buildIconRows(rows);
|
||||
this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1));
|
||||
|
||||
const gridTop = headerHeight(font);
|
||||
const gridBottom = height - 6;
|
||||
const visibleRows = Math.max(1, Math.floor((gridBottom - gridTop) / iconGridMinRowHeight(font, ICON_SIZE, LABEL_GAP)));
|
||||
const rowH = Math.floor((gridBottom - gridTop) / visibleRows);
|
||||
const colW = width / GRID_COLS;
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, visibleRows, iconRows.length);
|
||||
|
||||
const lastVisible = Math.min(iconRows.length, this.scrollRow + visibleRows);
|
||||
for (let rowIndex = this.scrollRow; rowIndex < lastVisible; rowIndex++) {
|
||||
const row = iconRows[rowIndex]!;
|
||||
const y = gridTop + (rowIndex - this.scrollRow) * rowH;
|
||||
const selected = rowIndex === this.selectedRow;
|
||||
|
||||
if (row.kind === "special") {
|
||||
const textY = y + (((rowH - font.lineHeight) / 2) | 0);
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, LIST_X - 6, textY - 2, width - 2 * LIST_X + 12, font.lineHeight + 4, focused, 4);
|
||||
}
|
||||
image.drawText(font, LIST_X, textY, truncateText(font, row.item.label, width - 2 * LIST_X), itemValue(row.item, selected));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (selected) {
|
||||
// Same preview rule as the launcher: while defocused with the watch
|
||||
// as the last-used source, show the cell a click would land on (watch
|
||||
// focus enters item mode directly; see onFocus) instead of a row band
|
||||
// the watch scheme never shows.
|
||||
const cellHighlight = this.iconMode === "item" || (!focused && shell.lastInputWasWatch());
|
||||
if (cellHighlight) {
|
||||
this.selectedCol = clamp(this.selectedCol, 0, row.items.length - 1);
|
||||
drawSelectionHighlight(image, this.selectedCol * colW + 4, y + 1, colW - 8, rowH - 2, focused, 6);
|
||||
} else {
|
||||
drawSelectionHighlight(image, 4, y + 1, width - 8, rowH - 2, focused, 6);
|
||||
}
|
||||
}
|
||||
|
||||
for (let col = 0; col < row.items.length; col++) {
|
||||
const item = row.items[col]!;
|
||||
const centerX = col * colW + colW / 2;
|
||||
const blockTop = y + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2);
|
||||
const icon = renderIcon(item.icon, ICON_SIZE);
|
||||
if (icon) {
|
||||
image.bitBlt(item.supported ? icon : dimmedIcon(item.icon, icon), Math.round(centerX - icon.width / 2), Math.round(blockTop), {
|
||||
transparentZero: true,
|
||||
});
|
||||
}
|
||||
const label = truncateText(font, item.label, colW - 8);
|
||||
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
|
||||
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, item.supported ? 210 : 100);
|
||||
}
|
||||
}
|
||||
|
||||
if (iconRows.length > visibleRows) {
|
||||
drawListScrollbar(image, width - 5, gridTop, visibleRows * rowH - 4, this.scrollRow, visibleRows, iconRows.length);
|
||||
}
|
||||
private drawListRow({ image, item, x, y, width, height, selected }: MenuDrawArgs<BrowserItem>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const label = truncateText(font, item.label, width - 2 * LIST_HIGHLIGHT_PAD);
|
||||
image.drawText(font, x + LIST_HIGHLIGHT_PAD, centeredTextY(font, y, height), label, itemValue(item, selected));
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
@@ -252,40 +188,24 @@ export class FileBrowserLayer implements Layer {
|
||||
// standard scroll / select / back meanings (the layer opted into
|
||||
// directional delivery for the icons view, so the stack won't).
|
||||
await this.handleListInput(directionalFallback(event), ctx);
|
||||
} else if (isWatchInput(event)) {
|
||||
await this.handleIconsWatchInput(event, ctx);
|
||||
} else {
|
||||
await this.handleIconsInput(event, ctx);
|
||||
await this.grid.handleInput(event, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus arriving from the watch goes straight to item selection, as in the
|
||||
* launcher: the watch has left/right swipes, so it never needs row mode.
|
||||
* Any other source keeps the two-level scheme and enters in row mode.
|
||||
*/
|
||||
onFocus(lastInput: InputEvent | null): void {
|
||||
if (filesViewModeSetting.get() !== "icons") return;
|
||||
if (lastInput && isWatchInput(lastInput)) {
|
||||
this.iconMode = "item";
|
||||
const iconRows = buildIconRows(this.flatRows());
|
||||
this.clampColToRow(iconRows[clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1))]);
|
||||
} else {
|
||||
this.iconMode = "row";
|
||||
}
|
||||
if (filesViewModeSetting.get() === "icons") this.grid.onFocus(lastInput);
|
||||
}
|
||||
|
||||
private async handleListInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
const rows = this.flatRows();
|
||||
this.listMenu.setItems(this.flatRows());
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
this.listIndex = Math.max(0, this.listIndex - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
this.listIndex = Math.min(Math.max(0, rows.length - 1), this.listIndex + 1);
|
||||
await this.listMenu.handleInput(event);
|
||||
return;
|
||||
case "click": {
|
||||
const row = rows[clamp(this.listIndex, 0, Math.max(0, rows.length - 1))];
|
||||
const row = this.listMenu.selectedItem;
|
||||
if (row) await this.activateItem(row, ctx);
|
||||
return;
|
||||
}
|
||||
@@ -297,147 +217,6 @@ export class FileBrowserLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
private async handleIconsInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
const rows = this.flatRows();
|
||||
const iconRows = buildIconRows(rows);
|
||||
this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1));
|
||||
const row = iconRows[this.selectedRow];
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
case "scroll-down": {
|
||||
const delta = event.type === "scroll-down" ? 1 : -1;
|
||||
if (this.iconMode === "item") {
|
||||
// Item selection traverses linearly: past a row's edge it continues
|
||||
// onto the adjacent row (a special row counts as a single item).
|
||||
if (row?.kind === "grid") {
|
||||
const next = clamp(this.selectedCol, 0, row.items.length - 1) + delta;
|
||||
if (next >= 0 && next < row.items.length) {
|
||||
this.selectedCol = next;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const adjacentIndex = this.selectedRow + delta;
|
||||
if (adjacentIndex < 0 || adjacentIndex >= iconRows.length) return;
|
||||
this.selectedRow = adjacentIndex;
|
||||
const adjacent = iconRows[adjacentIndex]!;
|
||||
if (adjacent.kind === "grid") {
|
||||
this.selectedCol = delta > 0 ? 0 : adjacent.items.length - 1;
|
||||
}
|
||||
} else {
|
||||
this.selectedRow = clamp(this.selectedRow + delta, 0, Math.max(0, iconRows.length - 1));
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "click": {
|
||||
if (!row) return;
|
||||
if (row.kind === "special") {
|
||||
await this.activateItem(row.item, ctx);
|
||||
return;
|
||||
}
|
||||
if (this.iconMode === "row") {
|
||||
this.iconMode = "item";
|
||||
// Default to the middle column (clamped to the row's item count).
|
||||
this.selectedCol = Math.min(Math.floor(GRID_COLS / 2), row.items.length - 1);
|
||||
} else {
|
||||
const item = row.items[clamp(this.selectedCol, 0, row.items.length - 1)];
|
||||
if (item) await this.activateItem(item, ctx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
if (this.iconMode === "item") {
|
||||
this.iconMode = "row";
|
||||
} else {
|
||||
this.navigateUp();
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch's scheme for the icons view — the launcher's: there is no row
|
||||
* mode, the selection is always one cell (a special row counts as its
|
||||
* single full-width item). Up/down (and the crown) move between rows
|
||||
* keeping the column, right/left move within the row, and left from the
|
||||
* leftmost column keeps going out — parent directory, Places, then the
|
||||
* sidebar. Row mode is restored on the way out so a ring user finds the
|
||||
* grid as they left it.
|
||||
*/
|
||||
private async handleIconsWatchInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
const iconRows = buildIconRows(this.flatRows());
|
||||
this.selectedRow = clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1));
|
||||
const row = iconRows[this.selectedRow];
|
||||
if (this.iconMode === "row") {
|
||||
this.iconMode = "item";
|
||||
this.clampColToRow(row);
|
||||
}
|
||||
switch (event.type) {
|
||||
case "swipe-up":
|
||||
case "swipe-down":
|
||||
case "scroll-up":
|
||||
case "scroll-down": {
|
||||
const delta = event.type === "swipe-down" || event.type === "scroll-down" ? 1 : -1;
|
||||
this.selectedRow = clamp(this.selectedRow + delta, 0, Math.max(0, iconRows.length - 1));
|
||||
// Keep the column; a shorter row (or a special one) clamps it.
|
||||
this.clampColToRow(iconRows[this.selectedRow]);
|
||||
return;
|
||||
}
|
||||
case "swipe-right":
|
||||
if (row?.kind === "grid") {
|
||||
this.selectedCol = clamp(this.selectedCol + 1, 0, row.items.length - 1);
|
||||
}
|
||||
return;
|
||||
case "swipe-left":
|
||||
if (row?.kind === "grid" && this.selectedCol > 0) {
|
||||
this.selectedCol--;
|
||||
} else {
|
||||
this.watchNavigateUp();
|
||||
}
|
||||
return;
|
||||
case "click": {
|
||||
if (!row) return;
|
||||
if (row.kind === "special") {
|
||||
await this.activateItem(row.item, ctx);
|
||||
} else {
|
||||
const item = row.items[clamp(this.selectedCol, 0, row.items.length - 1)];
|
||||
if (item) await this.activateItem(item, ctx);
|
||||
}
|
||||
// Descending into a directory resets the selection for the ring (row
|
||||
// mode at the top); the watch scheme stays in single-item selection.
|
||||
this.iconMode = "item";
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
this.watchNavigateUp();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private clampColToRow(row: IconRow | undefined): void {
|
||||
if (row?.kind === "grid") {
|
||||
this.selectedCol = clamp(this.selectedCol, 0, row.items.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* navigateUp for the watch scheme: inside the browser the selection stays
|
||||
* in item mode (resetSelection/selectPath put it back in row mode for the
|
||||
* ring); leaving from Places restores row mode on the way out.
|
||||
*/
|
||||
private watchNavigateUp(): void {
|
||||
if (this.location === null) {
|
||||
this.iconMode = "row";
|
||||
this.options.onLeave();
|
||||
return;
|
||||
}
|
||||
this.navigateUp();
|
||||
this.iconMode = "item";
|
||||
}
|
||||
|
||||
/**
|
||||
* App-specific entries for the window long-press menu: the view switch,
|
||||
* plus bookmark/unbookmark for the selected entry (in icons view only once
|
||||
@@ -461,8 +240,7 @@ export class FileBrowserLayer implements Layer {
|
||||
label: isBookmarked(path) ? `Remove bookmark: ${name}` : `Bookmark: ${name}`,
|
||||
onSelect: (ctx) => {
|
||||
toggleBookmark(path);
|
||||
const rows = this.flatRows();
|
||||
this.listIndex = clamp(this.listIndex, 0, Math.max(0, rows.length - 1));
|
||||
this.listMenu.setItems(this.flatRows());
|
||||
ctx.stack.pop();
|
||||
},
|
||||
});
|
||||
@@ -475,34 +253,27 @@ export class FileBrowserLayer implements Layer {
|
||||
const rows = this.flatRows();
|
||||
if (!rows.length) return null;
|
||||
if (filesViewModeSetting.get() === "list") {
|
||||
return rows[clamp(this.listIndex, 0, rows.length - 1)] ?? null;
|
||||
this.listMenu.setItems(rows);
|
||||
return this.listMenu.selectedItem;
|
||||
}
|
||||
const iconRows = buildIconRows(rows);
|
||||
const row = iconRows[clamp(this.selectedRow, 0, iconRows.length - 1)];
|
||||
if (!row) return null;
|
||||
if (row.kind === "special") return row.item;
|
||||
if (this.iconMode !== "item") return null;
|
||||
return row.items[clamp(this.selectedCol, 0, row.items.length - 1)] ?? null;
|
||||
return this.grid.selectedItem;
|
||||
}
|
||||
|
||||
private setViewMode(mode: FilesViewMode): void {
|
||||
if (filesViewModeSetting.get() === mode) return;
|
||||
const rows = this.flatRows();
|
||||
const iconRows = buildIconRows(rows);
|
||||
this.listMenu.setItems(this.flatRows());
|
||||
if (mode === "list") {
|
||||
// Carry the icon-grid selection into the flat list (clamped column when
|
||||
// only a row was selected).
|
||||
const row = iconRows[clamp(this.selectedRow, 0, Math.max(0, iconRows.length - 1))];
|
||||
if (row) {
|
||||
this.listIndex =
|
||||
row.kind === "special" ? row.flatIndex : row.firstIndex + clamp(this.selectedCol, 0, row.items.length - 1);
|
||||
}
|
||||
// Carry the icon-grid selection into the flat list (the remembered
|
||||
// column when only a row was selected).
|
||||
const index = this.grid.cursorIndex;
|
||||
if (index !== null) this.listMenu.select(index);
|
||||
} else {
|
||||
this.setGridSelectionFromFlatIndex(rows, clamp(this.listIndex, 0, Math.max(0, rows.length - 1)));
|
||||
this.iconMode = "row";
|
||||
const index = this.listMenu.selectedIndex ?? 0;
|
||||
this.grid.resetSelection();
|
||||
this.grid.selectIndex(index);
|
||||
}
|
||||
filesViewModeSetting.set(mode);
|
||||
this.scrollRow = 0;
|
||||
this.listMenu.scrollTop = 0;
|
||||
}
|
||||
|
||||
private async activateItem(item: BrowserItem, ctx: LayerContext): Promise<void> {
|
||||
@@ -528,11 +299,12 @@ export class FileBrowserLayer implements Layer {
|
||||
this.resetSelection();
|
||||
}
|
||||
|
||||
private navigateUp(): void {
|
||||
/** Back out one level; true when that left the browser (from Places). */
|
||||
private navigateUp(): boolean {
|
||||
const from = this.location;
|
||||
if (from === null) {
|
||||
this.options.onLeave();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
if (from === this.navRoot || from === "/") {
|
||||
this.location = null;
|
||||
@@ -540,19 +312,18 @@ export class FileBrowserLayer implements Layer {
|
||||
this.resetSelection();
|
||||
this.selectPath(this.navRoot ?? from);
|
||||
this.navRoot = null;
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
const parentRaw = from.slice(0, from.lastIndexOf("/"));
|
||||
this.navigateTo(parentRaw.length ? parentRaw : "/");
|
||||
this.selectPath(from);
|
||||
return false;
|
||||
}
|
||||
|
||||
private resetSelection(): void {
|
||||
this.listIndex = 0;
|
||||
this.selectedRow = 0;
|
||||
this.selectedCol = 0;
|
||||
this.iconMode = "row";
|
||||
this.scrollRow = 0;
|
||||
this.listMenu.select(0);
|
||||
this.listMenu.scrollTop = 0;
|
||||
this.grid.resetSelection();
|
||||
}
|
||||
|
||||
/** Select the item with the given path (e.g. the directory just left). */
|
||||
@@ -560,33 +331,25 @@ export class FileBrowserLayer implements Layer {
|
||||
const rows = this.flatRows();
|
||||
const index = rows.findIndex((row) => row.kind === "entry" && row.entry.path === path);
|
||||
if (index < 0) return;
|
||||
this.listIndex = index;
|
||||
this.setGridSelectionFromFlatIndex(rows, index);
|
||||
}
|
||||
|
||||
private setGridSelectionFromFlatIndex(rows: BrowserItem[], index: number): void {
|
||||
const specials = leadingSpecialCount(rows);
|
||||
if (index < specials) {
|
||||
this.selectedRow = index;
|
||||
this.selectedCol = 0;
|
||||
return;
|
||||
}
|
||||
const ordinal = index - specials;
|
||||
this.selectedRow = specials + Math.floor(ordinal / GRID_COLS);
|
||||
this.selectedCol = ordinal % GRID_COLS;
|
||||
// Items first, then the selection, so the viewport scrolls minimally from the top.
|
||||
this.listMenu.setItems(rows);
|
||||
this.listMenu.select(index);
|
||||
this.grid.selectIndex(index);
|
||||
}
|
||||
|
||||
private flatRows(): BrowserItem[] {
|
||||
const rows: BrowserItem[] = [];
|
||||
if (!hasAllFilesAccess()) {
|
||||
rows.push({ kind: "grant", label: "Grant file access (opens phone Settings)" });
|
||||
}
|
||||
if (this.location === null) {
|
||||
// Only on Places: without All Files access some folders (e.g. Download)
|
||||
// may still be readable, and the prompt shouldn't crowd their listings.
|
||||
if (!hasAllFilesAccess()) {
|
||||
rows.push({ kind: "grant", label: "Grant file access (opens phone Settings)" });
|
||||
}
|
||||
for (const path of getBookmarkedPaths()) {
|
||||
rows.push(this.bookmarkItem(path));
|
||||
}
|
||||
rows.push(this.placeItem("Internal storage", externalStorageRootPath()));
|
||||
rows.push(this.placeItem("/", "/"));
|
||||
rows.push(this.placeItem(global.isIOS ? "Faceclaw documents" : "Internal storage", externalStorageRootPath()));
|
||||
if (!global.isIOS) rows.push(this.placeItem("/", "/"));
|
||||
return rows;
|
||||
}
|
||||
this.loadEntries();
|
||||
@@ -654,27 +417,6 @@ export class FileBrowserLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
function buildIconRows(flat: BrowserItem[]): IconRow[] {
|
||||
const rows: IconRow[] = [];
|
||||
let index = 0;
|
||||
// Special rows (grant prompt, empty/unreadable info) lead the list; each
|
||||
// gets a full-width row of its own. Entries follow, chunked into grid rows.
|
||||
while (index < flat.length && flat[index]!.kind !== "entry") {
|
||||
rows.push({ kind: "special", item: flat[index]!, flatIndex: index });
|
||||
index++;
|
||||
}
|
||||
for (; index < flat.length; index += GRID_COLS) {
|
||||
rows.push({ kind: "grid", items: flat.slice(index, index + GRID_COLS) as EntryItem[], firstIndex: index });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function leadingSpecialCount(rows: BrowserItem[]): number {
|
||||
let count = 0;
|
||||
while (count < rows.length && rows[count]!.kind !== "entry") count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
function itemValue(item: BrowserItem, selected: boolean): number {
|
||||
if (item.kind === "info") return 120;
|
||||
if (item.kind === "grant") return selected ? 255 : 210;
|
||||
@@ -682,6 +424,11 @@ function itemValue(item: BrowserItem, selected: boolean): number {
|
||||
return selected ? 255 : 200;
|
||||
}
|
||||
|
||||
function gridIcon(item: EntryItem): GrayImage | null {
|
||||
const icon = renderIcon(item.icon, ICON_GRID_ICON_SIZE);
|
||||
return icon && !item.supported ? dimmedIcon(item.icon, icon) : icon;
|
||||
}
|
||||
|
||||
// Unsupported files draw their grid icon at half brightness; rendered once
|
||||
// per icon name and cached (all grid icons share one size).
|
||||
const dimmedIconCache = new Map<IconName, GrayImage>();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { wrapText } from "../../graphics/textwrap";
|
||||
import type { DirectoryEntry } from "../../native/file-access";
|
||||
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
|
||||
import { drawSelectionHighlight } from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
|
||||
|
||||
const DIALOG_X = 8;
|
||||
@@ -25,12 +25,21 @@ export type FileInfoAction = {
|
||||
* double-click closes it.
|
||||
*/
|
||||
export class FileInfoDialogLayer implements Layer {
|
||||
private selectedIndex = 0;
|
||||
private readonly menu: Menu<FileInfoAction>;
|
||||
|
||||
constructor(
|
||||
private readonly entry: DirectoryEntry,
|
||||
private readonly actions: FileInfoAction[],
|
||||
) {}
|
||||
) {
|
||||
this.menu = new Menu<FileInfoAction>({
|
||||
items: actions,
|
||||
wrap: true,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 8 },
|
||||
getHeight: () => listRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => drawActionRow(args),
|
||||
});
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
@@ -69,32 +78,23 @@ export class FileInfoDialogLayer implements Layer {
|
||||
image.drawText(font, DIALOG_X + PADDING + 2, y + 3, `${GESTURE_DOUBLE_CLICK} close`, 110);
|
||||
return image;
|
||||
}
|
||||
const focused = ctx.stack.isFocused();
|
||||
for (let index = 0; index < this.actions.length; index++) {
|
||||
const rowY = y + index * rowH;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, DIALOG_X + 12, rowY, DIALOG_WIDTH - 24, rowH - 1, focused, 8);
|
||||
}
|
||||
image.drawText(font, DIALOG_X + 22, rowY + LIST_ROW_TEXT_INSET, this.actions[index]!.label, selected ? 255 : 200);
|
||||
}
|
||||
// The rows fill the rest of the dialog (and scroll if a clamped dialog is too short).
|
||||
this.menu.paint(
|
||||
image,
|
||||
{ x: DIALOG_X + 12, y, width: DIALOG_WIDTH - 24, height: Math.max(0, DIALOG_Y + height - PADDING - y) },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
if (this.actions.length) {
|
||||
this.selectedIndex = (this.selectedIndex + this.actions.length - 1) % this.actions.length;
|
||||
}
|
||||
return;
|
||||
case "scroll-down":
|
||||
if (this.actions.length) {
|
||||
this.selectedIndex = (this.selectedIndex + 1) % this.actions.length;
|
||||
}
|
||||
await this.menu.handleInput(event);
|
||||
return;
|
||||
case "click":
|
||||
await this.actions[this.selectedIndex]?.onSelect(ctx);
|
||||
await this.menu.selectedItem?.onSelect(ctx);
|
||||
return;
|
||||
case "double-click":
|
||||
ctx.stack.pop();
|
||||
@@ -105,6 +105,10 @@ export class FileInfoDialogLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
function drawActionRow({ image, item, x, y, selected }: MenuDrawArgs<FileInfoAction>): void {
|
||||
image.drawText(getDefaultSmallFont(), x + 10, y + LIST_ROW_TEXT_INSET, item.label, selected ? 255 : 200);
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
|
||||
@@ -45,7 +45,7 @@ export type FilesAppOptions = InProcessAppOptions & {
|
||||
export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow {
|
||||
let created: InProcessWindow | null = null;
|
||||
const browser = new FileBrowserLayer({
|
||||
isSupportedFile: (name) => TEXT_FILE.test(name) || isDecodableImageFile(name) || EHPK_FILE.test(name) || isFontFile(name),
|
||||
isSupportedFile: (name) => TEXT_FILE.test(name) || isFontFile(name) || EHPK_FILE.test(name) || (!global.isIOS && isDecodableImageFile(name)),
|
||||
// The browser handles double-click itself (up a level), so it is not
|
||||
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
|
||||
onLeave: () => shell.yieldFocusToSidebar(),
|
||||
@@ -170,6 +170,7 @@ function confirmEhpkPermissions(ctx: LayerContext, entry: DirectoryEntry, procee
|
||||
* window for viewable types, empty for everything else (metadata only).
|
||||
*/
|
||||
function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileInfoAction[] {
|
||||
if (global.isIOS && !TEXT_FILE.test(entry.name) && !isFontFile(entry.name) && !EHPK_FILE.test(entry.name)) return [];
|
||||
if (TEXT_FILE.test(entry.name)) {
|
||||
return [
|
||||
{
|
||||
@@ -191,7 +192,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
|
||||
];
|
||||
}
|
||||
if (EHPK_FILE.test(entry.name)) {
|
||||
return [
|
||||
const actions: FileInfoAction[] = [
|
||||
{
|
||||
label: "Run app",
|
||||
onSelect: (ctx) => {
|
||||
@@ -209,6 +210,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
|
||||
},
|
||||
},
|
||||
];
|
||||
return actions;
|
||||
}
|
||||
if (isDecodableImageFile(entry.name)) {
|
||||
return [
|
||||
|
||||
@@ -27,7 +27,7 @@ const PARAGRAPH =
|
||||
|
||||
/**
|
||||
* Font previewer for a font file on disk (TTF/OTF/TTC), rendered through the
|
||||
* Android text stack: a single-line pangram, a character-set sample, and a
|
||||
* native text stack: a single-line pangram, a character-set sample, and a
|
||||
* wrapped paragraph, all at an adjustable pixel size. Scroll changes size,
|
||||
* click cycles the coverage gamma (for judging antialiasing on the lens),
|
||||
* double-click closes. Sized to its hosting stack (a Files document window,
|
||||
|
||||
@@ -64,6 +64,7 @@ const filesApp: AppDefinition = {
|
||||
openEhpkApp: (path) => {
|
||||
void openEvenHubPackage(ctx, path).catch((error) => {
|
||||
ctx.appendLog(`evenhub launch failed: ${error}`);
|
||||
openTextDocumentWindow(ctx, 'Could not run app', String(error));
|
||||
});
|
||||
},
|
||||
installEhpkApp: async (path) => {
|
||||
|
||||
@@ -18,19 +18,21 @@
|
||||
* small and rare.
|
||||
*
|
||||
* Controls (a watch swipe in either direction is the primary flap):
|
||||
* swipe-up, swipe-down, click, or scroll-up flaps; double-click pauses;
|
||||
* ring-press flaps immediately; watch swipes/clicks also flap. Double-click pauses;
|
||||
* tap-then-hold opens the window menu. Ready / paused / game over: click or
|
||||
* a swipe starts or resumes, double-click yields focus. Losing input focus
|
||||
* mid-flight (a shell overlay such as the system menu or a notification,
|
||||
* focus to the sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
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 { playWorkerBuzzerSequence } from "../../native/worker-buzzer";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
|
||||
@@ -64,7 +66,6 @@ import {
|
||||
} from "./flappy-sprites";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
@@ -180,6 +181,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FlappyWindow = {
|
||||
windowId: message.windowId,
|
||||
@@ -311,7 +318,7 @@ function saveHighScore(window: FlappyWindow): void {
|
||||
|
||||
/**
|
||||
* Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the
|
||||
* steps on its own timer, and the Java call is safe from the worker thread.
|
||||
* steps on its own timer; the platform bridge routes it from the worker.
|
||||
* Minor (frequent) effects are dropped when they'd arrive within the
|
||||
* rate-limit gap; newsworthy ones always play.
|
||||
*/
|
||||
@@ -321,9 +328,7 @@ function playSfx(window: FlappyWindow, steps: Step[], minor = false): void {
|
||||
if (minor && now - window.lastMinorSfxAtMs < MINOR_SFX_MIN_GAP_MS) return;
|
||||
if (minor) window.lastMinorSfxAtMs = now;
|
||||
try {
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) return;
|
||||
communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer);
|
||||
playWorkerBuzzerSequence(buildSoundSequencePayload(steps));
|
||||
} catch (error) {
|
||||
console.warn(`flappy sfx failed: ${error}`);
|
||||
}
|
||||
@@ -412,10 +417,16 @@ function handleFlightInput(window: FlappyWindow, event: InputEvent, frameId: num
|
||||
// which way the thumb went shouldn't matter.
|
||||
case "swipe-up":
|
||||
case "swipe-down":
|
||||
case "click":
|
||||
case "scroll-up":
|
||||
case "ring-press":
|
||||
flap(window);
|
||||
break;
|
||||
case "click":
|
||||
// The ring already flapped on down; its later click must not flap again.
|
||||
if (event.source !== "ring") flap(window);
|
||||
break;
|
||||
case "scroll-up":
|
||||
if (event.source === "watch") flap(window);
|
||||
break;
|
||||
case "double-click":
|
||||
if (window.phase === "playing") {
|
||||
window.phase = "paused";
|
||||
@@ -698,7 +709,7 @@ function paintHud(image: GrayImage, window: FlappyWindow): void {
|
||||
if (window.highScore > 0) {
|
||||
drawCenteredIn(image, smallFont, 0, width, 44, `best ${window.highScore}`, 150);
|
||||
}
|
||||
drawCenteredIn(image, smallFont, 0, width, groundTop(window) - 26, `swipe / ${GESTURE_CLICK} flap`, 150);
|
||||
drawCenteredIn(image, smallFont, 0, width, groundTop(window) - 26, "Touch ring / swipe to flap", 150);
|
||||
break;
|
||||
case "paused":
|
||||
paintDialog(image, window, "PAUSED", [`${GESTURE_CLICK} resume`, `${GESTURE_DOUBLE_CLICK} leave`]);
|
||||
@@ -757,17 +768,19 @@ function renderAndSubmit(window: FlappyWindow, inputFrameId: number): void {
|
||||
}
|
||||
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)),
|
||||
frameTimings.span(frameId, "submitSurfaceFrame", () =>
|
||||
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) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
* Safe cards auto-play to the foundations after every move.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -25,6 +26,7 @@ import { getFont } from "../../graphics/bdffont";
|
||||
import { ensurePreinstalledFonts, installedFontPath } from "../../graphics/installed-fonts";
|
||||
import { TtfFont } from "../../graphics/ttf-font";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import { playWorkerBuzzerSequence } from "../../native/worker-buzzer";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
|
||||
import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting";
|
||||
@@ -34,7 +36,6 @@ import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-win
|
||||
import { directionalFallback, GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_LONG_PRESS, type InputEvent } from "../../ui/gestures";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
ensurePreinstalledFonts();
|
||||
const fontPath = installedFontPath("Roboto-Regular.ttf");
|
||||
@@ -144,6 +145,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FreecellWindow = {
|
||||
windowId: message.windowId,
|
||||
@@ -206,14 +213,12 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
|
||||
/**
|
||||
* Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the
|
||||
* steps on its own timer, and the Java call is safe from the worker thread.
|
||||
* steps on its own timer; the platform bridge routes it from the worker.
|
||||
*/
|
||||
function playSfx(window: FreecellWindow, steps: Step[]): void {
|
||||
if (!window.soundOn || steps.length === 0) return;
|
||||
try {
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) return;
|
||||
communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer);
|
||||
playWorkerBuzzerSequence(buildSoundSequencePayload(steps));
|
||||
} catch (error) {
|
||||
console.warn(`freecell sfx failed: ${error}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getStringSetting } from "../../native/settings-store";
|
||||
import { QUADRANT_LAYOUT, SIX_SLOT_LAYOUT } from "./layout";
|
||||
|
||||
/** Configuration-only query usable by workers without loading widget/UI modules. */
|
||||
export function isTerminalWidgetConfigured(): boolean {
|
||||
const layout = getStringSetting("glanceboard.layout", "2x2") === "2x3" ? SIX_SLOT_LAYOUT : QUADRANT_LAYOUT;
|
||||
// Both layouts store their slots under the original quadrants key. None
|
||||
// of the default slots needs a worker, so absent keys cannot retain one.
|
||||
return layout.slots.some((_, index) =>
|
||||
getStringSetting(`glanceboard.${QUADRANT_LAYOUT.id}.slot.${index}`, "none") === "terminal");
|
||||
}
|
||||
@@ -3,15 +3,17 @@ import { truncateText, wrapText } from "../../graphics/textwrap";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { enumSettingMenuItem, onAnySettingChanged, toggleSettingMenuItem } from "../../ui/dashboard-settings";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
|
||||
import { drawSelectionHighlight, MenuLayer, openModalMenu, type MenuItem } from "../../ui/menu";
|
||||
import { LIST_ROW_TEXT_INSET, lineStep } from "../../ui/metrics";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, type MenuItem } from "../../ui/menu";
|
||||
import { Menu } from "../../ui/menu-core";
|
||||
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 { GlanceBoard } from "./board";
|
||||
import {
|
||||
clearConflictingSlots,
|
||||
glanceboardEnabledSetting,
|
||||
glanceDepthSetting,
|
||||
glanceLayout,
|
||||
glanceLayoutSetting,
|
||||
glanceShowLinesSetting,
|
||||
@@ -35,6 +37,15 @@ const PARAGRAPH_X = 24;
|
||||
const PREVIEW_MARGIN = 8;
|
||||
const PREVIEW_MIN_LINE_VALUE = 20;
|
||||
const PREVIEW_LINE_VALUE = 100;
|
||||
/** The entry menu's row boxes: left inset, gap below the paragraph, and inset from the page's bottom. */
|
||||
const HOME_MENU_X = 20;
|
||||
const HOME_MENU_TOP_GAP = 12;
|
||||
const HOME_MENU_BOTTOM_MARGIN = 8;
|
||||
/** Horizontal inset of row text (and custom row content) from its selection box. */
|
||||
const HOME_ROW_TEXT_X = 10;
|
||||
// A throwaway menu to satisfy MenuItem.onSelect's second parameter; the
|
||||
// entry page's items never use it (they act via ctx only).
|
||||
const NO_MENU = new MenuLayer(null, []);
|
||||
|
||||
const INTRO =
|
||||
"Your Glanceboard is a display for things you want to look at quickly. Starting " +
|
||||
@@ -55,25 +66,21 @@ function pageMenuLayout(width: number) {
|
||||
* a double-tap returns focus to the menu.
|
||||
*/
|
||||
class GlanceboardHomeLayer implements Layer {
|
||||
private menu: MenuLayer | null = null;
|
||||
private menuTop = 0;
|
||||
private menuHeight = 0;
|
||||
private readonly menu: Menu<MenuItem>;
|
||||
private focus: "menu" | "preview" = "menu";
|
||||
private selectedSlot = 0;
|
||||
/** The context of the paint in progress, handed to item render callbacks. */
|
||||
private paintCtx: LayerContext | null = null;
|
||||
|
||||
constructor(private readonly setPreviewVisible: (visible: boolean) => void) {}
|
||||
|
||||
private currentMenu(ctx: LayerContext, menuTop: number): MenuLayer {
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
if (!this.menu || this.menuTop !== menuTop || this.menuHeight !== height) {
|
||||
const half = (width / 2) | 0;
|
||||
const items: MenuItem[] = [
|
||||
constructor(private readonly setPreviewVisible: (visible: boolean) => void) {
|
||||
this.menu = new Menu<MenuItem>({
|
||||
items: [
|
||||
toggleSettingMenuItem(glanceboardEnabledSetting),
|
||||
{
|
||||
label: "Preview",
|
||||
onSelect: (menuCtx) => {
|
||||
menuCtx.stack.push(new GlancePreviewLayer(
|
||||
() => menuCtx.actions.requestRender(),
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new GlancePreviewLayer(
|
||||
() => ctx.actions.requestRender(),
|
||||
() => this.setPreviewVisible(false),
|
||||
));
|
||||
this.setPreviewVisible(true);
|
||||
@@ -87,17 +94,32 @@ class GlanceboardHomeLayer implements Layer {
|
||||
},
|
||||
{
|
||||
label: "Settings",
|
||||
onSelect: (menuCtx) => menuCtx.stack.push(new GlanceSettingsLayer()),
|
||||
onSelect: openGlanceSettings,
|
||||
},
|
||||
];
|
||||
this.menuTop = menuTop;
|
||||
this.menuHeight = height;
|
||||
this.menu = new MenuLayer(null, items, {
|
||||
x: 8, y: menuTop, width: half - 16,
|
||||
showBorder: false, minHeight: 0, maxHeight: height - menuTop,
|
||||
});
|
||||
}
|
||||
return this.menu;
|
||||
],
|
||||
wrap: true,
|
||||
rowGap: 1,
|
||||
getHeight: () => listRowHeight(getDefaultSmallFont()),
|
||||
draw: ({ image, item, x, y, width, height, selected }) => {
|
||||
const disabled = isMenuItemDisabled(item);
|
||||
if (item.render) {
|
||||
item.render({
|
||||
image,
|
||||
x: x + HOME_ROW_TEXT_X,
|
||||
y,
|
||||
width: width - 2 * HOME_ROW_TEXT_X,
|
||||
height: height - 2,
|
||||
selected,
|
||||
disabled,
|
||||
text: item.label,
|
||||
ctx: this.paintCtx!,
|
||||
});
|
||||
} else {
|
||||
image.drawText(getDefaultSmallFont(), x + HOME_ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label,
|
||||
disabled ? 70 : selected ? 255 : 200);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Where the scaled board sits: the right half, board aspect, vertically centred. */
|
||||
@@ -128,13 +150,19 @@ class GlanceboardHomeLayer implements Layer {
|
||||
image.drawText(font, PARAGRAPH_X, y, line, 160);
|
||||
y += step;
|
||||
}
|
||||
// The menu paints onto this page below the paragraph (its fill is raster,
|
||||
// so the deferred paragraph glyphs above stay untouched either way).
|
||||
// While the preview has focus the menu keeps its outline-only selection.
|
||||
const menu = this.currentMenu(ctx, y + 4);
|
||||
const menuFocused = ctx.stack.isFocused() && this.focus === "menu";
|
||||
const menuCtx: LayerContext = { ...ctx, stack: Object.assign(Object.create(ctx.stack), { isFocused: () => menuFocused }) };
|
||||
menu.paint(menuCtx, () => image);
|
||||
// The menu sits below the paragraph in the left half. While the preview
|
||||
// has focus the menu keeps its outline-only selection.
|
||||
const menuTop = y + HOME_MENU_TOP_GAP;
|
||||
const menuWidth = half - 2 * HOME_MENU_X;
|
||||
const menuHeight = Math.max(0, height - menuTop - HOME_MENU_BOTTOM_MARGIN);
|
||||
this.paintCtx = ctx;
|
||||
try {
|
||||
this.menu.paint(image, { x: HOME_MENU_X, y: menuTop, width: menuWidth, height: menuHeight },
|
||||
ctx.stack.isFocused() && this.focus === "menu");
|
||||
} finally {
|
||||
this.paintCtx = null;
|
||||
}
|
||||
this.menu.drawScrollbar(image, HOME_MENU_X + menuWidth + 5, menuTop, menuHeight - 4);
|
||||
|
||||
this.selectedSlot = Math.min(this.selectedSlot, glanceLayout().slots.length - 1);
|
||||
const preview = this.previewRect(width, height);
|
||||
@@ -173,7 +201,12 @@ class GlanceboardHomeLayer implements Layer {
|
||||
shell.yieldFocusToSidebar();
|
||||
return;
|
||||
}
|
||||
await this.currentMenu(ctx, this.menuTop).handleInput(event, ctx);
|
||||
if (event.type === "click") {
|
||||
const item = this.menu.selectedItem;
|
||||
if (item && !isMenuItemDisabled(item)) await item.onSelect(ctx, NO_MENU);
|
||||
return;
|
||||
}
|
||||
await this.menu.handleInput(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,32 +298,17 @@ function openSlotPicker(ctx: LayerContext, slotIndex: number): void {
|
||||
openModalMenu(ctx, setting.label, items, Math.max(0, setting.values.indexOf(current)));
|
||||
}
|
||||
|
||||
/** Settings: layout, sleep gestures, duration, and slot lines. */
|
||||
class GlanceSettingsLayer implements Layer {
|
||||
private menu: MenuLayer | null = null;
|
||||
|
||||
private currentMenu(ctx: LayerContext): MenuLayer {
|
||||
if (!this.menu) {
|
||||
const { width } = ctx.stack.getBaseSize();
|
||||
const items: MenuItem[] = [
|
||||
enumSettingMenuItem(glanceLayoutSetting),
|
||||
enumSettingMenuItem(glanceTapDurationSetting),
|
||||
toggleSettingMenuItem(glanceShowOnLongPressSetting),
|
||||
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
|
||||
toggleSettingMenuItem(glanceShowLinesSetting),
|
||||
];
|
||||
this.menu = new MenuLayer("Glanceboard settings", items, pageMenuLayout(width));
|
||||
}
|
||||
return this.menu;
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
|
||||
return this.currentMenu(ctx).paint(ctx, paintBelow);
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
await this.currentMenu(ctx).handleInput(event, ctx);
|
||||
}
|
||||
/** Settings: layout, sleep gestures, duration, slot lines, and stereo depth. */
|
||||
function openGlanceSettings(ctx: LayerContext): void {
|
||||
const items: MenuItem[] = [
|
||||
enumSettingMenuItem(glanceLayoutSetting),
|
||||
enumSettingMenuItem(glanceTapDurationSetting),
|
||||
toggleSettingMenuItem(glanceShowOnLongPressSetting),
|
||||
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
|
||||
toggleSettingMenuItem(glanceShowLinesSetting),
|
||||
enumSettingMenuItem(glanceDepthSetting),
|
||||
];
|
||||
ctx.stack.push(new MenuLayer("Glanceboard settings", items, pageMenuLayout(ctx.stack.getBaseSize().width)));
|
||||
}
|
||||
|
||||
/** The live board in the window; any click or double-click returns to the list. */
|
||||
|
||||
@@ -104,6 +104,31 @@ export const glanceShowOnHeadTiltSetting = new ConfigSettingBoolean({
|
||||
description: "Tilting your head up while asleep shows the Glanceboard instead of waking the regular UI.",
|
||||
});
|
||||
|
||||
const DEPTH_VALUES = ["-64", "-48", "-32", "-16", "0", "16", "32", "48", "64"] as const;
|
||||
export type GlanceDepth = (typeof DEPTH_VALUES)[number];
|
||||
|
||||
/**
|
||||
* Stereo depth of the board, in the firmware's depth units: the lenses shift
|
||||
* it by half this many pixels each, in opposite directions.
|
||||
*/
|
||||
export const glanceDepthSetting = new ConfigSettingEnum<GlanceDepth>({
|
||||
id: "glanceboard-depth",
|
||||
label: "Depth",
|
||||
storageKey: "glanceboard.depth",
|
||||
defaultValue: "0",
|
||||
values: DEPTH_VALUES,
|
||||
formatValue: (value) => {
|
||||
const depth = Number(value);
|
||||
return depth === 0 ? "0" : depth > 0 ? `+${depth} (nearer)` : `${depth} (farther)`;
|
||||
},
|
||||
description:
|
||||
"Moves the Glanceboard nearer (positive) or farther away (negative) by shifting it in opposite directions on the two lenses.",
|
||||
});
|
||||
|
||||
export function glanceDepth(): number {
|
||||
return Number(glanceDepthSetting.get());
|
||||
}
|
||||
|
||||
/** Hairlines between the board's slots. */
|
||||
export const glanceShowLinesSetting = new ConfigSettingBoolean({
|
||||
id: "glanceboard-show-lines",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { GlanceBoard } from "./board";
|
||||
import { createGlanceboardAppWindow, GLANCEBOARD_SURFACE_ID, GLANCEBOARD_WINDOW_ID } from "./glanceboard-app";
|
||||
import {
|
||||
glanceboardEnabledSetting,
|
||||
glanceDepth,
|
||||
glanceLayout,
|
||||
glanceShowOnHeadTiltSetting,
|
||||
glanceShowOnLongPressSetting,
|
||||
@@ -25,6 +26,7 @@ const glanceboardApp: AppDefinition = {
|
||||
tapTimeoutMs: glanceTapTimeoutMs,
|
||||
showOnLongPress: () => glanceShowOnLongPressSetting.get(),
|
||||
showOnHeadTilt: () => glanceShowOnHeadTiltSetting.get(),
|
||||
depth: glanceDepth,
|
||||
createBoard: (requestRender) => new GlanceBoard(requestRender),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { type GrayImage, type UiFont } from "../../../graphics/image";
|
||||
import { truncateText } from "../../../graphics/textwrap";
|
||||
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
|
||||
import { hasCalendarPermission } from "../../../g2/android-permissions";
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../../../native/calendar";
|
||||
import { hasCalendarPermission } from "../../../native/calendar-permissions";
|
||||
import { getCalendarReadState, onCalendarChanged, readUpcomingEvents, type CalendarEvent } from "../../../native/calendar";
|
||||
import { lineStep } from "../../../ui/metrics";
|
||||
import { dayHeaderLabel, formatEventTime } from "../../calendar/calendar";
|
||||
import { type GlanceWidget } from "../widget";
|
||||
@@ -22,14 +22,19 @@ const HOUR_MS = 60 * MINUTE_MS;
|
||||
*/
|
||||
export class CalendarWidget implements GlanceWidget {
|
||||
private tick: ReturnType<typeof setInterval> | null = null;
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
|
||||
start(requestRender: () => void): void {
|
||||
this.stop();
|
||||
this.unsubscribe = onCalendarChanged(requestRender);
|
||||
this.tick = setInterval(requestRender, MINUTE_MS);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.tick !== null) clearInterval(this.tick);
|
||||
this.tick = null;
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
}
|
||||
|
||||
paint(image: GrayImage): void {
|
||||
@@ -50,7 +55,9 @@ export class CalendarWidget implements GlanceWidget {
|
||||
const events = readUpcomingEvents().filter((event) => event.endMs > nowMs);
|
||||
if (!events.length) {
|
||||
image.drawText(small, PAD, PAD, "Calendar", 150);
|
||||
image.drawText(small, PAD, PAD + step + 4, "No upcoming events", 140);
|
||||
const state = getCalendarReadState();
|
||||
image.drawText(small, PAD, PAD + step + 4, state === "loading" ? "Loading calendar..."
|
||||
: state === "error" ? "Calendar unavailable" : "No upcoming events", 140);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type GrayImage } from "../../../graphics/image";
|
||||
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
|
||||
import { hasLocationPermission } from "../../../g2/android-permissions";
|
||||
import { hasLocationPermission } from "../../../native/location-permissions";
|
||||
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled } from "../../../native/compass";
|
||||
import { isCompassCalibrated, normalizeHeading } from "../../compass/calibration";
|
||||
import { cardinalDirection, createCompassBackground, drawCompassRose, layoutCompassRose, TICK_HEIGHT } from "../../compass/compass-rose";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type GrayImage } from "../../../graphics/image";
|
||||
import { GrayImage } from "../../../graphics/image";
|
||||
import { getDefaultLargeFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
|
||||
import { truncateText } from "../../../graphics/textwrap";
|
||||
import { nightscoutBridge, type NightscoutState } from "../../../native/nightscout-bridge";
|
||||
@@ -91,22 +91,6 @@ export class NightscoutWidget implements GlanceWidget {
|
||||
image.drawText(small, PAD, y, `IOB ${state.iob === null ? "--" : state.iob.toFixed(2)}`, 160);
|
||||
y += step;
|
||||
|
||||
// Breached limits only, one per line while they fit, inverted like the
|
||||
// app's warning fields. Nothing here means nothing is out of range.
|
||||
const alerts = evaluateNightscoutAlerts(state, loadNightscoutThresholds(), nowMs);
|
||||
const warnings: string[] = [];
|
||||
if (alerts.cannula) warnings.push(`CAGE ${formatAgeShortFromTimestamp(state.cageTimestampMs, nowMs)}`);
|
||||
if (alerts.cartridge) warnings.push(`Reservoir ${state.reservoirUnits === null ? "--" : Math.round(state.reservoirUnits)}U`);
|
||||
if (alerts.battery) warnings.push(`Battery ${state.batteryVoltage === null ? "--" : state.batteryVoltage.toFixed(2)}V`);
|
||||
if (alerts.loop) warnings.push(`Loop ${formatAgeShortFromTimestamp(state.loopTimestampMs, nowMs)}`);
|
||||
for (const warning of warnings) {
|
||||
if (y + small.lineHeight > image.height - 2) break;
|
||||
const text = truncateText(small, warning, READOUT_WIDTH - 4);
|
||||
image.fillRect(PAD - 2, y - 1, small.measureText(text) + 4, small.lineHeight + 2, 230);
|
||||
image.drawText(small, PAD, y, text, 1);
|
||||
y += step;
|
||||
}
|
||||
|
||||
const graphX = PAD + READOUT_WIDTH + PAD;
|
||||
drawNightscoutGraph(
|
||||
image,
|
||||
@@ -115,5 +99,32 @@ export class NightscoutWidget implements GlanceWidget {
|
||||
nowMs,
|
||||
small,
|
||||
);
|
||||
|
||||
// Breached limits only, inverted like the app's warning fields. Continue
|
||||
// at the top of a second column over the graph when the readout is full.
|
||||
const alerts = evaluateNightscoutAlerts(state, loadNightscoutThresholds(), nowMs);
|
||||
const warnings: string[] = [];
|
||||
if (alerts.cannula) warnings.push(`CAGE ${formatAgeShortFromTimestamp(state.cageTimestampMs, nowMs)}`);
|
||||
if (alerts.cartridge) warnings.push(`Reservoir ${state.reservoirUnits === null ? "--" : Math.round(state.reservoirUnits)}U`);
|
||||
if (alerts.battery) warnings.push(`Battery ${state.batteryVoltage === null ? "--" : state.batteryVoltage.toFixed(2)}V`);
|
||||
if (alerts.loop) warnings.push(`Loop ${formatAgeShortFromTimestamp(state.loopTimestampMs, nowMs)}`);
|
||||
let warningX = PAD;
|
||||
for (const warning of warnings) {
|
||||
if (y + small.lineHeight > image.height - 2) {
|
||||
warningX = graphX;
|
||||
y = PAD;
|
||||
}
|
||||
const text = truncateText(small, warning, READOUT_WIDTH - 4);
|
||||
const width = Math.ceil(small.measureText(text)) + 4;
|
||||
if (warningX === PAD) {
|
||||
image.fillRect(warningX - 2, y - 1, width, small.lineHeight + 2, 230);
|
||||
} else {
|
||||
// Graph labels are deferred glyphs: a deferred opaque background
|
||||
// covers those as well as the graph's raster lines.
|
||||
image.drawImage(new GrayImage(width, small.lineHeight + 2, 230), warningX - 2, y - 1);
|
||||
}
|
||||
image.drawText(small, warningX, y, text, 1);
|
||||
y += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Native services still outside the current iOS app-screen milestone. */
|
||||
const unavailable: Record<string, string> = {
|
||||
music: 'Media-player integration is not available on iOS yet.',
|
||||
transcribe: 'Voice capture and transcription are not available on iOS yet.',
|
||||
microphones: 'Glasses microphone capture is not available on iOS yet.',
|
||||
}
|
||||
export function iosAppUnavailableReason(appId: string): string | null {
|
||||
return unavailable[appId] ?? null
|
||||
}
|
||||
+23
-18
@@ -7,6 +7,28 @@ import {
|
||||
renderInstalledEvenHubIcon,
|
||||
} from "../evenhub/installed-apps";
|
||||
|
||||
/** Shared built-in and installed-app listing for both phone hosts. */
|
||||
export function launcherEntries(apps: readonly AppDefinition[]) {
|
||||
return [
|
||||
...apps
|
||||
.filter((app) => app.showInLauncher !== false)
|
||||
.map((app) => ({
|
||||
appId: app.appId,
|
||||
label: app.title,
|
||||
icon: app.icon,
|
||||
renderIcon: app.renderIcon,
|
||||
})),
|
||||
...getInstalledEvenHubApps().map((app) => ({
|
||||
appId: installedEvenHubAppId(app.packageId),
|
||||
label: app.name,
|
||||
icon: "package" as const,
|
||||
renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app),
|
||||
iconKey: `${app.installedAt}:${app.iconFile ?? ""}`,
|
||||
uninstallable: true,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
const launcherApp: AppDefinition = {
|
||||
appId: "launcher",
|
||||
title: "Apps",
|
||||
@@ -22,24 +44,7 @@ const launcherApp: AppDefinition = {
|
||||
...ctx.actions,
|
||||
requestRender: () => shell.foregroundWindow()?.requestRender(),
|
||||
},
|
||||
apps: () => [
|
||||
...ctx.apps
|
||||
.filter((app) => app.showInLauncher !== false)
|
||||
.map((app) => ({
|
||||
appId: app.appId,
|
||||
label: app.title,
|
||||
icon: app.icon,
|
||||
renderIcon: app.renderIcon,
|
||||
})),
|
||||
...getInstalledEvenHubApps().map((app) => ({
|
||||
appId: installedEvenHubAppId(app.packageId),
|
||||
label: app.name,
|
||||
icon: "package" as const,
|
||||
renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app),
|
||||
iconKey: `${app.installedAt}:${app.iconFile ?? ""}`,
|
||||
uninstallable: true,
|
||||
})),
|
||||
],
|
||||
apps: () => launcherEntries(ctx.apps),
|
||||
launchApp: (appId) => ctx.launchApp(appId),
|
||||
uninstallApp: (appId) => ctx.uninstallApp(appId),
|
||||
submitFrame: (planes, paintMs, frameId) => ctx.submitWindowFrame(LAUNCHER_SURFACE_ID, planes, paintMs, frameId),
|
||||
|
||||
@@ -4,11 +4,10 @@ import { truncateText } from "../../graphics/textwrap";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { type Plane } from "../../graphics/plane";
|
||||
import { renderIcon, type IconName } from "../../graphics/icons";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { InputEvent, isWatchInput } from "../../ui/gestures";
|
||||
import { InputEvent } from "../../ui/gestures";
|
||||
import { IconGrid, ICON_GRID_ICON_SIZE } from "../../ui/icon-grid";
|
||||
import { Layer, LayerActions, LayerContext } from "../../ui/layers";
|
||||
import { drawSelectionHighlight, MenuLayer, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
|
||||
import { iconGridMinRowHeight } from "../../ui/metrics";
|
||||
import { MenuLayer, type MenuItem } from "../../ui/menu";
|
||||
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
|
||||
import { onAnySettingChanged } from "../../ui/dashboard-settings";
|
||||
import { createInProcessWindow } from "../../ui/shell/in-process-window";
|
||||
@@ -45,12 +44,7 @@ export type LauncherOptions = {
|
||||
export const LAUNCHER_WINDOW_ID = "launcher";
|
||||
export const LAUNCHER_SURFACE_ID = "window:launcher";
|
||||
|
||||
const COLS = 5;
|
||||
const GRID_TOP = 6;
|
||||
const ICON_SIZE = 44;
|
||||
const LABEL_GAP = 2;
|
||||
|
||||
type LauncherMode = "row" | "item";
|
||||
|
||||
/** One cell of the grid: an app, or a folder holding some of the apps. */
|
||||
type LauncherGridEntry =
|
||||
@@ -58,15 +52,11 @@ type LauncherGridEntry =
|
||||
| { kind: "folder"; label: string; name: string };
|
||||
|
||||
/**
|
||||
* The launcher grid: app and folder icons with labels, arranged in a grid.
|
||||
* Navigation has two levels so the max number of swipes to any app is halved:
|
||||
* entering from the sidebar starts in "row" mode (scroll picks a row); a tap
|
||||
* drops into "item" mode on that row, defaulting to the middle column (scroll
|
||||
* picks the item); a tap launches an app or opens a folder (the same grid,
|
||||
* restricted to that folder's apps). Double-click backs out one level (item →
|
||||
* row, folder → top grid), and from the top level yields to the sidebar.
|
||||
* That is the ring's scheme; the watch (see handleWatchInput) skips row mode
|
||||
* and moves one cell at a time in four directions.
|
||||
* The launcher grid: app and folder icons with labels, in an IconGrid (which
|
||||
* owns layout, selection and the ring/watch navigation schemes). Opening a
|
||||
* folder shows the same grid restricted to that folder's apps; backing out
|
||||
* of a folder returns to the top grid, and from the top grid yields to the
|
||||
* sidebar.
|
||||
*
|
||||
* The folder grouping lives in the settings store (see launcher-folders.ts)
|
||||
* and is re-read every paint, so assistant folder tools take effect without
|
||||
@@ -78,28 +68,24 @@ class LauncherGridLayer implements Layer {
|
||||
// open folder if there is one, else yields to the sidebar — "left" points
|
||||
// toward the sidebar all the way out.
|
||||
readonly acceptsDirectional = true;
|
||||
private mode: LauncherMode = "row";
|
||||
private selectedRow = 0;
|
||||
private selectedCol = 1;
|
||||
private scrollRow = 0;
|
||||
/** Folder whose contents the grid is showing, or null for the top grid. */
|
||||
private currentFolder: string | null = null;
|
||||
private readonly grid = new IconGrid<LauncherGridEntry>({
|
||||
items: () => this.entries(),
|
||||
describe: (entry) => ({
|
||||
label: entry.label,
|
||||
icon: entry.kind === "app"
|
||||
? entry.renderIcon?.(ICON_GRID_ICON_SIZE) ?? renderIcon(entry.icon, ICON_GRID_ICON_SIZE)
|
||||
: renderIcon("folder-filled", ICON_GRID_ICON_SIZE),
|
||||
}),
|
||||
onActivate: (entry) => this.openEntry(entry),
|
||||
onBack: () => this.back(),
|
||||
});
|
||||
|
||||
constructor(private readonly options: LauncherOptions) {}
|
||||
|
||||
/**
|
||||
* Focus arriving from the watch goes straight to item selection: the watch
|
||||
* has left/right swipes, so it never needs row mode (see handleWatchInput),
|
||||
* and starting there would paint a row band its scheme can't produce. Any
|
||||
* other source keeps the two-level scheme and enters in row mode.
|
||||
*/
|
||||
onFocus(lastInput: InputEvent | null): void {
|
||||
if (lastInput && isWatchInput(lastInput)) {
|
||||
this.mode = "item";
|
||||
this.selectedCol = clamp(this.selectedCol, 0, this.itemsInRow(this.entries().length, this.selectedRow) - 1);
|
||||
} else {
|
||||
this.mode = "row";
|
||||
}
|
||||
this.grid.onFocus(lastInput);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,22 +136,38 @@ class LauncherGridLayer implements Layer {
|
||||
return entries.sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
private rowCount(entryCount: number): number {
|
||||
return Math.max(1, Math.ceil(entryCount / COLS));
|
||||
}
|
||||
|
||||
private itemsInRow(entryCount: number, row: number): number {
|
||||
return Math.max(0, Math.min(COLS, entryCount - row * COLS));
|
||||
}
|
||||
|
||||
/** Leave the current folder, putting the selection back on its cell. */
|
||||
private exitFolder(): void {
|
||||
const folder = this.currentFolder;
|
||||
this.currentFolder = null;
|
||||
this.mode = "row";
|
||||
this.grid.resetSelection();
|
||||
const index = this.entries().findIndex((entry) => entry.kind === "folder" && entry.name === folder);
|
||||
this.selectedRow = index >= 0 ? Math.floor(index / COLS) : 0;
|
||||
this.selectedCol = index >= 0 ? index % COLS : 0;
|
||||
if (index >= 0) this.grid.selectIndex(index);
|
||||
}
|
||||
|
||||
/** Enter a folder or launch an app; true when that left the grid (a launch). */
|
||||
private async openEntry(entry: LauncherGridEntry): Promise<boolean> {
|
||||
if (entry.kind === "folder") {
|
||||
this.currentFolder = entry.name;
|
||||
this.grid.resetSelection();
|
||||
return false;
|
||||
}
|
||||
// Return to the top grid before launching, so the launcher never
|
||||
// shows (even briefly) stale folder contents when re-entered.
|
||||
if (this.currentFolder !== null) this.exitFolder();
|
||||
this.grid.enterRowMode();
|
||||
await this.options.launchApp(entry.appId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Leave the open folder, else yield to the sidebar; true when that left the grid. */
|
||||
private back(): boolean {
|
||||
if (this.currentFolder !== null) {
|
||||
this.exitFolder();
|
||||
return false;
|
||||
}
|
||||
shell.yieldFocusToSidebar();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -174,8 +176,7 @@ class LauncherGridLayer implements Layer {
|
||||
* so anywhere else the menu falls back to just the defaults.
|
||||
*/
|
||||
menuItems(): MenuItem[] {
|
||||
if (this.mode !== "item") return [];
|
||||
const entry = this.entries()[this.selectedRow * COLS + this.selectedCol];
|
||||
const entry = this.grid.selectedItem;
|
||||
if (!entry || entry.kind !== "app") return [];
|
||||
return [
|
||||
{
|
||||
@@ -202,7 +203,7 @@ class LauncherGridLayer implements Layer {
|
||||
confirmCtx.stack.pop();
|
||||
setAppFolder(entry.appId, null);
|
||||
await this.options.uninstallApp(entry.appId);
|
||||
this.mode = "row";
|
||||
this.grid.enterRowMode();
|
||||
},
|
||||
},
|
||||
{ label: "Cancel", onSelect: (confirmCtx) => confirmCtx.stack.pop() },
|
||||
@@ -257,246 +258,23 @@ class LauncherGridLayer implements Layer {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const focused = ctx.stack.isFocused();
|
||||
const entries = this.entries();
|
||||
const rows = this.rowCount(entries.length);
|
||||
this.selectedRow = clamp(this.selectedRow, 0, rows - 1);
|
||||
this.selectedCol = clamp(
|
||||
this.selectedCol,
|
||||
0,
|
||||
Math.max(0, this.itemsInRow(entries.length, this.selectedRow) - 1),
|
||||
);
|
||||
|
||||
// The folder-name header band scales with the font.
|
||||
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : GRID_TOP;
|
||||
if (this.currentFolder !== null) {
|
||||
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
|
||||
}
|
||||
const gridBottom = height - 4;
|
||||
// Rows are exactly as tall as their content (icon + label + breathing
|
||||
// room), so row height tracks the font instead of stretching to fill the
|
||||
// viewport. Leftover space below the last full row shows the top of the
|
||||
// next row when there are more apps to scroll to.
|
||||
const rowH = iconGridMinRowHeight(font, ICON_SIZE, LABEL_GAP);
|
||||
const fullRows = Math.max(1, Math.floor((gridBottom - gridTop) / rowH));
|
||||
const colW = width / COLS;
|
||||
|
||||
// Scroll to keep the selected row among the fully-visible rows.
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedRow, fullRows, rows);
|
||||
|
||||
const rowY = (row: number) => gridTop + (row - this.scrollRow) * rowH;
|
||||
|
||||
// Selection highlight: a row band, or a single cell in item mode. While
|
||||
// defocused with the watch as the last-used source, the cell outline is
|
||||
// shown even in row mode: watch focus enters item mode directly (see
|
||||
// onFocus), so the outline previews the cell a click would land on
|
||||
// rather than a row band the watch scheme never shows.
|
||||
const cellHighlight = this.mode === "item" || (!focused && shell.lastInputWasWatch());
|
||||
const selY = rowY(this.selectedRow);
|
||||
if (cellHighlight) {
|
||||
drawSelectionHighlight(image, this.selectedCol * colW + 6, selY + 2, colW - 12, rowH - 4, focused, 6);
|
||||
} else {
|
||||
drawSelectionHighlight(image, 4, selY + 2, width - 8, rowH - 4, focused, 6);
|
||||
}
|
||||
|
||||
for (let index = 0; index < entries.length; index++) {
|
||||
const entry = entries[index]!;
|
||||
const row = Math.floor(index / COLS);
|
||||
if (row < this.scrollRow) continue;
|
||||
const blockTop = rowY(row) + Math.max(2, (rowH - ICON_SIZE - font.lineHeight - LABEL_GAP) / 2);
|
||||
if (blockTop >= gridBottom) break; // fully below the grid
|
||||
const centerX = (index % COLS) * colW + colW / 2;
|
||||
const icon = entry.kind === "app"
|
||||
? entry.renderIcon?.(ICON_SIZE) ?? renderIcon(entry.icon, ICON_SIZE)
|
||||
: renderIcon("folder-filled", ICON_SIZE);
|
||||
if (icon) {
|
||||
// Clip the icon at the grid bottom so a peeking row shows only its top.
|
||||
// A fully visible icon goes through the deferred-image path (texture
|
||||
// cacheable); the clipped peeking row falls back to a raster blit,
|
||||
// since cached draws are whole-image only.
|
||||
// Icons narrower/shorter than ICON_SIZE (a non-square logo scaled to
|
||||
// fit) are centered in the square the row reserves for them.
|
||||
const iconX = Math.round(centerX - icon.width / 2);
|
||||
const iconY = Math.round(blockTop + Math.max(0, (ICON_SIZE - icon.height) / 2));
|
||||
const clipHeight = Math.min(icon.height, Math.floor(gridBottom - iconY));
|
||||
if (clipHeight >= icon.height) {
|
||||
image.drawImage(icon, iconX, iconY);
|
||||
} else if (clipHeight > 0) {
|
||||
image.bitBlt(icon, iconX, iconY, { height: clipHeight, transparentZero: true });
|
||||
}
|
||||
}
|
||||
const labelY = Math.round(blockTop + ICON_SIZE + LABEL_GAP);
|
||||
if (labelY + font.lineHeight <= gridBottom) {
|
||||
const label = truncateText(font, entry.label, colW - 8);
|
||||
image.drawText(font, Math.round(centerX - font.measureText(label) / 2), labelY, label, 210);
|
||||
}
|
||||
}
|
||||
|
||||
this.grid.paint(image, { x: 0, y: gridTop, width, height: gridBottom - gridTop }, ctx.stack.isFocused());
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
if (isWatchInput(event)) {
|
||||
await this.handleWatchInput(event, ctx);
|
||||
return;
|
||||
}
|
||||
const entries = this.entries();
|
||||
const rows = this.rowCount(entries.length);
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
case "scroll-down": {
|
||||
const delta = event.type === "scroll-down" ? 1 : -1;
|
||||
if (this.mode === "row") {
|
||||
this.selectedRow = clamp(this.selectedRow + delta, 0, rows - 1);
|
||||
} else {
|
||||
// Item selection traverses the grid linearly: past a row's edge it
|
||||
// continues onto the adjacent row (stopping at the grid's ends).
|
||||
const itemCount = this.itemsInRow(entries.length, this.selectedRow);
|
||||
const next = clamp(this.selectedCol, 0, itemCount - 1) + delta;
|
||||
if (next >= 0 && next < itemCount) {
|
||||
this.selectedCol = next;
|
||||
} else if (next < 0 && this.selectedRow > 0) {
|
||||
this.selectedRow--;
|
||||
this.selectedCol = this.itemsInRow(entries.length, this.selectedRow) - 1;
|
||||
} else if (next >= itemCount && this.selectedRow < rows - 1) {
|
||||
this.selectedRow++;
|
||||
this.selectedCol = 0;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "click": {
|
||||
if (this.mode === "row") {
|
||||
this.mode = "item";
|
||||
// Default to the middle column (clamped to the row's item count).
|
||||
this.selectedCol = Math.min(
|
||||
Math.floor(COLS / 2),
|
||||
this.itemsInRow(entries.length, this.selectedRow) - 1,
|
||||
);
|
||||
} else {
|
||||
await this.openSelected(entries);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "double-click":
|
||||
if (this.mode === "item") {
|
||||
this.mode = "row";
|
||||
} else if (this.currentFolder !== null) {
|
||||
this.exitFolder();
|
||||
} else {
|
||||
shell.yieldFocusToSidebar();
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
await this.grid.handleInput(event, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch's scheme: there is no row mode to enter first. The selection is
|
||||
* always one cell; up/down/left/right (and the crown) move it spatially,
|
||||
* select opens it, back leaves the folder or the grid, and stepping left
|
||||
* past the first column leaves for the sidebar, which is where "left" goes.
|
||||
* Row mode is restored on the way out so a ring user finds the grid as
|
||||
* they left it.
|
||||
*/
|
||||
private async handleWatchInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
const entries = this.entries();
|
||||
const rows = this.rowCount(entries.length);
|
||||
if (this.mode === "row") {
|
||||
this.mode = "item";
|
||||
this.selectedCol = clamp(this.selectedCol, 0, this.itemsInRow(entries.length, this.selectedRow) - 1);
|
||||
}
|
||||
const leave = () => {
|
||||
this.mode = "row";
|
||||
shell.yieldFocusToSidebar();
|
||||
};
|
||||
switch (event.type) {
|
||||
case "swipe-up":
|
||||
case "swipe-down":
|
||||
case "scroll-up":
|
||||
case "scroll-down": {
|
||||
const delta = event.type === "swipe-down" || event.type === "scroll-down" ? 1 : -1;
|
||||
this.selectedRow = clamp(this.selectedRow + delta, 0, rows - 1);
|
||||
// Keep the column; a shorter last row clamps it.
|
||||
this.selectedCol = clamp(this.selectedCol, 0, this.itemsInRow(entries.length, this.selectedRow) - 1);
|
||||
return;
|
||||
}
|
||||
case "swipe-right":
|
||||
this.selectedCol = clamp(this.selectedCol + 1, 0, this.itemsInRow(entries.length, this.selectedRow) - 1);
|
||||
return;
|
||||
case "swipe-left":
|
||||
if (this.selectedCol > 0) {
|
||||
this.selectedCol--;
|
||||
} else if (this.currentFolder !== null) {
|
||||
this.exitFolder();
|
||||
this.mode = "item";
|
||||
} else {
|
||||
leave();
|
||||
}
|
||||
return;
|
||||
case "click":
|
||||
await this.openSelected(entries, true);
|
||||
return;
|
||||
case "double-click":
|
||||
if (this.currentFolder !== null) {
|
||||
this.exitFolder();
|
||||
this.mode = "item";
|
||||
} else {
|
||||
leave();
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A touch on the phone's mirror: the cell under it becomes the selection
|
||||
* and opens (the same as a watch select on it). Uses the geometry paint
|
||||
* lays the grid out with, so it lands on what the mirror showed.
|
||||
*/
|
||||
/** A touch on the phone's mirror opens the cell under it. */
|
||||
async hitTest(x: number, y: number, ctx: LayerContext): Promise<boolean> {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const entries = this.entries();
|
||||
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : GRID_TOP;
|
||||
const gridBottom = height - 4;
|
||||
if (y < gridTop || y >= gridBottom || x < 0 || x >= width) return false;
|
||||
const rowH = iconGridMinRowHeight(font, ICON_SIZE, LABEL_GAP);
|
||||
const colW = width / COLS;
|
||||
const row = this.scrollRow + Math.floor((y - gridTop) / rowH);
|
||||
const col = Math.floor(x / colW);
|
||||
if (row < 0 || row >= this.rowCount(entries.length)) return false;
|
||||
if (col < 0 || col >= this.itemsInRow(entries.length, row)) return false;
|
||||
this.mode = "item";
|
||||
this.selectedRow = row;
|
||||
this.selectedCol = col;
|
||||
await this.openSelected(entries);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the selected cell: enter a folder, or launch the app. A folder
|
||||
* entered by watch input stays in single-item selection (the watch scheme
|
||||
* has no row mode), starting at the folder's first cell.
|
||||
*/
|
||||
private async openSelected(entries: readonly LauncherGridEntry[], watch = false): Promise<void> {
|
||||
const entry = entries[this.selectedRow * COLS + this.selectedCol];
|
||||
if (!entry) return;
|
||||
if (entry.kind === "folder") {
|
||||
this.currentFolder = entry.name;
|
||||
this.mode = watch ? "item" : "row";
|
||||
this.selectedRow = 0;
|
||||
this.selectedCol = watch ? 0 : this.selectedCol;
|
||||
this.scrollRow = 0;
|
||||
} else {
|
||||
// Return to the top grid before launching, so the launcher never
|
||||
// shows (even briefly) stale folder contents when re-entered.
|
||||
if (this.currentFolder !== null) this.exitFolder();
|
||||
this.mode = "row";
|
||||
await this.options.launchApp(entry.appId);
|
||||
}
|
||||
return await this.grid.hitTest(x, y, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
* launches.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -25,6 +26,7 @@ import { getFont } from "../../graphics/bdffont";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import { playWorkerBuzzerSequence } from "../../native/worker-buzzer";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
|
||||
import { loadSoundEnabled, saveSoundEnabled } from "../../ui/sound-setting";
|
||||
@@ -43,7 +45,6 @@ import {
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
@@ -152,6 +153,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: MinesweeperWindow = {
|
||||
windowId: message.windowId,
|
||||
@@ -278,14 +285,12 @@ function saveDifficultyIndex(window: MinesweeperWindow): void {
|
||||
|
||||
/**
|
||||
* Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the
|
||||
* steps on its own timer, and the Java call is safe from the worker thread.
|
||||
* steps on its own timer; the platform bridge routes it from the worker.
|
||||
*/
|
||||
function playSfx(window: MinesweeperWindow, steps: Step[]): void {
|
||||
if (!window.soundOn || steps.length === 0) return;
|
||||
try {
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) return;
|
||||
communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer);
|
||||
playWorkerBuzzerSequence(buildSoundSequencePayload(steps));
|
||||
} catch (error) {
|
||||
console.warn(`minesweeper sfx failed: ${error}`);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures";
|
||||
import {
|
||||
MenuLayer,
|
||||
drawListScrollbar,
|
||||
drawSelectionHighlight,
|
||||
drawSubmenuIndicator,
|
||||
scrollToKeepSelectionVisible,
|
||||
} from "../../ui/menu";
|
||||
import { lineStep, tightRowHeight } from "../../ui/metrics";
|
||||
import { MenuLayer, drawSubmenuIndicator } from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics";
|
||||
import {
|
||||
mediaBrowserBridge,
|
||||
type MediaBrowseItem,
|
||||
@@ -22,6 +16,8 @@ function headerHeight(font: UiFont): number {
|
||||
return 8 + lineStep(font) + font.lineHeight;
|
||||
}
|
||||
const LIST_X = 20;
|
||||
/** The selection box extends this far left and right of the row text. */
|
||||
const LIST_HIGHLIGHT_PAD = 6;
|
||||
|
||||
export type MediaBrowseOptions = {
|
||||
app: MediaBrowserApp;
|
||||
@@ -37,8 +33,8 @@ type BrowseLevel = {
|
||||
/** null while the listing is loading. */
|
||||
items: MediaBrowseItem[] | null;
|
||||
error: string;
|
||||
selectedIndex: number;
|
||||
scrollRow: number;
|
||||
/** Holds the loaded items; keeps this level's selection and scroll while a child level is open. */
|
||||
menu: Menu<MediaBrowseItem>;
|
||||
};
|
||||
|
||||
type BrowsePhase = "idle" | "connecting" | "ready" | "failed";
|
||||
@@ -97,50 +93,16 @@ export class MediaBrowseLayer implements Layer {
|
||||
return image;
|
||||
}
|
||||
|
||||
level.selectedIndex = clamp(level.selectedIndex, 0, items.length - 1);
|
||||
const listHeight = height - headerHeight(font) - font.lineHeight - 10;
|
||||
const rowH = tightRowHeight(font);
|
||||
const visibleRows = Math.max(1, (listHeight / rowH) | 0);
|
||||
level.scrollRow = scrollToKeepSelectionVisible(level.scrollRow, level.selectedIndex, visibleRows, items.length);
|
||||
|
||||
const rowWidth = width - 2 * LIST_X;
|
||||
const lastVisible = Math.min(items.length, level.scrollRow + visibleRows);
|
||||
for (let index = level.scrollRow; index < lastVisible; index++) {
|
||||
const item = items[index]!;
|
||||
const y = headerHeight(font) + (index - level.scrollRow) * rowH;
|
||||
const selected = index === level.selectedIndex;
|
||||
const highlightX = LIST_X - 6;
|
||||
const highlightY = y - 1;
|
||||
const highlightWidth = rowWidth + 12;
|
||||
const highlightHeight = rowH - 1;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, highlightX, highlightY, highlightWidth, highlightHeight, ctx.stack.isFocused(), 4);
|
||||
}
|
||||
const value = selected ? 255 : 200;
|
||||
const title = truncateRight(font, item.title || "(untitled)", rowWidth - 16);
|
||||
image.drawText(font, LIST_X, y + 1, title, value);
|
||||
if (item.subtitle) {
|
||||
const titleWidth = font.measureText(title);
|
||||
const subtitleWidth = font.measureText(item.subtitle);
|
||||
if (titleWidth + subtitleWidth + 24 <= rowWidth - 16) {
|
||||
image.drawText(font, LIST_X + rowWidth - 16 - subtitleWidth, y + 1, item.subtitle, 110);
|
||||
}
|
||||
}
|
||||
if (item.browsable) {
|
||||
drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, selected ? value : 110);
|
||||
}
|
||||
}
|
||||
if (items.length > visibleRows) {
|
||||
drawListScrollbar(
|
||||
image,
|
||||
width - 12,
|
||||
headerHeight(font),
|
||||
visibleRows * rowH - 4,
|
||||
level.scrollRow,
|
||||
visibleRows,
|
||||
items.length,
|
||||
);
|
||||
}
|
||||
const listTop = headerHeight(font);
|
||||
const listHeight = height - listTop - font.lineHeight - 10;
|
||||
const visibleRows = Math.max(1, (listHeight / tightRowHeight(font)) | 0);
|
||||
// Row boxes start one pixel above the header's bottom edge.
|
||||
level.menu.paint(
|
||||
image,
|
||||
{ x: LIST_X - LIST_HIGHLIGHT_PAD, y: listTop - 1, width: width - 2 * LIST_X + 2 * LIST_HIGHLIGHT_PAD, height: listHeight },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
level.menu.drawScrollbar(image, width - 12, listTop, visibleRows * tightRowHeight(font) - 4);
|
||||
|
||||
image.drawText(
|
||||
font,
|
||||
@@ -175,13 +137,11 @@ export class MediaBrowseLayer implements Layer {
|
||||
if (!level || !items || !items.length) return;
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
level.selectedIndex = Math.max(0, level.selectedIndex - 1);
|
||||
return;
|
||||
case "scroll-down":
|
||||
level.selectedIndex = Math.min(items.length - 1, level.selectedIndex + 1);
|
||||
await level.menu.handleInput(event);
|
||||
return;
|
||||
case "click": {
|
||||
const item = items[clamp(level.selectedIndex, 0, items.length - 1)];
|
||||
const item = level.menu.selectedItem;
|
||||
if (!item) return;
|
||||
if (item.browsable && item.playable) {
|
||||
ctx.stack.push(
|
||||
@@ -233,18 +193,46 @@ export class MediaBrowseLayer implements Layer {
|
||||
}
|
||||
|
||||
private descendInto(ctx: LayerContext, item: MediaBrowseItem): void {
|
||||
const level: BrowseLevel = {
|
||||
parentId: item.mediaId,
|
||||
title: item.title || "(untitled)",
|
||||
items: null,
|
||||
error: "",
|
||||
selectedIndex: 0,
|
||||
scrollRow: 0,
|
||||
};
|
||||
const level = this.createLevel(item.mediaId, item.title || "(untitled)");
|
||||
this.levels.push(level);
|
||||
this.loadLevel(ctx, level);
|
||||
}
|
||||
|
||||
private createLevel(parentId: string, title: string): BrowseLevel {
|
||||
return {
|
||||
parentId,
|
||||
title,
|
||||
items: null,
|
||||
error: "",
|
||||
menu: new Menu<MediaBrowseItem>({
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => this.drawItem(args),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private drawItem({ image, item, x, y, width, height, selected }: MenuDrawArgs<MediaBrowseItem>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const value = selected ? 255 : 200;
|
||||
const textWidth = width - 2 * LIST_HIGHLIGHT_PAD - 16;
|
||||
const textY = centeredTextY(font, y, height);
|
||||
const title = truncateRight(font, item.title || "(untitled)", textWidth);
|
||||
image.drawText(font, x + LIST_HIGHLIGHT_PAD, textY, title, value);
|
||||
if (item.subtitle) {
|
||||
const titleWidth = font.measureText(title);
|
||||
const subtitleWidth = font.measureText(item.subtitle);
|
||||
if (titleWidth + subtitleWidth + 24 <= textWidth) {
|
||||
image.drawText(font, x + LIST_HIGHLIGHT_PAD + textWidth - subtitleWidth, textY, item.subtitle, 110);
|
||||
}
|
||||
}
|
||||
if (item.browsable) {
|
||||
drawSubmenuIndicator(image, font, x, y, width, height, selected ? value : 110);
|
||||
}
|
||||
}
|
||||
|
||||
private startConnect(ctx: LayerContext): void {
|
||||
this.phase = "connecting";
|
||||
mediaBrowserBridge
|
||||
@@ -252,14 +240,7 @@ export class MediaBrowseLayer implements Layer {
|
||||
.then((rootId) => {
|
||||
if (this.removed) return;
|
||||
this.phase = "ready";
|
||||
const root: BrowseLevel = {
|
||||
parentId: rootId,
|
||||
title: "Library",
|
||||
items: null,
|
||||
error: "",
|
||||
selectedIndex: 0,
|
||||
scrollRow: 0,
|
||||
};
|
||||
const root = this.createLevel(rootId, "Library");
|
||||
this.levels = [root];
|
||||
this.loadLevel(ctx, root);
|
||||
ctx.actions.requestRender();
|
||||
@@ -278,6 +259,7 @@ export class MediaBrowseLayer implements Layer {
|
||||
.then((items) => {
|
||||
if (this.removed) return;
|
||||
level.items = items;
|
||||
level.menu.setItems(items, 0);
|
||||
ctx.actions.requestRender();
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
+57
-87
@@ -3,8 +3,9 @@ import { GrayImage } from "../../graphics/image";
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { directionalFallback, GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL_DOWN, GESTURE_SCROLL_UP, type InputEvent, isDirectionalInput } from "../../ui/gestures";
|
||||
import { MenuLayer, drawSelectionHighlight, drawSubmenuIndicator } from "../../ui/menu";
|
||||
import { lineStep, tightRowHeight } from "../../ui/metrics";
|
||||
import { MenuLayer, drawSubmenuIndicator } from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { centeredTextY, 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";
|
||||
@@ -28,6 +29,8 @@ const ACTION_X = 22;
|
||||
const ACTION_WIDTH = 154;
|
||||
const COLUMN_DIVIDER_X = 190;
|
||||
const QUEUE_X = 204;
|
||||
/** Horizontal inset of row text from its selection box. */
|
||||
const LIST_TEXT_INSET = 6;
|
||||
const PLAYLIST_ACTION_INDEX = 1;
|
||||
|
||||
type MusicAction =
|
||||
@@ -49,9 +52,20 @@ class MusicAppLayer implements Layer {
|
||||
// Watch swipes skip tracks: right = next, left = previous.
|
||||
readonly acceptsDirectional = true;
|
||||
private focusColumn: FocusColumn = "actions";
|
||||
private selectedActionIndex = 0;
|
||||
private selectedQueueIndex = 0;
|
||||
private queueScrollRow = 0;
|
||||
private readonly actionsMenu = new Menu<MusicAction>({
|
||||
wrap: true,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => this.drawAction(args),
|
||||
});
|
||||
private readonly queueMenu = new Menu<MediaQueueItem>({
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
highlight: { radius: 4 },
|
||||
getHeight: () => tightRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => this.drawQueueItem(args),
|
||||
});
|
||||
private art: GrayImage | null = null;
|
||||
private artKey = "";
|
||||
|
||||
@@ -124,83 +138,49 @@ class MusicAppLayer implements Layer {
|
||||
const actions = this.buildActions(media, queue);
|
||||
this.reconcileSelection(actions, queue);
|
||||
const listHeight = height - LIST_TOP - LIST_BOTTOM_MARGIN;
|
||||
const rowH = tightRowHeight(font);
|
||||
const visibleRows = Math.max(1, (listHeight / rowH) | 0);
|
||||
if (this.selectedQueueIndex < this.queueScrollRow) {
|
||||
this.queueScrollRow = this.selectedQueueIndex;
|
||||
} else if (this.selectedQueueIndex >= this.queueScrollRow + visibleRows) {
|
||||
this.queueScrollRow = this.selectedQueueIndex - visibleRows + 1;
|
||||
}
|
||||
this.queueScrollRow = clamp(this.queueScrollRow, 0, Math.max(0, queue.length - visibleRows));
|
||||
|
||||
for (let index = 0; index < actions.length; index++) {
|
||||
const action = actions[index]!;
|
||||
const y = LIST_TOP + index * rowH;
|
||||
const selected = index === this.selectedActionIndex;
|
||||
const highlightX = ACTION_X - 6;
|
||||
const highlightY = y - 1;
|
||||
const highlightWidth = ACTION_WIDTH + 8;
|
||||
const highlightHeight = rowH - 1;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(
|
||||
image,
|
||||
highlightX,
|
||||
highlightY,
|
||||
highlightWidth,
|
||||
highlightHeight,
|
||||
ctx.stack.isFocused() && this.focusColumn === "actions",
|
||||
4,
|
||||
);
|
||||
}
|
||||
const value = !action.enabled ? (selected ? 130 : 90) : selected ? 255 : 200;
|
||||
image.drawText(font, ACTION_X, y + 1, truncateText(font, action.label, ACTION_WIDTH - 16), value);
|
||||
if ((action.kind === "playlist" || action.kind === "browse") && action.enabled) {
|
||||
drawSubmenuIndicator(image, font, highlightX, highlightY, highlightWidth, highlightHeight, value);
|
||||
}
|
||||
}
|
||||
const focused = ctx.stack.isFocused();
|
||||
// Row boxes start one pixel above LIST_TOP, level with the column divider.
|
||||
this.actionsMenu.paint(
|
||||
image,
|
||||
{ x: ACTION_X - LIST_TEXT_INSET, y: LIST_TOP - 1, width: ACTION_WIDTH + 2 * LIST_TEXT_INSET - 4, height: listHeight },
|
||||
focused && this.focusColumn === "actions",
|
||||
);
|
||||
|
||||
image.drawLine(COLUMN_DIVIDER_X, LIST_TOP - 3, COLUMN_DIVIDER_X, height - LIST_BOTTOM_MARGIN - 3, 45);
|
||||
if (!queue.length) {
|
||||
image.drawText(font, QUEUE_X, LIST_TOP + 1, "Playlist unavailable", 90);
|
||||
} else {
|
||||
const queueWidth = width - QUEUE_X - 20;
|
||||
const lastVisible = Math.min(queue.length, this.queueScrollRow + visibleRows);
|
||||
for (let index = this.queueScrollRow; index < lastVisible; index++) {
|
||||
const item = queue[index]!;
|
||||
const y = LIST_TOP + (index - this.queueScrollRow) * rowH;
|
||||
const selected = index === this.selectedQueueIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(
|
||||
image,
|
||||
QUEUE_X - 6,
|
||||
y - 1,
|
||||
queueWidth + 8,
|
||||
rowH - 1,
|
||||
ctx.stack.isFocused() && this.focusColumn === "playlist",
|
||||
4,
|
||||
);
|
||||
}
|
||||
const label = `${item.active ? "> " : " "}${item.title || "(untitled)"}`;
|
||||
image.drawText(font, QUEUE_X, y + 1, truncateText(font, label, queueWidth - 4), selected ? 255 : 200);
|
||||
}
|
||||
if (queue.length > visibleRows) {
|
||||
const trackHeight = visibleRows * rowH - 4;
|
||||
const trackX = width - 12;
|
||||
image.fillRect(trackX, LIST_TOP, 3, trackHeight, 30);
|
||||
const thumbHeight = Math.max(8, (trackHeight * visibleRows / queue.length) | 0);
|
||||
const maxScrollRow = queue.length - visibleRows;
|
||||
const thumbY = LIST_TOP + (((trackHeight - thumbHeight) * this.queueScrollRow / maxScrollRow) | 0);
|
||||
image.fillRect(trackX, thumbY, 3, thumbHeight, 120);
|
||||
}
|
||||
this.queueMenu.paint(
|
||||
image,
|
||||
{ x: QUEUE_X - LIST_TEXT_INSET, y: LIST_TOP - 1, width: queueWidth + 2 * LIST_TEXT_INSET - 4, height: listHeight },
|
||||
focused && this.focusColumn === "playlist",
|
||||
);
|
||||
this.queueMenu.drawScrollbar(image, width - 12, LIST_TOP, listHeight - 4);
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
private drawAction({ image, item: action, x, y, width, height, selected }: MenuDrawArgs<MusicAction>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const value = !action.enabled ? (selected ? 130 : 90) : selected ? 255 : 200;
|
||||
image.drawText(font, x + LIST_TEXT_INSET, centeredTextY(font, y, height), truncateText(font, action.label, ACTION_WIDTH - 16), value);
|
||||
if ((action.kind === "playlist" || action.kind === "browse") && action.enabled) {
|
||||
drawSubmenuIndicator(image, font, x, y, width, height, value);
|
||||
}
|
||||
}
|
||||
|
||||
private drawQueueItem({ image, item, x, y, width, height, selected }: MenuDrawArgs<MediaQueueItem>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const label = `${item.active ? "> " : " "}${item.title || "(untitled)"}`;
|
||||
image.drawText(font, x + LIST_TEXT_INSET, centeredTextY(font, y, height), truncateText(font, label, width - 2 * LIST_TEXT_INSET), selected ? 255 : 200);
|
||||
}
|
||||
|
||||
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||
if (event.type === "double-click" && this.focusColumn === "playlist") {
|
||||
this.focusColumn = "actions";
|
||||
this.selectedActionIndex = PLAYLIST_ACTION_INDEX;
|
||||
this.actionsMenu.select(PLAYLIST_ACTION_INDEX);
|
||||
return;
|
||||
}
|
||||
const media = mediaControllerBridge.snapshot();
|
||||
@@ -237,31 +217,20 @@ class MusicAppLayer implements Layer {
|
||||
case "swipe-down":
|
||||
return this.handleInput({ type: "scroll-down", timestampMs: event.timestampMs }, ctx);
|
||||
case "scroll-up":
|
||||
if (this.focusColumn === "playlist") {
|
||||
this.selectedQueueIndex = Math.max(0, this.selectedQueueIndex - 1);
|
||||
} else {
|
||||
this.selectedActionIndex = (this.selectedActionIndex + actions.length - 1) % actions.length;
|
||||
}
|
||||
return;
|
||||
case "scroll-down":
|
||||
if (this.focusColumn === "playlist") {
|
||||
this.selectedQueueIndex = Math.min(Math.max(0, queue.length - 1), this.selectedQueueIndex + 1);
|
||||
} else {
|
||||
this.selectedActionIndex = (this.selectedActionIndex + 1) % actions.length;
|
||||
}
|
||||
await (this.focusColumn === "playlist" ? this.queueMenu : this.actionsMenu).handleInput(event);
|
||||
return;
|
||||
case "click": {
|
||||
if (this.focusColumn === "playlist") {
|
||||
const item = queue[this.selectedQueueIndex];
|
||||
const item = this.queueMenu.selectedItem;
|
||||
if (item) {
|
||||
await mediaControllerBridge.skipToQueueItem(item.id);
|
||||
// The player rebuilds the queue with the chosen track at index 0.
|
||||
this.selectedQueueIndex = 0;
|
||||
this.queueScrollRow = 0;
|
||||
this.queueMenu.select(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const action = actions[this.selectedActionIndex];
|
||||
const action = this.actionsMenu.selectedItem;
|
||||
if (!action || !action.enabled) return;
|
||||
if (action.kind === "play-pause") await mediaControllerBridge.playPause();
|
||||
else if (action.kind === "previous") await mediaControllerBridge.skipPrevious();
|
||||
@@ -271,7 +240,7 @@ class MusicAppLayer implements Layer {
|
||||
ctx.stack.push(new VolumeModalLayer(mediaControllerBridge.getMediaVolumePercent()));
|
||||
} else if (action.kind === "playlist") {
|
||||
const activeIndex = queue.findIndex((item) => item.active);
|
||||
if (activeIndex >= 0) this.selectedQueueIndex = activeIndex;
|
||||
if (activeIndex >= 0) this.queueMenu.select(activeIndex);
|
||||
this.focusColumn = "playlist";
|
||||
}
|
||||
return;
|
||||
@@ -332,12 +301,13 @@ class MusicAppLayer implements Layer {
|
||||
];
|
||||
}
|
||||
|
||||
/** Hand the menus the freshly built rows; each keeps its selection index, clamped. */
|
||||
private reconcileSelection(actions: MusicAction[], queue: MediaQueueItem[]): void {
|
||||
this.selectedActionIndex = clamp(this.selectedActionIndex, 0, actions.length - 1);
|
||||
this.selectedQueueIndex = clamp(this.selectedQueueIndex, 0, Math.max(0, queue.length - 1));
|
||||
this.actionsMenu.setItems(actions);
|
||||
this.queueMenu.setItems(queue);
|
||||
if (!queue.length && this.focusColumn === "playlist") {
|
||||
this.focusColumn = "actions";
|
||||
this.selectedActionIndex = PLAYLIST_ACTION_INDEX;
|
||||
this.actionsMenu.select(PLAYLIST_ACTION_INDEX);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,39 +10,45 @@ 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 = "";
|
||||
private menuWidth = 0;
|
||||
/** The package behind each current row, parallel to the menu's items. */
|
||||
private packages: string[] = [];
|
||||
|
||||
constructor() {
|
||||
// Refresh installed browser services, remembering ignored services too.
|
||||
mediaBrowserBridge.listBrowsableApps(true);
|
||||
}
|
||||
|
||||
/** Refresh the rows from the remembered apps, keeping the selection on the same package. */
|
||||
private currentMenu(ctx: LayerContext): MenuLayer {
|
||||
const apps = readMediaApps().sort((a, b) =>
|
||||
a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
|
||||
const items: MenuItem[] = apps.map((app) => ({
|
||||
label: app.appName,
|
||||
onSelect: () => setMediaAppEnabled(app, !isMediaAppEnabled(app.packageName)),
|
||||
render: ({ image, x, y, width, selected }) => {
|
||||
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: () => {} });
|
||||
const selectedPackage = this.menu?.selectedIndex != null ? this.packages[this.menu.selectedIndex] : undefined;
|
||||
const index = apps.findIndex((app) => app.packageName === selectedPackage);
|
||||
this.packages = apps.map((app) => app.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: () => {} });
|
||||
if (!this.menu || width !== this.menuWidth) {
|
||||
this.menuWidth = width;
|
||||
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)));
|
||||
}).selectItem(Math.max(0, index));
|
||||
} else {
|
||||
this.menu.setItems(items, index >= 0 ? index : undefined);
|
||||
}
|
||||
return this.menu;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ensureFineLocationPermission } from "../../g2/android-permissions";
|
||||
import { ensureFineLocationPermission } from "../../native/location-permissions";
|
||||
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
|
||||
|
||||
const navigateApp: AppDefinition = {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* guidance text (right pane) updates per GPS fix and ships as small deltas.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -15,14 +16,12 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import {
|
||||
drawListScrollbar,
|
||||
drawRightValueMenuItem,
|
||||
drawSelectionHighlight,
|
||||
drawSubmenuIndicator,
|
||||
drawToggleMenuItem,
|
||||
scrollToKeepSelectionVisible,
|
||||
type MenuItem,
|
||||
} from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { LIST_ROW_TEXT_INSET, listRowHeight } from "../../ui/metrics";
|
||||
import { WindowMenu, WindowMenuLayer } from "../../ui/window-menu";
|
||||
import type { LayerContext } from "../../ui/layers";
|
||||
@@ -64,7 +63,7 @@ import {
|
||||
GESTURE_SHORT_THEN_LONG_PRESS,
|
||||
type InputEvent,
|
||||
} from "../../ui/gestures";
|
||||
import { LocationTracker, type TrackedLocation } from "../../native/location-tracker";
|
||||
import { LocationTracker, type TrackedLocation } from "./navigation-sensors";
|
||||
import {
|
||||
fetchRoute,
|
||||
fetchStaticMapGray,
|
||||
@@ -76,8 +75,8 @@ import {
|
||||
type RouteProfile,
|
||||
type StaticMapCamera,
|
||||
} from "../../native/mapbox";
|
||||
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "../../native/compass";
|
||||
import { magneticDeclinationDegrees } from "../../native/geomagnetic";
|
||||
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "./navigation-sensors";
|
||||
import { magneticDeclinationDegrees, handleNavigationSensorEvent } from "./navigation-sensors";
|
||||
import { calibrateHeading, normalizeHeading } from "../compass/calibration";
|
||||
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower";
|
||||
import { drawManeuverGlyph } from "./maneuver-icons";
|
||||
@@ -114,7 +113,7 @@ const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
const smallFont = getDefaultSmallFont();
|
||||
|
||||
type NavPhase = "idle" | "acquiring" | "routing" | "navigating" | "arrived";
|
||||
type NavPhase = "idle" | "acquiring" | "routing" | "navigating" | "map" | "arrived";
|
||||
type MapMode = "follow" | "overview";
|
||||
|
||||
type NavWindow = {
|
||||
@@ -184,6 +183,8 @@ let lastRerouteAtMs = 0;
|
||||
let rerouteInFlight = false;
|
||||
/** Bumped on every new route/mode so stale map fetches can be discarded. */
|
||||
let routeGeneration = 0;
|
||||
/** Invalidates GPS/geocoding/routing work when the route is replaced or closed. */
|
||||
let navigationGeneration = 0;
|
||||
|
||||
/**
|
||||
* Where to go: free text to geocode (optionally shown under a saved
|
||||
@@ -194,17 +195,16 @@ type NavTarget =
|
||||
| { kind: "place"; name: string; place: string; longitude: number; latitude: number };
|
||||
|
||||
/**
|
||||
* An entry on the idle page's list: a destination, or (while no Mapbox
|
||||
* token is set) one of the setup actions offered in its place.
|
||||
* An entry on the idle page's list: the map, a destination, or (while no
|
||||
* Mapbox token is set) one of the setup actions offered in its place.
|
||||
*/
|
||||
type IdleEntry =
|
||||
| { kind: "saved"; destination: SavedDestination }
|
||||
| { kind: "recent"; destination: RecentDestination }
|
||||
| { kind: "action"; label: string; detail: string; run: () => void };
|
||||
|
||||
/** Idle-page list selection (index into idleEntries()). */
|
||||
let idleSelection = 0;
|
||||
let idleScrollRow = 0;
|
||||
/** The idle page's list; created on first use (idleList) so module load stays free of paint dependencies. */
|
||||
let idleMenu: Menu<IdleEntry> | null = null;
|
||||
|
||||
/**
|
||||
* In-progress destination edit: the phone text editor is open on `setting`
|
||||
@@ -239,7 +239,6 @@ let compassActive = false;
|
||||
let unsubscribeCompass: (() => void) | null = null;
|
||||
/** Wearer's true heading (degrees clockwise from north) as last drawn, or null before compass data arrives. */
|
||||
let headHeadingDeg: number | null = null;
|
||||
let declinationCache: { latitude: number; longitude: number; degrees: number | null } | null = null;
|
||||
|
||||
let tickTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
|
||||
@@ -248,7 +247,7 @@ const tracker = new LocationTracker({
|
||||
onLocation: (fix) => handleFix(fix),
|
||||
onError: (message) => {
|
||||
statusMessage = message;
|
||||
if (phase === "acquiring") phase = "idle";
|
||||
if (phase === "acquiring") stopNavigation(message);
|
||||
render();
|
||||
},
|
||||
});
|
||||
@@ -274,6 +273,15 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "navigation-sensors":
|
||||
handleNavigationSensorEvent(message.event);
|
||||
break;
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
@@ -295,6 +303,10 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
window.viewportHeight = message.viewport.height;
|
||||
window.menu?.resize(message.viewport);
|
||||
window.lastSubmittedFingerprint = "";
|
||||
if (phase === "map") {
|
||||
resetMapState();
|
||||
maybeRefreshMap();
|
||||
}
|
||||
render();
|
||||
break;
|
||||
case "close-window":
|
||||
@@ -382,6 +394,31 @@ function startNavigation(query: string, requestedProfile: RouteProfile): Promise
|
||||
);
|
||||
}
|
||||
|
||||
async function startMap(): Promise<void> {
|
||||
if (!isMapboxConfigured()) return;
|
||||
stopNavigation("");
|
||||
const generation = navigationGeneration;
|
||||
phase = "acquiring";
|
||||
mapMode = "follow";
|
||||
zoomOffset = 0;
|
||||
statusMessage = "Locating you for the map...";
|
||||
render();
|
||||
try {
|
||||
ensureTracking();
|
||||
await waitForFix();
|
||||
if (generation !== navigationGeneration) return;
|
||||
phase = "map";
|
||||
statusMessage = "";
|
||||
ensureTickTimer();
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
} catch (error) {
|
||||
if (generation !== navigationGeneration) return;
|
||||
stopNavigation(String((error as Error)?.message ?? error));
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfile): Promise<string> {
|
||||
const query = target.kind === "query" ? target.query : target.name;
|
||||
if (!isMapboxConfigured()) {
|
||||
@@ -390,7 +427,10 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
|
||||
render();
|
||||
throw new Error(statusMessage);
|
||||
}
|
||||
const generation = ++navigationGeneration;
|
||||
const checkCurrent = () => { if (generation !== navigationGeneration) throw new Error("Navigation cancelled."); };
|
||||
const hadActiveRoute = phase === "navigating" && follower !== null;
|
||||
const hadActiveMap = phase === "map";
|
||||
const previous = {
|
||||
destination,
|
||||
destinationName,
|
||||
@@ -404,6 +444,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
|
||||
render();
|
||||
ensureTracking();
|
||||
const fix = await waitForFix();
|
||||
checkCurrent();
|
||||
|
||||
phase = "routing";
|
||||
let picked: GeocodeCandidate;
|
||||
@@ -420,6 +461,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
|
||||
statusMessage = `Finding ${query}...`;
|
||||
render();
|
||||
candidates = await geocodeForward(query, fix, 5);
|
||||
checkCurrent();
|
||||
if (!candidates.length) {
|
||||
throw new Error(`No places found matching "${query}".`);
|
||||
}
|
||||
@@ -432,6 +474,7 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
|
||||
statusMessage = `Routing to ${destinationName}...`;
|
||||
render();
|
||||
const route = await fetchRoute(fix, destination, profile);
|
||||
checkCurrent();
|
||||
adoptRoute(route);
|
||||
// Saved destinations already have a row of their own on the idle page;
|
||||
// everything else (voice, assistant, a re-picked recent) goes on the
|
||||
@@ -447,13 +490,13 @@ async function startNavigationTo(target: NavTarget, requestedProfile: RouteProfi
|
||||
if (window) post({ type: "focus-window", windowId: window.windowId });
|
||||
return startSummary(picked, candidates, route);
|
||||
} catch (error) {
|
||||
if (generation !== navigationGeneration) throw error;
|
||||
const message = String((error as Error)?.message ?? error);
|
||||
statusMessage = message;
|
||||
// A failed new destination shouldn't kill guidance that was already
|
||||
// running; fall back to the ongoing route (and its destination, which
|
||||
// the geocode step may have partially overwritten).
|
||||
if (hadActiveRoute) {
|
||||
phase = "navigating";
|
||||
// A failed new destination shouldn't close the existing map or guidance.
|
||||
// Restore the destination too: geocoding may have overwritten it.
|
||||
if (hadActiveRoute || hadActiveMap) {
|
||||
phase = hadActiveRoute ? "navigating" : "map";
|
||||
destination = previous.destination;
|
||||
destinationName = previous.destinationName;
|
||||
destinationPlace = previous.destinationPlace;
|
||||
@@ -474,7 +517,6 @@ function adoptRoute(route: Route): void {
|
||||
mapMode = "follow";
|
||||
zoomOffset = 0;
|
||||
statusMessage = "";
|
||||
routeGeneration++;
|
||||
resetMapState();
|
||||
ensureTracking();
|
||||
ensureTickTimer();
|
||||
@@ -484,6 +526,7 @@ function adoptRoute(route: Route): void {
|
||||
}
|
||||
|
||||
function stopNavigation(finalStatus: string): void {
|
||||
++navigationGeneration;
|
||||
phase = "idle";
|
||||
statusMessage = finalStatus;
|
||||
follower = null;
|
||||
@@ -491,7 +534,6 @@ function stopNavigation(finalStatus: string): void {
|
||||
destination = null;
|
||||
destinationName = "";
|
||||
destinationPlace = "";
|
||||
routeGeneration++;
|
||||
resetMapState();
|
||||
stopTrackingIfIdle();
|
||||
ensureTickTimer();
|
||||
@@ -512,6 +554,12 @@ function handleFix(fix: TrackedLocation): void {
|
||||
}
|
||||
for (const waiter of firstFixWaiters.splice(0)) waiter(fix);
|
||||
|
||||
if (phase === "map") {
|
||||
statusMessage = "";
|
||||
maybeRefreshMap();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (phase !== "navigating" || !follower) return;
|
||||
progress = follower.update(fix.longitude, fix.latitude);
|
||||
|
||||
@@ -533,14 +581,16 @@ function handleFix(fix: TrackedLocation): void {
|
||||
async function maybeReroute(fix: TrackedLocation): Promise<void> {
|
||||
if (rerouteInFlight || !destination) return;
|
||||
if (Date.now() - lastRerouteAtMs < REROUTE_MIN_INTERVAL_MS) return;
|
||||
const generation = navigationGeneration;
|
||||
rerouteInFlight = true;
|
||||
lastRerouteAtMs = Date.now();
|
||||
statusMessage = "Rerouting...";
|
||||
render();
|
||||
try {
|
||||
const route = await fetchRoute(fix, destination, profile);
|
||||
if (phase === "navigating") adoptRoute(route);
|
||||
if (generation === navigationGeneration && phase === "navigating") adoptRoute(route);
|
||||
} catch (error) {
|
||||
if (generation !== navigationGeneration) return;
|
||||
statusMessage = `Reroute failed: ${String((error as Error)?.message ?? error)}`;
|
||||
render();
|
||||
} finally {
|
||||
@@ -582,7 +632,7 @@ function waitForFix(): Promise<TrackedLocation> {
|
||||
/** 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";
|
||||
window !== null && window.foreground && screenOn && (phase === "navigating" || phase === "map") && mapMode === "follow";
|
||||
if (wanted === compassActive) return;
|
||||
compassActive = wanted;
|
||||
if (wanted) {
|
||||
@@ -601,7 +651,9 @@ function handleCompassEvent(event: CompassEvent): void {
|
||||
// Wearer-fit offset from the Compass app's calibration, then declination
|
||||
// from our own GPS fix: the map is always true-north referenced.
|
||||
const magnetic = calibrateHeading(event.headingDegrees);
|
||||
const heading = normalizeHeading(magnetic + (currentDeclination() ?? 0));
|
||||
const correction = currentDeclination();
|
||||
if (correction === null) return; // Keep the travel-direction arrow until true north is known.
|
||||
const heading = normalizeHeading(magnetic + correction);
|
||||
if (headHeadingDeg !== null && angularDistance(heading, headHeadingDeg) < HEADING_STEP_DEG) return;
|
||||
headHeadingDeg = heading;
|
||||
render();
|
||||
@@ -609,19 +661,7 @@ function handleCompassEvent(event: CompassEvent): void {
|
||||
|
||||
/** Declination at the last fix; it only varies over tens of kilometres, so cache per coarse position. */
|
||||
function currentDeclination(): number | null {
|
||||
if (!lastFix) return null;
|
||||
if (
|
||||
!declinationCache ||
|
||||
Math.abs(declinationCache.latitude - lastFix.latitude) > 0.5 ||
|
||||
Math.abs(declinationCache.longitude - lastFix.longitude) > 0.5
|
||||
) {
|
||||
declinationCache = {
|
||||
latitude: lastFix.latitude,
|
||||
longitude: lastFix.longitude,
|
||||
degrees: magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude),
|
||||
};
|
||||
}
|
||||
return declinationCache.degrees;
|
||||
return lastFix ? magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude) : null;
|
||||
}
|
||||
|
||||
function angularDistance(a: number, b: number): number {
|
||||
@@ -630,7 +670,7 @@ function angularDistance(a: number, b: number): number {
|
||||
}
|
||||
|
||||
function ensureTickTimer(): void {
|
||||
const shouldRun = phase === "navigating";
|
||||
const shouldRun = phase === "navigating" || phase === "map";
|
||||
if (shouldRun && tickTimer === null) {
|
||||
tickTimer = setInterval(() => {
|
||||
maybeRefreshMap();
|
||||
@@ -646,6 +686,7 @@ function ensureTickTimer(): void {
|
||||
// Map pane
|
||||
|
||||
function resetMapState(): void {
|
||||
routeGeneration++;
|
||||
mapImage = null;
|
||||
mapFetchedKey = "";
|
||||
mapInFlight = false;
|
||||
@@ -676,7 +717,7 @@ function currentBearing(): number {
|
||||
|
||||
function currentZoom(): number {
|
||||
let zoom: number;
|
||||
if (profile === "walking") {
|
||||
if (phase === "map" || profile === "walking") {
|
||||
zoom = 16.5;
|
||||
} else if (progress && progress.metersToNextManeuver < 250) {
|
||||
zoom = 16.5;
|
||||
@@ -703,7 +744,7 @@ function desiredMapView(): { camera: StaticMapCamera; key: string; path: Array<[
|
||||
const position = currentPosition();
|
||||
if (!position) return null;
|
||||
const zoom = currentZoom();
|
||||
const bearing = Math.round(currentBearing() / BEARING_BUCKET_DEG) * BEARING_BUCKET_DEG;
|
||||
const bearing = phase === "map" ? 0 : Math.round(currentBearing() / BEARING_BUCKET_DEG) * BEARING_BUCKET_DEG;
|
||||
const path =
|
||||
follower && progress
|
||||
? simplifyPath(follower.routeSliceAround(progress.alongMeters, 250, 3000), 80)
|
||||
@@ -721,6 +762,7 @@ function desiredMapView(): { camera: StaticMapCamera; key: string; path: Array<[
|
||||
* a few seconds passed while moving. Single-flight with failure backoff.
|
||||
*/
|
||||
function maybeRefreshMap(): void {
|
||||
if (phase !== "navigating" && phase !== "map") return;
|
||||
if (!window || !window.foreground || !screenOn) return;
|
||||
if (mapInFlight || Date.now() < mapNextRetryAtMs) return;
|
||||
if (!isMapboxConfigured()) return;
|
||||
@@ -730,7 +772,8 @@ function maybeRefreshMap(): void {
|
||||
let stale = mapImage === null || view.key !== mapFetchedKey;
|
||||
if (!stale && view.camera.kind === "center" && mapLastFetchCenter) {
|
||||
const moved = haversineMeters(mapLastFetchCenter, [view.camera.longitude, view.camera.latitude]);
|
||||
const viewportMeters = MAP_SIZE * metersPerPixel(view.camera.zoom, view.camera.latitude);
|
||||
const size = mapDimensions();
|
||||
const viewportMeters = Math.min(size.width, size.height) * metersPerPixel(view.camera.zoom, view.camera.latitude);
|
||||
if (moved > viewportMeters * MOVE_REFRESH_FRACTION) stale = true;
|
||||
else if (Date.now() - mapLastFetchAtMs > IDLE_REFRESH_MS && moved > IDLE_REFRESH_MIN_MOVE_M) stale = true;
|
||||
}
|
||||
@@ -740,13 +783,12 @@ function maybeRefreshMap(): void {
|
||||
const generation = routeGeneration;
|
||||
fetchStaticMapGray({
|
||||
camera: view.camera,
|
||||
width: MAP_SIZE,
|
||||
height: MAP_SIZE,
|
||||
...mapDimensions(),
|
||||
routePath: view.path.length >= 2 ? view.path : undefined,
|
||||
})
|
||||
.then((image) => {
|
||||
mapInFlight = false;
|
||||
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
|
||||
mapInFlight = false;
|
||||
levelMap(image);
|
||||
mapImage = image;
|
||||
mapFetchedKey = view.key;
|
||||
@@ -757,6 +799,7 @@ function maybeRefreshMap(): void {
|
||||
render();
|
||||
})
|
||||
.catch((error) => {
|
||||
if (generation !== routeGeneration) return;
|
||||
mapInFlight = false;
|
||||
mapNextRetryAtMs = Date.now() + MAP_RETRY_BACKOFF_MS;
|
||||
mapLastError = String((error as Error)?.message ?? error);
|
||||
@@ -764,6 +807,12 @@ function maybeRefreshMap(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function mapDimensions(): { width: number; height: number } {
|
||||
return phase === "map" && window
|
||||
? { width: window.viewportWidth, height: Math.max(1, window.viewportHeight - 30) }
|
||||
: { width: MAP_SIZE, height: MAP_SIZE };
|
||||
}
|
||||
|
||||
/** Keep every Nth point (ends always included) to bound the overlay URL size. */
|
||||
function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[number, number]> {
|
||||
if (path.length <= maxPoints) return path;
|
||||
@@ -845,6 +894,7 @@ function startSummary(picked: GeocodeCandidate, candidates: GeocodeCandidate[],
|
||||
}
|
||||
|
||||
function describeRouteStatus(): string {
|
||||
if (phase === "map") return "Showing the map around your current location. No destination set.";
|
||||
if (phase === "arrived") return `Arrived at ${destinationName}.`;
|
||||
if (phase !== "navigating" || !follower) return "Navigation is not active.";
|
||||
if (!progress) return `Navigating to ${destinationName}; waiting for a GPS fix.`;
|
||||
@@ -866,12 +916,12 @@ function describeRouteStatus(): string {
|
||||
*/
|
||||
function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
if (phase === "navigating" || phase === "arrived") {
|
||||
if (phase !== "idle") {
|
||||
items.push({
|
||||
label: "Stop navigation",
|
||||
label: phase === "map" ? "Close map" : "Stop navigation",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
stopNavigation("Navigation stopped.");
|
||||
stopNavigation(phase === "map" ? "" : "Navigation stopped.");
|
||||
render();
|
||||
},
|
||||
});
|
||||
@@ -895,7 +945,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
onSelect: () => {
|
||||
const enabled = navigateRememberRecentSetting.toggle();
|
||||
if (!enabled) clearRecentDestinations();
|
||||
clampIdleSelection();
|
||||
syncIdleList();
|
||||
},
|
||||
render: ({ image, x, y, width, selected }) => {
|
||||
drawToggleMenuItem(
|
||||
@@ -910,7 +960,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
);
|
||||
},
|
||||
});
|
||||
const selectedEntry = phase === "idle" ? idleEntries()[idleSelection] : undefined;
|
||||
const selectedEntry = phase === "idle" ? syncIdleList().selectedItem : null;
|
||||
if (selectedEntry?.kind === "recent") {
|
||||
const recent = selectedEntry.destination;
|
||||
items.push({
|
||||
@@ -918,7 +968,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
removeRecentDestination(recent);
|
||||
clampIdleSelection();
|
||||
syncIdleList();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -928,7 +978,7 @@ function windowMenuItems(win: NavWindow): MenuItem[] {
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
clearRecentDestinations();
|
||||
clampIdleSelection();
|
||||
syncIdleList();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1013,7 +1063,7 @@ function customDestinationMenuItems(destination: SavedDestination): MenuItem[] {
|
||||
onSelect: (ctx) => {
|
||||
closeMenusAnd(ctx, () => {
|
||||
removeCustomDestination(destination.id);
|
||||
clampIdleSelection();
|
||||
syncIdleList();
|
||||
});
|
||||
},
|
||||
},
|
||||
@@ -1068,7 +1118,7 @@ function finishEdit(confirmed: boolean): void {
|
||||
if (!editing) {
|
||||
navigateDestinationNameDraftSetting.set("");
|
||||
navigateDestinationAddressDraftSetting.set("");
|
||||
clampIdleSelection();
|
||||
syncIdleList();
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1123,7 +1173,7 @@ function tokenSetupEntries(): IdleEntry[] {
|
||||
detail: "Get a free token in the phone browser",
|
||||
run: () => {
|
||||
statusMessage = openUrlOnPhone(MAPBOX_TOKENS_URL)
|
||||
? "Opened mapbox.com on your phone. Copy your public token (pk...) and pick Edit token."
|
||||
? "Opening mapbox.com on your phone. Copy your public token (pk...) and pick Edit token."
|
||||
: "Could not open a browser on the phone. Visit account.mapbox.com/access-tokens to get a token.";
|
||||
},
|
||||
},
|
||||
@@ -1138,18 +1188,42 @@ function tokenSetupEntries(): IdleEntry[] {
|
||||
|
||||
function idleEntries(): IdleEntry[] {
|
||||
if (!isMapboxConfigured()) return tokenSetupEntries();
|
||||
const entries: IdleEntry[] = loadSavedDestinations()
|
||||
const entries: IdleEntry[] = [{
|
||||
kind: "action",
|
||||
label: "Map around me",
|
||||
detail: "Follow my location",
|
||||
run: () => { void startMap(); },
|
||||
}];
|
||||
entries.push(...loadSavedDestinations()
|
||||
.filter((destination) => destination.address)
|
||||
.map((destination): IdleEntry => ({ kind: "saved", destination }));
|
||||
.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));
|
||||
/** Horizontal inset of the idle list's selection boxes. */
|
||||
const IDLE_LIST_X = 20;
|
||||
/** Pixels between consecutive idle rows' selection boxes. */
|
||||
const IDLE_ROW_GAP = 2;
|
||||
|
||||
function idleList(): Menu<IdleEntry> {
|
||||
idleMenu ??= new Menu<IdleEntry>({
|
||||
wrap: false,
|
||||
rowGap: IDLE_ROW_GAP,
|
||||
highlight: { radius: 6 },
|
||||
getHeight: () => listRowHeight(smallFont),
|
||||
draw: drawIdleRow,
|
||||
});
|
||||
return idleMenu;
|
||||
}
|
||||
|
||||
/** Refresh the idle list from idleEntries(); the selection keeps its index, clamped into range. */
|
||||
function syncIdleList(): Menu<IdleEntry> {
|
||||
const list = idleList();
|
||||
list.setItems(idleEntries());
|
||||
return list;
|
||||
}
|
||||
|
||||
function navigateToIdleEntry(entry: IdleEntry): void {
|
||||
@@ -1220,10 +1294,10 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
|
||||
mapMode = mapMode === "follow" ? "overview" : "follow";
|
||||
resetMapState();
|
||||
maybeRefreshMap();
|
||||
} else if (phase === "arrived") {
|
||||
} else if (phase === "arrived" || phase === "map") {
|
||||
stopNavigation("");
|
||||
} else if (phase === "idle") {
|
||||
const entry = idleEntries()[idleSelection];
|
||||
const entry = syncIdleList().selectedItem;
|
||||
if (!entry) {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate ignored click");
|
||||
return;
|
||||
@@ -1237,13 +1311,12 @@ function handleInput(win: NavWindow, event: InputEvent, frameId: number): void {
|
||||
return;
|
||||
}
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
if (phase === "navigating" && mapMode === "follow") {
|
||||
if ((phase === "navigating" || phase === "map") && mapMode === "follow") {
|
||||
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)));
|
||||
syncIdleList().moveSelection(event.type === "scroll-down" ? 1 : -1);
|
||||
renderAndSubmit(win, frameId);
|
||||
} else {
|
||||
frameTimings.finishFrame(frameId, "discarded: navigate ignored scroll");
|
||||
@@ -1264,6 +1337,8 @@ function paintContent(win: NavWindow): GrayImage {
|
||||
const image = new GrayImage(win.viewportWidth, win.viewportHeight, 0);
|
||||
if (editing) {
|
||||
paintEdit(image, editing);
|
||||
} else if (phase === "map") {
|
||||
paintMap(image);
|
||||
} else if (phase === "idle" || phase === "acquiring" || phase === "routing") {
|
||||
paintIdle(image, win);
|
||||
} else {
|
||||
@@ -1300,7 +1375,7 @@ function paintIdle(image: GrayImage, win: NavWindow): void {
|
||||
const hint = !configured
|
||||
? "Navigation needs a Mapbox public token (free at mapbox.com). Get one, then enter it here or in Settings > API Keys."
|
||||
: entries.length
|
||||
? "Pick a destination below, or say one via Voice input (system menu, long-press)."
|
||||
? "View the map or pick a destination below. Use Voice input (system menu, long-press) to say a destination."
|
||||
: "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;
|
||||
@@ -1326,64 +1401,38 @@ function paintIdle(image: GrayImage, win: NavWindow): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Saved destinations (name + address) then recent places, one selectable row each. */
|
||||
/** Map action, saved destinations, 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 === "action") {
|
||||
const label = truncateText(smallFont, entry.label, labelWidth);
|
||||
image.drawText(smallFont, textX, textY, label, selected ? 245 : 210);
|
||||
const detailX = textX + labelWidth + 8;
|
||||
image.drawText(
|
||||
smallFont,
|
||||
detailX,
|
||||
textY,
|
||||
truncateText(smallFont, entry.detail, rowX + rowWidth - 6 - detailX),
|
||||
selected ? 170 : 130,
|
||||
);
|
||||
} else 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);
|
||||
const list = idleList();
|
||||
list.setItems(entries);
|
||||
list.paint(image, { x: IDLE_LIST_X, y: top, width: rowWidth, height: visibleRows * rowHeight - IDLE_ROW_GAP }, win.focused);
|
||||
list.drawScrollbar(image, IDLE_LIST_X + rowWidth + 4, top, visibleRows * rowHeight - 2);
|
||||
}
|
||||
|
||||
/** Two columns: the entry's name, then its detail (action hint, address or place). */
|
||||
function drawIdleRow({ image, item: entry, x, y, width, selected }: MenuDrawArgs<IdleEntry>): void {
|
||||
const labelWidth = Math.floor(width * 0.4);
|
||||
const textX = x + 6;
|
||||
const textY = y + LIST_ROW_TEXT_INSET;
|
||||
let label: string;
|
||||
let detail: string;
|
||||
if (entry.kind === "action") {
|
||||
label = entry.label;
|
||||
detail = entry.detail;
|
||||
} else if (entry.kind === "saved") {
|
||||
label = entry.destination.name;
|
||||
detail = entry.destination.address;
|
||||
} else {
|
||||
label = entry.destination.name;
|
||||
detail = entry.destination.place ? `${entry.destination.place} (recent)` : "(recent)";
|
||||
}
|
||||
image.drawText(smallFont, textX, textY, truncateText(smallFont, label, labelWidth), selected ? 245 : 210);
|
||||
const detailX = textX + labelWidth + 8;
|
||||
image.drawText(smallFont, detailX, textY, truncateText(smallFont, detail, x + width - 6 - detailX), selected ? 170 : 130);
|
||||
}
|
||||
|
||||
function paintNavigating(image: GrayImage, win: NavWindow): void {
|
||||
@@ -1455,6 +1504,21 @@ function paintNavigating(image: GrayImage, win: NavWindow): void {
|
||||
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8);
|
||||
}
|
||||
|
||||
function paintMap(image: GrayImage): void {
|
||||
const { width, height } = mapDimensions();
|
||||
if (mapImage) {
|
||||
image.bitBlt(mapImage, 0, 0);
|
||||
drawChevron(image, width / 2, height / 2, headHeadingDeg ?? 0);
|
||||
} else {
|
||||
image.drawText(smallFont, 24, height / 2 - 8, mapLastError ? "Map unavailable; retrying..." : "Loading map...", 170);
|
||||
}
|
||||
if (statusMessage) {
|
||||
image.fillRect(0, 0, width, smallFont.lineHeight + 8, 0);
|
||||
image.drawText(smallFont, 16, 4, truncateText(smallFont, statusMessage, width - 32), 200);
|
||||
}
|
||||
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} destinations ${GESTURE_DOUBLE_CLICK} back`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { type TrackedLocation } from '../../native/location-types'
|
||||
import { type CompassEvent } from '../../native/compass-types'
|
||||
|
||||
export type NavigationSensorRequest =
|
||||
| { action: 'start'; id: number; intervalMs: number }
|
||||
| { action: 'stop'; id: number }
|
||||
| { action: 'compass'; enabled: boolean }
|
||||
export type NavigationSensorEvent =
|
||||
| { kind: 'location'; id: number; location: TrackedLocation }
|
||||
| { kind: 'error'; id: number; message: string }
|
||||
| { kind: 'compass'; event: CompassEvent; declination: number | null }
|
||||
@@ -0,0 +1,45 @@
|
||||
import { type LocationTrackerCallbacks } from '../../native/location-types'
|
||||
import { type CompassEvent } from '../../native/compass-types'
|
||||
import { type NavigationSensorEvent, type NavigationSensorRequest } from './navigation-sensors-messages'
|
||||
export { type TrackedLocation } from '../../native/location-types'
|
||||
export { COMPASS_CHANGED, type CompassEvent } from '../../native/compass-types'
|
||||
declare const global: any
|
||||
|
||||
const listeners = new Set<(event: CompassEvent) => void>()
|
||||
const trackers = new Map<number, LocationTracker>()
|
||||
let nextId = 0
|
||||
let declination: number | null = null
|
||||
function send(request: NavigationSensorRequest): void {
|
||||
global.postMessage({ type: 'navigation-sensors', request })
|
||||
}
|
||||
export class LocationTracker {
|
||||
private id = 0
|
||||
constructor(private readonly callbacks: LocationTrackerCallbacks) {}
|
||||
isRunning(): boolean { return this.id !== 0 }
|
||||
start(intervalMs = 1000): void {
|
||||
if (this.id) return
|
||||
this.id = ++nextId; trackers.set(this.id, this)
|
||||
send({ action: 'start', id: this.id, intervalMs })
|
||||
}
|
||||
stop(): void {
|
||||
if (!this.id) return
|
||||
const id = this.id; this.id = 0; trackers.delete(id)
|
||||
send({ action: 'stop', id })
|
||||
}
|
||||
receive(event: NavigationSensorEvent): void {
|
||||
if (event.kind === 'location') this.callbacks.onLocation(event.location)
|
||||
else if (event.kind === 'error') { this.stop(); this.callbacks.onError(event.message) }
|
||||
}
|
||||
}
|
||||
export function handleNavigationSensorEvent(event: NavigationSensorEvent): void {
|
||||
if (event.kind === 'compass') {
|
||||
declination = event.declination
|
||||
for (const listener of [...listeners]) listener(event.event)
|
||||
} else trackers.get(event.id)?.receive(event)
|
||||
}
|
||||
export function addCompassListener(listener: (event: CompassEvent) => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
}
|
||||
export function setCompassEnabled(enabled: boolean, _owner?: string): void { send({ action: 'compass', enabled }) }
|
||||
export function magneticDeclinationDegrees(_latitude: number, _longitude: number): number | null { return declination }
|
||||
@@ -0,0 +1,13 @@
|
||||
import { type NavigationSensorEvent } from './navigation-sensors-messages'
|
||||
export { LocationTracker, type TrackedLocation } from '../../native/location-tracker'
|
||||
export { addCompassListener, setCompassEnabled, COMPASS_CHANGED, type CompassEvent } from '../../native/compass'
|
||||
import { magneticDeclinationDegrees as calculate } from '../../native/geomagnetic'
|
||||
let cached: { latitude: number; longitude: number; degrees: number | null } | null = null
|
||||
export function magneticDeclinationDegrees(latitude: number, longitude: number): number | null {
|
||||
if (!cached || Math.abs(latitude - cached.latitude) > 0.5 || Math.abs(longitude - cached.longitude) > 0.5)
|
||||
cached = { latitude, longitude, degrees: calculate(latitude, longitude) }
|
||||
return cached.degrees
|
||||
}
|
||||
|
||||
/** Android delivers native callbacks directly on the worker's Looper. */
|
||||
export function handleNavigationSensorEvent(_event: NavigationSensorEvent): void {}
|
||||
@@ -62,6 +62,7 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
reconfigureSurface: options.reconfigureSurface,
|
||||
onClosed: () => {
|
||||
windowRenders.delete(render);
|
||||
syncNightscout();
|
||||
|
||||
@@ -420,11 +420,11 @@ export function nightscoutMenuItems(): MenuItem[] {
|
||||
openSettingsSubMenu(ctx, "Nightscout settings", [
|
||||
textSettingMenuItem(nightscoutSiteUrlSetting),
|
||||
textSettingMenuItem(nightscoutApiTokenSetting),
|
||||
toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting),
|
||||
textSettingMenuItem(nightscoutMaxCannulaAgeSetting),
|
||||
textSettingMenuItem(nightscoutCartridgeLowSetting),
|
||||
textSettingMenuItem(nightscoutBatteryLowSetting),
|
||||
textSettingMenuItem(nightscoutMaxLoopAgeSetting),
|
||||
toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting),
|
||||
]);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
* keep the BLE payload down to the dirty region around the ball.
|
||||
*
|
||||
* Controls (ball ready): scroll sets launch power, click launches. In play:
|
||||
* click flips both flippers, scroll-up/down flips left/right individually,
|
||||
* double-click pauses. Watch swipes: left/right work the matching flipper,
|
||||
* ring-press flips both flippers for 300 ms; click launches from the plunger,
|
||||
* double-click pauses. Swipes no longer trigger individual flippers;
|
||||
* up/down raise and lower launch power at the plunger.
|
||||
* Paused/game over: click resumes or starts a new game, double-click yields
|
||||
* focus, long-press opens the window menu. Losing input focus mid-game (a
|
||||
@@ -21,12 +21,14 @@
|
||||
* sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
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 { playWorkerBuzzerSequence } from "../../native/worker-buzzer";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import { buildSoundSequencePayload, type Step } from "../../ui/sound-effects";
|
||||
@@ -44,7 +46,6 @@ import {
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
@@ -92,8 +93,8 @@ const FLIPPER_REST_DEG = 32;
|
||||
const FLIPPER_UP_DEG = -34;
|
||||
const FLIPPER_RISE_DEG_PER_S = 950;
|
||||
const FLIPPER_FALL_DEG_PER_S = 480;
|
||||
/** Held at the top this long before falling, so early flips still connect. */
|
||||
const FLIPPER_HOLD_MS = 140;
|
||||
/** Activation duration from input to release, including the rise animation. */
|
||||
const FLIPPER_HOLD_MS = 300;
|
||||
const FLIPPER_E = 0.4;
|
||||
|
||||
type SegmentKind = "wall" | "gate" | "sling";
|
||||
@@ -290,6 +291,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: PinballWindow = {
|
||||
windowId: message.windowId,
|
||||
@@ -429,7 +436,7 @@ function saveHighScore(window: PinballWindow): void {
|
||||
|
||||
/**
|
||||
* Fire a buzzer effect. Non-blocking: the firmware's sequencer plays the
|
||||
* steps on its own timer, and the Java call is safe from the worker thread.
|
||||
* steps on its own timer; the platform bridge routes it from the worker.
|
||||
* Minor (frequent) effects are dropped when they'd arrive within the
|
||||
* rate-limit gap; newsworthy ones always play.
|
||||
*/
|
||||
@@ -439,9 +446,7 @@ function playSfx(window: PinballWindow, steps: Step[], minor = false): void {
|
||||
if (minor && now - window.lastMinorSfxAtMs < MINOR_SFX_MIN_GAP_MS) return;
|
||||
if (minor) window.lastMinorSfxAtMs = now;
|
||||
try {
|
||||
const communicator = com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
if (!communicator) return;
|
||||
communicator.playBuzzerSequence(buildSoundSequencePayload(steps).buffer);
|
||||
playWorkerBuzzerSequence(buildSoundSequencePayload(steps));
|
||||
} catch (error) {
|
||||
console.warn(`pinball sfx failed: ${error}`);
|
||||
}
|
||||
@@ -509,25 +514,14 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n
|
||||
case "scroll-up":
|
||||
if (ready) {
|
||||
window.launchPower = clamp(window.launchPower + 1, 1, LAUNCH_SPEEDS.length);
|
||||
} else {
|
||||
flip(window, window.flippers[0]!);
|
||||
}
|
||||
break;
|
||||
case "scroll-down":
|
||||
if (ready) {
|
||||
window.launchPower = clamp(window.launchPower - 1, 1, LAUNCH_SPEEDS.length);
|
||||
} else {
|
||||
flip(window, window.flippers[1]!);
|
||||
}
|
||||
break;
|
||||
// Watch swipes: left/right work the matching flipper; up/down set the
|
||||
// launch power at the plunger.
|
||||
case "swipe-left":
|
||||
if (!ready) flip(window, window.flippers[0]!);
|
||||
break;
|
||||
case "swipe-right":
|
||||
if (!ready) flip(window, window.flippers[1]!);
|
||||
break;
|
||||
// Watch swipes up/down still set launch power at the plunger.
|
||||
case "swipe-up":
|
||||
if (ready) {
|
||||
window.launchPower = clamp(window.launchPower + 1, 1, LAUNCH_SPEEDS.length);
|
||||
@@ -538,10 +532,14 @@ function handlePlayingInput(window: PinballWindow, event: InputEvent, frameId: n
|
||||
window.launchPower = clamp(window.launchPower - 1, 1, LAUNCH_SPEEDS.length);
|
||||
}
|
||||
break;
|
||||
case "ring-press":
|
||||
flip(window, window.flippers[0]!);
|
||||
flip(window, window.flippers[1]!);
|
||||
break;
|
||||
case "click":
|
||||
if (ready) {
|
||||
launchBall(window);
|
||||
} else {
|
||||
} else if (event.source !== "ring") {
|
||||
flip(window, window.flippers[0]!);
|
||||
flip(window, window.flippers[1]!);
|
||||
}
|
||||
@@ -618,10 +616,9 @@ function launchBall(window: PinballWindow): void {
|
||||
}
|
||||
|
||||
function flip(window: PinballWindow, flipper: Flipper): void {
|
||||
if (flipper.state === "hold") {
|
||||
flipper.holdUntilMs = Date.now() + FLIPPER_HOLD_MS;
|
||||
return;
|
||||
}
|
||||
// Time the pulse from the input, including the rise animation.
|
||||
flipper.holdUntilMs = Date.now() + FLIPPER_HOLD_MS;
|
||||
if (flipper.state === "hold") return;
|
||||
flipper.state = "rising";
|
||||
playSfx(window, SFX_FLIPPER, true);
|
||||
}
|
||||
@@ -727,7 +724,7 @@ function stepFlippers(window: PinballWindow, dt: number): void {
|
||||
if (flipper.angleDeg <= FLIPPER_UP_DEG) {
|
||||
flipper.angleDeg = FLIPPER_UP_DEG;
|
||||
flipper.state = "hold";
|
||||
flipper.holdUntilMs = now + FLIPPER_HOLD_MS;
|
||||
if (now >= flipper.holdUntilMs) flipper.state = "falling";
|
||||
}
|
||||
break;
|
||||
case "hold":
|
||||
@@ -1015,7 +1012,7 @@ function paintPanel(image: GrayImage, window: PinballWindow): void {
|
||||
image.drawText(smallFont, PANEL_X, 216, `${GESTURE_SCROLL} power ${GESTURE_CLICK} launch`, 115);
|
||||
image.drawText(smallFont, PANEL_X, 236, `${GESTURE_DOUBLE_CLICK} pause`, 115);
|
||||
} else {
|
||||
image.drawText(smallFont, PANEL_X, 216, `${GESTURE_CLICK} flip ${GESTURE_SCROLL} L/R flip`, 115);
|
||||
image.drawText(smallFont, PANEL_X, 216, "Touch ring: both flippers", 115);
|
||||
image.drawText(smallFont, PANEL_X, 236, `${GESTURE_DOUBLE_CLICK} pause`, 115);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* menu, via the phone app's text editor.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -165,6 +166,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -52,10 +52,8 @@ export type TeleprompterAppOptions = InProcessAppOptions & {
|
||||
* 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);
|
||||
// The home menu's items are replaced (refreshHome) whenever the recents change.
|
||||
const home = new MenuLayer("Teleprompter", [], HOME_LAYOUT);
|
||||
let created: InProcessWindow | null = null;
|
||||
let notice = "";
|
||||
|
||||
@@ -142,10 +140,8 @@ export function createTeleprompterAppWindow(options: TeleprompterAppOptions): In
|
||||
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);
|
||||
home.setItems(items, getRecentScripts().length > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
refreshHome();
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isTerminalWidgetConfigured } from "../glanceboard/configuration";
|
||||
import { loadConnections, parseConnectionString } from "./connections";
|
||||
|
||||
/** Keep session-list connections alive for a configured widget, even while it is hidden. */
|
||||
export function hasTerminalBackgroundWork(): boolean {
|
||||
return isTerminalWidgetConfigured() &&
|
||||
loadConnections().some(connection => connection.enabled && parseConnectionString(connection.url) !== null);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { wrapText, type WrapFont } from '../../graphics/textwrap';
|
||||
|
||||
/** Keep short status on the title row; give long errors their full width. */
|
||||
export function layoutHubHeader(font: WrapFont, title: string, status: string, width: number, step: number) {
|
||||
const inlineX = 18 + font.measureText(title) + 16;
|
||||
const inline = !/[\r\n]/.test(status) && font.measureText(status) <= Math.max(0, width - inlineX - 12);
|
||||
const lines = inline ? [status] : wrapText(font, status, Math.max(1, width - 30));
|
||||
const x = inline ? inlineX : 18;
|
||||
const y = inline ? 10 : 10 + step;
|
||||
return { x, y, lines, listTop: inline ? 16 + step : 16 + step * (1 + lines.length) };
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
* Terminal app, hosted in its own worker thread. Window model:
|
||||
* - "terminal:hub": the window opened from the launcher; shows the list of
|
||||
* live g2mirror sessions across every connected host (grouped by host when
|
||||
* more than one is connected), and hosts the Manage Connections section
|
||||
* more than one is connected; selecting a host's heading launches a shell
|
||||
* there), and hosts the Manage Connections section
|
||||
* where g2mirror:// connections are added, removed, and toggled.
|
||||
* - "terminal:view:N": opened by selecting a session in the hub; each has
|
||||
* its own websocket connection (the protocol allows one attached session
|
||||
@@ -31,10 +32,13 @@
|
||||
* re-attach snapshot resyncs contents and scrollback only once it's needed.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { hasTerminalBackgroundWork } from "./background";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts";
|
||||
import { layoutHubHeader } from "./hub-header";
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
import { TERMINAL_ICON_GLYPHS, type IconActivity } from "../../graphics/icons";
|
||||
import {
|
||||
@@ -51,7 +55,8 @@ import { clamp } from "../../util/numeric-util";
|
||||
import { terminalAutoReconnectSetting, terminalLaunchPresetsSetting, terminalNewConnectionSetting, terminalWakeOnBellSetting } from "../../ui/dashboard-settings";
|
||||
import { connectionDisplayName, loadConnections, parseConnectionString, saveConnections, TERMINAL_CONNECTIONS_KEY, updateConnection, type TerminalConnection } from "./connections";
|
||||
import { TerminalEmulator } from "./terminal-emulator";
|
||||
import { drawListScrollbar, drawSelectionHighlight, scrollToKeepSelectionVisible, type MenuItem } from "../../ui/menu";
|
||||
import { type MenuItem } from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { lineStep, listRowHeight } from "../../ui/metrics";
|
||||
import { WindowMenu } from "../../ui/window-menu";
|
||||
import { appViewportSize } from "../../ui/shell/geometry";
|
||||
@@ -123,8 +128,8 @@ type HubMode = "sessions" | "connections" | "add";
|
||||
type HubWindow = BaseWindow & {
|
||||
kind: "hub";
|
||||
mode: HubMode;
|
||||
selectedIndex: number;
|
||||
scrollRow: number;
|
||||
/** The section's item list; created on first paint or input (hubMenu). */
|
||||
list: Menu<HubItem> | null;
|
||||
/**
|
||||
* Session recency keys in display order, captured when the window last
|
||||
* became visible so the list doesn't reshuffle under the user while it's
|
||||
@@ -310,6 +315,14 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
reportIdle();
|
||||
break;
|
||||
case "shutdown":
|
||||
for (const control of controls.values()) stopControl(control);
|
||||
controls.clear();
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
openWindow(message.windowId, message.surfaceId, message.title, message.viewport);
|
||||
break;
|
||||
@@ -361,7 +374,8 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
// Enter ("\r") after a wrapper-side pause so paste-detecting apps
|
||||
// (e.g. Claude Code) submit instead of inserting a newline.
|
||||
if (window && window.kind === "view") {
|
||||
window.client.submitInput(message.text);
|
||||
if (message.submit === false) window.client.sendInput(message.text);
|
||||
else window.client.submitInput(message.text);
|
||||
} else if (window && window.kind === "hub" && window.mode === "add") {
|
||||
terminalNewConnectionSetting.set(message.text);
|
||||
scheduleRender(window);
|
||||
@@ -422,12 +436,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
// toggles edited in the Settings app, the Add-connection draft typed on the
|
||||
// phone).
|
||||
onSettingsStoreChanged((key) => {
|
||||
if (key.startsWith("glanceboard.")) {
|
||||
reportIdle();
|
||||
return;
|
||||
}
|
||||
if (!key.startsWith("terminal.")) return;
|
||||
switch (key) {
|
||||
case TERMINAL_CONNECTIONS_KEY:
|
||||
// Only once the app has actually been opened.
|
||||
if (controlsInitialized) syncControlsFromSettings();
|
||||
renderHubWindows();
|
||||
reportIdle();
|
||||
return;
|
||||
case NEW_CONNECTION_DRAFT_KEY:
|
||||
// Live keystrokes from the phone editor; repaint the add screen.
|
||||
@@ -436,7 +455,7 @@ onSettingsStoreChanged((key) => {
|
||||
case "terminal.autoReconnect":
|
||||
if (!terminalAutoReconnectSetting.get()) {
|
||||
cancelPendingReconnects();
|
||||
} else if (windows.size > 0) {
|
||||
} else if (windows.size > 0 || hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
if ((control.state?.phase ?? "idle") === "failed") scheduleControlReconnect(control);
|
||||
}
|
||||
@@ -448,6 +467,10 @@ onSettingsStoreChanged((key) => {
|
||||
}
|
||||
});
|
||||
|
||||
function reportIdle(): void {
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) post({ type: "worker-idle" });
|
||||
}
|
||||
|
||||
/** Cancel scheduled retries (auto-reconnect turned off); stale views stay marked. */
|
||||
function cancelPendingReconnects(): void {
|
||||
for (const control of controls.values()) {
|
||||
@@ -486,8 +509,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
|
||||
lastSubmittedFingerprint: "",
|
||||
menu: null,
|
||||
mode: "sessions",
|
||||
selectedIndex: 0,
|
||||
scrollRow: 0,
|
||||
list: null,
|
||||
sessionOrder: [],
|
||||
addError: "",
|
||||
});
|
||||
@@ -519,8 +541,8 @@ function closeWindow(windowId: string): void {
|
||||
windows.delete(windowId);
|
||||
windowIconActivity.delete(windowId);
|
||||
updateHubAnimation();
|
||||
// Auto-reconnect only runs while at least one terminal window is open.
|
||||
if (windows.size === 0) {
|
||||
// A configured widget owns the control connections after the last window closes.
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
cancelControlReconnect(control);
|
||||
}
|
||||
@@ -674,19 +696,18 @@ function noteSessionListRecency(control: ControlConnection, state: G2MirrorState
|
||||
/**
|
||||
* Retry a control connection after a backoff delay. The delay doubles per
|
||||
* scheduled attempt and resets when a connection reaches "connected" (or on
|
||||
* a manual Connect). No-op when auto-reconnect is off, no terminal window is
|
||||
* open, or the connection was disabled/removed meanwhile.
|
||||
* a manual Connect). Windows and a configured widget can both own the client.
|
||||
*/
|
||||
function scheduleControlReconnect(control: ControlConnection): void {
|
||||
if (control.reconnectTimer) return;
|
||||
if (!terminalAutoReconnectSetting.get()) return;
|
||||
if (windows.size === 0) return;
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) return;
|
||||
if (!control.config.enabled) return;
|
||||
const delayMs = control.reconnectDelayMs;
|
||||
control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS);
|
||||
control.reconnectTimer = setTimeout(() => {
|
||||
control.reconnectTimer = null;
|
||||
if (!terminalAutoReconnectSetting.get() || windows.size === 0) return;
|
||||
if (!terminalAutoReconnectSetting.get() || (windows.size === 0 && !hasTerminalBackgroundWork())) return;
|
||||
if (controls.get(control.config.id) !== control || !control.config.enabled) return;
|
||||
if ((control.state?.phase ?? "idle") === "failed") startControl(control);
|
||||
}, delayMs);
|
||||
@@ -1027,10 +1048,7 @@ function windowMenuItems(window: TerminalWindow): MenuItem[] {
|
||||
label,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
launchAndOpenView(control, preset).catch((error) => {
|
||||
// The hub status line also shows the server's error message.
|
||||
console.warn(`terminal launch ${preset} failed: ${error}`);
|
||||
});
|
||||
launchFromUi(control, preset);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1160,7 +1178,10 @@ function applyHistoryReply(window: ViewWindow, reply: { start: number; oldest: n
|
||||
|
||||
type HubItem = {
|
||||
label: string;
|
||||
/** Group heading (host name): drawn differently and skipped by selection. */
|
||||
/**
|
||||
* Group heading (host name): drawn unindented and dimmer. Selectable only
|
||||
* when it has an onSelect (launch a shell on that host).
|
||||
*/
|
||||
heading?: boolean;
|
||||
/** Session with recent output: an animated indicator marks the row. */
|
||||
active?: boolean;
|
||||
@@ -1169,11 +1190,48 @@ type HubItem = {
|
||||
onSelect?: () => void;
|
||||
};
|
||||
|
||||
/** Vertical offset of a row's text line from the top of its selection box. */
|
||||
const HUB_ROW_TEXT_INSET = 4;
|
||||
/** Horizontal inset of the list's selection boxes from the viewport edges. */
|
||||
const HUB_LIST_X = 20;
|
||||
|
||||
/** The hub window's list, created on first use so openWindow stays free of paint dependencies. */
|
||||
function hubMenu(window: HubWindow): Menu<HubItem> {
|
||||
window.list ??= new Menu<HubItem>({
|
||||
wrap: false,
|
||||
rowGap: 1,
|
||||
getHeight: () => listRowHeight(chromeFont()),
|
||||
isSelectable: (item) => Boolean(item.onSelect),
|
||||
onSelect: (item) => item.onSelect?.(),
|
||||
draw: drawHubRow,
|
||||
});
|
||||
return window.list;
|
||||
}
|
||||
|
||||
function drawHubRow({ image, item, x, y, width, selected }: MenuDrawArgs<HubItem>): void {
|
||||
const font = chromeFont();
|
||||
if (item.heading) {
|
||||
image.drawText(font, x, y + HUB_ROW_TEXT_INSET, item.label, selected ? 255 : 140);
|
||||
return;
|
||||
}
|
||||
// Activity gutter, open-window number column, then the label, truncated
|
||||
// to the row (shared with the Glanceboard's Terminal widget).
|
||||
drawSessionRow(image, font, {
|
||||
x: x + 2,
|
||||
y: y + HUB_ROW_TEXT_INSET,
|
||||
width: width - 8,
|
||||
label: item.label,
|
||||
openGlyph: item.openGlyph ?? null,
|
||||
active: Boolean(item.active),
|
||||
phase: hubAnimationPhase,
|
||||
value: selected ? 255 : 200,
|
||||
});
|
||||
}
|
||||
|
||||
/** Switch the hub between its sections, resetting selection state. */
|
||||
function setHubMode(window: HubWindow, mode: HubMode): void {
|
||||
window.mode = mode;
|
||||
window.selectedIndex = 0;
|
||||
window.scrollRow = 0;
|
||||
window.list?.select(0);
|
||||
window.addError = "";
|
||||
}
|
||||
|
||||
@@ -1225,9 +1283,14 @@ function hubSessionItems(window: HubWindow): HubItem[] {
|
||||
];
|
||||
const connected = connectedControls();
|
||||
const multiHost = connected.length > 1;
|
||||
const canLaunch = launchPresetNames().length > 0;
|
||||
for (const control of connected) {
|
||||
if (multiHost) {
|
||||
items.push({ label: connectionDisplayName(control.config), heading: true });
|
||||
items.push({
|
||||
label: connectionDisplayName(control.config),
|
||||
heading: true,
|
||||
onSelect: canLaunch ? () => launchOnHost(window, control) : undefined,
|
||||
});
|
||||
}
|
||||
const sessions = orderedSessions(window, control);
|
||||
for (const session of sessions) {
|
||||
@@ -1403,34 +1466,6 @@ function endAddConnection(window: HubWindow): void {
|
||||
post({ type: "end-text-setting-edit" });
|
||||
}
|
||||
|
||||
/** Move the hub selection to the next selectable item in `direction`. */
|
||||
function moveHubSelection(window: HubWindow, items: HubItem[], direction: -1 | 1): void {
|
||||
let index = window.selectedIndex + direction;
|
||||
while (index >= 0 && index < items.length && !items[index]!.onSelect) {
|
||||
index += direction;
|
||||
}
|
||||
if (index >= 0 && index < items.length) {
|
||||
window.selectedIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
/** Clamp the selection into range and off heading rows (prefer moving down). */
|
||||
function clampHubSelection(window: HubWindow, items: HubItem[]): void {
|
||||
if (!items.length) {
|
||||
window.selectedIndex = 0;
|
||||
return;
|
||||
}
|
||||
let index = Math.max(0, Math.min(window.selectedIndex, items.length - 1));
|
||||
if (!items[index]!.onSelect) {
|
||||
let forward = index;
|
||||
while (forward < items.length && !items[forward]!.onSelect) forward++;
|
||||
let backward = index;
|
||||
while (backward >= 0 && !items[backward]!.onSelect) backward--;
|
||||
index = forward < items.length ? forward : Math.max(0, backward);
|
||||
}
|
||||
window.selectedIndex = index;
|
||||
}
|
||||
|
||||
function handleHubInput(window: HubWindow, event: InputEvent, frameId: number): void {
|
||||
if (window.mode === "add") {
|
||||
if (event.type === "click") {
|
||||
@@ -1441,23 +1476,18 @@ function handleHubInput(window: HubWindow, event: InputEvent, frameId: number):
|
||||
frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input");
|
||||
return;
|
||||
}
|
||||
const items = hubItems(window);
|
||||
clampHubSelection(window, items);
|
||||
const list = hubMenu(window);
|
||||
list.setItems(hubItems(window));
|
||||
switch (event.type) {
|
||||
case "scroll-up":
|
||||
moveHubSelection(window, items, -1);
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
case "scroll-down":
|
||||
moveHubSelection(window, items, 1);
|
||||
case "click":
|
||||
// The menu's input handler is async only to await onSelect; hub item
|
||||
// callbacks are synchronous, so the selection move or action has
|
||||
// already applied when it returns and the frame can paint right away.
|
||||
list.handleInput(event).catch((error) => console.error("terminal hub action failed", error));
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
case "click": {
|
||||
const item = items[window.selectedIndex];
|
||||
item?.onSelect?.();
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
frameTimings.finishFrame(frameId, "discarded: terminal hub ignored input");
|
||||
return;
|
||||
@@ -1544,6 +1574,37 @@ function launchPresetNames(): string[] {
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* A host heading in the hub was selected: launch a shell there. With a single
|
||||
* launch preset it starts right away; with several, a submenu titled with the
|
||||
* host's name picks which.
|
||||
*/
|
||||
function launchOnHost(window: HubWindow, control: ControlConnection): void {
|
||||
const presets = launchPresetNames();
|
||||
if (presets.length === 1) {
|
||||
launchFromUi(control, presets[0]!);
|
||||
return;
|
||||
}
|
||||
windowMenu(window).open(
|
||||
presets.map((preset) => ({
|
||||
label: `Launch ${preset}`,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
launchFromUi(control, preset);
|
||||
},
|
||||
})),
|
||||
connectionDisplayName(control.config),
|
||||
);
|
||||
}
|
||||
|
||||
/** Launch started from a menu or list row; failures only get logged. */
|
||||
function launchFromUi(control: ControlConnection, preset: string): void {
|
||||
launchAndOpenView(control, preset).catch((error) => {
|
||||
// The hub status line also shows the server's error message.
|
||||
console.warn(`terminal launch ${preset} failed: ${error}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** Launch a preset on a host and open a view window on the new session. */
|
||||
async function launchAndOpenView(control: ControlConnection, preset: string): Promise<string> {
|
||||
if (!control.client) throw new Error("Not connected to the g2mirror server.");
|
||||
@@ -1568,62 +1629,31 @@ function paintHub(window: HubWindow): GrayImage {
|
||||
const font = chromeFont();
|
||||
const step = lineStep(font);
|
||||
// No border box: the shell chrome (top bar + sidebar) already frames the app.
|
||||
// Title and status share the top line.
|
||||
// Long statuses get a wrapped block and move the list below it.
|
||||
const title = window.mode === "connections" ? "Terminal - Connections" : "Terminal";
|
||||
image.drawText(font, 18, 10, title, 220);
|
||||
const statusX = 18 + font.measureText(title) + 16;
|
||||
image.drawText(font, statusX, 10, truncateText(font, hubStatusLine(window), Math.max(0, window.viewportWidth - statusX - 12)), 170);
|
||||
const header = layoutHubHeader(font, title, hubStatusLine(window), window.viewportWidth, step);
|
||||
header.lines.forEach((line, index) => image.drawText(font, header.x, header.y + index * step, line, 170));
|
||||
|
||||
let listTop = 16 + step;
|
||||
let listTop = header.listTop;
|
||||
if (window.mode === "sessions" && controls.size === 0) {
|
||||
image.drawText(font, 24, listTop, "Add a g2mirror:// connection to get started, see:", 150);
|
||||
image.drawText(font, 24, listTop + step, "https://github.com/jimrandomh/g2mirror", 190);
|
||||
listTop += 2 * step + 6;
|
||||
}
|
||||
|
||||
const items = hubItems(window);
|
||||
clampHubSelection(window, items);
|
||||
const hubRowH = listRowHeight(chromeFont());
|
||||
const visibleRowCount = Math.max(1, ((window.viewportHeight - 6 - listTop) / hubRowH) | 0);
|
||||
window.scrollRow = scrollToKeepSelectionVisible(window.scrollRow, window.selectedIndex, visibleRowCount, items.length);
|
||||
const lastVisibleRow = Math.min(items.length, window.scrollRow + visibleRowCount);
|
||||
for (let index = window.scrollRow; index < lastVisibleRow; index++) {
|
||||
const y = listTop + (index - window.scrollRow) * hubRowH;
|
||||
const item = items[index]!;
|
||||
if (item.heading) {
|
||||
image.drawText(chromeFont(), 20, y + 2, item.label, 140);
|
||||
continue;
|
||||
}
|
||||
const selected = index === window.selectedIndex;
|
||||
if (selected) {
|
||||
// Match the shell convention: fill only when this window has focus, so
|
||||
// an outline-only selection signals the sidebar owns input.
|
||||
drawSelectionHighlight(image, 20, y - 2, window.viewportWidth - 40, hubRowH - 1, window.focused, 8);
|
||||
}
|
||||
// Activity gutter, open-window number column, then the label, truncated
|
||||
// to the row (shared with the Glanceboard's Terminal widget).
|
||||
drawSessionRow(image, chromeFont(), {
|
||||
x: 22,
|
||||
y: y + 2,
|
||||
width: window.viewportWidth - 22 - 26,
|
||||
label: item.label,
|
||||
openGlyph: item.openGlyph ?? null,
|
||||
active: Boolean(item.active),
|
||||
phase: hubAnimationPhase,
|
||||
value: selected ? 255 : 200,
|
||||
});
|
||||
}
|
||||
if (items.length > visibleRowCount) {
|
||||
drawListScrollbar(
|
||||
image,
|
||||
window.viewportWidth - 10,
|
||||
listTop,
|
||||
visibleRowCount * hubRowH - 4,
|
||||
window.scrollRow,
|
||||
visibleRowCount,
|
||||
items.length,
|
||||
);
|
||||
}
|
||||
const list = hubMenu(window);
|
||||
list.setItems(hubItems(window));
|
||||
// Selection boxes start above the text line; the menu fills the selected
|
||||
// box only while this window has focus (an outline alone means the sidebar
|
||||
// owns input), matching the shell convention.
|
||||
const listHeight = window.viewportHeight - 6 - listTop;
|
||||
list.paint(
|
||||
image,
|
||||
{ x: HUB_LIST_X, y: listTop - 2, width: window.viewportWidth - 2 * HUB_LIST_X, height: listHeight },
|
||||
window.focused,
|
||||
);
|
||||
list.drawScrollbar(image, window.viewportWidth - 10, listTop, listHeight - 4);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
+104
-89
@@ -31,14 +31,12 @@ import {
|
||||
} from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import {
|
||||
drawListScrollbar,
|
||||
drawRightValueMenuItem,
|
||||
drawSelectionHighlight,
|
||||
drawToggleMenuItem,
|
||||
scrollToKeepSelectionVisible,
|
||||
TextPageLayer,
|
||||
type MenuItem,
|
||||
} from "../../ui/menu";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
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";
|
||||
@@ -91,6 +89,8 @@ const LIST_SHARE = 0.4;
|
||||
const LIST_MIN_WIDTH = 190;
|
||||
const LIST_MAX_WIDTH = 240;
|
||||
const LIST_TOP = 6;
|
||||
/** Pixels between consecutive list rows' selection boxes. */
|
||||
const LIST_ROW_GAP = 1;
|
||||
const STAGE_X = 10;
|
||||
/** Gap between the stage's right edge and the list's divider. */
|
||||
const STAGE_LIST_GAP = 14;
|
||||
@@ -183,8 +183,22 @@ function fittingDigitFont(text: string, maxWidth: number, sizes: readonly number
|
||||
export class TimersLayer implements Layer {
|
||||
readonly acceptsDirectional = true;
|
||||
|
||||
/**
|
||||
* The selected row's key: the source of truth for the selection, which
|
||||
* survives row rebuilds and is pinned to newly ringing items. The list
|
||||
* menu is re-synced from it before each paint, hit test and move.
|
||||
*/
|
||||
private selectionKey = "";
|
||||
private scrollRow = 0;
|
||||
private readonly list = new Menu<Row>({
|
||||
wrap: true,
|
||||
rowGap: LIST_ROW_GAP,
|
||||
highlight: { radius: 6 },
|
||||
getHeight: () => listRowHeight(smallFont()),
|
||||
isSelectable: (row) => row.kind !== "header",
|
||||
draw: (args) => this.drawListRow(args),
|
||||
});
|
||||
/** Per-paint inputs to drawListRow. */
|
||||
private listPaint = { dim: 1, now: 0 };
|
||||
private mode: Mode = { kind: "list" };
|
||||
/** Which of the ringing stage's two buttons is highlighted. */
|
||||
private ringButton = 0;
|
||||
@@ -232,7 +246,8 @@ export class TimersLayer implements Layer {
|
||||
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);
|
||||
const firstVisibleRow = Math.floor(this.list.scrollTop / listRowHeight(smallFont()));
|
||||
index = clamp(firstVisibleRow, 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;
|
||||
@@ -244,14 +259,16 @@ export class TimersLayer implements Layer {
|
||||
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;
|
||||
/** Point the list menu at these rows and the current selection. */
|
||||
private syncList(rows: Row[]): void {
|
||||
this.list.setItems(rows, this.reconcileSelection(rows));
|
||||
}
|
||||
|
||||
private moveSelection(rows: Row[], delta: -1 | 1): void {
|
||||
this.syncList(rows);
|
||||
this.list.moveSelection(delta);
|
||||
const index = this.list.selectedIndex;
|
||||
if (index !== null) this.selectionKey = rows[index]!.key;
|
||||
}
|
||||
|
||||
/** Called on every engine change: jump to a newly ringing item. */
|
||||
@@ -547,15 +564,14 @@ export class TimersLayer implements Layer {
|
||||
/** 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 { width } = 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;
|
||||
this.syncList(rows);
|
||||
const index = this.list.indexAt(y);
|
||||
if (index === null) return true;
|
||||
const row = rows[index]!;
|
||||
if (this.selectionKey === row.key) {
|
||||
this.activateRow(row);
|
||||
} else {
|
||||
@@ -882,79 +898,78 @@ export class TimersLayer implements Layer {
|
||||
dim: number,
|
||||
now: number,
|
||||
): void {
|
||||
const font = smallFont();
|
||||
const rowHeight = listRowHeight(font);
|
||||
const rowHeight = listRowHeight(smallFont());
|
||||
const visible = Math.max(1, Math.floor((height - 2 * LIST_TOP) / rowHeight));
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, selectedIndex, visible, rows.length);
|
||||
this.listPaint = { dim, now };
|
||||
// While a picker owns the stage the list has no live selection, so no
|
||||
// highlight; drawListRow still brightens the selected row by key.
|
||||
this.list.setItems(rows, dim === 1 ? selectedIndex : null);
|
||||
this.list.paint(image, { x: listX, y: LIST_TOP, width: listWidth - 12, height: visible * rowHeight - LIST_ROW_GAP }, focused);
|
||||
this.list.drawScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4);
|
||||
}
|
||||
|
||||
private drawListRow({ image, item: row, x, y, width, height }: MenuDrawArgs<Row>): void {
|
||||
const font = smallFont();
|
||||
const { dim, now } = this.listPaint;
|
||||
const rowHeight = height + LIST_ROW_GAP;
|
||||
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;
|
||||
}
|
||||
const textX = x + 8;
|
||||
const textWidth = width - 12;
|
||||
const textY = y + LIST_ROW_TEXT_INSET;
|
||||
if (row.kind === "header") {
|
||||
image.drawText(font, textX, textY, row.title!, shade(90));
|
||||
return;
|
||||
}
|
||||
if (rows.length > visible) {
|
||||
drawListScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4, this.scrollRow, visible, rows.length);
|
||||
const selected = row.key === this.selectionKey;
|
||||
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, x + width - 10, 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, x + width - 4 - 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 = x + width - 10;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* 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
|
||||
* (FaceclawAlarms.kt) 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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
|
||||
import { ensureLocationPermission, hasLocationPermission } from "../../native/location-permissions";
|
||||
import { weatherBridge } from "../../native/weather";
|
||||
import { WeatherLayer } from "./weather";
|
||||
import {
|
||||
@@ -13,12 +13,13 @@ export const WEATHER_SURFACE_ID = "window:weather";
|
||||
|
||||
/** Local current conditions and forecast from the National Weather Service. */
|
||||
export function createWeatherAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
let closed = false;
|
||||
let requestingPermission = false;
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
let app: InProcessWindow;
|
||||
|
||||
const requestUpdate = () => {
|
||||
if (requestingPermission) return;
|
||||
if (closed || requestingPermission) return;
|
||||
if (hasLocationPermission()) {
|
||||
weatherBridge.start();
|
||||
return;
|
||||
@@ -26,9 +27,10 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
|
||||
requestingPermission = true;
|
||||
void ensureLocationPermission().then((granted) => {
|
||||
requestingPermission = false;
|
||||
if (closed) return;
|
||||
if (granted) weatherBridge.start();
|
||||
app.requestRender();
|
||||
});
|
||||
}).catch((error) => { requestingPermission = false; console.warn(`Weather permission: ${error}`); });
|
||||
};
|
||||
|
||||
app = createInProcessWindow({
|
||||
@@ -52,7 +54,9 @@ export function createWeatherAppWindow(options: InProcessAppOptions): InProcessW
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
reconfigureSurface: options.reconfigureSurface,
|
||||
onClosed: () => {
|
||||
closed = true;
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
weatherBridge.stop();
|
||||
|
||||
+57
-26
@@ -1,12 +1,11 @@
|
||||
import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { type ForecastPeriod, type WeatherState } from "../../native/weather";
|
||||
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { drawSelectionHighlight, scrollToKeepSelectionVisible } from "../../ui/menu";
|
||||
import { lineStep, tightRowHeight } from "../../ui/metrics";
|
||||
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
|
||||
import { centeredTextY, lineStep, tightRowHeight } from "../../ui/metrics";
|
||||
|
||||
const PAGE_X = 18;
|
||||
const HEADER_Y = 8;
|
||||
@@ -18,11 +17,26 @@ const FORECAST_TOP = 124;
|
||||
const FORECAST_MIN_ROW_HEIGHT = 23;
|
||||
/** Gap between forecast columns. */
|
||||
const FORECAST_COL_GAP = 14;
|
||||
/** Left edge of the forecast rows' selection boxes. */
|
||||
const FORECAST_BOX_X = PAGE_X - 7;
|
||||
/** Pixels between consecutive forecast rows' selection boxes. */
|
||||
const FORECAST_ROW_GAP = 2;
|
||||
|
||||
/** Forecast column x offsets from the row box's left edge. */
|
||||
type ForecastColumns = { name: number; temp: number; precip: number; summary: number };
|
||||
|
||||
/** Weather's current-conditions summary and scrollable 12-hour forecast. */
|
||||
export class WeatherLayer implements Layer {
|
||||
private selectedIndex = 0;
|
||||
private scrollRow = 0;
|
||||
/** Forecast table rows: selection only, a click does nothing there. */
|
||||
private readonly forecastMenu = new Menu<ForecastPeriod>({
|
||||
wrap: false,
|
||||
rowGap: FORECAST_ROW_GAP,
|
||||
highlight: { radius: 5 },
|
||||
getHeight: () => forecastRowHeight(getDefaultSmallFont()),
|
||||
draw: (args) => this.drawForecastRow(args),
|
||||
});
|
||||
/** Column layout for drawForecastRow, set by each drawForecast. */
|
||||
private columns: ForecastColumns = { name: 0, temp: 0, precip: 0, summary: 0 };
|
||||
|
||||
constructor(
|
||||
private readonly state: () => WeatherState,
|
||||
@@ -81,10 +95,9 @@ export class WeatherLayer implements Layer {
|
||||
return;
|
||||
}
|
||||
if (!weather.forecast.length || weather.phase !== "ready") return;
|
||||
if (event.type === "scroll-up") {
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
} else if (event.type === "scroll-down") {
|
||||
this.selectedIndex = Math.min(weather.forecast.length - 1, this.selectedIndex + 1);
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
this.forecastMenu.setItems(weather.forecast);
|
||||
void this.forecastMenu.handleInput(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,12 +147,14 @@ export class WeatherLayer implements Layer {
|
||||
image.drawText(font, PAGE_X, FORECAST_TOP, "No upcoming forecast periods.", 160);
|
||||
return;
|
||||
}
|
||||
this.selectedIndex = clamp(this.selectedIndex, 0, forecast.length - 1);
|
||||
const rowH = Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3);
|
||||
const rowH = forecastRowHeight(font);
|
||||
// The last row only needs its text line (not a full row pitch of
|
||||
// clearance below), which usually fits one more row before the bottom.
|
||||
// The menu only draws rows whose whole selection box fits, so the box
|
||||
// holds that many rows, cut at the image's bottom edge.
|
||||
const visibleRows = Math.max(1, 1 + Math.floor((height - FORECAST_TOP - (font.lineHeight + 4)) / rowH));
|
||||
this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, this.selectedIndex, visibleRows, forecast.length);
|
||||
const boxTop = FORECAST_TOP - 2;
|
||||
const boxHeight = Math.min(visibleRows * rowH - FORECAST_ROW_GAP, height - boxTop);
|
||||
|
||||
// Columns are sized to the widest period name so names ("Wednesday
|
||||
// Night") never truncate; the summary column absorbs what's left.
|
||||
@@ -155,20 +170,31 @@ export class WeatherLayer implements Layer {
|
||||
image.drawText(font, tempX, FORECAST_HEADER_Y, "Temp", 105);
|
||||
image.drawText(font, precipX, FORECAST_HEADER_Y, "Rain", 105);
|
||||
|
||||
const last = Math.min(forecast.length, this.scrollRow + visibleRows);
|
||||
for (let index = this.scrollRow; index < last; index++) {
|
||||
const period = forecast[index]!;
|
||||
const y = FORECAST_TOP + (index - this.scrollRow) * rowH;
|
||||
const selected = index === this.selectedIndex;
|
||||
if (selected) {
|
||||
drawSelectionHighlight(image, PAGE_X - 7, y - 2, width - 2 * (PAGE_X - 7), rowH - 2, ctx.stack.isFocused(), 5);
|
||||
}
|
||||
const shade = selected ? 245 : 190;
|
||||
image.drawText(font, PAGE_X, y + 2, period.name, shade);
|
||||
image.drawText(font, tempX, y + 2, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade);
|
||||
image.drawText(font, precipX, y + 2, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155);
|
||||
image.drawText(font, summaryX, y + 2, truncateText(font, period.shortForecast, width - summaryX - PAGE_X), selected ? 220 : 165);
|
||||
}
|
||||
this.columns = {
|
||||
name: PAGE_X - FORECAST_BOX_X,
|
||||
temp: tempX - FORECAST_BOX_X,
|
||||
precip: precipX - FORECAST_BOX_X,
|
||||
summary: summaryX - FORECAST_BOX_X,
|
||||
};
|
||||
this.forecastMenu.setItems(forecast);
|
||||
this.forecastMenu.paint(
|
||||
image,
|
||||
{ x: FORECAST_BOX_X, y: boxTop, width: width - 2 * FORECAST_BOX_X, height: boxHeight },
|
||||
ctx.stack.isFocused(),
|
||||
);
|
||||
}
|
||||
|
||||
private drawForecastRow({ image, item: period, x, y, width, height, selected }: MenuDrawArgs<ForecastPeriod>): void {
|
||||
const font = getDefaultSmallFont();
|
||||
const columns = this.columns;
|
||||
const shade = selected ? 245 : 190;
|
||||
const textY = centeredTextY(font, y, height);
|
||||
image.drawText(font, x + columns.name, textY, period.name, shade);
|
||||
image.drawText(font, x + columns.temp, textY, period.temperatureF === null ? "--" : `${Math.round(period.temperatureF)}°F`, shade);
|
||||
image.drawText(font, x + columns.precip, textY, period.precipitationPercent === null ? "--" : `${Math.round(period.precipitationPercent)}%`, selected ? 220 : 155);
|
||||
// The summary stops PAGE_X short of the viewport's right edge, as the name starts PAGE_X in from the left.
|
||||
const summaryWidth = width - columns.summary - columns.name;
|
||||
image.drawText(font, x + columns.summary, textY, truncateText(font, period.shortForecast, summaryWidth), selected ? 220 : 165);
|
||||
}
|
||||
|
||||
private drawMessage(
|
||||
@@ -190,6 +216,11 @@ export class WeatherLayer implements Layer {
|
||||
}
|
||||
}
|
||||
|
||||
/** Forecast row pitch, including the gap between selection boxes. */
|
||||
function forecastRowHeight(font: UiFont): number {
|
||||
return Math.max(FORECAST_MIN_ROW_HEIGHT, tightRowHeight(font) + 3);
|
||||
}
|
||||
|
||||
function formatAge(ageMs: number): string {
|
||||
const minutes = Math.max(0, Math.round(ageMs / 60_000));
|
||||
if (minutes < 1) return "just now";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AssistantSession, type AssistantBackendConfig, type AssistantSessionHistory } from "./session";
|
||||
import { ASSISTANT_MODEL_VALUES, type AssistantModel } from "./models";
|
||||
import { ASSISTANT_MODEL_VALUES, supportedAssistantModel, type AssistantModel } from "./models";
|
||||
|
||||
export type ReasoningLevel = "default" | "low" | "medium" | "high";
|
||||
export type Conversation = {
|
||||
@@ -31,7 +31,7 @@ export class AssistantConversations {
|
||||
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 }));
|
||||
).map((record) => ({ ...record, model: supportedAssistantModel(record.model), session: null }));
|
||||
this.selectedId = data.selectedId;
|
||||
}
|
||||
} catch { /* First launch or invalid saved state. */ }
|
||||
|
||||
@@ -51,10 +51,13 @@ export class DirectAssistantBackend {
|
||||
let cancelled = false;
|
||||
let streamHandle: LlmStreamHandle | null = null;
|
||||
let priorText = "";
|
||||
let deadline: ReturnType<typeof setTimeout> | null = null;
|
||||
const clearDeadline = () => { if (deadline !== null) clearTimeout(deadline); deadline = null; };
|
||||
|
||||
const finishError = (message: string) => {
|
||||
if (cancelled) return;
|
||||
cancelled = true;
|
||||
clearDeadline(); streamHandle?.cancel(); streamHandle = null;
|
||||
options.callbacks.onError(message);
|
||||
};
|
||||
|
||||
@@ -102,10 +105,11 @@ export class DirectAssistantBackend {
|
||||
block.type === "tool_use",
|
||||
);
|
||||
if (result.stopReason !== "tool_use" || toolUses.length === 0) {
|
||||
clearDeadline();
|
||||
options.callbacks.onTurnDone({ stopReason: result.stopReason });
|
||||
return;
|
||||
}
|
||||
void this.runToolCalls(toolUses, options)
|
||||
void this.runToolCalls(toolUses, options, () => cancelled)
|
||||
.then((toolResults) => {
|
||||
// Always record the results, even if cancelled mid-flight: an
|
||||
// assistant tool_use with no matching tool_result would make the
|
||||
@@ -131,11 +135,13 @@ export class DirectAssistantBackend {
|
||||
: streamAnthropicMessage(streamOptions);
|
||||
};
|
||||
|
||||
deadline = setTimeout(() => finishError("Assistant stopped: turn took too long"), MAX_TURN_MS);
|
||||
runIteration(0);
|
||||
|
||||
return {
|
||||
cancel: () => {
|
||||
cancelled = true;
|
||||
clearDeadline();
|
||||
streamHandle?.cancel();
|
||||
streamHandle = null;
|
||||
},
|
||||
@@ -145,9 +151,14 @@ export class DirectAssistantBackend {
|
||||
private async runToolCalls(
|
||||
toolUses: Array<Extract<LlmContentBlock, { type: "tool_use" }>>,
|
||||
options: DirectTurnOptions,
|
||||
isCancelled: () => boolean,
|
||||
): Promise<LlmContentBlock[]> {
|
||||
const results: LlmContentBlock[] = [];
|
||||
for (const toolUse of toolUses) {
|
||||
if (isCancelled()) {
|
||||
results.push({ type: "tool_result", tool_use_id: toolUse.id, content: "Cancelled", is_error: true });
|
||||
continue;
|
||||
}
|
||||
const canonicalName = options.resolveToolName(toolUse.name);
|
||||
options.callbacks.onToolActivity(canonicalName);
|
||||
const result = await options.registry.callTool(canonicalName, toolUse.input);
|
||||
|
||||
@@ -13,6 +13,13 @@ export const ASSISTANT_MODEL_VALUES = [
|
||||
] as const;
|
||||
|
||||
export type AssistantModel = (typeof ASSISTANT_MODEL_VALUES)[number];
|
||||
/** Keep saved model IDs portable, while offering only supported choices. */
|
||||
export const ASSISTANT_MODEL_CHOICES: readonly AssistantModel[] =
|
||||
global.isIOS ? ASSISTANT_MODEL_VALUES.filter(value => value !== "qwen") : ASSISTANT_MODEL_VALUES;
|
||||
export function supportedAssistantModel(value: AssistantModel): AssistantModel {
|
||||
return global.isIOS && value === "qwen" ? "auto" : value;
|
||||
}
|
||||
|
||||
export type AssistantProvider = "anthropic" | "openai" | "local";
|
||||
|
||||
export type AssistantApiKeys = {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* the app closed — so these always-available wrappers launch the app first,
|
||||
* wait for its tools to register, and forward the call.
|
||||
*/
|
||||
import { ensureFineLocationPermission } from "../g2/android-permissions";
|
||||
import { ensureFineLocationPermission } from "../native/location-permissions";
|
||||
import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
|
||||
import { callAppToolWithLaunch } from "./launch-on-call";
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../native/calendar";
|
||||
import { readUpcomingEventsAsync, type CalendarEvent } from "../native/calendar";
|
||||
import { hasCalendarPermission } from "../native/calendar-permissions";
|
||||
import { mediaControllerBridge } from "../native/media-controller";
|
||||
import { dismissNotification, readActiveNotifications } from "../native/notification-icons";
|
||||
import { shell } from "../ui/shell/shell";
|
||||
@@ -20,7 +21,7 @@ export function registerSystemTools(registry: ToolRegistry = toolRegistry): void
|
||||
registered = true;
|
||||
|
||||
// Keep a media listener warm so "what's playing" works without opening Music.
|
||||
void mediaControllerBridge.start();
|
||||
if (!global.isIOS) void mediaControllerBridge.start();
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
@@ -71,15 +72,23 @@ export function registerSystemTools(registry: ToolRegistry = toolRegistry): void
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
(args) => {
|
||||
async (args) => {
|
||||
if (!hasCalendarPermission()) return err("Calendar access is not granted. Open Calendar or Permissions on your phone to allow access.");
|
||||
const withinHours = clampNumber(args?.within_hours, 1, 24 * 60, 168);
|
||||
const maxEvents = clampNumber(args?.max_events, 1, 50, 10);
|
||||
const events = readUpcomingEvents(maxEvents, withinHours * 60 * 60 * 1000);
|
||||
if (!events.length) return ok("No upcoming events in that window.");
|
||||
return ok(events.map(formatEvent).join("\n"));
|
||||
try {
|
||||
const events = await readUpcomingEventsAsync(maxEvents, withinHours * 60 * 60 * 1000);
|
||||
if (!events.length) return ok("No upcoming events in that window.");
|
||||
return ok(events.map(formatEvent).join("\n"));
|
||||
} catch {
|
||||
return err("Calendar events could not be read. Check calendar access on your phone and try again.");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Phone media and Android notification tools are still platform-specific.
|
||||
if (global.isIOS) return;
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "media.now_playing",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Application } from '@nativescript/core'
|
||||
import { registerShareIntentHandler } from './native/share-intents'
|
||||
import { installNativeUserAgent } from './util/http'
|
||||
import { registerPhoneRotation } from './native/phone-rotation'
|
||||
import { startLiveHealthSync, startAlignedRingPull } from './health/health-live'
|
||||
|
||||
import { runKotlinBridgeSmokeTest } from './native/kotlin-bridge'
|
||||
|
||||
declare const __DEV__: boolean;
|
||||
|
||||
if (__DEV__) runKotlinBridgeSmokeTest()
|
||||
|
||||
installNativeUserAgent()
|
||||
registerShareIntentHandler()
|
||||
registerPhoneRotation()
|
||||
|
||||
// Ring health records live only in the communicator's memory until something
|
||||
// stores them. Both health surfaces store on open, but a pull that lands while
|
||||
// they are closed would be lost if the process restarted first, so this keeps
|
||||
// them reaching disk regardless. No-op when there is nothing new.
|
||||
startLiveHealthSync()
|
||||
|
||||
// Collect from the ring on a wall-clock cadence (:01 and :31). Without this
|
||||
// nothing drives a pull on a timer at all - only onRingReady() on reconnect -
|
||||
// so a ring that stays connected is never read.
|
||||
startAlignedRingPull()
|
||||
|
||||
Application.run({ moduleName: 'app-root' })
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Application, Frame } from '@nativescript/core'
|
||||
import { runKotlinBridgeSmokeTest } from './native/kotlin-bridge'
|
||||
declare const FaceclawConfigPort: any
|
||||
declare const __DEV__: boolean;
|
||||
|
||||
if (__DEV__) runKotlinBridgeSmokeTest()
|
||||
|
||||
// Apply transferred preferences before settings getters or app workers load.
|
||||
FaceclawConfigPort.processPendingRequest()
|
||||
require('./phone-ui/onboarding-register.ios')
|
||||
const { hasCompletedOnboarding } = require('./phone-ui/onboarding-state') as typeof import('./phone-ui/onboarding-state')
|
||||
Application.run({ create: () => {
|
||||
const frame = new Frame()
|
||||
frame.navigate({ moduleName: hasCompletedOnboarding() ? 'phone-ui/main-page' : 'phone-ui/onboarding-page' })
|
||||
return frame
|
||||
} })
|
||||
@@ -0,0 +1,287 @@
|
||||
import type { AndroidNotification } from '../native/notification-types'
|
||||
|
||||
export const ANCS_FIRMWARE_VERSION = 16
|
||||
export const ANCS_CONNECT_MESSAGE = 'Connect glasses to receive iPhone notifications.'
|
||||
const MAX_ACTIVE = 128
|
||||
const MAX_RESPONSE = 2048
|
||||
const MAX_COMMAND = 80 // Firmware relay limit, including its 8-byte header.
|
||||
const HEADER = 11
|
||||
const read32 = (b: Uint8Array, i: number) => (b[i] | b[i+1]<<8 | b[i+2]<<16 | b[i+3]<<24) >>> 0
|
||||
const le32 = (n: number) => [n & 255, n>>>8 & 255, n>>>16 & 255, n>>>24]
|
||||
// NativeScript does not supply TextDecoder in every isolate.
|
||||
function utf8(bytes: Uint8Array): string {
|
||||
let result = ''
|
||||
for (let i=0; i<bytes.length;) {
|
||||
const first = bytes[i]
|
||||
if (first < 128) { result += String.fromCharCode(first); i++; continue }
|
||||
const count = first >= 0xc2 && first <= 0xdf ? 2 : first >= 0xe0 && first <= 0xef ? 3 : first >= 0xf0 && first <= 0xf4 ? 4 : 0
|
||||
if (!count) { result += '\uFFFD'; i++; continue }
|
||||
let code = first & (0x7f >> count), valid = i+count <= bytes.length
|
||||
for (let j=1; j<count && valid; j++) {
|
||||
if ((bytes[i+j] & 0xc0) !== 0x80) valid = false
|
||||
else code = (code << 6) | (bytes[i+j] & 63)
|
||||
}
|
||||
if (!valid || code < (count === 2 ? 128 : count === 3 ? 2048 : 65536) ||
|
||||
code > 0x10ffff || code >= 0xd800 && code <= 0xdfff) {
|
||||
result += '\uFFFD'; i++; continue
|
||||
}
|
||||
result += String.fromCodePoint(code); i += count
|
||||
}
|
||||
return result
|
||||
}
|
||||
function fallbackAppName(identifier: string): string {
|
||||
return identifier.split('.').filter(Boolean).pop() || 'Unknown app'
|
||||
}
|
||||
function notificationDate(value: string): number | undefined {
|
||||
const parts = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})$/.exec(value)
|
||||
if (!parts) return undefined
|
||||
const [year,month,day,hour,minute,second] = parts.slice(1).map(Number)
|
||||
const date = new Date(year,month-1,day,hour,minute,second)
|
||||
return date.getFullYear() === year && date.getMonth() === month-1 && date.getDate() === day &&
|
||||
date.getHours() === hour && date.getMinutes() === minute && date.getSeconds() === second ? date.getTime() : undefined
|
||||
}
|
||||
type Source = { flags: number; category: number; revision: number; postTime: number; popup: boolean }
|
||||
type Request = { uid: number; revision: number; action?: number; metadata?: boolean; appId?: string }
|
||||
export type AncsState = 'disconnected' | 'starting' | 'ready' | 'unavailable'
|
||||
|
||||
/** Owns one phone/lens BLE session. Nothing is persisted. Firmware enforces
|
||||
* peer ownership; token/sequence checks here additionally reject stale chunks. */
|
||||
export class AncsClient {
|
||||
state: AncsState = 'disconnected'
|
||||
statusMessage = ANCS_CONNECT_MESSAGE
|
||||
private resetReceived = false
|
||||
private token = 0
|
||||
private lastStartToken = 0
|
||||
private sequence = 0
|
||||
private packetKind = -1
|
||||
private fragments: number[] = []
|
||||
private response: number[] = []
|
||||
private sources = new Map<number, Source>()
|
||||
private notifications = new Map<number, AndroidNotification>()
|
||||
private appNames = new Map<string, string>()
|
||||
private maxWrite = 20
|
||||
private queue: Request[] = []
|
||||
private acknowledged = false
|
||||
private responseDone = false
|
||||
private pending: Request | null = null
|
||||
private timer: ReturnType<typeof setTimeout> | null = null
|
||||
private retry: ReturnType<typeof setTimeout> | null = null
|
||||
private revision = 0
|
||||
private disposed = true
|
||||
constructor(private readonly send: (packet: Uint8Array) => Promise<void>,
|
||||
private readonly changed: (key?: string, popup?: boolean) => void,
|
||||
private readonly log: (message: string) => void = () => {}) {}
|
||||
|
||||
private status(state: AncsState, message: string): void {
|
||||
this.state = state; this.statusMessage = message; this.log(message); this.changed()
|
||||
}
|
||||
|
||||
start(token: number, maxWrite = 20): void {
|
||||
this.stop(); this.disposed = false; this.token = token >>> 0 || 1
|
||||
this.maxWrite = Math.min(MAX_COMMAND, maxWrite)
|
||||
this.begin()
|
||||
}
|
||||
private begin(): void {
|
||||
if (this.disposed) return
|
||||
this.clear(); this.resetReceived = false
|
||||
this.status('starting', 'Connecting to iPhone notifications…')
|
||||
this.deadline()
|
||||
const token = this.token
|
||||
this.lastStartToken = token
|
||||
void this.send(this.command(0)).catch(() => { if (token === this.token) this.recover() })
|
||||
}
|
||||
stop(message = ANCS_CONNECT_MESSAGE): void {
|
||||
this.disposed = true
|
||||
if (this.retry !== null) clearTimeout(this.retry)
|
||||
this.retry = null; this.clear(); this.token = 0
|
||||
this.status('disconnected', message)
|
||||
}
|
||||
stopCommand(): Uint8Array { return new Uint8Array([65,78,1,1,...le32(this.lastStartToken)]) }
|
||||
private clear(): void {
|
||||
if (this.timer !== null) clearTimeout(this.timer)
|
||||
this.timer = null; this.sources.clear(); this.notifications.clear(); this.appNames.clear(); this.queue = []
|
||||
this.pending = null; this.response = []; this.fragments = []; this.packetKind = -1; this.sequence = 0
|
||||
}
|
||||
private recover(message = 'Notification relay interrupted. Retrying…'): void {
|
||||
if (this.disposed || this.retry !== null) return
|
||||
this.clear(); this.status('unavailable', message)
|
||||
// New token rejects every queued packet/response from the previous attempt.
|
||||
this.token = (this.token + 1) >>> 0 || 1
|
||||
this.retry = setTimeout(() => { this.retry = null; this.begin() }, 5000)
|
||||
}
|
||||
private deadline(): void {
|
||||
if (this.timer !== null) clearTimeout(this.timer)
|
||||
this.timer = setTimeout(() => this.recover(this.state === 'starting'
|
||||
? this.resetReceived ? 'Glasses did not finish subscribing to iPhone notifications. Retrying…'
|
||||
: 'No notification relay response. Check Share System Notifications on the right lens. Retrying…'
|
||||
: 'Notification retrieval timed out. Retrying…'), 10000)
|
||||
}
|
||||
private command(op: number, payload: number[] = []): Uint8Array {
|
||||
return new Uint8Array([65,78,1,op,...le32(this.token),...payload])
|
||||
}
|
||||
read(limit = 50): AndroidNotification[] {
|
||||
return [...this.notifications.values()].sort((a,b) => b.postTime-a.postTime).slice(0, Math.max(0,limit))
|
||||
.map(n => ({...n, lines: [...n.lines], actions: n.actions.map(a => ({...a}))}))
|
||||
}
|
||||
action(key: string, action: number): boolean {
|
||||
const notification = [...this.notifications.entries()].find(([,n]) => n.key === key)
|
||||
if (this.state !== 'ready' || this.queue.length >= MAX_ACTIVE || !notification || ![0,1].includes(action) ||
|
||||
!notification[1].actions.some(a => a.index === action && a.enabled)) return false
|
||||
const [uid] = notification, source = this.sources.get(uid)!
|
||||
this.queue.push({uid, revision: source.revision, action}); this.pump(); return true
|
||||
}
|
||||
/** Local hide: ANCS negative action can decline a call, so Dismiss must never
|
||||
* silently translate into a destructive negative action. */
|
||||
dismiss(key: string): boolean {
|
||||
const entry = [...this.notifications.entries()].find(([,n]) => n.key === key)
|
||||
if (!entry) return false
|
||||
this.notifications.delete(entry[0]); this.sources.delete(entry[0]); this.changed(); return true
|
||||
}
|
||||
receive(packet: Uint8Array): boolean {
|
||||
if (packet[0] !== 65 || packet[1] !== 78) return false
|
||||
if (this.disposed || this.state === 'unavailable' || packet.length < HEADER || packet[2] !== 1 || read32(packet,4) !== this.token) return true
|
||||
const sequence = packet[8] | packet[9]<<8, flags = packet[10], kind = packet[3]
|
||||
if (sequence !== this.sequence || flags > 3 || kind > 3 || packet.length > 244) { this.recover(); return true }
|
||||
this.sequence = (sequence + 1) & 65535
|
||||
if (flags & 1) {
|
||||
if (this.packetKind !== -1) { this.recover(); return true }
|
||||
this.packetKind = kind; this.fragments = []
|
||||
}
|
||||
if (this.packetKind !== kind || this.fragments.length + packet.length - HEADER > 512) { this.recover(); return true }
|
||||
this.fragments.push(...packet.subarray(HEADER))
|
||||
if (flags & 2) {
|
||||
const data = new Uint8Array(this.fragments); this.fragments = []; this.packetKind = -1
|
||||
if (kind === 0) {
|
||||
if (data.length !== 1 || data[0] > 2) { this.recover(); return true }
|
||||
if (data[0] === 2) { this.recover('Glasses reported a notification relay error. Retrying…'); return true }
|
||||
if (data[0] === 0) { this.resetReceived = true; this.log('Glasses accepted notification relay START; awaiting subscription') }
|
||||
if (data[0] === 1) {
|
||||
if (this.timer !== null) clearTimeout(this.timer)
|
||||
this.timer = null; this.status('ready', 'No current iOS notifications.'); this.pump()
|
||||
}
|
||||
} else if (kind === 1) this.source(data)
|
||||
else if (kind === 2) this.attributes(data)
|
||||
else if (this.pending) {
|
||||
this.acknowledged = true
|
||||
if (this.pending.action !== undefined || this.responseDone) this.complete()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
private source(data: Uint8Array): void {
|
||||
if (data.length !== 8 || data[0] > 2) { this.recover(); return }
|
||||
const uid = read32(data,4)
|
||||
if (data[0] === 2) {
|
||||
this.sources.delete(uid); this.notifications.delete(uid)
|
||||
this.queue = this.queue.filter(r => r.uid !== uid); this.changed(); return
|
||||
}
|
||||
const old = this.sources.get(uid)
|
||||
const source = {flags: data[1], category: data[2], revision: ++this.revision,
|
||||
postTime: old?.postTime ?? Date.now(), popup: !old && data[0] === 0 && !(data[1] & 4)}
|
||||
this.sources.set(uid, source)
|
||||
while (this.sources.size > MAX_ACTIVE) {
|
||||
const oldest = this.sources.keys().next().value!
|
||||
this.sources.delete(oldest); this.notifications.delete(oldest)
|
||||
this.queue = this.queue.filter(r => r.uid !== oldest)
|
||||
}
|
||||
this.queue = this.queue.filter(r => r.uid !== uid || r.action !== undefined)
|
||||
this.queue.push({uid, revision: source.revision}); this.pump()
|
||||
}
|
||||
private pump(): void {
|
||||
if (this.state !== 'ready' || this.pending) return
|
||||
while (this.queue.length) {
|
||||
const request = this.queue.shift()!
|
||||
if (this.sources.get(request.uid)?.revision !== request.revision) continue
|
||||
this.pending = request; this.response = []; this.acknowledged = this.responseDone = false; this.deadline()
|
||||
// Notification attributes use two requests, each fitting a 20-byte ATT
|
||||
// payload. App IDs cannot be fragmented by this firmware's CP relay.
|
||||
const cp = request.appId !== undefined
|
||||
? [1,...Array.from(request.appId, c => c.charCodeAt(0)),0,0]
|
||||
: request.action === undefined
|
||||
? request.metadata ? [0,...le32(request.uid),2,128,0,4,5,6,7] : [0,...le32(request.uid),0,1,128,0,3,0,2]
|
||||
: [2,...le32(request.uid),request.action]
|
||||
const token = this.token
|
||||
void this.send(this.command(2,cp)).catch(() => { if (token === this.token) this.recover() })
|
||||
return
|
||||
}
|
||||
}
|
||||
private attributes(data: Uint8Array): void {
|
||||
if (!this.pending || this.pending.action !== undefined) return
|
||||
if (this.response.length + data.length > MAX_RESPONSE) { this.recover(); return }
|
||||
this.response.push(...data)
|
||||
const b = new Uint8Array(this.response)
|
||||
if (!b.length) return
|
||||
const appId = this.pending.appId
|
||||
let cursor: number
|
||||
if (appId !== undefined) {
|
||||
if (b[0] !== 1) { this.recover(); return }
|
||||
const end = b.indexOf(0,1)
|
||||
if (end < 0) { if (b.length > appId.length+1) this.recover(); return }
|
||||
if (utf8(b.subarray(1,end)) !== appId) { this.recover(); return }
|
||||
cursor = end+1
|
||||
} else {
|
||||
if (b.length < 5) return
|
||||
if (b[0] !== 0 || read32(b,1) !== this.pending.uid) { this.recover(); return }
|
||||
cursor = 5
|
||||
}
|
||||
const expected = appId !== undefined ? [0] : this.pending.metadata ? [2,4,5,6,7] : [0,1,3]
|
||||
const attrs = new Map<number,string>()
|
||||
while (cursor < b.length) {
|
||||
if (cursor+3 > b.length) return
|
||||
const id = b[cursor], length = b[cursor+1] | b[cursor+2]<<8
|
||||
if (!expected.includes(id) || attrs.has(id) || length > 512) { this.recover(); return }
|
||||
if (cursor+3+length > b.length) return
|
||||
attrs.set(id,utf8(b.subarray(cursor+3,cursor+3+length))); cursor += 3+length
|
||||
}
|
||||
if (attrs.size !== expected.length) return
|
||||
const {uid,revision} = this.pending, source = this.sources.get(uid)
|
||||
if (appId !== undefined) {
|
||||
const displayName = attrs.get(0)!.trim()
|
||||
const name = displayName && displayName !== appId ? displayName : fallbackAppName(appId)
|
||||
this.appNames.set(appId,name)
|
||||
while (this.appNames.size > MAX_ACTIVE) this.appNames.delete(this.appNames.keys().next().value!)
|
||||
for (const notification of this.notifications.values()) {
|
||||
if (notification.packageName === appId) notification.appName = name
|
||||
}
|
||||
}
|
||||
if (source?.revision === revision) {
|
||||
const key = `ancs:${this.token}:${uid}`
|
||||
if (appId !== undefined) {
|
||||
this.publish(uid,source)
|
||||
} else if (this.pending.metadata) {
|
||||
const notification = this.notifications.get(uid)
|
||||
if (notification) {
|
||||
notification.subText = attrs.get(2)!
|
||||
notification.when = notificationDate(attrs.get(5)!) ?? source.postTime
|
||||
const size = attrs.get(4)!
|
||||
if (/^\d+$/.test(size) && Number.isSafeInteger(Number(size))) notification.messageSize = Number(size)
|
||||
notification.actions = [
|
||||
...(source.flags & 8 && attrs.get(6) ? [{index:0,title:attrs.get(6)!,enabled:true}] : []),
|
||||
...(source.flags & 16 && attrs.get(7) ? [{index:1,title:attrs.get(7)!,enabled:true}] : []),
|
||||
]
|
||||
const id = notification.packageName
|
||||
// Bundle IDs are ASCII. Reject embedded NULs/invalid IDs and use the
|
||||
// readable fallback if the entire command cannot fit either link.
|
||||
if (!this.appNames.has(id) && /^[A-Za-z0-9.-]+$/.test(id) && id.length+11 <= this.maxWrite) {
|
||||
this.queue.unshift({uid,revision,appId:id})
|
||||
} else this.publish(uid,source)
|
||||
}
|
||||
} else {
|
||||
const packageName = attrs.get(0)!, title = attrs.get(1)!, text = attrs.get(3)!
|
||||
this.notifications.set(uid,{key,packageName,appName:this.appNames.get(packageName) || fallbackAppName(packageName),title,text,bigText:text,
|
||||
subText:'',infoText:'',summaryText:'',category:String(source.category),lines:[],postTime:source.postTime,when:source.postTime,actions:[],dismissLabel:'Hide on glasses'})
|
||||
this.queue.unshift({uid,revision,metadata:true}); this.changed(key,false)
|
||||
}
|
||||
}
|
||||
this.responseDone = true
|
||||
if (this.acknowledged) this.complete()
|
||||
}
|
||||
private publish(uid: number, source: Source): void {
|
||||
const popup = source.popup; source.popup = false
|
||||
this.changed(`ancs:${this.token}:${uid}`,popup)
|
||||
}
|
||||
private complete(): void {
|
||||
if (this.timer !== null) clearTimeout(this.timer)
|
||||
this.timer = null; this.pending = null; this.response = []; this.pump()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { type RingInput } from "./ring-input";
|
||||
import { type CompassEvent } from '../native/compass-types'
|
||||
/** iOS binary bridge to the same Kotlin protocol used by Android. */
|
||||
import { fromData, toData, nativeArray } from '../native/kotlin-data'
|
||||
import { OsEventTypeList } from './events'
|
||||
declare const FaceclawKitIosProtocol: any, FaceclawKitIosMessageReceiver: any
|
||||
const protocol = FaceclawKitIosProtocol.new()
|
||||
export const G2_WRITE = '00002760-08c2-11e1-9073-0e8ac72e5401'
|
||||
export const G2_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e5402'
|
||||
export const G2_RENDER_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e6402'
|
||||
export const RING_NOTIFY = ['bae80011-4f05-4503-8e65-3af1f7329d1f', 'bae80013-4f05-4503-8e65-3af1f7329d1f']
|
||||
export const SID = { auth: 0x80, launch: 1, hub: 0xe0, settings: 9, cfw: 0xf0 } as const
|
||||
export function concat(...parts: Uint8Array[]): Uint8Array {
|
||||
const output = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
|
||||
let offset = 0
|
||||
for (const part of parts) { output.set(part, offset); offset += part.length }
|
||||
return output
|
||||
}
|
||||
export const integer = (field: number, value: number): Uint8Array => fromData(protocol.integerFieldValue(field, value))
|
||||
export const bytes = (field: number, value: Uint8Array): Uint8Array => fromData(protocol.bytesFieldData(field, toData(value)))
|
||||
export const authentication = (magic: number) => fromData(protocol.authenticationMagic(magic))
|
||||
export const prelude = () => fromData(protocol.prelude())
|
||||
export const heartbeat = (magic: number) => fromData(protocol.heartbeatMagic(magic))
|
||||
export const audioControl = (magic: number, enabled: boolean) => fromData(protocol.audioControlMagicEnabled(magic, enabled))
|
||||
export const settingsQuery = (magic: number) => fromData(protocol.settingsQueryMagic(magic))
|
||||
export const shutdown = (magic: number) => fromData(protocol.shutdownMagic(magic))
|
||||
export const framebufferLease = (acquire: boolean) => fromData(protocol.framebufferLeaseAcquire(acquire))
|
||||
export const createLayout = (magic: number) => fromData(protocol.createLayoutMagic(magic))
|
||||
export const crc16 = (data: Uint8Array): number => protocol.crcData(toData(data))
|
||||
export function frameMessage(payload: Uint8Array, sid: number, flag: number, sequence: number, maxWrite = 240): Uint8Array[] {
|
||||
const capacity = Math.min(232, Math.floor(maxWrite) - 8)
|
||||
if (capacity < 12 || !Number.isFinite(capacity)) throw new Error('Negotiated BLE write size is too small')
|
||||
if (Math.ceil((payload.length + 2) / capacity) > 255) throw new Error('Protocol message exceeds the fragment limit')
|
||||
return nativeArray(protocol.frameDataSidFlagSequenceMaxWrite(toData(payload), sid, flag, sequence, Math.floor(maxWrite)), fromData)
|
||||
}
|
||||
export type ProtocolMessage = { sid: number; flag: number; payload: Uint8Array; command: number; magic: number; packet?: Uint8Array }
|
||||
export class MessageReceiver {
|
||||
private native = FaceclawKitIosMessageReceiver.new()
|
||||
clear(): void { this.native.clear() }
|
||||
receive(link: string, data: Uint8Array, now = Date.now()): ProtocolMessage[] {
|
||||
return nativeArray(this.native.receiveLinkDataNow(link, toData(data), now), (message: any) => ({
|
||||
sid: message.sid, flag: message.flag, payload: fromData(message.payload), command: message.command,
|
||||
magic: message.magic, ...(message.packet ? { packet: fromData(message.packet) } : {}),
|
||||
}))
|
||||
}
|
||||
}
|
||||
export const readInteger = (data: Uint8Array, field: number, fallback = 0): number => protocol.readIntegerDataFieldFallback(toData(data), field, fallback)
|
||||
export const readBytes = (data: Uint8Array, field: number): Uint8Array | undefined => {
|
||||
const value = protocol.readBytesDataField(toData(data), field)
|
||||
return value ? fromData(value) : undefined
|
||||
}
|
||||
export const readString = (data: Uint8Array, field: number): string => protocol.readStringDataField(toData(data), field)
|
||||
export function authenticationSucceeded(message: ProtocolMessage, magic: number): boolean {
|
||||
return message.sid === SID.auth && message.command === 4 && message.magic === magic && readBytes(message.payload, 3)?.length === 0
|
||||
}
|
||||
export type GlassesInput = { ringInput?: RingInput; kind: 'sys-event' | 'list-click' | 'text-click' | 'display-wake' | 'even-ai'; eventType: number; eventSource: number; systemExitReasonCode: number; containerName: string; frameId: number }
|
||||
function input(event: any): GlassesInput | null {
|
||||
return event ? { kind: event.kind === 'sys-event' && event.eventType === OsEventTypeList.HEAD_UP_EVENT ? 'display-wake' : event.kind,
|
||||
eventType: event.eventType, eventSource: event.eventSource, systemExitReasonCode: event.systemExitReasonCode,
|
||||
ringInput: Number(event.ringTick) >= 0 ? { tick: Number(event.ringTick), type: Number(event.ringType),
|
||||
aux: Number(event.ringAux), speed: Number(event.ringSpeed) } : undefined,
|
||||
containerName: event.containerName, frameId: 0 } : null
|
||||
}
|
||||
export const decodeGlassesInput = (message: ProtocolMessage): GlassesInput | null => input(protocol.glassesInputDataSidFlag(toData(message.payload), message.sid, message.flag))
|
||||
export const decodeRingInput = (data: Uint8Array): GlassesInput | null => input(protocol.ringInputData(toData(data)))
|
||||
export function packGray4(gray: Uint8Array, width: number, height: number): Uint8Array {
|
||||
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || gray.length !== width * height) throw new Error('Invalid display frame')
|
||||
return fromData(protocol.packDataWidthHeight(toData(gray), width, height))
|
||||
}
|
||||
export const rle4 = (packed: Uint8Array): Uint8Array => fromData(protocol.rleData(toData(packed)))
|
||||
|
||||
export function decodeCompassInput(message: ProtocolMessage): CompassEvent | null {
|
||||
const event = protocol.compassInputDataSidFlag(toData(message.payload), message.sid, message.flag)
|
||||
return event ? { command: event.command, headingDegrees: event.headingDegrees,
|
||||
...(event.diagnosticFlags >= 0 ? { diagnostics: {
|
||||
magneticAccuracy: event.magneticAccuracy, magneticAnomalies: event.magneticAnomalies,
|
||||
orientationSource: event.orientationSource, flags: event.diagnosticFlags, sampleTimeMs: Number(event.sampleTimeMs),
|
||||
} } : {}),
|
||||
} : null
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export const DEFAULT_BRIGHTNESS_CURVE = "0:0,0.2:7,1.5:33,5:100";
|
||||
const PREVIOUS_DEFAULT_CURVE = "0:0,1:10,10:30,100:65,1000:100";
|
||||
|
||||
/** Percent of the configured range; defaults (20–100) give 20/26/46/100. */
|
||||
export function brightnessCurveError(value: string): string | null {
|
||||
const pairs = value.split(",").map(part => part.trim().split(":"));
|
||||
if (pairs.length < 2 || pairs.length > 16 || pairs.some(p => p.length !== 2 || p.some(s => !s.trim())))
|
||||
return "Use 2–16 lux:percent pairs separated by commas.";
|
||||
const points = pairs.map(pair => pair.map(Number));
|
||||
if (points.some(([lux, percent]) => !Number.isFinite(lux) || !Number.isFinite(percent)
|
||||
|| lux < 0 || lux > 1_000_000 || percent < 0 || percent > 100))
|
||||
return "Lux must be 0–1000000 and percent must be 0–100.";
|
||||
if (points[0][0] !== 0 || points[0][1] !== 0 || points[points.length - 1][1] !== 100)
|
||||
return "Start at 0:0 and end at 100%. Set dark-room brightness with Auto minimum.";
|
||||
if (points.some(([lux, percent], i) => i > 0 && (lux <= points[i-1][0] || percent < points[i-1][1])))
|
||||
return "Lux must increase and brightness must not decrease.";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Keep incomplete drafts intact. Validation must never replace typed input. */
|
||||
export function normalizeBrightnessCurve(value: string | null | undefined): string {
|
||||
if (value == null) return DEFAULT_BRIGHTNESS_CURVE;
|
||||
if (brightnessCurveError(value)) return value;
|
||||
const canonical = value.split(",").map(pair => pair.split(":").map(Number).join(":")).join(",");
|
||||
return canonical === PREVIOUS_DEFAULT_CURVE ? DEFAULT_BRIGHTNESS_CURVE : canonical;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** Message IDs and header flags mirror g2flash/patches/zlib_glue.c. */
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_BOUNDING_BOX = 3
|
||||
export const CFW_MSG_BUZZER = 5
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_FULL_FRAME = 6
|
||||
export const CFW_MSG_DIAGNOSTICS = 7
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_MULTI_SEGMENT = 8
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_RECT_COPY = 9
|
||||
export const CFW_MSG_COMPASS = 10
|
||||
export const CFW_MSG_CLEANUP = 11
|
||||
export const CFW_MSG_RETIRED_12 = 12
|
||||
export const CFW_MSG_RETIRED_13 = 13
|
||||
export const CFW_MSG_RETIRED_14 = 14
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_STOCK_FONT_STRING = 15
|
||||
export const CFW_MSG_AMBIENT_LIGHT = 16
|
||||
export const CFW_MSG_RING_BATTERY = 17
|
||||
export const CFW_MSG_RETIRED_CACHE_WRITE = 18
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_CACHED_IMAGE = 19
|
||||
/** Retired wire ID; used internally by the phone optimizer. */
|
||||
export const CFW_MSG_CACHED_TEXT = 20
|
||||
export const CFW_MSG_UPLOAD_RESOURCE = 21
|
||||
export const CFW_MSG_EVICT_RESOURCE = 22
|
||||
export const CFW_MSG_PANEL_READ = 23
|
||||
export const CFW_MSG_PANEL_WRITE = 24
|
||||
export const CFW_MSG_PANEL_PATTERN = 25
|
||||
export const CFW_MSG_DRAW_CALLS = 26
|
||||
export const CFW_MSG_SET_ROOT_DISPLAY_LIST = 27
|
||||
export const CFW_MSG_PRESENT = 28
|
||||
export const CFW_MSG_CREATE_SURFACE = 29
|
||||
export const CFW_MSG_BRIGHTNESS = 30
|
||||
export const CFW_MSG_TYPE_MASK = 127
|
||||
export const CFW_MSG_FLAG_LENSES_DIFFER = 128
|
||||
+148
-83
@@ -1,4 +1,6 @@
|
||||
import { Application, ImageSource } from "@nativescript/core";
|
||||
import { startRemoteInput } from "../remote/service";
|
||||
import { acceptInput, resetRingInputFilter } from "../ui/input-monitor";
|
||||
import { Application, Dialogs, ImageSource } from "@nativescript/core";
|
||||
import { EvenAIStatus, EvenAIStatusName, EventSourceType, EventSourceTypeName, OsEventTypeList, OsEventTypeName, WatchGestureType, WatchGestureTypeName } from "./events";
|
||||
import { isValidMacAddress, loadDeviceAddresses } from "./device-addresses";
|
||||
import {
|
||||
@@ -51,8 +53,7 @@ import { voiceControlBridge } from "../native/voice-control";
|
||||
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../graphics/plane";
|
||||
import { prepareFrameDraws } from "../graphics/glyph-wire";
|
||||
import { getDefaultMediumFont } from "../graphics/ui-fonts";
|
||||
import { wrapText } from "../graphics/textwrap";
|
||||
import { createLockScreenImage, LOCK_SCREEN_SURFACE_ID } from "./lock-screen";
|
||||
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
|
||||
import { type InputEvent } from "../ui/gestures";
|
||||
import { registerSystemTools } from "../assistant/system-tools";
|
||||
@@ -70,7 +71,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
|
||||
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible, type WindowHeightMode } from "../ui/shell/geometry";
|
||||
import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers";
|
||||
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 { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, 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,
|
||||
@@ -141,8 +142,6 @@ type DashboardListener = (snapshot: DashboardSnapshot) => void;
|
||||
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
|
||||
// it reflects every app (including worker apps the TS side never renders).
|
||||
const SHELL_REFRESH_INTERVAL_MS = 60_000;
|
||||
@@ -172,24 +171,6 @@ function createInitialDisplayPreview(): ImageSource | null {
|
||||
return grayImageToPreviewSource(new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0));
|
||||
}
|
||||
|
||||
function createLockScreenImage(): GrayImage {
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
const font = getDefaultMediumFont();
|
||||
const boxWidth = 480;
|
||||
const boxHeight = 150;
|
||||
const boxX = Math.round((G2_LENS_WIDTH - boxWidth) / 2);
|
||||
const boxY = Math.round((G2_LENS_HEIGHT - boxHeight) / 2);
|
||||
image.drawRoundedRect(boxX, boxY, boxWidth, boxHeight, 150, 12);
|
||||
const lines = wrapText(font, LOCK_SCREEN_MESSAGE, boxWidth - 64);
|
||||
const textHeight = lines.length * font.lineHeight;
|
||||
const firstY = boxY + Math.round((boxHeight - textHeight) / 2);
|
||||
lines.forEach((line, index) => {
|
||||
const x = Math.round((G2_LENS_WIDTH - font.measureText(line)) / 2);
|
||||
image.drawText(font, x, firstY + index * font.lineHeight, line, 230);
|
||||
});
|
||||
return image;
|
||||
}
|
||||
|
||||
function formatTimestamp(date: Date): string {
|
||||
return date.toISOString().slice(11, 23);
|
||||
}
|
||||
@@ -223,7 +204,22 @@ class DashboardController {
|
||||
private activeTextSettings: ConfigSettingString[] = [];
|
||||
private activeTextEditorTitle = "";
|
||||
private activeTextEditorOnFinish: (() => void) | null = null;
|
||||
/**
|
||||
* The caller's cancel callback. LayerActions has always declared this fifth
|
||||
* parameter, but neither the wiring below nor startTextSettingsEdit accepted
|
||||
* it, so it was dropped silently -- a 4-parameter function is assignable to a
|
||||
* 5-parameter type, so nothing failed to compile. A caller that tracks its own
|
||||
* "editor is open" state therefore had no way to learn the editor closed.
|
||||
*/
|
||||
private activeTextEditorOnCancel: (() => void) | null = null;
|
||||
private activeTextEditorToggle: TextSettingsEditToggle | null = null;
|
||||
/**
|
||||
* The active settings' values (and the toggle's) when the edit began. The
|
||||
* phone fields write through on every keystroke, so this is what the
|
||||
* editor's Cancel button puts back.
|
||||
*/
|
||||
private activeTextSettingOriginalValues: string[] = [];
|
||||
private activeTextEditorToggleOriginalValue = false;
|
||||
private evenNotificationActive = false;
|
||||
private evenAppConflictMessage = "";
|
||||
private firmwareWarningMessage = "";
|
||||
@@ -287,7 +283,6 @@ class DashboardController {
|
||||
private lockSurfaceConfigured = false;
|
||||
private lastLockScreenEnabled = lockScreenEnabledSetting.get();
|
||||
private offState: (() => void) | null = null;
|
||||
private offLog: (() => void) | null = null;
|
||||
private offRing: (() => void) | null = null;
|
||||
private offBattery: (() => void) | null = null;
|
||||
private offSilentMode: (() => void) | null = null;
|
||||
@@ -340,7 +335,8 @@ class DashboardController {
|
||||
title: string,
|
||||
onFinish?: () => void,
|
||||
toggle?: TextSettingsEditToggle,
|
||||
) => this.startTextSettingsEdit(settings, title, onFinish, toggle),
|
||||
onCancel?: () => void,
|
||||
) => this.startTextSettingsEdit(settings, title, onFinish, toggle, onCancel),
|
||||
endTextSettingEdit: () => this.endTextSettingEdit(),
|
||||
startVoiceCapture: (endpointing = false) => this.startVoiceCapture(endpointing),
|
||||
stopVoiceCapture: () => this.stopVoiceCapture(),
|
||||
@@ -424,6 +420,15 @@ class DashboardController {
|
||||
this.syncAssistantBridge();
|
||||
// The watch drives the same synthetic-input path as the phone UI's test
|
||||
// buttons, plus app/window/lock commands; it mirrors the state below.
|
||||
startRemoteInput({
|
||||
ready: () => this.phase === "connected" || this.phase === "charging",
|
||||
locked: () => this.glassesLocked,
|
||||
input: (gesture, source) => this.injectSyntheticRingInput(gesture, source),
|
||||
acceptsText: () => !!shell.foregroundWindow()?.receiveTextInput,
|
||||
text: (text, submit) => { if (!shell.isScreenOn()) shell.wake("window"); shell.sendTextToForegroundWindow(text, { submit }); this.requestShellRender(); },
|
||||
assistantAvailable: () => shell.isAssistantAvailable(),
|
||||
assistant: text => shell.sendToAssistant(text),
|
||||
});
|
||||
this.wearRemote = new WearRemote({
|
||||
apps: LAUNCHABLE_APPS,
|
||||
injectInput: (kind) => this.injectSyntheticRingInput(kind, "watch"),
|
||||
@@ -505,7 +510,7 @@ class DashboardController {
|
||||
window.relayout();
|
||||
await this.configureWindowSurface(
|
||||
window.surfaceId,
|
||||
window.windowId === foregroundWindowId,
|
||||
this.isForegroundWindow(window.windowId),
|
||||
window.heightMode,
|
||||
);
|
||||
} else if (window.closeable) {
|
||||
@@ -543,7 +548,7 @@ class DashboardController {
|
||||
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);
|
||||
await this.configureWindowSurface(window.surfaceId, this.isForegroundWindow(window.windowId), window.heightMode);
|
||||
window.relayout?.();
|
||||
}
|
||||
shell.foregroundWindow()?.requestRender();
|
||||
@@ -555,12 +560,11 @@ class DashboardController {
|
||||
const position = verticalPositionSetting.get();
|
||||
if (position === this.lastVerticalPosition) return;
|
||||
this.lastVerticalPosition = position;
|
||||
const foregroundWindowId = shell.foregroundWindow()?.windowId;
|
||||
void (async () => {
|
||||
for (const window of shell.getWindows()) {
|
||||
await this.configureWindowSurface(
|
||||
window.surfaceId,
|
||||
window.windowId === foregroundWindowId,
|
||||
this.isForegroundWindow(window.windowId),
|
||||
window.heightMode,
|
||||
);
|
||||
}
|
||||
@@ -910,11 +914,14 @@ class DashboardController {
|
||||
*/
|
||||
private pushBrightness(force = false): void {
|
||||
if (!this.communicator) return;
|
||||
const value = brightnessSetting.get();
|
||||
const preferences = getBrightnessPreferences();
|
||||
const value = JSON.stringify(preferences);
|
||||
if (!force && value === this.lastPushedBrightness) return;
|
||||
this.lastPushedBrightness = value;
|
||||
const level = brightnessSettingToLevel(value);
|
||||
void this.communicator.setBrightness(level === null, level ?? 0).catch(() => {});
|
||||
void this.communicator.configureBrightness(preferences).catch((error) => {
|
||||
this.lastPushedBrightness = null;
|
||||
this.appendLog(`brightness configuration failed: ${this.formatError(error)}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** Save the occupied part of the composited screen as a 4-bit grayscale PNG. */
|
||||
@@ -1013,7 +1020,13 @@ class DashboardController {
|
||||
return this.glassesDisplayLabel();
|
||||
}
|
||||
if (this.silentMode && this.phase === "connected") {
|
||||
return "Connected (Silent mode enabled)";
|
||||
// Say how to leave it. Silent mode is entered and exited only by the
|
||||
// same gesture on the glasses, the firmware ignores all input and blanks
|
||||
// the display while it is on, and nothing here can turn it off -- there
|
||||
// is no setter, only onSilentMode. So a user who triggered it by
|
||||
// accident sees a connected pair of glasses that answers nothing, with
|
||||
// no way to find out why. The instruction belongs where they are looking.
|
||||
return "Connected (Silent mode — long-press both touchpads on the glasses to exit)";
|
||||
}
|
||||
// The preview compositor keeps the mirror live (including as a black
|
||||
// frame while the simulated screen is off), so never cover it.
|
||||
@@ -1235,11 +1248,10 @@ class DashboardController {
|
||||
// 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(
|
||||
window.surfaceId,
|
||||
window.windowId === foregroundWindowId,
|
||||
this.isForegroundWindow(window.windowId),
|
||||
window.heightMode,
|
||||
target,
|
||||
);
|
||||
@@ -1337,10 +1349,15 @@ class DashboardController {
|
||||
ring: ringAddress,
|
||||
});
|
||||
this.communicator = communicator;
|
||||
this.offLog = communicator.onLog((line) => {
|
||||
this.appendLog(line);
|
||||
});
|
||||
// Size the compositor before anything else is awaited: windows opened
|
||||
// during the bridge start-ups below (the terminal hub, restored apps)
|
||||
// configure their surfaces through this.communicator, and the Java call
|
||||
// queue is FIFO, so enqueuing the screen size first guarantees it lands
|
||||
// ahead of them. Mirrors ensurePreviewDisplay.
|
||||
await communicator.configureCompositorScreen(G2_LENS_WIDTH, G2_LENS_HEIGHT);
|
||||
await communicator.configureBrightness(getBrightnessPreferences());
|
||||
this.offState = communicator.onStateChange((state) => {
|
||||
if (state.phase !== "connected") resetRingInputFilter();
|
||||
if (state.phase === "unpaired") {
|
||||
// Java parked its retry loop: an arm's Android bond is gone, so
|
||||
// every redial would fail the same way until the user re-pairs.
|
||||
@@ -1506,7 +1523,6 @@ class DashboardController {
|
||||
await nightscoutBridge.start();
|
||||
// Register the compositor surfaces: the shell chrome above all windows,
|
||||
// and a surface per live window (only the foreground one is composited).
|
||||
await communicator.configureCompositorScreen(G2_LENS_WIDTH, G2_LENS_HEIGHT);
|
||||
await communicator.configureSurface(SHELL_SURFACE_ID, {
|
||||
x: 0,
|
||||
y: 0,
|
||||
@@ -1520,11 +1536,10 @@ class DashboardController {
|
||||
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()) {
|
||||
await this.configureWindowSurface(
|
||||
window.surfaceId,
|
||||
window.windowId === foregroundWindowId,
|
||||
this.isForegroundWindow(window.windowId),
|
||||
window.heightMode,
|
||||
);
|
||||
}
|
||||
@@ -1551,8 +1566,6 @@ class DashboardController {
|
||||
const message = this.formatError(error);
|
||||
this.offState?.();
|
||||
this.offState = null;
|
||||
this.offLog?.();
|
||||
this.offLog = null;
|
||||
this.offRing?.();
|
||||
this.offRing = null;
|
||||
this.offBattery?.();
|
||||
@@ -1691,8 +1704,6 @@ class DashboardController {
|
||||
this.clearDashboardTimer();
|
||||
this.offState?.();
|
||||
this.offState = null;
|
||||
this.offLog?.();
|
||||
this.offLog = null;
|
||||
this.offRing?.();
|
||||
this.offRing = null;
|
||||
this.offBattery?.();
|
||||
@@ -1893,11 +1904,15 @@ class DashboardController {
|
||||
title: string,
|
||||
onFinish?: () => void,
|
||||
toggle?: TextSettingsEditToggle,
|
||||
onCancel?: () => void,
|
||||
): void {
|
||||
this.activeTextSettings = Array.from(settings.slice(0, 2));
|
||||
this.activeTextSettingOriginalValues = this.activeTextSettings.map((setting) => setting.get());
|
||||
this.activeTextEditorTitle = title;
|
||||
this.activeTextEditorOnFinish = onFinish ?? null;
|
||||
this.activeTextEditorToggle = toggle ?? null;
|
||||
this.activeTextEditorToggleOriginalValue = toggle?.setting.get() ?? false;
|
||||
this.activeTextEditorOnCancel = onCancel ?? null;
|
||||
this.emit();
|
||||
}
|
||||
|
||||
@@ -2014,11 +2029,17 @@ class DashboardController {
|
||||
|
||||
private endTextSettingEdit(): void {
|
||||
const finishedSettings = this.activeTextSettings;
|
||||
// Closing without the done key is a cancel from the caller's point of view.
|
||||
// finishTextSettingEdit clears this first, so a completed edit never fires it.
|
||||
const onCancel = this.activeTextEditorOnCancel;
|
||||
this.activeTextSettings = [];
|
||||
this.activeTextSettingOriginalValues = [];
|
||||
this.activeTextEditorTitle = "";
|
||||
this.activeTextEditorOnFinish = null;
|
||||
this.activeTextEditorToggle = null;
|
||||
this.activeTextEditorOnCancel = null;
|
||||
this.emit();
|
||||
onCancel?.();
|
||||
if (finishedSettings.includes(nightscoutSiteUrlSetting) || finishedSettings.includes(nightscoutApiTokenSetting)) {
|
||||
void this.refreshNightscoutAfterSettingsChange();
|
||||
}
|
||||
@@ -2031,7 +2052,15 @@ class DashboardController {
|
||||
*/
|
||||
finishActiveTextSettingEdit(): void {
|
||||
if (!this.activeTextSettings.length) return;
|
||||
const invalid = this.activeTextSettings.find(setting => setting.validationError());
|
||||
if (invalid) {
|
||||
void Dialogs.alert({ title: invalid.editorTitle, message: invalid.validationError()!, okButtonText: "OK" });
|
||||
return;
|
||||
}
|
||||
const onFinish = this.activeTextEditorOnFinish;
|
||||
// Completing is not cancelling: drop the cancel callback before
|
||||
// endTextSettingEdit, which fires whatever is still set.
|
||||
this.activeTextEditorOnCancel = null;
|
||||
const closesGlassesEditor = this.activeTextSettings.length === 1;
|
||||
this.endTextSettingEdit();
|
||||
if (closesGlassesEditor && this.textEditorHost?.closeTextEditor()) {
|
||||
@@ -2040,6 +2069,28 @@ class DashboardController {
|
||||
onFinish?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone editor's Cancel button: put back the values the edit started
|
||||
* with, end the edit as a cancel (the caller's onCancel fires), and
|
||||
* navigate the Settings app's glasses editor out of the edit page.
|
||||
*/
|
||||
cancelActiveTextSettingEdit(): void {
|
||||
if (!this.activeTextSettings.length) return;
|
||||
this.activeTextSettings.forEach((setting, index) => {
|
||||
const original = this.activeTextSettingOriginalValues[index] ?? "";
|
||||
if (setting.get() !== original) setting.set(original);
|
||||
});
|
||||
const toggle = this.activeTextEditorToggle;
|
||||
if (toggle && toggle.setting.get() !== this.activeTextEditorToggleOriginalValue) {
|
||||
toggle.setting.set(this.activeTextEditorToggleOriginalValue);
|
||||
}
|
||||
const closesGlassesEditor = this.activeTextSettings.length === 1;
|
||||
this.endTextSettingEdit();
|
||||
if (closesGlassesEditor && this.textEditorHost?.closeTextEditor()) {
|
||||
this.textEditorHost.requestRender();
|
||||
}
|
||||
}
|
||||
|
||||
private updateTextSetting(setting: ConfigSettingString, value: string): void {
|
||||
if (setting.get() !== value) {
|
||||
setting.set(value);
|
||||
@@ -2068,6 +2119,7 @@ class DashboardController {
|
||||
let frameOwned = false;
|
||||
try {
|
||||
const inputEvent = rawInputEventToInputEvent(event);
|
||||
if (!acceptInput(inputEvent)) return;
|
||||
// The gesture, plus which app is on screen and whether input goes to it,
|
||||
// the sidebar, or a shell overlay. Java only knows the raw event codes,
|
||||
// and without the target the export says what was pressed but not who
|
||||
@@ -2221,8 +2273,7 @@ class DashboardController {
|
||||
reconfigureSurface: (heightMode) => {
|
||||
// Resize the surface rect to the new band; a foreground window stays
|
||||
// visible. The shell re-renders so the chrome (top bar) follows.
|
||||
const visible = shell.foregroundWindow()?.windowId === windowId;
|
||||
void this.configureWindowSurface(surfaceId, visible, heightMode);
|
||||
void this.configureWindowSurface(surfaceId, this.isForegroundWindow(windowId), heightMode);
|
||||
this.requestShellRender();
|
||||
},
|
||||
onClosed: () => {
|
||||
@@ -2244,6 +2295,7 @@ class DashboardController {
|
||||
const host = new WorkerAppHost({
|
||||
appId,
|
||||
worker: createWorker(),
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId); },
|
||||
configureSurface: (surfaceId, visible, heightMode) =>
|
||||
this.configureWindowSurface(surfaceId, visible, heightMode),
|
||||
setSurfaceVisible: (surfaceId, visible) => this.setWindowSurfaceVisible(surfaceId, visible),
|
||||
@@ -2374,10 +2426,21 @@ class DashboardController {
|
||||
}
|
||||
}
|
||||
|
||||
/** Create/refresh a window surface on the compositor, if a display target exists. */
|
||||
/**
|
||||
* Create/refresh a window surface on the compositor, if a display target exists.
|
||||
*
|
||||
* `visible` may be a function, asked only after the surface is configured,
|
||||
* right when the visibility call is queued. Callers that loop over windows
|
||||
* or resize one in place must pass one (isForegroundWindow): the configure
|
||||
* call yields, the foreground can change meanwhile, and a visibility decided
|
||||
* before the await then lands AFTER the focus change's own calls, since the
|
||||
* bridge runs Java calls in order. At startup, restoreOpenApps focuses
|
||||
* windows while connect() registers surfaces, so a foreground read before
|
||||
* that loop left the old window visible and the new foreground hidden.
|
||||
*/
|
||||
private async configureWindowSurface(
|
||||
surfaceId: string,
|
||||
visible: boolean,
|
||||
visible: boolean | (() => boolean),
|
||||
heightMode: WindowHeightMode = "min",
|
||||
// ensurePreviewDisplay passes its not-yet-published target explicitly.
|
||||
target: DisplayTarget | null = this.display,
|
||||
@@ -2388,7 +2451,12 @@ class DashboardController {
|
||||
zOrder: 0,
|
||||
transparency: "opaque",
|
||||
});
|
||||
await target.setSurfaceVisible(surfaceId, visible);
|
||||
await target.setSurfaceVisible(surfaceId, typeof visible === "function" ? visible() : visible);
|
||||
}
|
||||
|
||||
/** A late answer to "is this window in front?", for configureWindowSurface. */
|
||||
private isForegroundWindow(windowId: string): () => boolean {
|
||||
return () => shell.foregroundWindow()?.windowId === windowId;
|
||||
}
|
||||
|
||||
private removeWindowSurface(surfaceId: string): void {
|
||||
@@ -2475,7 +2543,7 @@ class DashboardController {
|
||||
beginRenderPass(!wantFreshData);
|
||||
const paintStartedAtMs = Date.now();
|
||||
const planes = frameTimings.span(frameId, "paint", () =>
|
||||
frameTimings.runWithFrame(frameId, () => shell.paintSurface()),
|
||||
frameTimings.runWithFrame(frameId, () => shell.paintScene()),
|
||||
);
|
||||
const paintMs = Date.now() - paintStartedAtMs;
|
||||
const paintUsedStaleData = endRenderPass();
|
||||
@@ -2492,32 +2560,7 @@ 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());
|
||||
const preparedDraws = frameTimings.span(frameId, "prepareFrameDraws", () => prepareFrameDraws(draws));
|
||||
// Spanned because the bridge serializes Java calls: a frame can sit here
|
||||
// behind another surface's submission, which is otherwise an unexplained
|
||||
// jump between the paint spans and the composite.
|
||||
await frameTimings.spanAsync(frameId, "submit", () =>
|
||||
display.submitSurfaceFrame(
|
||||
SHELL_SURFACE_ID,
|
||||
buffer,
|
||||
{ x: 0, y: 0, width: image.width, height: image.height },
|
||||
fingerprint,
|
||||
paintMs,
|
||||
frameId,
|
||||
preparedDraws,
|
||||
),
|
||||
);
|
||||
await frameTimings.spanAsync(frameId, "submit", () => display.submitShellScene(planes, paintMs, frameId));
|
||||
// Backpressure: the next shell render waits for this one to reach the
|
||||
// glasses. Timing out here means the loop was blocked for the full timeout
|
||||
// and any input arriving meanwhile had its chrome repaint delayed, so say
|
||||
@@ -2626,7 +2669,7 @@ class DashboardController {
|
||||
}
|
||||
|
||||
private appendLog(line: string): void {
|
||||
console.log(`[${formatTimestamp(new Date())}] ${line}`);
|
||||
//console.log(`[${formatTimestamp(new Date())}] ${line}`);
|
||||
}
|
||||
|
||||
private setDisplayPreview(preview: ImageSource | null): void {
|
||||
@@ -2643,6 +2686,22 @@ class DashboardController {
|
||||
*/
|
||||
private previewTrailingTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastRecordCaptureAtMs = 0;
|
||||
private phonePreviewVisible: (() => boolean) | null = null;
|
||||
|
||||
/** The main page owns the mirror; other phone pages must not keep it rendering. */
|
||||
attachPhonePreview(isVisible: () => boolean): () => void {
|
||||
this.phonePreviewVisible = isVisible;
|
||||
this.lastConnectedPreviewUpdateAtMs = 0;
|
||||
this.updateCompositePreview();
|
||||
return () => {
|
||||
if (this.phonePreviewVisible !== isVisible) return;
|
||||
this.phonePreviewVisible = null;
|
||||
if (this.previewTrailingTimer) {
|
||||
clearTimeout(this.previewTrailingTimer);
|
||||
this.previewTrailingTimer = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the preview now if the floor allows, otherwise once the floor
|
||||
@@ -2650,6 +2709,7 @@ class DashboardController {
|
||||
* of waiting for the safety-net poll.
|
||||
*/
|
||||
private schedulePreviewUpdate(): void {
|
||||
if (!this.phonePreviewVisible && !this.screenRecordingActive) return;
|
||||
if (this.previewTrailingTimer) return;
|
||||
const wait = this.lastConnectedPreviewUpdateAtMs + CONNECTED_PREVIEW_MIN_UPDATE_MS - Date.now();
|
||||
if (wait <= 0) {
|
||||
@@ -2677,6 +2737,13 @@ class DashboardController {
|
||||
return;
|
||||
}
|
||||
this.lastConnectedPreviewUpdateAtMs = now;
|
||||
// A user-requested GIF is an independent consumer, including while the
|
||||
// phone is asleep or another page/app is foregrounded.
|
||||
if (this.screenRecordingActive && now - this.lastRecordCaptureAtMs >= RECORDING_MIN_CAPTURE_MS) {
|
||||
this.lastRecordCaptureAtMs = now;
|
||||
display.recordScreenFrame();
|
||||
}
|
||||
if (!this.phonePreviewVisible?.()) return;
|
||||
// The connected foreground service intentionally keeps this controller
|
||||
// alive after the phone UI is backgrounded. Do not keep constructing
|
||||
// 640x480 Android Bitmaps for a window that cannot display them: besides
|
||||
@@ -2685,10 +2752,8 @@ class DashboardController {
|
||||
if (global.isAndroid) {
|
||||
const activity = Application.android.foregroundActivity;
|
||||
if (!activity || !activity.hasWindowFocus()) return;
|
||||
}
|
||||
if (this.screenRecordingActive && now - this.lastRecordCaptureAtMs >= RECORDING_MIN_CAPTURE_MS) {
|
||||
this.lastRecordCaptureAtMs = now;
|
||||
display.recordScreenFrame();
|
||||
const power = activity.getSystemService(android.content.Context.POWER_SERVICE) as android.os.PowerManager;
|
||||
if (!power?.isInteractive()) return;
|
||||
}
|
||||
const preview = display.getCompositePreview(previewColorSetting.get() === "green");
|
||||
if (preview) {
|
||||
|
||||
@@ -77,6 +77,8 @@ export const OsEventTypeList = {
|
||||
* this eventType; the glance host treats it as a press.
|
||||
*/
|
||||
HEAD_UP_EVENT: 12,
|
||||
/** Faceclaw/18: R1 touch-down, before click/hold/slide recognition. */
|
||||
RING_PRESS_EVENT: 14,
|
||||
} as const;
|
||||
|
||||
export const OsEventTypeName: Record<number, string> = {
|
||||
@@ -93,4 +95,5 @@ export const OsEventTypeName: Record<number, string> = {
|
||||
10: "RING_LONG_PRESS_RELEASE_EVENT",
|
||||
11: "SHORT_THEN_LONG_PRESS_EVENT",
|
||||
12: "HEAD_UP_EVENT",
|
||||
14: "RING_PRESS_EVENT",
|
||||
};
|
||||
+10
-10
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Builds the Faceclaw custom firmware on-device: downloads the stock Even
|
||||
* 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
|
||||
* currently 2.3.0.24) 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.
|
||||
@@ -23,15 +23,15 @@ import { fetchWithUserAgent } from "../util/http";
|
||||
import { bytesToHex, hexToBytes as hexToBytesLenient } from "../util/hex-util";
|
||||
import { EvenHubFont } from "../graphics/evenhub-font";
|
||||
|
||||
declare const com: any;
|
||||
import { firmwareSha256, writeFirmwareFile } from "../native/firmware-files";
|
||||
|
||||
// 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.
|
||||
// (2.3.0.24 = 1dbdf37b…; the older 2.2.9.22 base was fc250b05….)
|
||||
const FIRMWARE_URL = "https://cdn.evenreal.co/firmware/1dbdf37b03a1169c384945e94d671371.bin";
|
||||
// Output names follow the patch set's base name (e.g. g2_2.3.0.24.bin →
|
||||
// g2_2.3.0.24_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";
|
||||
|
||||
@@ -281,12 +281,12 @@ function tightBuffer(bytes: Uint8Array): ArrayBuffer {
|
||||
return bytes.slice().buffer;
|
||||
}
|
||||
|
||||
/** SHA-256 hex digest of an ArrayBuffer, via Android's MessageDigest. */
|
||||
/** SHA-256 hex digest using the platform's native crypto implementation. */
|
||||
function sha256Hex(buffer: ArrayBuffer): string {
|
||||
return String(com.faceclaw.app.FaceclawFirmwareUtil.sha256Hex(buffer));
|
||||
return firmwareSha256(buffer);
|
||||
}
|
||||
|
||||
/** Write an ArrayBuffer's bytes to `path`, via a native FileChannel write. */
|
||||
/** Persist the verified image using the platform's native file API. */
|
||||
function writeFile(path: string, buffer: ArrayBuffer): void {
|
||||
com.faceclaw.app.FaceclawFirmwareUtil.writeFile(path, buffer);
|
||||
writeFirmwareFile(path, buffer);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export type FirmwareInfo = {
|
||||
};
|
||||
|
||||
/** The Faceclaw firmware revision this build of the app needs. */
|
||||
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 13;
|
||||
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 35;
|
||||
|
||||
const FACECLAW_PREFIX = "Faceclaw/";
|
||||
const LEGACY_PREFIX = "EVENCFW";
|
||||
@@ -34,9 +34,9 @@ const LEGACY_PREFIX = "EVENCFW";
|
||||
// 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 BASE_STOCK_VERSION = [2, 2, 9, 22];
|
||||
export const BASE_STOCK_VERSION = [2, 3, 0, 24];
|
||||
export const BASE_STOCK_VERSION_TEXT = BASE_STOCK_VERSION.join(".");
|
||||
export const VALIDATED_STOCK_VERSION = [2, 2, 10, 10];
|
||||
export const VALIDATED_STOCK_VERSION = [2, 3, 0, 24];
|
||||
export const VALIDATED_STOCK_VERSION_TEXT = VALIDATED_STOCK_VERSION.join(".");
|
||||
|
||||
export type FirmwareExtension =
|
||||
|
||||
@@ -25,12 +25,13 @@ type FontSpec = {
|
||||
// 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.3.0.24: 0x007b699c, 0x007b69b0, 0x007b68c0
|
||||
// 2.2.9.22: 0x007a8954, 0x007a8968, 0x007a8878
|
||||
// 2.2.6.10: 0x0077f414, 0x0077f428, 0x0077f374
|
||||
const FONT_SPECS: FontSpec[] = [
|
||||
{ descriptor: 0x007a8954, lineHeight: 27, baseLine: 5 },
|
||||
{ descriptor: 0x007a8968, lineHeight: 26, baseLine: 5 },
|
||||
{ descriptor: 0x007a8878, lineHeight: 20, baseLine: 2 },
|
||||
{ descriptor: 0x007b699c, lineHeight: 27, baseLine: 5 },
|
||||
{ descriptor: 0x007b69b0, lineHeight: 26, baseLine: 5 },
|
||||
{ descriptor: 0x007b68c0, lineHeight: 20, baseLine: 2 },
|
||||
];
|
||||
|
||||
type ExtractedGlyph = {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export type FlashState = "validating" | "connecting" | "flashing" | "rebooting" | "done" | "error";
|
||||
|
||||
export type FlashProgress = {
|
||||
lens: string;
|
||||
componentIndex: number;
|
||||
componentCount: number;
|
||||
blockIndex: number;
|
||||
blockCount: number;
|
||||
/** Bytes flashed so far across the whole lens image — the size-weighted progress signal. */
|
||||
bytesSent: number;
|
||||
bytesTotal: number;
|
||||
};
|
||||
|
||||
+137
-95
@@ -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.9.22 image into the Faceclaw custom firmware.
|
||||
// Turns the stock G2 2.3.0.24 image into the Faceclaw custom firmware.
|
||||
|
||||
export type FirmwarePatchOp = {
|
||||
offset: number;
|
||||
@@ -17,194 +17,236 @@ export type FirmwarePatchSet = {
|
||||
};
|
||||
|
||||
export const CFW_PATCH_SET: FirmwarePatchSet = {
|
||||
"base": "g2_2.2.9.22.bin",
|
||||
"baseSha256": "a03fbea9f68a9de6bc271daabb9f3a41c59053d1086622c76a4e990f829cc561",
|
||||
"outputSha256": "32cea69474252a2b2f9c0fdc5f89bf0d5d6f745b4eec10aea8e9c34e3f106b3f",
|
||||
"base": "g2_2.3.0.24.bin",
|
||||
"baseSha256": "187ccf2bcc5c17a212106e8a376745511e8289c4232b634a7ea94b9bf25a0979",
|
||||
"outputSha256": "d7971b68add0c5187fec81d1cb1ef8cc12322db426a98cb445f1b3a274272817",
|
||||
"patches": [
|
||||
{
|
||||
"offset": 935280,
|
||||
"offset": 1045797,
|
||||
"old": "38b584b0",
|
||||
"new": "5df3b9b8",
|
||||
"desc": "ring receiver entry: timestamped unfiltered reports under framebuffer lease"
|
||||
},
|
||||
{
|
||||
"offset": 1437929,
|
||||
"old": "15e0",
|
||||
"new": "fae7",
|
||||
"desc": "route ANCS write completions through relay event hook"
|
||||
},
|
||||
{
|
||||
"offset": 1437923,
|
||||
"old": "fef788ff",
|
||||
"new": "fdf2c8fd",
|
||||
"desc": "cfw_ancs_event"
|
||||
},
|
||||
{
|
||||
"offset": 1437951,
|
||||
"old": "fef7e8fb",
|
||||
"new": "fdf202fb",
|
||||
"desc": "cfw_ancs_open"
|
||||
},
|
||||
{
|
||||
"offset": 1437969,
|
||||
"old": "fef7e7fb",
|
||||
"new": "fdf219fb",
|
||||
"desc": "cfw_ancs_close"
|
||||
},
|
||||
{
|
||||
"offset": 1388387,
|
||||
"old": "39694d00",
|
||||
"new": "79637d00",
|
||||
"desc": "connection-bound ANCS EUS write callback"
|
||||
},
|
||||
{
|
||||
"offset": 971497,
|
||||
"old": "fff717f8",
|
||||
"new": "64f395fb",
|
||||
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
|
||||
"new": "6ff3e9f9",
|
||||
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
|
||||
},
|
||||
{
|
||||
"offset": 935628,
|
||||
"offset": 971845,
|
||||
"old": "fef769ff",
|
||||
"new": "64f3e7fa",
|
||||
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
|
||||
"new": "6ff33bf9",
|
||||
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
|
||||
},
|
||||
{
|
||||
"offset": 943818,
|
||||
"old": "fcf76aff",
|
||||
"new": "62f3e8fa",
|
||||
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
|
||||
"offset": 979579,
|
||||
"old": "fdf74ef8",
|
||||
"new": "6df320fa",
|
||||
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
|
||||
},
|
||||
{
|
||||
"offset": 1415004,
|
||||
"old": "fcf745f8",
|
||||
"new": "eef23dfb",
|
||||
"offset": 1428895,
|
||||
"old": "f8f76cfd",
|
||||
"new": "fcf238fa",
|
||||
"desc": "bl cfw_receive_packet (private SID-f0 probe before TPL reassembly)"
|
||||
},
|
||||
{
|
||||
"offset": 1363762,
|
||||
"offset": 1376071,
|
||||
"old": "7c20",
|
||||
"new": "7d20",
|
||||
"desc": "Set Local Feature: enable LE 2M bit 8"
|
||||
},
|
||||
{
|
||||
"offset": 4410298,
|
||||
"offset": 4468651,
|
||||
"old": "0c001800",
|
||||
"new": "06000600",
|
||||
"desc": "fast connection interval min=max=7.5 ms; latency remains 0"
|
||||
},
|
||||
{
|
||||
"offset": 1053266,
|
||||
"offset": 1057215,
|
||||
"old": "0500",
|
||||
"new": "a325",
|
||||
"desc": "_connectParamReq_impl: force requested mode to fast (0xa3); disables idle slow requests"
|
||||
},
|
||||
{
|
||||
"offset": 1124178,
|
||||
"offset": 1130227,
|
||||
"old": "5ff43432",
|
||||
"new": "5ff43332",
|
||||
"desc": "reserve final 1 KiB of primary TLSF arena for CFW context anchor"
|
||||
},
|
||||
{
|
||||
"offset": 1242342,
|
||||
"old": "d4f790fb",
|
||||
"new": "1af33cfc",
|
||||
"offset": 1248487,
|
||||
"old": "d4f712fb",
|
||||
"new": "2af302fb",
|
||||
"desc": "bl settings_send_wrapper (append caps field 100)"
|
||||
},
|
||||
{
|
||||
"offset": 1240038,
|
||||
"old": "f5f710f9",
|
||||
"new": "1af3dafd",
|
||||
"offset": 1246183,
|
||||
"old": "f5f7e2f8",
|
||||
"new": "2af386fc",
|
||||
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
|
||||
},
|
||||
{
|
||||
"offset": 939336,
|
||||
"old": "0bf02af9",
|
||||
"new": "64f351f8",
|
||||
"desc": "bl faceclaw_display_start @ 0x45f146 (fail-open wake takeover)"
|
||||
"offset": 975219,
|
||||
"old": "02f083fc",
|
||||
"new": "6cf3f2fc",
|
||||
"desc": "bl faceclaw_display_start @ 0x467d68 (fail-open wake takeover)"
|
||||
},
|
||||
{
|
||||
"offset": 939528,
|
||||
"old": "0bf0caf8",
|
||||
"new": "64f3bff8",
|
||||
"desc": "bl faceclaw_display_start_headup @ 0x45f206 (fail-open wake takeover)"
|
||||
"offset": 975411,
|
||||
"old": "02f023fc",
|
||||
"new": "6cf356fd",
|
||||
"desc": "bl faceclaw_display_start_headup @ 0x467e28 (fail-open wake takeover)"
|
||||
},
|
||||
{
|
||||
"offset": 939016,
|
||||
"old": "10f096f8",
|
||||
"new": "65f397fd",
|
||||
"offset": 975103,
|
||||
"old": "07f085fb",
|
||||
"new": "6ef3f2f9",
|
||||
"desc": "bl headup_gate (head-up sensor event -> EvenHub sys event 12 under lease)"
|
||||
},
|
||||
{
|
||||
"offset": 939036,
|
||||
"old": "fff765fb",
|
||||
"new": "63f3ddff",
|
||||
"desc": "bl faceclaw_idle_input_gate (idle tap/long/release -> field-102 events 2/3/4)"
|
||||
"offset": 830549,
|
||||
"old": "19f03efb",
|
||||
"new": "91f3a1fb",
|
||||
"desc": "bl gesture_ring_press_mode (observe ring touch-down, preserve stock dispatch)"
|
||||
},
|
||||
{
|
||||
"offset": 831036,
|
||||
"old": "1df057fc",
|
||||
"new": "7ff373ff",
|
||||
"desc": "bl gesture_press (Faceclaw lease gates event 9 vs stock UI event 8)"
|
||||
"offset": 830795,
|
||||
"old": "1ff071ff",
|
||||
"new": "91f35afb",
|
||||
"desc": "bl gesture_press (owned event 9 before stock menu gate)"
|
||||
},
|
||||
{
|
||||
"offset": 831042,
|
||||
"old": "24f023f9",
|
||||
"new": "80f314f8",
|
||||
"offset": 830887,
|
||||
"old": "1ff043ff",
|
||||
"new": "91f354fb",
|
||||
"desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
|
||||
},
|
||||
{
|
||||
"offset": 831800,
|
||||
"old": "1df0d9fa",
|
||||
"new": "7ff3f9fd",
|
||||
"desc": "bl gesture_release (source-qualified event 10 vs stock UI event 0x4a)"
|
||||
"offset": 831763,
|
||||
"old": "1ff08dfd",
|
||||
"new": "91f38af9",
|
||||
"desc": "bl gesture_release (owned event 10 before stock menu gate)"
|
||||
},
|
||||
{
|
||||
"offset": 1553752,
|
||||
"offset": 1570209,
|
||||
"old": "7fb50600",
|
||||
"new": "cef2f1bb",
|
||||
"new": "dbf293be",
|
||||
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
|
||||
},
|
||||
{
|
||||
"offset": 1047796,
|
||||
"old": "f6f7edff",
|
||||
"new": "45f32ffd",
|
||||
"desc": "bl display_copy_hook @ 0x4798f2 (640x480 direct framebuffer)"
|
||||
"offset": 1051545,
|
||||
"old": "f6f787f9",
|
||||
"new": "55f321f9",
|
||||
"desc": "bl display_copy_hook @ 0x47a78e (640x480 direct framebuffer)"
|
||||
},
|
||||
{
|
||||
"offset": 1048112,
|
||||
"old": "f6f74fff",
|
||||
"new": "45f391fc",
|
||||
"desc": "bl display_copy_hook @ 0x479a2e (640x480 direct framebuffer)"
|
||||
"offset": 1051861,
|
||||
"old": "f6f7e9f8",
|
||||
"new": "55f383f8",
|
||||
"desc": "bl display_copy_hook @ 0x47a8ca (640x480 direct framebuffer)"
|
||||
},
|
||||
{
|
||||
"offset": 1255404,
|
||||
"old": "d9f758ff",
|
||||
"new": "16f3f9fd",
|
||||
"desc": "bl faceclaw_send_wear_event @ 0x4ac3ea (outside onboarding)"
|
||||
"offset": 1262237,
|
||||
"old": "d9f7d0fd",
|
||||
"new": "26f343fb",
|
||||
"desc": "bl faceclaw_send_wear_event @ 0x4ade92 (outside onboarding)"
|
||||
},
|
||||
{
|
||||
"offset": 1255504,
|
||||
"old": "d9f726ff",
|
||||
"new": "16f3c7fd",
|
||||
"desc": "bl faceclaw_send_wear_event @ 0x4ac44e (outside onboarding)"
|
||||
"offset": 1262337,
|
||||
"old": "d9f79efd",
|
||||
"new": "26f311fb",
|
||||
"desc": "bl faceclaw_send_wear_event @ 0x4adef6 (outside onboarding)"
|
||||
},
|
||||
{
|
||||
"offset": 1297700,
|
||||
"old": "65f0affd",
|
||||
"new": "0cf351f8",
|
||||
"offset": 1309405,
|
||||
"old": "67f02dff",
|
||||
"new": "1af31bfc",
|
||||
"desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
|
||||
},
|
||||
{
|
||||
"offset": 1296176,
|
||||
"old": "fff759fc",
|
||||
"new": "0cf3c7fb",
|
||||
"offset": 1307865,
|
||||
"old": "fff7c9fb",
|
||||
"new": "1af399ff",
|
||||
"desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
|
||||
},
|
||||
{
|
||||
"offset": 4476518,
|
||||
"offset": 1300937,
|
||||
"old": "00210170",
|
||||
"new": "1cf37ffc",
|
||||
"desc": "bl compass_preserve_accuracy (retain magnetic calibration under Faceclaw framebuffer lease)"
|
||||
},
|
||||
{
|
||||
"offset": 4537963,
|
||||
"old": "",
|
||||
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf2de9f04fa5b04ef66c6b4ff2a84416460d46ccf2ff0bc2f229044ff6ff7900274ff00108019006e048f2c731c0f24501bff32f8f8847d4f800a0bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0bb804ff4377005f039f8002800f0a1824ff62451cff6ff7142183d3182f8dc7282f8dd7282f8de7282f8df7282f8e07282f8e17282f8e27282f8e37282f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382d1c0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001f51457ff436afbff35f8f44e8000121b154e8001f5145f8d02be7aa4645ea064100260127c0f8701206e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0bc804ff4377004f05eff002800f0c6814ff62451cff6ff7100bf42183d3182f8dc6282f8dd6282f8de6282f8df6282f8e06282f8e16282f8e26282f8e36282f8e46282f8e56282f8e66282f8e76282f8e86282f8e96282f8ea6282f8eb6282f8ec6282f8ed6282f8ee6282f8ef6282f8f06282f8f16282f8f26282f8f36282f8f46282f8f56282f8f66282f8f76282f8f86282f8f96282f8fa6282f8fb6282f8fc6282f8fd6282f8fe6282f8ff6282f8006382f8016382f8026382f8036382f8046382f8056382f8066382f8076382f8086382f8096382f80a6382f80b6382f80c6382f80d6382f80e6382f80f6382f8106382f8116382f8126382f8136382f8146382f8156382f8166382f8176382f8186382d1c0f800b08772a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff437afbff35f8f00bf44e8000121b154e8001fa942f8d02be7d0f8746242f6f767c0f24407002ebff35f8f00f0eb8007f19a0230464ff0ff314ff0ff379047002840f0418143f67750c0f24f00804700274ff001080397adf8107006e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0e1804ff4377004f068fe002800f0d9804ff62451cff6ff7100bf42183d3182f8dc7282f8dd7282f8de7282f8df7282f8e07282f8e17282f8e27282f8e37282f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382d1c0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff436afbff35f8f44e8000149b354e8001fa942f8d02be705460020b847b0b105f51d7151e8006f4eb9bff35f8f00bf41e8000292b151e8006f002ef8d00021bff32f8fbff35f8f21b10646f9e64ff0ff3742e007f5a9718847f2e60121f1e70020019d42f6f764002d4ff0010bc0f2440418bfbaf1000f33d10df108098046484602f07df903ab28465146012205f0abfc9df8111007464846002918bf4ff0ff3702f0a3fabbf1000f044608d19df8100028b949f28340c0f247004c308047b8f1000f18bfc8f80c4042f6f764c0f2440404f5807130468847384625b0bde8f08f2a7802f07f01a1f1150313f1030f0bd802f07b030b2b07d002f07e02082a03d0032901d00629b7d140b149f28341c0f247010746884797f8641111b14ff0ff37d6e738464ff0000ba6e770b500284dd001684ef66c62ccf2ff02914218bf70bd90f8441090f8455046f6756c8d42c0f2510c2ad205eb8501014491f8492091f84a4091f846e091f8473091f8481042ea0424012c4ff0010298bf14466e1c054680f84560b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f84410bde870406047e047286c38b142f64d42c0f244022146bde87040104770bd02464ff64b70cff6ff7042f6653c7844c0f2440c00210023604700bf2de9f04f9fb04ff2a840c2f229000668bff35f8f30466ff39600b0f1005f42d130684ef66c65ccf2ff05a8423bd196f8640130b3d6f860411cb340f6b400c2f20000076804a802f0a5f8002f00f06a8140f2030a384621464ff416320296cff6807a4ff6ff760397fff752fb4ff6245b48f2c738cff6ff7b00270124c0f245081ce096f8660170b1d6f8680140b146f68051c2f207010968401a002802f37080002086f8660140f6d100c0f247001fb0bde8f04f0047bff32f8fc0474ff2a840c2f22900d0f80090bff35f8f0Line truncated
|
||||
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc5b04ff62c484ef66c694ff29c5b1446cff6ff78ccf2ff09c2f2290b4ff6ff75002701260d93cde90e0106e048f2a351c0f24501bff32f8f8847dbf800a0bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0ba804ff4757007f0b6fa002800f0078241464218463182f8d47382f8d57382f8d67382f8d77382f8d87382f8d97382f8da7382f8db7382f8dc7382f8dd7382f8de7382f8df7382f8e07382f8e17382f8e27382f8e37382f8e47382f8e57382f8e67382f8e77382f8e87382f8e97382f8ea7382f8eb7382f8ec7382f8ed7382f8ee7382f8ef7382f8f07382f8f17382f8f27382f8f37382f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f819747ff470afc0f8009086728583c583058445848584c584058545858585c585058645868586c586058745875be8001f51457ff436afbff35f8f4be8000121b15be8001f5145f8d02be70f99012641ea04410024c0f8701206e048f2a351c0f24501bff32f8f8847dbf80070bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0ba804ff4757007f0daf9002800f02b8141464218463182f8d44382f8d54382f8d64382f8d74382f8d84382f8d94382f8da4382f8db4382f8dc4382f8dd4382f8de4382f8df4382f8e04382f8e14382f8e24382f8e34382f8e44382f8e54382f8e64382f8e74382f8e84382f8e94382f8ea4382f8eb4382f8ec4382f8ed4382f8ee4382f8ef4382f8f04382f8f14382f8f24382f8f34382f8f44382f8f54382f8f64382f8f74382f8f84382f8f94382f8fa4382f8fb4382f8fc4382f8fd4382f8fe4382f8ff4382f8004482f8014482f8024482f8034482f8044482f8054482f8064482f8074482f8084482f8094482f80a4482f80b4482f80c4482f80d4482f80e4482f80f4482f8104482f8114482f8124482f8134482f8144482f8154482f8164482f8174482f8184482f819447ff470afc0f8009086728583c583058445848584c584058545858585c585058645868586c586058745875be8001fb9427ff436afbff35f8f4be8000121b15be8001fb942f8d02be7d0f874a242f6f766c0f24406baf1000fbff35f8f4ad006f19a0250464ff0ff314ff0ff379047002840f09d810f98002861d00e980778a7f1170002285bd80f980c2840f086810e9e7078b178084300f08081f0780138022800f27b81b279f379747a42ea0322337a307942ea0342717942ea0463b27af67a192f42ea062200f01082172f40f02682002a40f06281fe2800f07786812800f06a86002840f07d8651ea030040f0558100f0c7be04460020b047e8b104f51d7151e800afbaf1000f0cd1bff35f8f00bf41e80002002a00f0f58051e800afbaf1000ff5d00021bff32f8f0029bff35f8f00f0e480824692e74ff0ff3737e147f6df40c0f24f008047002701241197adf8487006e048f2a351c0f24501bff32f8f8847dbf80060bff35f8fdbf800000321cff680710140b1f1005fbff35f8f03d10168494500f0c1804ff4757007f080f8002800f0b98041464218463182f8d47382f8d57382f8d67382f8d77382f8d87382f8d97382f8da7382f8db7382f8dc7382f8dd7382f8de7382f8df7382f8e07382f8e17382f8e27382f8e37382f8e47382f8e57382f8e67382f8e77382f8e87382f8e97382f8ea7382f8eb7382f8ec7382f8ed7382f8ee7382f8ef7382f8f07382f8f17382f8f27382f8f37382f8f47382f8f57382f8f67382f8f77382f8f87382f8f97382f8fa7382f8fb7382f8fc7382f8fd7382f8fe7382f8ff7382f8007482f8017482f8027482f8037482f8047482f8057482f8067482f8077482f8087482f8097482f80a7482f80b7482f80c7482f80d7482f80e7482f80f7482f8107482f8117482f8127482f8137482f8147482f8157482f8167482f8177482f8187482f819747ff470afc0f8009084728583c583058445848584c584058545858585c585058645868586c586058745875be8001fb1427ff436afbff35f8f4be8000159b15be8001fb142f8d02be706f5a9718847ace6012110e700200e9999b10f9a8ab1097801f07f02b2f10b0618bf0126b2f11c0718bf01278a2924dc0b2926d01c2924d03fe00d9010a804f0a7fa4ff0ff3701249df84900002810a818bf4ff0ff3704f0e3fb054644b99df8480028b94af21f30c0f247004c3080470d98002818bfc56013e09c2901d08b291bd160b14af21f31c0f247010446884794f8641119b994f80413204669b14ff0ff3742f6f760c0f2440000f5807150468847384645b0bde8f08f0d9010a806ea070404f065fa0e98017801f07f061e2e04d10f9908f086fb0746b5e71d2e01f07e0018bf1a2811d1dbf800100322cff680720a40b2f1005fbff35f8f0ad10a684a4504bf002281f8812303e0a6f115010129e9d90f2e0adc092e00f37381052e00f0ef82072e40f01c8300279ae0142e00f32182102e00f0eb82112e40f011830f98022841f0d5800e9908781Line truncated
|
||||
"desc": "append injected blobs to main-app payload"
|
||||
},
|
||||
{
|
||||
"offset": 779114,
|
||||
"old": "846a3800",
|
||||
"new": "7c1b3900",
|
||||
"offset": 779123,
|
||||
"old": "805a3900",
|
||||
"new": "34733a00",
|
||||
"desc": "main-app subheader payload size (ps)"
|
||||
},
|
||||
{
|
||||
"offset": 152,
|
||||
"old": "046b3800",
|
||||
"new": "fc1b3900",
|
||||
"old": "005b3900",
|
||||
"new": "b4733a00",
|
||||
"desc": "main-app TOC entry size (ps + 128)"
|
||||
},
|
||||
{
|
||||
"offset": 779234,
|
||||
"old": "846a3804",
|
||||
"new": "7c1b3904",
|
||||
"offset": 779243,
|
||||
"old": "805a3904",
|
||||
"new": "34733a04",
|
||||
"desc": "main-app preamble length (low 24 bits)"
|
||||
},
|
||||
{
|
||||
"offset": 779238,
|
||||
"old": "85c355a2",
|
||||
"new": "a1afb7e4",
|
||||
"offset": 779247,
|
||||
"old": "effdbcea",
|
||||
"new": "85d22153",
|
||||
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
|
||||
},
|
||||
{
|
||||
"offset": 156,
|
||||
"old": "ed292ee4",
|
||||
"new": "b1adc0d0",
|
||||
"old": "c0c6322a",
|
||||
"new": "817b5baa",
|
||||
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
|
||||
},
|
||||
{
|
||||
"offset": 779118,
|
||||
"old": "ed292ee4",
|
||||
"new": "b1adc0d0",
|
||||
"offset": 779127,
|
||||
"old": "c0c6322a",
|
||||
"new": "817b5baa",
|
||||
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
|
||||
}
|
||||
]
|
||||
|
||||
+16
-3
@@ -21,8 +21,12 @@ export const GLANCE_SURFACE_ID = "glance";
|
||||
/** Above the shell (1) and every window (0); below the lock screen (1000). */
|
||||
export const GLANCE_SURFACE_Z_ORDER = 900;
|
||||
|
||||
/** Surface operations needed by the board, shared by Android and iOS. */
|
||||
export type GlanceDisplay = Pick<DisplayTarget,
|
||||
"configureSurface" | "setSurfaceVisible" | "setSurfaceDepth" | "setScreenBlanked" | "submitSurfaceFrame">;
|
||||
|
||||
export type GlanceHostOptions = {
|
||||
getDisplay: () => DisplayTarget | null;
|
||||
getDisplay: () => GlanceDisplay | null;
|
||||
getProvider: () => GlanceboardProvider | null;
|
||||
/** Whether a board may show right now (connected or preview, not locked). */
|
||||
canShow: () => boolean;
|
||||
@@ -47,7 +51,9 @@ export class GlanceHost {
|
||||
/** Whether the surface is currently visible on the compositor. */
|
||||
private shown = false;
|
||||
private hideTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private configuredFor: DisplayTarget | null = null;
|
||||
private configuredFor: GlanceDisplay | null = null;
|
||||
/** Last depth given to the surface; null forces the next render to set it. */
|
||||
private configuredDepth: number | null = null;
|
||||
/** Serializes show/hide against each other and against in-flight renders. */
|
||||
private queue: Promise<void> = Promise.resolve();
|
||||
private rendering = false;
|
||||
@@ -144,7 +150,7 @@ export class GlanceHost {
|
||||
}, Math.max(0, hideAtMs - Date.now()));
|
||||
}
|
||||
|
||||
private async configureSurface(display: DisplayTarget): Promise<void> {
|
||||
private async configureSurface(display: GlanceDisplay): Promise<void> {
|
||||
await display.configureSurface(GLANCE_SURFACE_ID, {
|
||||
x: 0,
|
||||
y: 0,
|
||||
@@ -154,6 +160,7 @@ export class GlanceHost {
|
||||
transparency: "opaque",
|
||||
});
|
||||
await display.setSurfaceVisible(GLANCE_SURFACE_ID, false);
|
||||
this.configuredDepth = null;
|
||||
this.configuredFor = display;
|
||||
}
|
||||
|
||||
@@ -252,6 +259,12 @@ export class GlanceHost {
|
||||
const { image, draws } = frameTimings.span(frameId, "flatten", () => flattenPlanesWithDraws(planes));
|
||||
const buffer = frameTimings.span(frameId, "to8bpp", () => image.to8bppBuffer());
|
||||
const preparedDraws = frameTimings.span(frameId, "prepareFrameDraws", () => prepareFrameDraws(draws));
|
||||
// The glasses copy the screen shifted per lens while the board covers it.
|
||||
const depth = this.options.getProvider()?.depth() ?? 0;
|
||||
if (depth !== this.configuredDepth) {
|
||||
await display.setSurfaceDepth(GLANCE_SURFACE_ID, depth);
|
||||
this.configuredDepth = depth;
|
||||
}
|
||||
await frameTimings.spanAsync(frameId, "submit", () =>
|
||||
display.submitSurfaceFrame(
|
||||
GLANCE_SURFACE_ID,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { classifyAdvertisement, hasEvenManufacturerSignature, type EvenAdvertisement } from './even-advertisement'
|
||||
import { hexToBytes } from '../util/hex-util'
|
||||
|
||||
export type IosAdvertisement = { identifier: string; name: string; manufacturerData: string; rssi: number; connectable: boolean }
|
||||
export type IosDevice = EvenAdvertisement & { identifier: string }
|
||||
|
||||
/** Only a full vendor-advertised MAC may bind a manually entered address. */
|
||||
export function identifyIosPeripheral(raw: IosAdvertisement): IosDevice | null {
|
||||
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(raw.identifier)) return null
|
||||
if (!hasEvenManufacturerSignature(hexToBytes(raw.manufacturerData))) return null
|
||||
const candidate = classifyAdvertisement({ ...raw, address: '', source: 'scan', bonded: false,
|
||||
txPower: null, seenAtMs: Date.now() })
|
||||
if (!candidate?.embeddedMac) return null
|
||||
return { ...candidate, address: candidate.embeddedMac, embeddedMacMismatch: false, identifier: raw.identifier.toUpperCase() }
|
||||
}
|
||||
|
||||
export function deviceAddressError(addresses: { left: string; right: string; ring: string }): string | null {
|
||||
for (const role of ['right', 'left', 'ring'] as const) {
|
||||
const address = addresses[role]
|
||||
if (role === 'ring' && !address) continue
|
||||
if (!/^[0-9A-F]{2}(?::[0-9A-F]{2}){5}$/.test(address)) return `${role === 'ring' ? 'Ring' : role === 'left' ? 'Left arm' : 'Right arm'} MAC address is invalid.`
|
||||
}
|
||||
const values = Object.values(addresses).filter(Boolean)
|
||||
return new Set(values).size === values.length ? null : 'Each device must have a different MAC address.'
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
import { startRemoteInput } from "../remote/service"
|
||||
import type { KeyboardInputSession } from '../ui/shell/keyboard-input'
|
||||
import { acceptInput, resetRingInputFilter } from "../ui/input-monitor";
|
||||
import { bindIosNotifications, iosNotificationsChanged, onIosNotificationPopup } from '../native/notification-icons.ios'
|
||||
import { shouldShowNotificationOnGlasses } from '../native/notification-sources'
|
||||
import { readActiveNotifications } from '../native/notification-icons.ios'
|
||||
import { launcherEntries } from '../apps/launcher'
|
||||
import { getInstalledEvenHubAppById, installedEvenHubPackageId, uninstallEvenHubPackage } from '../apps/evenhub/installed-apps'
|
||||
import { isInstalledPackagePresent } from '../apps/evenhub/updates'
|
||||
import { openEvenHubStoreForPackage } from '../apps/evenhub'
|
||||
import { launchInstalledPackage, closeRunningPackage } from '../apps/evenhub/manager'
|
||||
import { registerSystemTools } from '../assistant/system-tools'
|
||||
import { registerWindowTools } from '../assistant/window-tools'
|
||||
import { registerNavigateTools } from '../assistant/navigate-tools'
|
||||
import { registerRoamTools } from '../assistant/roam-tools'
|
||||
import { IosNavigationSensors } from '../native/ios-navigation-sensors'
|
||||
import { Utils } from '@nativescript/core'
|
||||
import { bindCompassSession, receiveCompassEvent } from '../native/compass.ios'
|
||||
import { Dialogs, File, knownFolders, path, type ImageSource } from '@nativescript/core'
|
||||
import { iosVoiceInput } from '../native/ios-voice-input'
|
||||
import { nightscoutBridge } from '../native/nightscout-bridge'
|
||||
import { FaceclawCommunicatorBridge, resolveIosPeripherals, type CommunicatorState, type RawInputEvent } from '../native/faceclaw-communicator.ios'
|
||||
import { PreviewDisplayTarget, type DisplayTarget } from '../native/preview-display.ios'
|
||||
import { AncsClient, ANCS_FIRMWARE_VERSION } from './ancs-client'
|
||||
import { GlanceHost, type GlanceDisplay } from './glance-host'
|
||||
import { createLockScreenImage, LOCK_SCREEN_SURFACE_ID } from './lock-screen'
|
||||
import { OsEventTypeList } from './events'
|
||||
import { loadDeviceAddresses } from './device-addresses'
|
||||
import { deviceAddressError } from './ios-peripheral-identity'
|
||||
import { createLauncherWindow, LAUNCHER_SURFACE_ID } from '../apps/launcher/launcher-app'
|
||||
import { ALL_APPS } from '../apps/all-apps'
|
||||
import type { AppContext, AppDefinition, AppLaunchParams } from '../apps/app-definition'
|
||||
import { WorkerAppHost } from '../ui/shell/worker-window'
|
||||
import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from '../ui/shell/in-process-window'
|
||||
import { getStringSettingById, nightscoutSiteUrlSetting, nightscoutApiTokenSetting } from '../ui/dashboard-settings'
|
||||
import { readPhoneBatteryState } from '../native/phone-battery'
|
||||
import { iosAppUnavailableReason } from '../apps/ios-availability'
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from '../graphics/plane'
|
||||
import { prepareFrameDraws } from '../graphics/glyph-wire'
|
||||
import { G2_LENS_WIDTH, G2_LENS_HEIGHT } from '../graphics/image'
|
||||
import { makeInputEvent, type InputEvent, type InputEventPayload } from '../ui/gestures'
|
||||
import { noopLayerActions, type LayerActions } from '../ui/layers'
|
||||
import { TextViewerLayer } from '../apps/files/text-viewer'
|
||||
import { shell, rawInputEventToInputEvent, type ShellWindow } from '../ui/shell/shell'
|
||||
import { appViewportRect, SIDEBAR_WIDTH, sidebarStripVisible } from '../ui/shell/geometry'
|
||||
import { DISPLAY_MODE_VALUES, displayModeLabel, displayModeSetting, onAnySettingChanged,
|
||||
previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences } from '../ui/dashboard-settings'
|
||||
import type { PhoneGesture } from '../phone-ui/phone-gestures'
|
||||
import { isWelcomeSoundPending, setWelcomeSoundPending } from '../phone-ui/onboarding-state'
|
||||
import { findSoundEffect, playSoundEffect } from '../ui/sound-effects'
|
||||
|
||||
const SHELL_SURFACE_ID = 'shell'
|
||||
const SHELL_SURFACE_Z_ORDER = 1
|
||||
const LOCK_SURFACE_Z_ORDER = 1000
|
||||
/** The shell render loop waits this long for the glasses to take a frame before moving on. */
|
||||
const FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS = 2000
|
||||
|
||||
export type SessionPhase = 'disconnected' | 'connecting' | 'connected' | 'retrying' | 'disconnecting' | 'error'
|
||||
export type SessionState = { phase: SessionPhase; status: string; battery: number | null; charging: boolean | null;
|
||||
ring: boolean; frames: number; capabilities: string; leftVersion: string; rightVersion: string }
|
||||
|
||||
function ancsCapable(capabilities: string): boolean {
|
||||
return /^Faceclaw\/(\d+)/.test(capabilities) && Number(capabilities.split('/')[1]) >= ANCS_FIRMWARE_VERSION
|
||||
}
|
||||
|
||||
/**
|
||||
* iOS host for the shared app registry, shell and BLE session. The session,
|
||||
* compositor and transport live in shared Kotlin (FaceclawCommunicatorBridge
|
||||
* over FaceclawKitIosGlassesSession); with no glasses connected the same
|
||||
* compositor runs headless (PreviewDisplayTarget) so the phone mirror works.
|
||||
*/
|
||||
export class IosPreviewController {
|
||||
private previewTarget: PreviewDisplayTarget | null = null
|
||||
private communicator: FaceclawCommunicatorBridge | null = null
|
||||
private readonly startedCommunicators = new WeakSet<FaceclawCommunicatorBridge>()
|
||||
state: SessionState = { phase: 'disconnected', status: 'Preview only', battery: null, charging: null, ring: false,
|
||||
frames: 0, capabilities: '', leftVersion: '', rightVersion: '' }
|
||||
private notifications: AncsClient | null = null
|
||||
private readonly sessionOffs: (() => void)[] = []
|
||||
private stopping: Promise<void> | null = null
|
||||
/** Resolves once the current display target has every surface configured. */
|
||||
private displayReady: Promise<void> = Promise.resolve()
|
||||
private connecting = false
|
||||
private sessionCreated = false
|
||||
private wearDetectionRequested = false
|
||||
private readonly glanceDisplay: GlanceDisplay = {
|
||||
configureSurface: async (id, options) => { await this.display?.configureSurface(id, options) },
|
||||
setSurfaceVisible: async (id, visible) => { await this.display?.setSurfaceVisible(id, visible); this.schedulePreviewUpdate() },
|
||||
setSurfaceDepth: async (id, depth) => { await this.display?.setSurfaceDepth(id, depth) },
|
||||
setScreenBlanked: async blanked => { await this.display?.setScreenBlanked(blanked); this.schedulePreviewUpdate() },
|
||||
submitSurfaceFrame: async (id, pixels, rect, fingerprint, paintMs, frameId, draws) => {
|
||||
await this.display?.submitSurfaceFrame(id, pixels, rect, fingerprint, paintMs, frameId, draws); this.schedulePreviewUpdate()
|
||||
},
|
||||
}
|
||||
private readonly glance = new GlanceHost({
|
||||
getDisplay: () => this.display ? this.glanceDisplay : null,
|
||||
getProvider: () => ALL_APPS.find(app => app.glanceboard)?.glanceboard ?? null,
|
||||
canShow: () => this.runtimeNeeded && !this.glassesLocked,
|
||||
// iOS retains the EvenHub session while the shell sleeps. The board's
|
||||
// opaque first frame is ready before we unblank the compositor.
|
||||
ensureSessionActive: async () => {
|
||||
await this.display?.setScreenBlanked(false); this.schedulePreviewUpdate(); return true
|
||||
},
|
||||
onHiddenWhileAsleep: () => {
|
||||
if (!shell.isScreenOn()) void this.display?.setScreenBlanked(true).then(() => this.schedulePreviewUpdate())
|
||||
else this.schedulePreviewUpdate()
|
||||
},
|
||||
onVisibilityChanged: () => this.schedulePreviewUpdate(),
|
||||
appendLog: message => this.logBluetooth(message),
|
||||
})
|
||||
private previewTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private clockTimer: ReturnType<typeof setInterval> | null = null
|
||||
private offSettings: (() => void) | null = null
|
||||
private lastBrightness: string | null = null
|
||||
private active = false
|
||||
private runtimeRunning = false
|
||||
private clockMinute = -1
|
||||
private shellRenderInProgress = false
|
||||
private shellRenderQueued = false
|
||||
private nextFrameId = 1
|
||||
private nextWorkerFrame = 0
|
||||
private inputQueue: Promise<void> = Promise.resolve()
|
||||
private lastLayout = ''
|
||||
private readonly appHosts = new Map<string, WorkerAppHost>()
|
||||
private readonly inProcessApps = new Map<string, InProcessWindow>()
|
||||
private readonly batteryObservers: any[] = []
|
||||
private readonly lockObservers: any[] = []
|
||||
private phoneLocked = false
|
||||
private glassesWorn: boolean | null = null
|
||||
private glassesLocked = false
|
||||
private lockEnabled = lockScreenEnabledSetting.get()
|
||||
private acknowledgedFrames = 0
|
||||
private logLines: string[] = []
|
||||
private logTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly actions: LayerActions = {
|
||||
...noopLayerActions,
|
||||
playBuzzerSequence: payload => this.communicator?.playBuzzerSequence(payload),
|
||||
requestRender: () => this.requestShellRender(),
|
||||
disconnect: () => this.disconnect(),
|
||||
startVoiceCapture: endpointing => this.startVoiceCapture(endpointing),
|
||||
stopVoiceCapture: () => iosVoiceInput.stopPushToTalk(),
|
||||
startContinuousVoiceCapture: () => this.onError("Voice capture is not available on iOS yet."),
|
||||
startTextSettingEdit: async setting => { await this.editSetting(setting) },
|
||||
startTextSettingsEdit: async (settings, title, finished, toggle, cancelled) => {
|
||||
for (const setting of settings) if (!await this.editSetting(setting)) { cancelled?.(); return }
|
||||
if (toggle) {
|
||||
const choice = await Dialogs.action({ title, cancelButtonText: 'Cancel', actions: [toggle.label, 'This session only'] })
|
||||
if (choice === 'Cancel') { cancelled?.(); return }
|
||||
toggle.setting.set(choice === toggle.label)
|
||||
}
|
||||
finished?.()
|
||||
},
|
||||
}
|
||||
|
||||
constructor(private readonly onFrame: (image: ImageSource, focus: string) => void,
|
||||
private readonly onError: (message: string) => void,
|
||||
private readonly onConnectionState: (state: SessionState) => void = () => {},
|
||||
private readonly onKeyboardInputChanged: (session: KeyboardInputSession | null) => void = () => {}) {
|
||||
this.ensurePreviewDisplay()
|
||||
shell.configure({
|
||||
actions: this.actions,
|
||||
voiceInputEnabled: true,
|
||||
onKeyboardInputChanged: session => this.onKeyboardInputChanged(session ? {
|
||||
targets: session.targets,
|
||||
setText: text => { if (this.active && !this.glassesLocked) session.setText(text) },
|
||||
send: () => { if (this.active && !this.glassesLocked) session.send() },
|
||||
sendTo: id => { if (this.active && !this.glassesLocked) session.sendTo(id) },
|
||||
discard: () => session.discard(),
|
||||
} : null),
|
||||
prepareVoiceCapture: () => this.prepareVoiceCapture(),
|
||||
getScreenTimeoutMs: () => null,
|
||||
requestShellRender: () => this.requestShellRender(),
|
||||
onWindowsChanged: () => this.requestShellRender(),
|
||||
onScreenStateChanged: on => {
|
||||
if (on) this.glance.dismiss()
|
||||
void this.display?.setScreenBlanked(!on).catch(error => this.fail(error))
|
||||
this.requestShellRender()
|
||||
},
|
||||
})
|
||||
const launcher = createLauncherWindow({
|
||||
actions: this.actions,
|
||||
apps: () => launcherEntries(ALL_APPS),
|
||||
launchApp: id => this.launchApp(id),
|
||||
uninstallApp: id => this.uninstallApp(id),
|
||||
submitFrame: planes => this.submit(LAUNCHER_SURFACE_ID, planes),
|
||||
setSurfaceVisible: visible => this.setWindowSurfaceVisible(LAUNCHER_SURFACE_ID, visible),
|
||||
})
|
||||
void this.configureWindow(launcher)
|
||||
shell.registerWindow(launcher)
|
||||
shell.wake('window')
|
||||
shell.focusWindow(launcher.windowId)
|
||||
onIosNotificationPopup(key => {
|
||||
const notification = readActiveNotifications(128).find(n => n.key === key)
|
||||
if (this.glassesLocked || !notification || !shouldShowNotificationOnGlasses(notification.packageName)) return
|
||||
const woke = !shell.isScreenOn() && shell.wake('sidebar')
|
||||
shell.openNotificationModal(key, woke)
|
||||
this.requestShellRender()
|
||||
})
|
||||
startRemoteInput({
|
||||
ready: () => this.runtimeRunning,
|
||||
locked: () => this.glassesLocked,
|
||||
input: (gesture, source) => {
|
||||
// Share the controller queue with physical input. A discrete hold includes its release.
|
||||
const task = this.inputQueue.then(async () => {
|
||||
await this.receiveInput(makeInputEvent({ type: gesture, source } as InputEventPayload))
|
||||
if (gesture === 'long-press') await this.receiveInput(makeInputEvent({ type: 'long-press-release', source }))
|
||||
})
|
||||
this.inputQueue = task.catch(error => this.fail(error))
|
||||
return task
|
||||
},
|
||||
acceptsText: () => !!shell.foregroundWindow()?.receiveTextInput,
|
||||
text: (text, submit) => { if (!shell.isScreenOn()) shell.wake('window'); shell.sendTextToForegroundWindow(text, { submit }); this.requestShellRender() },
|
||||
assistantAvailable: () => shell.isAssistantAvailable(),
|
||||
assistant: text => shell.sendToAssistant(text),
|
||||
})
|
||||
registerSystemTools()
|
||||
registerWindowTools({ apps: ALL_APPS.filter(app => !iosAppUnavailableReason(app.appId)),
|
||||
launchApp: id => this.launchApp(id), requestShellRender: () => this.requestShellRender() })
|
||||
registerNavigateTools(id => this.launchApp(id))
|
||||
registerRoamTools(id => this.launchApp(id))
|
||||
for (const app of ALL_APPS) if (app.appId !== 'launcher' && !iosAppUnavailableReason(app.appId)) app.boot?.(this.buildAppContext(app))
|
||||
}
|
||||
|
||||
/** The compositor frames go to: the live session, else the headless preview. */
|
||||
private get display(): DisplayTarget | null { return this.communicator ?? this.previewTarget }
|
||||
|
||||
private ensurePreviewDisplay(): void {
|
||||
if (this.communicator || this.previewTarget) return
|
||||
const target = new PreviewDisplayTarget()
|
||||
this.previewTarget = target
|
||||
target.activate(() => this.schedulePreviewUpdate())
|
||||
this.displayReady = this.registerSurfaces(target).catch(error => this.fail(error))
|
||||
}
|
||||
|
||||
private teardownPreviewDisplay(): void {
|
||||
const target = this.previewTarget
|
||||
if (!target) return
|
||||
this.previewTarget = null
|
||||
this.glance.reset()
|
||||
target.release()
|
||||
}
|
||||
|
||||
/** (Re)create every compositor surface on a fresh display target. */
|
||||
private async registerSurfaces(target: DisplayTarget): Promise<void> {
|
||||
await target.configureCompositorScreen(G2_LENS_WIDTH, G2_LENS_HEIGHT)
|
||||
await target.configureSurface(SHELL_SURFACE_ID, { x: 0, y: 0, width: G2_LENS_WIDTH, height: G2_LENS_HEIGHT,
|
||||
zOrder: SHELL_SURFACE_Z_ORDER, transparency: 'color-key' })
|
||||
await target.setUnderlayDim(SHELL_SURFACE_Z_ORDER, 1)
|
||||
await target.configureSurface(LOCK_SCREEN_SURFACE_ID, {
|
||||
x: 0, y: 0, width: G2_LENS_WIDTH, height: G2_LENS_HEIGHT, zOrder: LOCK_SURFACE_Z_ORDER, transparency: 'opaque',
|
||||
})
|
||||
if (this.glassesLocked) await this.submitLockImage(target)
|
||||
await target.setSurfaceVisible(LOCK_SCREEN_SURFACE_ID, this.glassesLocked)
|
||||
await target.setScreenBlanked(!shell.isScreenOn())
|
||||
this.lastLayout = ''
|
||||
for (const window of shell.getWindows()) await this.configureWindow(window, target)
|
||||
}
|
||||
|
||||
private async submitLockImage(target: DisplayTarget): Promise<void> {
|
||||
const image = createLockScreenImage()
|
||||
await target.submitSurfaceFrame(LOCK_SCREEN_SURFACE_ID, image.to8bppBuffer(),
|
||||
{ x: 0, y: 0, width: image.width, height: image.height }, 'lock-screen', 0, 0)
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
if (this.active) return
|
||||
this.active = true
|
||||
this.syncRuntime()
|
||||
this.handlePhoneLockState(!UIApplication.sharedApplication.protectedDataAvailable)
|
||||
this.logBluetooth('Phone foreground')
|
||||
if (this.communicator) this.onConnectionState({ ...this.state })
|
||||
this.relayout()
|
||||
shell.foregroundWindow()?.requestRender()
|
||||
this.requestShellRender()
|
||||
}
|
||||
pause(): void {
|
||||
if (!this.active) return
|
||||
this.active = false
|
||||
iosVoiceInput.stopPhoneCapture()
|
||||
// The phone preview is hidden; the glasses still own their screen and input.
|
||||
this.syncRuntime()
|
||||
this.logBluetooth(`Phone background; glasses ${this.state.phase}`)
|
||||
this.flushBluetoothLog()
|
||||
}
|
||||
private get runtimeNeeded(): boolean {
|
||||
return this.active || ['connected', 'connecting', 'retrying', 'disconnecting'].includes(this.state.phase)
|
||||
}
|
||||
private syncRuntime(): void {
|
||||
const running = this.runtimeNeeded
|
||||
if (running === this.runtimeRunning) return
|
||||
this.runtimeRunning = running
|
||||
for (const window of shell.getWindows()) window.setScreenOn?.(running && shell.isScreenOn())
|
||||
if (!running) {
|
||||
void nightscoutBridge.stop().catch(error => this.fail(error))
|
||||
this.glance.dismiss()
|
||||
void this.display?.setScreenBlanked(!shell.isScreenOn()).catch(error => this.fail(error))
|
||||
this.offSettings?.(); this.offSettings = null
|
||||
for (const observer of this.batteryObservers.splice(0)) NSNotificationCenter.defaultCenter.removeObserver(observer)
|
||||
for (const observer of this.lockObservers.splice(0)) NSNotificationCenter.defaultCenter.removeObserver(observer)
|
||||
UIDevice.currentDevice.batteryMonitoringEnabled = false
|
||||
if (this.clockTimer !== null) clearInterval(this.clockTimer)
|
||||
if (this.previewTimer !== null) clearTimeout(this.previewTimer)
|
||||
this.clockTimer = this.previewTimer = null
|
||||
return
|
||||
}
|
||||
UIDevice.currentDevice.batteryMonitoringEnabled = true
|
||||
// Keep these observers alive while BLE owns the runtime, including background.
|
||||
for (const [name, locked] of [
|
||||
[UIApplicationProtectedDataWillBecomeUnavailable, true],
|
||||
[UIApplicationProtectedDataDidBecomeAvailable, false],
|
||||
] as const) {
|
||||
this.lockObservers.push(NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
|
||||
name, null, NSOperationQueue.mainQueue, () => this.handlePhoneLockState(locked)))
|
||||
}
|
||||
this.handlePhoneLockState(!UIApplication.sharedApplication.protectedDataAvailable)
|
||||
this.syncLockSetting()
|
||||
void nightscoutBridge.start().catch(error => this.fail(error))
|
||||
for (const name of [UIDeviceBatteryLevelDidChangeNotification, UIDeviceBatteryStateDidChangeNotification]) {
|
||||
this.batteryObservers.push(NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(name, null, NSOperationQueue.mainQueue, () => this.requestShellRender()))
|
||||
}
|
||||
const phone = readPhoneBatteryState()
|
||||
this.logBluetooth(`Phone battery ${phone.battery ?? "unknown"}% charging=${phone.charging}`)
|
||||
this.offSettings = onAnySettingChanged(() => {
|
||||
this.syncLockSetting()
|
||||
this.pushBrightness()
|
||||
this.relayout()
|
||||
shell.foregroundWindow()?.requestRender()
|
||||
this.requestShellRender()
|
||||
})
|
||||
this.clockTimer = setInterval(() => this.refreshClock(), 60_000)
|
||||
}
|
||||
private pushBrightness(): void {
|
||||
const communicator = this.communicator
|
||||
if (!communicator || this.state.phase !== 'connected') { this.lastBrightness = null; return }
|
||||
const preferences = getBrightnessPreferences()
|
||||
const value = JSON.stringify(preferences)
|
||||
if (value === this.lastBrightness) return
|
||||
this.lastBrightness = value
|
||||
void communicator.configureBrightness(preferences).catch(error => {
|
||||
this.lastBrightness = null
|
||||
this.logBluetooth(`Brightness: ${String(error)}`)
|
||||
})
|
||||
}
|
||||
private syncLockSetting(): void {
|
||||
const enabled = lockScreenEnabledSetting.get()
|
||||
if (enabled === this.lockEnabled) return
|
||||
this.lockEnabled = enabled
|
||||
if (!enabled) this.setGlassesLocked(false)
|
||||
else {
|
||||
if (this.phoneLocked && this.glassesWorn === false) this.setGlassesLocked(true)
|
||||
if (this.communicator && this.state.phase === 'connected')
|
||||
void this.communicator.enableWearDetectionAndRequestState().catch(error => this.fail(error))
|
||||
}
|
||||
}
|
||||
private handlePhoneLockState(locked: boolean): void {
|
||||
this.phoneLocked = locked
|
||||
this.communicator?.onPhoneLockSignal()
|
||||
if (!locked) this.setGlassesLocked(false)
|
||||
else if (this.lockEnabled && this.glassesWorn === false) this.setGlassesLocked(true)
|
||||
}
|
||||
private handleWearState(wearing: boolean): void {
|
||||
// Sample false to catch a notification missed during suspension. Do not
|
||||
// sample true here: WillBecomeUnavailable precedes the property transition.
|
||||
if (!UIApplication.sharedApplication.protectedDataAvailable) this.handlePhoneLockState(true)
|
||||
this.glassesWorn = wearing
|
||||
this.logBluetooth(`Glasses wear state: ${wearing ? 'ON_HEAD' : 'OFF_HEAD'}`)
|
||||
if (!wearing && this.phoneLocked && this.lockEnabled) this.setGlassesLocked(true)
|
||||
}
|
||||
private setGlassesLocked(locked: boolean): void {
|
||||
if (locked === this.glassesLocked) return
|
||||
this.glassesLocked = locked
|
||||
if (locked) {
|
||||
this.glance.dismiss()
|
||||
iosVoiceInput.handleSessionEnded('Glasses locked. Unlock your phone to start voice input again.')
|
||||
}
|
||||
void (async () => {
|
||||
await this.displayReady
|
||||
const display = this.display
|
||||
if (!display) return
|
||||
{
|
||||
if (locked) await this.submitLockImage(display)
|
||||
await display.setSurfaceVisible(LOCK_SCREEN_SURFACE_ID, locked)
|
||||
this.schedulePreviewUpdate()
|
||||
}
|
||||
})().catch(error => this.fail(error))
|
||||
this.logBluetooth(`Glasses ${locked ? 'locked' : 'unlocked'}`)
|
||||
this.requestShellRender()
|
||||
}
|
||||
private refreshClock(): void {
|
||||
const minute = Math.floor(Date.now() / 60_000)
|
||||
if (minute !== this.clockMinute) { this.clockMinute = minute; this.requestShellRender() }
|
||||
}
|
||||
private async configureWindow(window: ShellWindow, target: DisplayTarget | null = this.display): Promise<void> {
|
||||
if (!target) return
|
||||
await target.configureSurface(window.surfaceId, {
|
||||
...appViewportRect(window.heightMode, window.appId), zOrder: 0, transparency: 'opaque',
|
||||
})
|
||||
await target.setSurfaceVisible(window.surfaceId, shell.foregroundWindow()?.windowId === window.windowId)
|
||||
}
|
||||
private relayout(): void {
|
||||
const layout = shell.getWindows().map(window => JSON.stringify(appViewportRect(window.heightMode, window.appId))).join(";")
|
||||
if (layout === this.lastLayout) return
|
||||
this.lastLayout = layout
|
||||
for (const window of shell.getWindows()) {
|
||||
void this.configureWindow(window).catch(error => this.fail(error))
|
||||
window.relayout?.()
|
||||
}
|
||||
}
|
||||
/** Submit a painted frame for an in-process window (e.g. the launcher). */
|
||||
private async submit(id: string, planes: Plane[]): Promise<void> {
|
||||
await this.displayReady
|
||||
const display = this.display
|
||||
if (!display) return
|
||||
const fingerprint = planesFingerprint(planes)
|
||||
const { image, draws } = flattenPlanesWithDraws(planes)
|
||||
await display.submitSurfaceFrame(id, image.pixels, { x: 0, y: 0, width: image.width, height: image.height },
|
||||
fingerprint, -1, 0, prepareFrameDraws(draws))
|
||||
this.schedulePreviewUpdate()
|
||||
}
|
||||
/** Worker windows ship baked pixels; every submit is new content to the compositor. */
|
||||
private async submitWorkerPixels(id: string, pixels: Uint8Array, width: number, height: number, draws: ArrayBuffer | null): Promise<void> {
|
||||
await this.displayReady
|
||||
const display = this.display
|
||||
if (!display) return
|
||||
await display.submitSurfaceFrame(id, pixels, { x: 0, y: 0, width, height }, `${id}#${++this.nextWorkerFrame}`, -1, 0, draws)
|
||||
this.schedulePreviewUpdate()
|
||||
}
|
||||
private setWindowSurfaceVisible(id: string, visible: boolean): void {
|
||||
void this.display?.setSurfaceVisible(id, visible).then(() => this.schedulePreviewUpdate()).catch(error => this.fail(error))
|
||||
}
|
||||
private removeWindowSurface(id: string): void {
|
||||
void this.display?.removeSurface(id).then(() => this.schedulePreviewUpdate()).catch(error => this.fail(error))
|
||||
}
|
||||
/** Re-render and resubmit the shell surface; one render in flight, at most one queued. */
|
||||
private requestShellRender(): void {
|
||||
if (this.shellRenderInProgress) { this.shellRenderQueued = true; return }
|
||||
this.shellRenderInProgress = true
|
||||
void (async () => {
|
||||
try {
|
||||
do {
|
||||
this.shellRenderQueued = false
|
||||
await this.renderShell()
|
||||
} while (this.shellRenderQueued)
|
||||
} catch (error) { this.fail(error) }
|
||||
finally { this.shellRenderInProgress = false }
|
||||
})()
|
||||
}
|
||||
private async renderShell(): Promise<void> {
|
||||
await this.displayReady
|
||||
const display = this.display
|
||||
if (!display) return
|
||||
const startedAt = Date.now()
|
||||
const bytes = shell.paintScene()
|
||||
const frameId = this.allocateFrameId()
|
||||
await display.submitShellScene(bytes, Date.now() - startedAt, frameId)
|
||||
// Backpressure: the next shell render waits for this one to reach the
|
||||
// glasses (the preview target resolves immediately; nothing transmits).
|
||||
await display.waitForFrameFinished(frameId, FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS)
|
||||
this.schedulePreviewUpdate()
|
||||
}
|
||||
private allocateFrameId(): number {
|
||||
const id = this.nextFrameId
|
||||
this.nextFrameId = this.nextFrameId >= 0x7fffffff ? 1 : this.nextFrameId + 1
|
||||
return id
|
||||
}
|
||||
/** Refresh the phone mirror from the composited screen, coalesced at 30 fps. */
|
||||
private schedulePreviewUpdate(): void {
|
||||
if (!this.active || this.previewTimer !== null) return
|
||||
this.previewTimer = setTimeout(() => {
|
||||
this.previewTimer = null
|
||||
if (!this.active) return
|
||||
try {
|
||||
const image = this.display?.getCompositePreview(previewColorSetting.get() === 'green')
|
||||
if (!image) return
|
||||
this.onFrame(image, this.glassesLocked ? 'Glasses locked' : this.glance.isVisible() ? 'Glanceboard'
|
||||
: `${shell.foregroundWindow()?.title ?? 'Apps'} · ${shell.getFocus() === 'sidebar' ? 'App switcher' : 'App'}`)
|
||||
} catch (error) { this.fail(error) }
|
||||
}, 33)
|
||||
}
|
||||
private fail(error: unknown): void {
|
||||
const message = error instanceof Error ? error.stack ?? error.message : String(error)
|
||||
console.error(`[ios-preview] ${message}`)
|
||||
this.logBluetooth(`App error: ${message}`)
|
||||
if (this.active) this.onError(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
gesture(gesture: PhoneGesture, origin: 'watch' | 'ring' | 'mirror', nx = 0, ny = 0): void {
|
||||
this.inputQueue = this.inputQueue.then(async () => {
|
||||
if (!this.active) return
|
||||
if (gesture === 'tap' && origin === 'mirror' && shell.isScreenOn() && !this.glassesLocked) {
|
||||
await this.mirrorTap(nx, ny)
|
||||
} else {
|
||||
let type: string = ({ tap: 'click', 'double-tap': 'double-click' } as Record<string, string>)[gesture] ?? gesture
|
||||
if (origin === 'ring' && type.startsWith('swipe-')) {
|
||||
if (type === 'swipe-left' || type === 'swipe-right') return
|
||||
type = type === 'swipe-up' ? 'scroll-up' : 'scroll-down'
|
||||
}
|
||||
const event = makeInputEvent({ type, source: origin === 'ring' ? 'ring' : 'watch' } as InputEventPayload)
|
||||
await this.receiveInput(event)
|
||||
}
|
||||
console.log(`[ios-preview] ${origin} ${gesture}: ${shell.describeInputTarget()}`)
|
||||
}).catch(error => this.fail(error))
|
||||
}
|
||||
private async receiveInput(event: InputEvent, headTilt = false): Promise<void> {
|
||||
if (!acceptInput(event)) return
|
||||
if (this.glassesLocked) {
|
||||
// Preserve the locked display's sleep/wake controls without dispatching
|
||||
// gestures to apps, shell menus, voice input or the Glanceboard.
|
||||
if (event.type === 'double-click' && (event.source === 'ring' || event.source === 'watch')) {
|
||||
if (shell.isScreenOn()) shell.sleep()
|
||||
else shell.wake('sidebar')
|
||||
} else if (event.type === 'display-wake' && !shell.isScreenOn()) shell.wake('sidebar')
|
||||
this.requestShellRender()
|
||||
return
|
||||
}
|
||||
if (!shell.isScreenOn()) {
|
||||
const glanceEvent = this.glance.eventForGesture(headTilt ? 'head-tilt' : event.type)
|
||||
if (glanceEvent?.type === 'dismiss') this.glance.dismiss()
|
||||
else if (glanceEvent) {
|
||||
await this.glance.handleEvent(glanceEvent, 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
await shell.receiveInput(event)
|
||||
this.requestShellRender()
|
||||
}
|
||||
private async mirrorTap(nx: number, ny: number): Promise<void> {
|
||||
const x = Math.max(0, Math.min(639, Math.floor(nx * 640)))
|
||||
const y = Math.max(0, Math.min(479, Math.floor(ny * 480)))
|
||||
const window = shell.foregroundWindow()
|
||||
if (!shell.hasOverlay() && sidebarStripVisible(shell.getFocus(), window?.appId) && x < SIDEBAR_WIDTH) {
|
||||
const target = shell.windowAtSidebarPoint(x, y)
|
||||
if (target) { shell.focusWindow(target.windowId); target.requestRender(); this.requestShellRender() }
|
||||
return
|
||||
}
|
||||
if (window && !shell.hasOverlay()) {
|
||||
const rect = appViewportRect(window.heightMode, window.appId)
|
||||
if (x < rect.x || x >= rect.x + rect.width || y < rect.y || y >= rect.y + rect.height) return
|
||||
shell.focusWindow(window.windowId)
|
||||
if (await window.hitTest?.(x - rect.x, y - rect.y)) { this.requestShellRender(); return }
|
||||
}
|
||||
await shell.receiveInput(makeInputEvent({ type: 'click', source: 'watch' }))
|
||||
this.requestShellRender()
|
||||
}
|
||||
async launchApp(id: string, params?: AppLaunchParams): Promise<void> {
|
||||
const app = ALL_APPS.find(app => app.appId === id)
|
||||
if (!app) {
|
||||
const installed = getInstalledEvenHubAppById(id)
|
||||
const host = ALL_APPS.find(app => app.appId === 'evenhub')
|
||||
if (installed && host) {
|
||||
try {
|
||||
if (isInstalledPackagePresent(installed.packageId))
|
||||
await launchInstalledPackage(this.buildAppContext({ ...host, appId: id }), installed)
|
||||
else await openEvenHubStoreForPackage(this.buildAppContext(host), installed)
|
||||
}
|
||||
catch (error) { this.fail(error) }
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
const reason = iosAppUnavailableReason(id)
|
||||
if (reason) {
|
||||
await this.launchInProcessApp(id, `window:${id}`, options => createInProcessWindow({
|
||||
...options, appId: id, windowId: id, title: app.title, icon: app.icon,
|
||||
iconLetter: app.title[0], closeable: true,
|
||||
baseLayer: new YieldAtRootLayer(new TextViewerLayer(reason, app.title)),
|
||||
}))
|
||||
} else await app.launch(this.buildAppContext(app), params)
|
||||
console.log(`[ios-preview] Launched ${id}`)
|
||||
} catch (error) { this.fail(error) }
|
||||
}
|
||||
private async uninstallApp(id: string): Promise<void> {
|
||||
const packageId = installedEvenHubPackageId(id)
|
||||
if (!packageId) return
|
||||
closeRunningPackage(packageId)
|
||||
uninstallEvenHubPackage(packageId)
|
||||
this.requestShellRender()
|
||||
}
|
||||
private buildAppContext(app: AppDefinition): AppContext {
|
||||
return {
|
||||
appId: app.appId, apps: ALL_APPS, actions: this.actions,
|
||||
launchApp: (id, params) => this.launchApp(id, params), uninstallApp: id => this.uninstallApp(id),
|
||||
launchInProcessApp: (id, surface, create) => this.launchInProcessApp(id, surface, create),
|
||||
ensureWorkerHost: create => this.ensureWorkerHost(app.appId, create),
|
||||
submitWindowFrame: (id, planes) => this.submit(id, planes),
|
||||
setWindowSurfaceVisible: (id, visible) => this.setWindowSurfaceVisible(id, visible),
|
||||
requestShellRender: () => this.requestShellRender(), appendLog: message => console.log(`[ios-app] ${message}`),
|
||||
setTextEditorHost: () => {},
|
||||
}
|
||||
}
|
||||
private async launchInProcessApp(windowId: string, surfaceId: string,
|
||||
create: (options: InProcessAppOptions) => InProcessWindow): Promise<void> {
|
||||
const existing = this.inProcessApps.get(windowId)
|
||||
if (existing) { shell.focusWindow(windowId); existing.requestRender(); this.requestShellRender(); return }
|
||||
// Apps can request a render while their factory runs (Nightscout's tray
|
||||
// subscription does). The surface only exists once the factory returns.
|
||||
// The explicit render below supplies a fresh frame after configuration.
|
||||
let surfaceReady = false
|
||||
const app = create({
|
||||
actions: this.actions, submitFrame: planes => surfaceReady ? this.submit(surfaceId, planes) : Promise.resolve(),
|
||||
setSurfaceVisible: visible => this.setWindowSurfaceVisible(surfaceId, visible),
|
||||
removeSurface: () => { surfaceReady = false; this.removeWindowSurface(surfaceId) },
|
||||
reconfigureSurface: () => {
|
||||
const window = shell.getWindows().find(w => w.windowId === windowId)
|
||||
if (window) void this.configureWindow(window).catch(error => this.fail(error))
|
||||
this.requestShellRender()
|
||||
},
|
||||
onClosed: () => { this.inProcessApps.delete(windowId) },
|
||||
})
|
||||
this.inProcessApps.set(windowId, app)
|
||||
await this.configureWindow(app.window)
|
||||
surfaceReady = true
|
||||
shell.registerWindow(app.window); shell.focusWindow(windowId)
|
||||
app.requestRender(); this.requestShellRender()
|
||||
}
|
||||
private ensureWorkerHost(appId: string, create: () => Worker): WorkerAppHost {
|
||||
const existing = this.appHosts.get(appId)
|
||||
if (existing) return existing
|
||||
const worker = create()
|
||||
const navigationSensors = appId === 'navigate'
|
||||
? new IosNavigationSensors(event => worker.postMessage({ type: 'navigation-sensors', event })) : undefined
|
||||
const host = new WorkerAppHost({
|
||||
appId, worker, navigationSensors,
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId) },
|
||||
playBuzzerSequence: payload => this.actions.playBuzzerSequence(payload),
|
||||
openUrl: url => { void Utils.openUrl(url) },
|
||||
configureSurface: async (id, visible, heightMode) => {
|
||||
const display = this.display
|
||||
if (!display) return
|
||||
await display.configureSurface(id, { ...appViewportRect(heightMode, appId), zOrder: 0, transparency: 'opaque' })
|
||||
await display.setSurfaceVisible(id, visible)
|
||||
},
|
||||
setSurfaceVisible: (id, visible) => this.setWindowSurfaceVisible(id, visible),
|
||||
removeSurface: id => this.removeWindowSurface(id),
|
||||
submitPixels: (id, pixels, width, height, draws) => {
|
||||
void this.submitWorkerPixels(id, pixels, width, height, draws).catch(error => this.fail(error))
|
||||
},
|
||||
requestShellRender: () => this.requestShellRender(),
|
||||
openSettings: section => { void this.launchApp('settings', { section }) },
|
||||
startTextSettingEdit: id => { const setting = getStringSettingById(id); if (setting) void this.editSetting(setting) },
|
||||
endTextSettingEdit: () => {},
|
||||
startTextInput: () => shell.startVoiceInput(),
|
||||
})
|
||||
this.appHosts.set(appId, host)
|
||||
return host
|
||||
}
|
||||
cycleDisplayMode(): void {
|
||||
const values = DISPLAY_MODE_VALUES
|
||||
displayModeSetting.set(values[(values.indexOf(displayModeSetting.get()) + 1) % values.length])
|
||||
}
|
||||
get displayModeLabel(): string { return displayModeLabel(displayModeSetting.get()) }
|
||||
get connectionState(): SessionState | null { return this.sessionCreated ? this.state : null }
|
||||
get connectionDetails(): string {
|
||||
const state = this.connectionState
|
||||
return state ? `${state.status}\nL: ${state.leftVersion || 'unknown'}\nR: ${state.rightVersion || 'unknown'}\nBattery: ${state.battery ?? '?'}%\nRing: ${state.ring ? 'connected' : 'disconnected'}\nFrames acknowledged: ${state.frames}\n${state.capabilities}\n\n${this.logLines.slice(-12).join('\n')}` : 'Preview only. Configure devices, then connect.'
|
||||
}
|
||||
private update(phase: SessionPhase, status: string): void {
|
||||
this.state = { ...this.state, phase, status }
|
||||
this.logBluetooth(status)
|
||||
this.emitState()
|
||||
}
|
||||
private emitState(): void {
|
||||
if (this.state.phase !== 'connected') resetRingInputFilter()
|
||||
this.pushBrightness()
|
||||
this.maybePlayWelcomeSound(this.state)
|
||||
if (this.state.phase !== 'connected' && this.state.phase !== 'connecting') this.glassesWorn = null
|
||||
if (this.state.phase !== 'connected') iosVoiceInput.handleSessionEnded()
|
||||
shell.setBatteryLevels({ headset: this.state.battery, headsetCharging: this.state.charging })
|
||||
this.syncRuntime()
|
||||
if (this.active) this.onConnectionState({ ...this.state })
|
||||
this.requestShellRender()
|
||||
}
|
||||
async connect(): Promise<void> {
|
||||
if (!this.active || this.connecting || this.stopping) return
|
||||
if (this.communicator && ['connecting', 'connected', 'retrying', 'disconnecting'].includes(this.state.phase)) return
|
||||
const addresses = loadDeviceAddresses(), error = deviceAddressError(addresses)
|
||||
if (error) { this.onError(error); return }
|
||||
this.connecting = true
|
||||
this.sessionCreated = true
|
||||
try {
|
||||
this.state = { ...this.state, capabilities: '', leftVersion: '', rightVersion: '', battery: null, charging: null, ring: false }
|
||||
this.update('connecting', 'Finding configured devices…')
|
||||
let identifiers
|
||||
try { identifiers = await resolveIosPeripherals(addresses) }
|
||||
catch (failure) {
|
||||
this.update('error', failure instanceof Error ? failure.message : String(failure))
|
||||
return
|
||||
}
|
||||
if (this.communicator) await this.closeCommunicator()
|
||||
const communicator = new FaceclawCommunicatorBridge(identifiers)
|
||||
this.teardownPreviewDisplay()
|
||||
this.communicator = communicator
|
||||
this.wearDetectionRequested = false
|
||||
this.bindCommunicator(communicator)
|
||||
this.displayReady = this.registerSurfaces(communicator)
|
||||
await this.displayReady
|
||||
this.update('connecting', 'Connecting to the glasses…')
|
||||
await communicator.configureBrightness(getBrightnessPreferences())
|
||||
this.startedCommunicators.add(communicator)
|
||||
await communicator.start()
|
||||
for (const window of shell.getWindows()) window.requestRender()
|
||||
this.requestShellRender()
|
||||
} catch (failure) {
|
||||
this.fail(failure)
|
||||
await this.closeCommunicator().catch(() => {})
|
||||
this.ensurePreviewDisplay()
|
||||
this.update('error', failure instanceof Error ? failure.message : String(failure))
|
||||
} finally {
|
||||
this.connecting = false
|
||||
}
|
||||
}
|
||||
private bindCommunicator(communicator: FaceclawCommunicatorBridge): void {
|
||||
const notifications = new AncsClient(packet => communicator.writeRawToRight(packet), (key, popup) => {
|
||||
iosNotificationsChanged(key, popup); this.requestShellRender()
|
||||
}, message => this.logBluetooth('ANCS: ' + message))
|
||||
this.notifications = notifications
|
||||
bindIosNotifications(notifications)
|
||||
bindCompassSession(communicator)
|
||||
communicator.setRequiresAncs(true)
|
||||
this.sessionOffs.push(
|
||||
communicator.onStateChange(state => this.handleSessionState(communicator, state)),
|
||||
communicator.onRingEvent(input => this.handleRingEvent(input)),
|
||||
communicator.onBatteryState(state => {
|
||||
if (this.communicator !== communicator) return
|
||||
this.state = { ...this.state, battery: state.battery >= 0 && state.battery <= 100 ? state.battery : this.state.battery,
|
||||
charging: state.chargingStatus >= 0 ? state.chargingStatus > 0 : this.state.charging,
|
||||
ring: (state.ringBattery ?? -1) >= 0 || this.state.ring }
|
||||
shell.setBatteryLevels({ headset: this.state.battery, headsetCharging: this.state.charging })
|
||||
if (this.active) this.onConnectionState({ ...this.state })
|
||||
this.requestShellRender()
|
||||
}),
|
||||
communicator.onFirmwareInfo(info => {
|
||||
if (this.communicator !== communicator) return
|
||||
this.state = { ...this.state, leftVersion: info.leftVersion || this.state.leftVersion,
|
||||
rightVersion: info.rightVersion || this.state.rightVersion, capabilities: info.extension || this.state.capabilities }
|
||||
if (this.active) this.onConnectionState({ ...this.state })
|
||||
this.syncNotifications(communicator)
|
||||
}),
|
||||
communicator.onFrameMetrics(() => {
|
||||
if (this.communicator !== communicator) return
|
||||
this.state = { ...this.state, frames: this.state.frames + 1 }
|
||||
this.onActivity()
|
||||
this.maybePlayWelcomeSound(this.state)
|
||||
if (this.active) this.onConnectionState({ ...this.state })
|
||||
this.schedulePreviewUpdate()
|
||||
}),
|
||||
communicator.onWearState(wearing => { if (this.communicator === communicator) this.handleWearState(wearing) }),
|
||||
communicator.addCompassListener(receiveCompassEvent),
|
||||
communicator.onAncsRelayFrame(frame => { if (this.communicator === communicator) notifications.receive(frame) }),
|
||||
communicator.onAncsAuthorization(authorized => {
|
||||
if (this.communicator !== communicator) return
|
||||
if (authorized) { this.syncNotifications(communicator); return }
|
||||
const active = notifications.state !== 'disconnected'
|
||||
const command = notifications.stopCommand()
|
||||
notifications.stop('Enable Share System Notifications in iPhone Settings → Bluetooth → right lens.')
|
||||
if (active && this.state.phase === 'connected') void communicator.writeRawToRight(command).catch(() => {})
|
||||
}),
|
||||
)
|
||||
}
|
||||
private handleSessionState(communicator: FaceclawCommunicatorBridge, state: CommunicatorState): void {
|
||||
if (this.communicator !== communicator) return
|
||||
// Registering the listener makes the Kotlin session report its current state, which is
|
||||
// "disconnected" before start(); that must not be mistaken for the session ending.
|
||||
if (!this.startedCommunicators.has(communicator)) return
|
||||
const phase: SessionPhase = state.phase === 'charging' ? 'connected' : state.phase === 'unpaired' ? 'error' : state.phase
|
||||
if (phase === 'connected' && this.state.phase !== 'connected') {
|
||||
this.state = { ...this.state, frames: this.state.frames }
|
||||
if (!this.wearDetectionRequested) {
|
||||
this.wearDetectionRequested = true
|
||||
void communicator.enableWearDetectionAndRequestState().catch(error => this.logBluetooth(`Wear detection: ${String(error)}`))
|
||||
}
|
||||
}
|
||||
this.update(phase, state.status)
|
||||
if (phase === 'connected') this.syncNotifications(communicator)
|
||||
else if ((phase === 'disconnected' || phase === 'error') && !this.stopping) {
|
||||
// The session ended on its own (retries exhausted, an arm unpaired): release it and go headless.
|
||||
void this.disconnect(state.status)
|
||||
}
|
||||
}
|
||||
private handleRingEvent(input: RawInputEvent): void {
|
||||
this.inputQueue = this.inputQueue.then(async () => {
|
||||
if (this.state.phase !== 'connected') return
|
||||
this.onActivity()
|
||||
if (input.ringInput) this.state = { ...this.state, ring: true }
|
||||
await this.receiveInput(rawInputEventToInputEvent(input),
|
||||
input.kind === 'display-wake' && input.eventType === OsEventTypeList.HEAD_UP_EVENT)
|
||||
this.logBluetooth(`Input ${input.eventType} source ${input.eventSource}`)
|
||||
}).catch(error => this.fail(error))
|
||||
}
|
||||
/** Any glasses traffic: CoreBluetooth can wake a suspended process, so refresh what timers would have. */
|
||||
private onActivity(): void {
|
||||
if (!UIApplication.sharedApplication.protectedDataAvailable) this.handlePhoneLockState(true)
|
||||
this.refreshClock()
|
||||
}
|
||||
/** Start iPhone notification relay once the firmware is known to support it and ANCS is authorized. */
|
||||
private syncNotifications(communicator: FaceclawCommunicatorBridge): void {
|
||||
const notifications = this.notifications
|
||||
if (!notifications || this.state.phase !== 'connected') return
|
||||
if (!ancsCapable(this.state.capabilities)) {
|
||||
if (this.state.capabilities) notifications.stop(`Update glasses to Faceclaw firmware ${ANCS_FIRMWARE_VERSION} or newer for iPhone notifications.`)
|
||||
return
|
||||
}
|
||||
if (notifications.state !== 'disconnected') return
|
||||
notifications.start((Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0, communicator.rightWriteLimit())
|
||||
}
|
||||
async disconnect(reason?: string): Promise<void> {
|
||||
if (this.stopping) return this.stopping
|
||||
const communicator = this.communicator
|
||||
if (!communicator) return
|
||||
// Marked before any bridge call: the session may report "disconnected" from inside disconnect().
|
||||
let finished!: () => void
|
||||
this.stopping = new Promise<void>(resolve => { finished = resolve })
|
||||
try {
|
||||
const notifications = this.notifications
|
||||
if (notifications && notifications.state !== 'disconnected') {
|
||||
const command = notifications.stopCommand()
|
||||
notifications.stop()
|
||||
if (this.state.phase === 'connected') { try { await communicator.writeRawToRight(command) } catch {} }
|
||||
}
|
||||
if (this.state.phase === 'connected' || this.state.phase === 'connecting' || this.state.phase === 'retrying')
|
||||
this.update('disconnecting', 'Disconnecting…')
|
||||
await communicator.disconnect().catch(error => this.logBluetooth(`Disconnect: ${String(error)}`))
|
||||
} finally {
|
||||
await this.closeCommunicator()
|
||||
this.ensurePreviewDisplay()
|
||||
this.update(reason ? 'error' : 'disconnected', reason ?? 'Preview only')
|
||||
this.stopping = null
|
||||
finished()
|
||||
}
|
||||
}
|
||||
private async closeCommunicator(): Promise<void> {
|
||||
const communicator = this.communicator
|
||||
if (!communicator) return
|
||||
for (const off of this.sessionOffs.splice(0)) off()
|
||||
this.notifications = null
|
||||
this.communicator = null
|
||||
this.glance.reset()
|
||||
await communicator.close().catch(error => this.logBluetooth(`Close: ${String(error)}`))
|
||||
}
|
||||
private maybePlayWelcomeSound(state: SessionState): void {
|
||||
const firstNewFrame = state.frames > this.acknowledgedFrames
|
||||
this.acknowledgedFrames = state.frames
|
||||
// Match Android: wait for an acknowledged frame before consuming the jingle.
|
||||
if (!firstNewFrame || state.phase !== 'connected' || !isWelcomeSoundPending()) return
|
||||
setWelcomeSoundPending(false)
|
||||
const effect = findSoundEffect('questcomplete')
|
||||
if (effect) void playSoundEffect(effect, payload => this.actions.playBuzzerSequence(payload),
|
||||
ms => new Promise(resolve => setTimeout(resolve, ms)))
|
||||
.catch(error => this.logBluetooth(`Welcome sound failed: ${error}`))
|
||||
}
|
||||
startVoiceInput(): void { if (!this.glassesLocked) shell.startVoiceInput() }
|
||||
private async prepareVoiceCapture(): Promise<boolean> {
|
||||
if (this.glassesLocked) return false
|
||||
const usePhoneMic = this.state.phase !== 'connected'
|
||||
if (usePhoneMic && !this.active) return false
|
||||
const ready = await iosVoiceInput.prepare(this.active, usePhoneMic)
|
||||
if (!ready && this.active) this.onError(iosVoiceInput.statusText)
|
||||
return ready && !this.glassesLocked && (this.state.phase === 'connected' || this.active)
|
||||
}
|
||||
private async startVoiceCapture(endpointing = false): Promise<void> {
|
||||
if (this.glassesLocked) return
|
||||
const log = (message: string) => this.logBluetooth(message)
|
||||
const communicator = this.communicator
|
||||
if (communicator && this.state.phase === 'connected') {
|
||||
await iosVoiceInput.startGlassesCapture(communicator, log, endpointing)
|
||||
} else if (this.active) {
|
||||
// Recheck microphone permission if the glasses disconnected after prepare.
|
||||
if (!await iosVoiceInput.prepare(this.active, true) || !this.active || this.glassesLocked) return
|
||||
await iosVoiceInput.startPhoneCapture(log, endpointing)
|
||||
}
|
||||
}
|
||||
private logBluetooth(message: string): void {
|
||||
const line = `${new Date().toISOString()} [${this.active ? 'foreground' : 'background'}${UIApplication.sharedApplication.protectedDataAvailable ? '' : ',protected-data-unavailable'}] ${message}`
|
||||
console.log(`[ios-ble] ${line}`); this.logLines.push(line)
|
||||
if (this.logLines.length > 1000) this.logLines.shift()
|
||||
if (this.logTimer !== null) return
|
||||
this.logTimer = setTimeout(() => {
|
||||
this.logTimer = null
|
||||
this.flushBluetoothLog()
|
||||
}, 500)
|
||||
}
|
||||
private flushBluetoothLog(): void {
|
||||
if (this.logTimer !== null) clearTimeout(this.logTimer)
|
||||
this.logTimer = null
|
||||
try { File.fromPath(path.join(knownFolders.documents().path, 'bluetooth.log')).writeTextSync(this.logLines.join('\n')) }
|
||||
catch (error) { console.warn(`Bluetooth log: ${error}`) }
|
||||
}
|
||||
typeIntoApp(): void {
|
||||
if (this.glassesLocked || !this.active) return
|
||||
shell.startKeyboardInput()
|
||||
}
|
||||
private async editSetting(setting: { editorTitle: string; inputKind?: string; get(): string; set(value: string): void; validationError?(value?: string): string | null }): Promise<boolean> {
|
||||
if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return false }
|
||||
let draft = setting.get()
|
||||
while (true) {
|
||||
const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: draft, inputType: setting.inputKind, okButtonText: 'Save', cancelButtonText: 'Cancel' })
|
||||
if (!result.result) return false
|
||||
draft = result.text
|
||||
const error = setting.validationError?.(draft)
|
||||
if (error) {
|
||||
await Dialogs.alert({ title: setting.editorTitle, message: error, okButtonText: 'OK' })
|
||||
continue
|
||||
}
|
||||
setting.set(draft)
|
||||
if (setting === nightscoutSiteUrlSetting || setting === nightscoutApiTokenSetting) await nightscoutBridge.refreshNow()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { GrayImage, G2_LENS_WIDTH, G2_LENS_HEIGHT } from "../graphics/image";
|
||||
import { getDefaultMediumFont } from "../graphics/ui-fonts";
|
||||
import { wrapText } from "../graphics/textwrap";
|
||||
|
||||
export const LOCK_SCREEN_SURFACE_ID = "lock-screen";
|
||||
const LOCK_SCREEN_MESSAGE = "Glasses locked; unlock the phone to unlock the glasses.";
|
||||
|
||||
export function createLockScreenImage(): GrayImage {
|
||||
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
|
||||
const font = getDefaultMediumFont();
|
||||
const boxWidth = 480;
|
||||
const boxHeight = 150;
|
||||
const boxX = Math.round((G2_LENS_WIDTH - boxWidth) / 2);
|
||||
const boxY = Math.round((G2_LENS_HEIGHT - boxHeight) / 2);
|
||||
image.drawRoundedRect(boxX, boxY, boxWidth, boxHeight, 150, 12);
|
||||
const lines = wrapText(font, LOCK_SCREEN_MESSAGE, boxWidth - 64);
|
||||
const textHeight = lines.length * font.lineHeight;
|
||||
const firstY = boxY + Math.round((boxHeight - textHeight) / 2);
|
||||
lines.forEach((line, index) => {
|
||||
const x = Math.round((G2_LENS_WIDTH - font.measureText(line)) / 2);
|
||||
image.drawText(font, x, firstY + index * font.lineHeight, line, 230);
|
||||
});
|
||||
return image;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Original R1 report metadata. Tick is unsigned ring uptime, not phone time.
|
||||
* Keep the native clock units: G2's deduplication threshold is 100 ticks. */
|
||||
export type RingInput = Readonly<{ tick: number; type: number; aux: number; speed: number }>;
|
||||
|
||||
/** Faceclaw/19 EvenHub SysEvent field 100, version 1. */
|
||||
export function decodeRingMetadata(raw: Uint8Array | null | undefined): RingInput | undefined {
|
||||
if (!raw || raw.length !== 12 || raw[0] !== 0x52 || raw[1] !== 0x49 ||
|
||||
raw[2] !== 1 || raw[3] !== 1 || raw[7] !== 0) return undefined;
|
||||
return { tick: (raw[8] | raw[9] << 8 | raw[10] << 16 | raw[11] << 24) >>> 0,
|
||||
type: raw[4], aux: raw[5], speed: raw[6] };
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# TypeScript display lists
|
||||
|
||||
`GrayImage.drawDisplayList(list, x, y, width, height, depth)` retains a list alongside
|
||||
the image's ordinary pixels. Existing frame submission (`prepareFrameDraws`) and
|
||||
shell scene submission carry it to Kotlin. Bounds describe its footprint for plane
|
||||
occlusion; draw coordinates are relative to its placement. Keep the list, its image
|
||||
resources, and their pixel buffers immutable after submission.
|
||||
|
||||
```ts
|
||||
import { DrawExpression as E } from './draw-expression';
|
||||
import { DrawOp, type DisplayList } from './display-list';
|
||||
|
||||
const list: DisplayList = {
|
||||
resources: [],
|
||||
timeline: { token: animationId, startedAt: Date.now() },
|
||||
calls: [{
|
||||
op: DrawOp.ROUNDED_RECT,
|
||||
x: E.progress(300).ease().lerp(E.f32(0), E.f32(100)).toInt(),
|
||||
y: 0,
|
||||
width: 40, height: 20, radius: 6,
|
||||
background: 4, border: 15,
|
||||
}],
|
||||
};
|
||||
frame.drawDisplayList(list, 20, 30, 140, 20, 0);
|
||||
```
|
||||
|
||||
Supported calls:
|
||||
|
||||
- `ROUNDED_RECT`: literal or expression `x`/`y`, literal dimensions/radius, and
|
||||
4-bit colors (0–15). Border 16 means no border. Fill takes the maximum of the
|
||||
background color and existing pixels.
|
||||
- `IMAGE`: a local resource index, integer `x`/`y`, and `transparent`. Transparent
|
||||
images skip pixels quantized to zero. Resources have `width`, `height`, and
|
||||
gray8 `pixels`; a baked `GrayImage` can be used directly.
|
||||
- `RECT_COPY`: a local resource index, source rectangle and destination
|
||||
`dx`/`dy`. Source x/y and `dx`/`dy` accept expressions (revision 29); the
|
||||
source rectangle must stay inside the source at every time, or firmware
|
||||
rejects the list. `SCREEN` reads the uncomposed frame; its source coordinates
|
||||
are also relative to this list's placement. Each call may add its own `depth`
|
||||
to the list's depth. A screen restore normally uses the negative of the list depth.
|
||||
- `CLEAR` (revision 35 with a clip): fill with a 4-bit `color`. Under a clip it
|
||||
fills just the clip rect, which is how to blank a region; without one it
|
||||
fills the whole screen.
|
||||
- `DRAWS` (bridge-only): replay glyph and icon draws offset by `x`/`y`, which
|
||||
may be expressions. `records`/`count` come from glyph-wire's
|
||||
`encodeReplayDraws(image.draws)`, which registers the rasters and returns null
|
||||
unless every draw is a replayable glyph (atlas font, ASCII, ink inside the
|
||||
line box) or plain image. Kotlin compiles them to firmware IMAGE calls on
|
||||
ImageAtlas resources and TEXT runs on FontResourceAtlas fonts (one run per
|
||||
line and color). `source` keeps the draws for software painting. If Kotlin
|
||||
cannot resolve a record, the whole list draws nothing, so the frame's own
|
||||
pixels show rather than content with a hole in it.
|
||||
|
||||
Any call may carry a `clip` (revision 35): a rect in list coordinates outside
|
||||
which it draws nothing. It moves with the call's depth, like the call itself.
|
||||
The firmware flag also nests (a clipped play-list call clips everything inside
|
||||
it, intersected with the calls' own clips), but TS lists are inlined into the
|
||||
root, so each call carries its own.
|
||||
|
||||
Kotlin allocates/cache-pins all image resources, resolves the local indices, applies
|
||||
surface placement, and includes the calls in the root firmware display list. The
|
||||
phone's existing display-list renderer consumes the same compiled calls. This uses
|
||||
the current firmware protocol; no firmware update is needed for this bridge change.
|
||||
|
||||
## Expressions and time
|
||||
|
||||
`E.i32` and `E.f32` construct typed constants. Builders support arithmetic, min/max,
|
||||
integer remainder, negation, explicit conversions, lerp, and the easing functions
|
||||
in `ExprOp`. `ease()` defaults to smoothstep. Integers wrap at 32 bits; float
|
||||
operations round to f32. The firmware's existing stack/error semantics apply.
|
||||
Rounded-rectangle x/y and rect-copy source/destination coordinates accept
|
||||
expressions. `E.progress(duration, delay)` stays 0 for the first `delay` ms of
|
||||
the timeline, so one list can run motions that started at different times.
|
||||
|
||||
`maximum.time()` returns `min(milliseconds since PRESENT, maximum)`. The existing
|
||||
45 ms repaint timer remains active while this is below maximum. `E.elapsed()` is
|
||||
a bridge binding: Kotlin replaces it with the timeline's elapsed milliseconds when
|
||||
building a new root list. It is a constant within that PRESENT, not a second clock.
|
||||
`E.progress(durationMs)` combines the two and clamps to 0..1 so intervening frames
|
||||
and PRESENTs continue an animation instead of restarting it.
|
||||
|
||||
Keep `timeline.token` and `timeline.startedAt` stable for an animation; use a new
|
||||
token when restarting it. JS sends an elapsed duration, so JS and native clocks
|
||||
need not share an epoch. Fingerprints include the token and expression code but
|
||||
exclude the changing elapsed duration. Without a timeline, raw `time()` expressions
|
||||
start at each PRESENT. Native compilation strips the bridge-only elapsed opcode.
|
||||
|
||||
`menu-selection-list.ts` authors both the rounded highlight and the transparent row
|
||||
image using this API. `IconGrid` (app/ui/icon-grid.ts) animates a whole grid
|
||||
this way: a clipped CLEAR of the grid box, the sliding highlight, then a DRAWS
|
||||
of every row visible during the scroll, offset by the scroll expression. `menu-scroll-list.ts` authors a menu scroll or bounce: a
|
||||
viewport-sized copy from a strip resource whose source y animates, then the
|
||||
highlight. The bounce curve (`app/ui/menu-scroll-motion.ts`) needs no branches:
|
||||
the easing ops clamp their input to 0..1, so `ease(t / p)` holds at 1 after the
|
||||
peak and `ease((t - p) / (1 - p))` holds at 0 before it. Navigation eligibility, duration, and easing remain in
|
||||
TypeScript. There is no animated-menu tag or menu animation policy in Kotlin.
|
||||
|
||||
## Bridge framing
|
||||
|
||||
Tag 7 is followed by a little-endian u32 byte length and a bounded body:
|
||||
placement (i16 x/y, u16 width/height, i8 depth), timeline (u32 token/elapsed),
|
||||
u16 resource count, gray8 images (u16 width/height followed by pixels), u16 call
|
||||
count, then calls. Calls start with the opcode (bit 7 set when a clip follows)
|
||||
and an i16 relative depth, then the clip if any (i16 x/y, u16 width/height);
|
||||
operands otherwise use their fixed-width fields, except rounded x/y, rect-copy
|
||||
x/y/dx/dy and DRAWS x/y which use extended varints. CLEAR is a u8 color. DRAWS
|
||||
(opcode 32) is followed by a u16 record count and the records, in the frame
|
||||
draw-buffer formats: glyph `[0][fontId u16][encoding u32][penX s16][lineY s16][value u8]`
|
||||
and image `[1][imageId u32][x s16][y s16]`. Expressions use the firmware bytecode plus bridge-only
|
||||
`ELAPSED = 128`. Resource indices are local to this record, never firmware IDs.
|
||||
Rect-copy source x/y are signed here to permit relative SCREEN coordinates.
|
||||
|
||||
Limits: 256 images per record, 64 KiB per packed image, 4 MiB per bridge record,
|
||||
4096 calls, and 900 input bytes per expression. Native validates the bound program
|
||||
against the firmware's 1024-byte limit. The combined scene must also fit the
|
||||
existing resource cache, root-list size, and VM stack limits.
|
||||
@@ -0,0 +1,191 @@
|
||||
import { DrawBytes, encodeValue, evaluate, integer, readValue, type DrawValue } from './draw-expression';
|
||||
import type { GrayImage } from './image';
|
||||
|
||||
/** Local resources are assigned firmware cache IDs by Kotlin. SCREEN reads the uncomposed frame. */
|
||||
export const SCREEN = 65535;
|
||||
/**
|
||||
* Firmware opcodes, plus DRAWS: a bridge-only call that replays glyph and icon
|
||||
* draws (from glyph-wire's encodeReplayDraws) as firmware image/text calls.
|
||||
*/
|
||||
export const DrawOp = { RECT_COPY: 2, IMAGE: 4, ROUNDED_RECT: 8, CLEAR: 9, DRAWS: 32 } as const;
|
||||
export const DISPLAY_LIST_RECORD = 7;
|
||||
/** Bridge opcode bit: a clip rect follows the call's depth. */
|
||||
const CLIPPED = 128;
|
||||
export type ListImage = { readonly width: number; readonly height: number; readonly pixels: Uint8Array };
|
||||
/** Revision 35: a call draws only inside its clip, in list coordinates (and moves with its depth). */
|
||||
export type ListClip = { readonly x: number; readonly y: number; readonly width: number; readonly height: number };
|
||||
export type ListCall = (
|
||||
| { op: typeof DrawOp.ROUNDED_RECT; x: DrawValue; y: DrawValue; width: number; height: number; radius: number; background: number; border: number }
|
||||
| { op: typeof DrawOp.IMAGE; resource: number; x: number; y: number; transparent: boolean }
|
||||
| { op: typeof DrawOp.RECT_COPY; resource: number; x: DrawValue; y: DrawValue; width: number; height: number; dx: DrawValue; dy: DrawValue }
|
||||
/** Fill with a 4-bit color: the clip rect when there is one, else the whole screen. */
|
||||
| { op: typeof DrawOp.CLEAR; color: number }
|
||||
/**
|
||||
* Glyph and icon draws offset by (x, y). `records`/`count` are the wire form;
|
||||
* `source` holds the same draws for software painting (a decoded list has none).
|
||||
*/
|
||||
| { op: typeof DrawOp.DRAWS; x: DrawValue; y: DrawValue; records: Uint8Array; count: number; source?: GrayImage }
|
||||
) & { depth?: number; clip?: ListClip };
|
||||
export type DisplayList = {
|
||||
readonly resources: readonly ListImage[];
|
||||
readonly calls: readonly ListCall[];
|
||||
/** Stable identity plus JS clock origin. Native binds ELAPSED again for each PRESENT. */
|
||||
/** Set by the decoder: the local PRESENT origin for software replay. */
|
||||
readonly presentedAt?: number;
|
||||
readonly timeline?: { readonly token: number; readonly startedAt: number };
|
||||
};
|
||||
export type PlacedDisplayList = { displayList: DisplayList; x: number; y: number; width: number; height: number; depth: number };
|
||||
|
||||
class Writer {
|
||||
bytes: number[] = [];
|
||||
u8(n: number): void { this.bytes.push(integer(n, 0, 255)); }
|
||||
i8(n: number): void { this.u8(integer(n, -128, 127) & 255); }
|
||||
u16(n: number): void { integer(n, 0, 65535); this.bytes.push(n & 255, n >>> 8); }
|
||||
i16(n: number): void { this.u16(integer(n, -32768, 32767) & 65535); }
|
||||
u32(n: number): void { integer(n, 0, 4294967295); this.u16(n & 65535); this.u16(n >>> 16); }
|
||||
raw(bytes: ArrayLike<number>): void { for (let i = 0; i < bytes.length; i++) this.bytes.push(bytes[i]); }
|
||||
}
|
||||
|
||||
/** Length-delimited bridge envelope; call operands use fixed widths except extended x/y. */
|
||||
export function encodeDisplayList(placed: PlacedDisplayList, now = Date.now()): Uint8Array {
|
||||
const { displayList: list } = placed, out = new Writer();
|
||||
integer(placed.width, 1, 640); integer(placed.height, 1, 480);
|
||||
out.i16(placed.x); out.i16(placed.y); out.u16(placed.width); out.u16(placed.height); out.i8(placed.depth);
|
||||
out.u32(list.timeline?.token ?? 0);
|
||||
out.u32(list.timeline ? Math.min(2147483647, Math.max(0, Math.trunc(now - list.timeline.startedAt))) : 0);
|
||||
integer(list.resources.length, 0, 256); out.u16(list.resources.length);
|
||||
for (const image of list.resources) {
|
||||
integer(image.width, 1, 640); integer(image.height, 1, 480);
|
||||
if (image.pixels.length !== image.width * image.height || 5 + Math.ceil(image.width / 2) * image.height > 65536) throw new Error('Invalid display-list image');
|
||||
out.u16(image.width); out.u16(image.height); out.raw(image.pixels);
|
||||
}
|
||||
integer(list.calls.length, 0, 4096); out.u16(list.calls.length);
|
||||
for (const call of list.calls) {
|
||||
out.u8(call.op | (call.clip ? CLIPPED : 0)); out.i16(call.depth ?? 0);
|
||||
integer(placed.depth + (call.depth ?? 0), -128, 127);
|
||||
if (call.clip) { out.i16(call.clip.x); out.i16(call.clip.y); out.u16(call.clip.width); out.u16(call.clip.height); }
|
||||
if (call.op === DrawOp.ROUNDED_RECT) {
|
||||
out.raw(encodeValue(call.x)); out.raw(encodeValue(call.y));
|
||||
out.u16(integer(call.width, 1, 640)); out.u16(integer(call.height, 1, 480)); out.u16(call.radius);
|
||||
out.u8(integer(call.background, 0, 15)); out.u8(integer(call.border, 0, 16));
|
||||
} else if (call.op === DrawOp.CLEAR) {
|
||||
out.u8(integer(call.color, 0, 15));
|
||||
} else if (call.op === DrawOp.DRAWS) {
|
||||
out.raw(encodeValue(call.x)); out.raw(encodeValue(call.y));
|
||||
out.u16(call.count); out.raw(call.records);
|
||||
} else {
|
||||
if (call.resource !== SCREEN) integer(call.resource, 0, list.resources.length - 1);
|
||||
if (call.op === DrawOp.RECT_COPY && call.resource !== SCREEN && [call.x, call.y].some(v => typeof v === 'number' && v < 0)) throw new Error('Negative image source coordinate');
|
||||
if (call.op === DrawOp.IMAGE && call.resource === SCREEN) throw new Error('Use rectCopy to read SCREEN');
|
||||
out.u16(call.resource);
|
||||
if (call.op === DrawOp.IMAGE) { out.i16(call.x); out.i16(call.y); out.u8(call.transparent ? 31 : 15); }
|
||||
else {
|
||||
out.raw(encodeValue(call.x)); out.raw(encodeValue(call.y)); out.u16(integer(call.width, 1, 640)); out.u16(integer(call.height, 1, 480));
|
||||
out.raw(encodeValue(call.dx)); out.raw(encodeValue(call.dy));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (out.bytes.length > 4 * 1024 * 1024) throw new Error('Display list exceeds bridge limit');
|
||||
const header = new Writer(); header.u8(DISPLAY_LIST_RECORD); header.u32(out.bytes.length); header.raw(out.bytes);
|
||||
return Uint8Array.from(header.bytes);
|
||||
}
|
||||
|
||||
/** Replay-record sizes by tag, as in glyph-wire's frame draw buffer. */
|
||||
const RECORD_BYTES: Record<number, number> = { 0: 12, 1: 9 };
|
||||
|
||||
export function readDisplayList(bytes: Uint8Array, offset: number, now = Date.now()): { placed: PlacedDisplayList; end: number } {
|
||||
const envelope = new DrawBytes(bytes.subarray(offset));
|
||||
if (envelope.u8() !== DISPLAY_LIST_RECORD) throw new Error('Invalid display-list record');
|
||||
const length = envelope.u32(); integer(length, 0, 4 * 1024 * 1024);
|
||||
const r = new DrawBytes(envelope.take(length));
|
||||
const x = r.i16(), y = r.i16(), width = r.u16(), height = r.u16(), depth = r.u8() << 24 >> 24;
|
||||
const token = r.u32(), elapsed = r.u32(), count = r.u16(); integer(count, 0, 256);
|
||||
const resources: ListImage[] = [];
|
||||
for (let i = 0; i < count; i++) { const width = r.u16(), height = r.u16(); resources.push({ width, height, pixels: r.take(width * height) }); }
|
||||
const calls: ListCall[] = [], callCount = r.u16(); integer(callCount, 0, 4096);
|
||||
for (let i = 0; i < callCount; i++) {
|
||||
const header = r.u8(), op = header & ~CLIPPED, depth = r.i16();
|
||||
const clip = header & CLIPPED ? { x: r.i16(), y: r.i16(), width: r.u16(), height: r.u16() } : undefined;
|
||||
const common = clip ? { depth, clip } : { depth };
|
||||
if (op === DrawOp.ROUNDED_RECT) calls.push({ op, ...common, x: readValue(r), y: readValue(r), width: r.u16(), height: r.u16(), radius: r.u16(), background: r.u8(), border: r.u8() });
|
||||
else if (op === DrawOp.IMAGE) calls.push({ op, ...common, resource: r.u16(), x: r.i16(), y: r.i16(), transparent: (r.u8() & 16) !== 0 });
|
||||
else if (op === DrawOp.RECT_COPY) calls.push({ op, ...common, resource: r.u16(), x: readValue(r), y: readValue(r), width: r.u16(), height: r.u16(), dx: readValue(r), dy: readValue(r) });
|
||||
else if (op === DrawOp.CLEAR) calls.push({ op, ...common, color: r.u8() });
|
||||
else if (op === DrawOp.DRAWS) {
|
||||
const x = readValue(r), y = readValue(r), records = r.u16(), start = r.offset;
|
||||
for (let n = 0; n < records; n++) {
|
||||
const size = RECORD_BYTES[r.bytes[r.offset]!];
|
||||
if (!size) throw new Error('Unsupported display-list draw record');
|
||||
r.take(size);
|
||||
}
|
||||
calls.push({ op, ...common, x, y, count: records, records: r.bytes.slice(start, r.offset) });
|
||||
} else throw new Error('Unsupported display-list call');
|
||||
}
|
||||
if (r.offset !== length) throw new Error('Trailing display-list bytes');
|
||||
const placed = { x, y, width, height, depth, displayList: { resources, calls, presentedAt: now, timeline: { token, startedAt: now - elapsed } } };
|
||||
// The writer is also the shared structural validator for software preview records.
|
||||
encodeDisplayList(placed, now);
|
||||
return { placed, end: offset + envelope.offset };
|
||||
}
|
||||
|
||||
/**
|
||||
* The list at `factor` brightness. Replayed icons cannot be dimmed on the
|
||||
* glasses, so a list with DRAWS calls becomes empty instead: the dimmed frame
|
||||
* underneath then shows its final state.
|
||||
*/
|
||||
export function dimDisplayList(list: DisplayList, factor: number): DisplayList {
|
||||
if (list.calls.some(c => c.op === DrawOp.DRAWS)) return { ...list, calls: [] };
|
||||
const dim = (v: number) => v === 0 ? 0 : Math.max(1, Math.round(v * factor));
|
||||
return { ...list, resources: list.resources.map(r => ({ ...r, pixels: r.pixels.map(dim) })),
|
||||
calls: list.calls.map(c => c.op === DrawOp.ROUNDED_RECT ? { ...c, background: Math.min(15, Math.round(c.background * factor)), border: c.border === 16 ? 16 : Math.min(15, Math.round(c.border * factor)) }
|
||||
: c.op === DrawOp.CLEAR ? { ...c, color: Math.min(15, Math.round(c.color * factor)) } : c) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback compositor; native preview and glasses replay the compiled list with their existing timers.
|
||||
* A DRAWS call paints from its `source`, so a decoded list skips them.
|
||||
*/
|
||||
export function paintDisplayList(output: Uint8Array, screen: Uint8Array, width: number, height: number, placed: PlacedDisplayList, right = false, now = Date.now()): void {
|
||||
const q = (n: number) => Math.min(15, (n + 8) >> 4) * 16;
|
||||
const list = placed.displayList;
|
||||
const elapsed = list.timeline ? Math.max(0, (list.presentedAt ?? now) - list.timeline.startedAt) : 0;
|
||||
const presentTime = list.presentedAt === undefined ? 0 : Math.max(0, now - list.presentedAt);
|
||||
const inside = (x: number, y: number, w: number, h: number, radius: number) => {
|
||||
if (x < 0 || y < 0 || x >= w || y >= h) return false;
|
||||
const r = Math.min(radius, Math.floor(w / 2), Math.floor(h / 2));
|
||||
const dx = Math.max(0, 2 * r - (2 * Math.min(x, w - 1 - x) + 1)), dy = Math.max(0, 2 * r - (2 * Math.min(y, h - 1 - y) + 1));
|
||||
return dx * dx + dy * dy <= 4 * r * r;
|
||||
};
|
||||
for (const c of placed.displayList.calls) {
|
||||
const depth = placed.depth + (c.depth ?? 0), shift = right ? -Math.floor((depth + 1) / 2) : Math.floor(depth / 2);
|
||||
// Writable region in screen pixels: the clip moves with the call's depth, like its content.
|
||||
const clip = c.clip ? { x: placed.x + c.clip.x + shift, y: placed.y + c.clip.y, width: c.clip.width, height: c.clip.height }
|
||||
: { x: 0, y: 0, width, height };
|
||||
const writable = (x: number, y: number) => x >= 0 && y >= 0 && x < width && y < height &&
|
||||
x >= clip.x && y >= clip.y && x < clip.x + clip.width && y < clip.y + clip.height;
|
||||
if (c.op === DrawOp.CLEAR) {
|
||||
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) if (writable(x, y)) output[y * width + x] = c.color * 16;
|
||||
} else if (c.op === DrawOp.DRAWS) {
|
||||
const at = (v: DrawValue) => evaluate(v, elapsed, presentTime).value;
|
||||
c.source?.paintReplayDraws(output, width, height, placed.x + at(c.x) + shift, placed.y + at(c.y), clip);
|
||||
} else if (c.op === DrawOp.ROUNDED_RECT) {
|
||||
const x = placed.x + evaluate(c.x, elapsed, presentTime).value + shift, y = placed.y + evaluate(c.y, elapsed, presentTime).value;
|
||||
for (let yy = 0; yy < c.height; yy++) for (let xx = 0; xx < c.width; xx++) {
|
||||
if (!writable(x + xx, y + yy) || !inside(xx, yy, c.width, c.height, c.radius)) continue;
|
||||
const p = (y + yy) * width + x + xx;
|
||||
output[p] = c.border !== 16 && !inside(xx - 1, yy - 1, c.width - 2, c.height - 2, Math.max(0, c.radius - 1)) ? c.border * 16 : Math.max(output[p], c.background * 16);
|
||||
}
|
||||
} else {
|
||||
const source = c.resource === SCREEN ? { width, height, pixels: screen } : placed.displayList.resources[c.resource];
|
||||
const w = c.op === DrawOp.IMAGE ? source.width : c.width, h = c.op === DrawOp.IMAGE ? source.height : c.height;
|
||||
const at = (v: DrawValue) => evaluate(v, elapsed, presentTime).value;
|
||||
const sx = c.op === DrawOp.IMAGE ? 0 : at(c.x) + (c.resource === SCREEN ? placed.x : 0), sy = c.op === DrawOp.IMAGE ? 0 : at(c.y) + (c.resource === SCREEN ? placed.y : 0);
|
||||
const x = placed.x + (c.op === DrawOp.IMAGE ? c.x : at(c.dx)) + shift, y = placed.y + (c.op === DrawOp.IMAGE ? c.y : at(c.dy));
|
||||
for (let yy = 0; yy < h; yy++) for (let xx = 0; xx < w; xx++) {
|
||||
if (!writable(x + xx, y + yy) || sx + xx < 0 || sy + yy < 0 || sx + xx >= source.width || sy + yy >= source.height) continue;
|
||||
const v = q(source.pixels[(sy + yy) * source.width + sx + xx]);
|
||||
if (c.op !== DrawOp.IMAGE || !c.transparent || v !== 0) output[(y + yy) * width + x + xx] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 822 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user