Compare commits

...
Author SHA1 Message Date
MasterControl 9ddc864b0d [verified] fix: hide notification background only on screen wake 2026-11-10 20:33:16 +00:00
MasterControl 22df4d76d9 feat: isolate notification popups and scroll selected menu labels 2026-11-10 17:31:13 +00:00
Blendman974 b4a2b2931b Merge pull request 'chore: synchroniser main avec jimrandomh/faceclaw' (#13) from MasterControl/faceclaw:sync/upstream-main into main
Reviewed-on: Blendman974/faceclaw#13
2026-11-09 06:13:40 +00:00
James Babcock 70ec2a0d6a Apple Watch app config changes for publishing 2026-11-08 01:36:54 -08:00
James Babcock 5e3f58764c 0.9.0 2026-11-08 01:08:55 -08:00
James Babcock bf66c5a53c Clean up redundant messages on the Pair Glasses page 2026-11-08 01:05:51 -08:00
James Babcock fa663804de Hide RayNeo iO from device selection screen (support is not ready to ship yet) 2026-11-08 01:00:51 -08:00
James Babcock 4759c55fb8 Fix spurious unit test failures 2026-11-08 00:31:10 -08:00
James Babcock 2b29c9e551 Update changelog 2026-11-08 00:25:53 -08:00
James Babcock 479308f4a6 Firmware uninstall/revert-to-stock for G1s 2026-11-08 00:11:13 -08:00
James Babcock e103b89510 Battery indicators and other places no longer say "G2" when a G1 or iO is paired 2026-11-07 22:56:31 -08:00
James Babcock ac68ba5991 Onboarding fixes: Stuck state on the Permissions page, some dark-on-dark text in dark mode 2026-11-07 22:54:48 -08:00
James Babcock b866224909 Don't show EvenHub store, and show compatibility warning on sideloaded apps, when using RayNeo iO 2026-11-07 22:53:28 -08:00
88 changed files with 2717 additions and 479 deletions

No files matched your search

@@ -5,10 +5,18 @@ import android.os.Handler
import android.os.Looper
/**
* Android host for the shared [G1ArmFlashFlow]: owns the GATT link and the worker thread for one G1 arm's install, or a
* question about what it runs, and delivers listener callbacks on the main thread. For app/native/g1-flasher.ts.
* Android host for the shared [G1ArmFlashFlow]: owns the GATT link and the worker thread for one G1 arm's install, its
* restore to Even's firmware, or a question about what it runs, and delivers listener callbacks on the main thread. For app/native/g1-flasher.ts.
*/
class FaceclawG1Flasher(context: Context, address: String?, side: String?, firmwarePath: String?, mode: String?, connectWindowMs: Int) {
class FaceclawG1Flasher(
context: Context,
address: String?,
side: String?,
firmwarePath: String?,
netCorePath: String?,
mode: String?,
connectWindowMs: Int,
) {
private val link = AndroidStockLink(context.applicationContext)
private val mainHandler = Handler(Looper.getMainLooper())
private val lock = Any()
@@ -25,6 +33,7 @@ class FaceclawG1Flasher(context: Context, address: String?, side: String?, firmw
address ?: "",
side ?: "",
firmwarePath ?: "",
netCorePath ?: "",
G1ArmFlashFlow.mode(mode ?: ""),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
+1 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundleDisplayName</key>
<string>Faceclaw</string>
<key>CFBundleShortVersionString</key>
<string>0.8.6</string>
<string>0.9.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
+21
View File
@@ -1,5 +1,26 @@
# Changelog
## 0.9.0 - 2026-11-08
### Major Features
* Add support for the Even Realities G1
* Add support for the Apple Watch
### Minor Features
* Show charging case battery for the G2
* Terminals now default to opening in the same window rather than opening a new window
* Better rendering of color emojis
* Inrease the max timeout for glanceboard show-on-tap display
* Fix some minor issues in the oboarding flow
* Add option to auto-close notification popups after a delay
### Bug Fixes
* Fix an issue that would cause microphone permission check to fail if you swiped away the Android Activity
* Fix an issue that broke the Nightscout widget on the status bar on iOS
* Fix an issue were EvenHub app texet containers weren't indented correctly
## 0.8.6 - 2026-11-01
* Connect directly to the R1 ring rather than indirectly via the glasses
-6
View File
@@ -81,12 +81,6 @@ Button.-primary {
font-size: 18;
}
/* The logo art is black-on-transparent; tint it light in dark mode so it
* doesn't vanish into the dark page background. */
.ns-dark .onboarding-logo {
tint-color: #e6e6e6;
}
/* License / privacy-policy links in the onboarding disclaimer footer. The
* padding widens the tap target beyond the small text. */
.footer-link {
+1
View File
@@ -5,6 +5,7 @@
.body-text { font-size: 18; }
.h1 { font-size: 28; font-weight: bold; }
.footer-link { color: #285c45; padding: 4 8; text-decoration: underline; }
.ns-dark .footer-link { color: #7bc47f; }
Page {
background-color: #f5f5f2;
@@ -0,0 +1,65 @@
import { wrapText } from "../../graphics/textwrap";
import { type LayerContext } from "../../ui/layers";
import { lineStep } from "../../ui/metrics";
import { ScrollingDialogLayer, type DialogBody, type DialogRow } from "./scrolling-dialog";
/** Wider than the permission dialog: the RayNeo iO's window is short, so fewer, longer lines fit better. */
const DIALOG_WIDTH = 420;
/**
* Shown over an EvenHub app the first time it runs with a RayNeo iO paired
* (see glasses-compat.ts): the app is made for Even Realities glasses and
* won't display correctly on the iO's screen. The app starts underneath.
* Continue (or double-click) dismisses the warning; Close app closes the
* app's window. Either answer counts as having seen it; a window closed with
* the warning still up shows it again next time.
*/
export class EvenHubDisplayWarningLayer extends ScrollingDialogLayer {
constructor(
private readonly appName: string,
private readonly onAnswered: () => void,
private readonly closeApp: () => void,
) {
super(DIALOG_WIDTH);
}
protected bodyRows({ image, font, left, textWidth }: DialogBody): DialogRow[] {
const step = lineStep(font);
const rows: DialogRow[] = [];
for (const line of wrapText(font, "Compatibility warning", textWidth)) {
rows.push({ height: step + 2, draw: (top) => image.drawText(font, left, top, line, 235) });
}
rows[rows.length - 1]!.height += 6;
const message =
`${this.appName} is an EvenHub app, made for Even Realities glasses. It will not display correctly ` +
"on the RayNeo iO, because the iO's screen has a different resolution.";
// One row per wrapped line, so a large font scrolls line by line.
const lines = wrapText(font, message, textWidth);
for (let index = 0; index < lines.length; index++) {
rows.push({
height: step + (index === lines.length - 1 ? 8 : 0),
draw: (top) => image.drawText(font, left, top, lines[index]!, 190),
});
}
return rows;
}
protected actions(): string[] {
return ["Continue", "Close app"];
}
protected activate(action: string, ctx: LayerContext): void {
this.close(ctx, () => {
this.onAnswered();
if (action === "Close app") this.closeApp();
});
}
protected backedOut(): void {
this.onAnswered();
}
protected abandoned(): void {
// Not answered: the next launch shows it again.
}
}
+13
View File
@@ -16,6 +16,8 @@ import { shell } from "../../ui/shell/shell";
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
import { EvenHubSession } from "./session";
import { renderInstalledEvenHubIcon } from "./installed-apps";
import { markDisplayWarningShown, needsDisplayWarning } from "./glasses-compat";
import { EvenHubDisplayWarningLayer } from "./display-warning-dialog";
class EvenHubAppLayer implements Layer {
/**
@@ -149,5 +151,16 @@ export function createEvenHubWindow(
session.setScreenOn(on);
};
// The app's first run with a RayNeo iO paired: warn, over the app itself,
// that it won't display correctly there.
const packageId = session.manifest.packageId;
if (needsDisplayWarning(packageId)) {
created.stack.push(new EvenHubDisplayWarningLayer(
session.manifest.name,
() => markDisplayWarningShown(packageId),
() => shell.closeWindow(windowId),
));
}
return created;
}
+38
View File
@@ -0,0 +1,38 @@
/**
* EvenHub with glasses that aren't Even Realities': with a RayNeo iO paired,
* the store is off (it is Even's, and its apps are made for their glasses),
* while apps sideloaded through Files or the Developer app still run, after a
* warning the first time each one launches that it won't display correctly
* (EvenHub apps lay out for the G2's 576x288 display; the iO's is 540x220).
*/
import { glassesTypeSetting } from "../../ui/dashboard-settings";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
/** The package IDs whose RayNeo iO display warning has been answered, as a JSON array. */
const DISPLAY_WARNED_KEY = "evenhub.rayneoDisplayWarned";
/** Whether the EvenHub store can be used: with Even Realities glasses paired, not a RayNeo iO. */
export function isEvenHubStoreAvailable(): boolean {
return glassesTypeSetting.get() !== "rayneo-io";
}
/** Whether launching this package should warn that it won't display correctly on these glasses. */
export function needsDisplayWarning(packageId: string): boolean {
return glassesTypeSetting.get() === "rayneo-io" && !displayWarnedPackages().includes(packageId);
}
/** The user answered the package's display warning: don't show it again. */
export function markDisplayWarningShown(packageId: string): void {
const warned = displayWarnedPackages();
if (warned.includes(packageId)) return;
setStringSetting(DISPLAY_WARNED_KEY, JSON.stringify([...warned, packageId]));
}
function displayWarnedPackages(): string[] {
try {
const parsed: unknown = JSON.parse(getStringSetting(DISPLAY_WARNED_KEY, "[]"));
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
} catch {
return [];
}
}
+14 -1
View File
@@ -5,6 +5,9 @@
* a phone WebView (its runtime + phone UI) and a 576x288 glasses window
* composited by Faceclaw instead of the stock firmware.
*
* With a RayNeo iO paired the store is unavailable and sideloaded apps warn
* on first run that they won't display correctly; see glasses-compat.ts.
*
* Design notes: notes/evenhub_compatibility.txt.
*/
import { type AppContext, type AppDefinition } from "../app-definition";
@@ -15,6 +18,7 @@ import { createInProcessWindow, type InProcessWindow } from "../../ui/shell/in-p
import { renderEvenRealitiesLogo } from "../../graphics/even-realities-logo";
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
import { type InstalledEvenHubApp } from "./installed-apps";
import { isEvenHubStoreAvailable } from "./glasses-compat";
const EVENHUB_STORE_WINDOW_ID = "evenhub:store";
const EVENHUB_STORE_SURFACE_ID = "window:evenhub:store";
@@ -104,8 +108,17 @@ const evenhubApp: AppDefinition = {
title: "EvenHub",
icon: "package",
renderIcon: renderEvenRealitiesLogo,
// Off the launcher with a RayNeo iO paired. A store window that opens
// anyway (restored from before a re-pair, or the launcher's route for an
// installed app whose package is missing) says why instead of loading.
isSupported: isEvenHubStoreAvailable,
launch: async (ctx) => {
await ensureStoreWindow(ctx);
const { window } = await ensureStoreWindow(ctx);
if (!isEvenHubStoreAvailable()) {
// Store pages opened while Even glasses were paired would cover the notice.
window.stack.clearToBase();
window.requestRender();
}
},
};
+31 -180
View File
@@ -1,17 +1,11 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { truncateText, wrapText } from "../../graphics/textwrap";
import { type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { drawListScrollbar, drawSelectionHighlight } from "../../ui/menu";
import { type LayerContext } from "../../ui/layers";
import { permissionDetail, permissionLabel, type EvenHubPermission } from "./permissions";
import { openPrivacyPolicyOnPhone } from "./privacy-policy";
import { lineStep, listRowHeight } from "../../ui/metrics";
import { lineStep } from "../../ui/metrics";
import { ScrollingDialogLayer, type DialogBody, type DialogRow } from "./scrolling-dialog";
/** Minimum gap between the dialog and the edges of the window it's centered in. */
const DIALOG_MARGIN = 8;
const DIALOG_WIDTH = 320;
const PADDING = 10;
const PERM_GAP = 4;
/**
@@ -20,59 +14,26 @@ const PERM_GAP = 4;
* Cancel (or double-click) backs out. A privacy-policy-only app still reaches
* this dialog so the user can review the policy before allowing first run.
*
* When the list overflows the viewport the dialog scrolls a page at a time,
* keeping one line of overlap (the last line of one page is the first of the
* next), and only once the bottom is fully visible do further scrolls move the
* action selection. The actions are inert until then (a click just pages
* down), so the user can't Allow without having had the whole list on screen.
* A long list scrolls a page at a time, and Allow stays inert until the
* bottom has been reached (see ScrollingDialogLayer), so the user can't
* Allow without having had the whole list on screen.
*/
export class EvenHubPermissionDialogLayer implements Layer {
/** Floats in front of the window content, like the context menus. */
readonly depth = 2;
/** Starts on Allow; the optional privacy-policy action is inserted after it. */
private selectedIndex = 0;
/** First content row drawn; rows above it are scrolled off. */
private firstRow = 0;
/** Scroll position at which the last row is fully visible; set by paint. */
private maxFirstRow = 0;
/** Heights of the content rows and of the viewport they scroll in, as last painted (for paging). */
private rowHeights: number[] = [];
private visibleHeight = 0;
private resolved = false;
export class EvenHubPermissionDialogLayer extends ScrollingDialogLayer {
constructor(
private readonly appName: string,
private readonly permissions: EvenHubPermission[],
private readonly privacyPolicyUrl: string,
private readonly onConfirm: () => void,
private readonly onCancel: () => void,
) {}
/** Whether the dialog is scrolled to the bottom, making the actions live. */
private atBottom(): boolean {
return this.firstRow >= this.maxFirstRow;
) {
super(DIALOG_WIDTH);
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const font = getDefaultSmallFont();
const { width: viewportWidth, height: viewportHeight } = ctx.stack.getBaseSize();
const image = paintBelow();
const dialogWidth = Math.min(DIALOG_WIDTH, viewportWidth - 2 * DIALOG_MARGIN);
const dialogX = ((viewportWidth - dialogWidth) / 2) | 0;
const textWidth = dialogWidth - 2 * PADDING - 4;
const left = dialogX + PADDING + 2;
protected bodyRows({ image, font, left, textWidth }: DialogBody): DialogRow[] {
const headerStep = lineStep(font) + 2;
const permLabelStep = lineStep(font) + 1;
const permDetailStep = lineStep(font) - 1;
const actionRowH = listRowHeight(font);
const actions = this.actions();
const focused = ctx.stack.isFocused();
// The dialog body as scrollable rows; each row's height includes the gap
// below it, so scrolling and visibility checks work on whole rows.
type Row = { height: number; draw: (top: number) => void };
const rows: Row[] = [];
const rows: DialogRow[] = [];
const heading = this.permissions.length ? `${this.appName} needs:` : `${this.appName} is ready to run`;
rows.push({
height: headerStep + 6,
@@ -101,138 +62,28 @@ export class EvenHubPermissionDialogLayer implements Layer {
});
}
}
for (let index = 0; index < actions.length; index++) {
rows.push({
height: actionRowH,
draw: (top) => {
const selected = this.atBottom() && index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, dialogX + 12, top, dialogWidth - 24, actionRowH - 1, focused, 8);
}
image.drawText(font, dialogX + 22, top + 3, actions[index]!, selected ? 255 : 200);
},
});
}
const contentHeight = rows.reduce((sum, row) => sum + row.height, 0);
const height = Math.min(contentHeight + 2 * PADDING, viewportHeight - 2 * DIALOG_MARGIN);
const dialogY = ((viewportHeight - height) / 2) | 0;
const visibleHeight = height - 2 * PADDING;
// The bottommost scroll position: the largest suffix of rows that fits.
let maxFirstRow = rows.length;
for (let suffixHeight = 0; maxFirstRow > 0; maxFirstRow--) {
const rowHeight = rows[maxFirstRow - 1]!.height;
if (suffixHeight + rowHeight > visibleHeight) break;
suffixHeight += rowHeight;
}
this.maxFirstRow = maxFirstRow;
this.firstRow = Math.max(0, Math.min(this.firstRow, maxFirstRow));
this.rowHeights = rows.map((row) => row.height);
this.visibleHeight = visibleHeight;
// Fill 1 (transparent color key is 0), outline for the dialog edge.
image.fillRoundedRect(dialogX, dialogY, dialogWidth, height, 1);
image.drawRoundedRect(dialogX, dialogY, dialogWidth, height, 72);
let y = dialogY + PADDING;
for (let index = this.firstRow; index < rows.length; index++) {
const row = rows[index]!;
if (y + row.height > dialogY + PADDING + visibleHeight) break;
row.draw(y);
y += row.height;
}
if (maxFirstRow > 0) {
drawListScrollbar(
image,
dialogX + dialogWidth - 7,
dialogY + PADDING,
visibleHeight,
this.firstRow,
rows.length - maxFirstRow,
rows.length,
);
}
return image;
return rows;
}
handleInput(event: InputEvent, ctx: LayerContext): void {
const actions = this.actions();
switch (event.type) {
case "scroll-up":
if (this.atBottom() && this.selectedIndex > 0) {
this.selectedIndex -= 1;
} else if (this.firstRow > 0) {
this.pageUp();
}
return;
case "scroll-down":
if (!this.atBottom()) {
this.pageDown();
} else {
this.selectedIndex = Math.min(actions.length - 1, this.selectedIndex + 1);
}
return;
case "click":
if (!this.atBottom()) {
this.pageDown();
return;
}
if (actions[this.selectedIndex] === "Privacy policy") {
openPrivacyPolicyOnPhone(this.privacyPolicyUrl, this.appName);
} else {
this.resolve(ctx, actions[this.selectedIndex] === "Allow");
}
return;
case "double-click":
this.resolve(ctx, false);
return;
default:
return;
}
}
/** Scroll so the last fully visible row becomes the first (one row of overlap). */
private pageDown(): void {
let y = 0;
let lastVisible = this.firstRow;
for (let index = this.firstRow; index < this.rowHeights.length; index++) {
y += this.rowHeights[index]!;
if (y > this.visibleHeight) break;
lastVisible = index;
}
this.firstRow = Math.min(this.maxFirstRow, Math.max(this.firstRow + 1, lastVisible));
}
/** Scroll so the current first row becomes the last fully visible one (one row of overlap). */
private pageUp(): void {
let first = this.firstRow;
let y = this.rowHeights[first] ?? 0;
while (first > 0 && y + this.rowHeights[first - 1]! <= this.visibleHeight) {
first -= 1;
y += this.rowHeights[first]!;
}
this.firstRow = Math.max(0, Math.min(this.firstRow - 1, first));
}
onRemoved(): void {
// Dismissed some other way (window closed, back button): treat as cancel.
if (!this.resolved) {
this.resolved = true;
this.onCancel();
}
}
private resolve(ctx: LayerContext, confirmed: boolean): void {
if (this.resolved) return;
this.resolved = true;
ctx.stack.pop();
if (confirmed) this.onConfirm();
else this.onCancel();
}
private actions(): string[] {
protected actions(): string[] {
return this.privacyPolicyUrl ? ["Allow", "Privacy policy", "Cancel"] : ["Allow", "Cancel"];
}
protected activate(action: string, ctx: LayerContext): void {
if (action === "Privacy policy") {
openPrivacyPolicyOnPhone(this.privacyPolicyUrl, this.appName);
} else if (action === "Allow") {
this.close(ctx, () => this.onConfirm());
} else {
this.close(ctx, () => this.onCancel());
}
}
protected backedOut(): void {
this.onCancel();
}
protected abandoned(): void {
this.onCancel();
}
}
+201
View File
@@ -0,0 +1,201 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { type GrayImage, type UiFont } from "../../graphics/image";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { drawListScrollbar, drawSelectionHighlight } from "../../ui/menu";
import { listRowHeight } from "../../ui/metrics";
/** Minimum gap between the dialog and the edges of the window it's centered in. */
const DIALOG_MARGIN = 8;
const PADDING = 10;
/** One row of a dialog's content. Its height includes the gap below it, so scrolling works on whole rows. */
export type DialogRow = { height: number; draw: (top: number) => void };
/** What a dialog's body rows draw with: the canvas, the font, and the text column. */
export type DialogBody = { image: GrayImage; font: UiFont; left: number; textWidth: number };
/**
* A dialog box centered over the window it opens in: body rows, then a
* column of actions, starting on the first. EvenHub's confirmations and
* warnings (permissions, the RayNeo iO display warning) are built on it.
*
* When the content overflows the viewport the dialog scrolls a page at a
* time, keeping one line of overlap (the last line of one page is the first
* of the next), and only once the bottom is fully visible do further scrolls
* move the action selection. The actions are inert until then (a click just
* pages down), so nothing can be chosen without the whole dialog having been
* on screen. Double-click backs out.
*/
export abstract class ScrollingDialogLayer implements Layer {
/** Floats in front of the window content, like the context menus. */
readonly depth = 2;
private selectedIndex = 0;
/** First content row drawn; rows above it are scrolled off. */
private firstRow = 0;
/** Scroll position at which the last row is fully visible; set by paint. */
private maxFirstRow = 0;
/** Heights of the content rows and of the viewport they scroll in, as last painted (for paging). */
private rowHeights: number[] = [];
private visibleHeight = 0;
private resolved = false;
constructor(private readonly maxWidth: number) {}
/** The rows above the actions. */
protected abstract bodyRows(body: DialogBody): DialogRow[];
/** The action labels, top to bottom. */
protected abstract actions(): string[];
/** A click on an action once the actions are live; close() dismisses the dialog with it. */
protected abstract activate(action: string, ctx: LayerContext): void;
/** Double-click: the user backed out of the dialog. */
protected abstract backedOut(): void;
/** The dialog left the stack unanswered (its window closed). */
protected abstract abandoned(): void;
/** Whether the dialog is scrolled to the bottom, making the actions live. */
private atBottom(): boolean {
return this.firstRow >= this.maxFirstRow;
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const font = getDefaultSmallFont();
const { width: viewportWidth, height: viewportHeight } = ctx.stack.getBaseSize();
const image = paintBelow();
const dialogWidth = Math.min(this.maxWidth, viewportWidth - 2 * DIALOG_MARGIN);
const dialogX = ((viewportWidth - dialogWidth) / 2) | 0;
const textWidth = dialogWidth - 2 * PADDING - 4;
const left = dialogX + PADDING + 2;
const actionRowH = listRowHeight(font);
const actions = this.actions();
const focused = ctx.stack.isFocused();
const rows = this.bodyRows({ image, font, left, textWidth });
for (let index = 0; index < actions.length; index++) {
rows.push({
height: actionRowH,
draw: (top) => {
const selected = this.atBottom() && index === this.selectedIndex;
if (selected) {
drawSelectionHighlight(image, dialogX + 12, top, dialogWidth - 24, actionRowH - 1, focused, 8);
}
image.drawText(font, dialogX + 22, top + 3, actions[index]!, selected ? 255 : 200);
},
});
}
const contentHeight = rows.reduce((sum, row) => sum + row.height, 0);
const height = Math.min(contentHeight + 2 * PADDING, viewportHeight - 2 * DIALOG_MARGIN);
const dialogY = ((viewportHeight - height) / 2) | 0;
const visibleHeight = height - 2 * PADDING;
// The bottommost scroll position: the largest suffix of rows that fits.
let maxFirstRow = rows.length;
for (let suffixHeight = 0; maxFirstRow > 0; maxFirstRow--) {
const rowHeight = rows[maxFirstRow - 1]!.height;
if (suffixHeight + rowHeight > visibleHeight) break;
suffixHeight += rowHeight;
}
this.maxFirstRow = maxFirstRow;
this.firstRow = Math.max(0, Math.min(this.firstRow, maxFirstRow));
this.rowHeights = rows.map((row) => row.height);
this.visibleHeight = visibleHeight;
// Fill 1 (transparent color key is 0), outline for the dialog edge.
image.fillRoundedRect(dialogX, dialogY, dialogWidth, height, 1);
image.drawRoundedRect(dialogX, dialogY, dialogWidth, height, 72);
let y = dialogY + PADDING;
for (let index = this.firstRow; index < rows.length; index++) {
const row = rows[index]!;
if (y + row.height > dialogY + PADDING + visibleHeight) break;
row.draw(y);
y += row.height;
}
if (maxFirstRow > 0) {
drawListScrollbar(
image,
dialogX + dialogWidth - 7,
dialogY + PADDING,
visibleHeight,
this.firstRow,
rows.length - maxFirstRow,
rows.length,
);
}
return image;
}
handleInput(event: InputEvent, ctx: LayerContext): void {
const actions = this.actions();
switch (event.type) {
case "scroll-up":
if (this.atBottom() && this.selectedIndex > 0) {
this.selectedIndex -= 1;
} else if (this.firstRow > 0) {
this.pageUp();
}
return;
case "scroll-down":
if (!this.atBottom()) {
this.pageDown();
} else {
this.selectedIndex = Math.min(actions.length - 1, this.selectedIndex + 1);
}
return;
case "click":
if (!this.atBottom()) {
this.pageDown();
return;
}
this.activate(actions[this.selectedIndex]!, ctx);
return;
case "double-click":
this.close(ctx, () => this.backedOut());
return;
default:
return;
}
}
/** Scroll so the last fully visible row becomes the first (one row of overlap). */
private pageDown(): void {
let y = 0;
let lastVisible = this.firstRow;
for (let index = this.firstRow; index < this.rowHeights.length; index++) {
y += this.rowHeights[index]!;
if (y > this.visibleHeight) break;
lastVisible = index;
}
this.firstRow = Math.min(this.maxFirstRow, Math.max(this.firstRow + 1, lastVisible));
}
/** Scroll so the current first row becomes the last fully visible one (one row of overlap). */
private pageUp(): void {
let first = this.firstRow;
let y = this.rowHeights[first] ?? 0;
while (first > 0 && y + this.rowHeights[first - 1]! <= this.visibleHeight) {
first -= 1;
y += this.rowHeights[first]!;
}
this.firstRow = Math.max(0, Math.min(this.firstRow - 1, first));
}
onRemoved(): void {
// Dismissed some other way (window closed, back button).
if (!this.resolved) {
this.resolved = true;
this.abandoned();
}
}
/** Take the dialog down, then run the answer's effect (once, however it was answered). */
protected close(ctx: LayerContext, then: () => void): void {
if (this.resolved) return;
this.resolved = true;
ctx.stack.pop();
then();
}
}
+38 -2
View File
@@ -14,6 +14,7 @@ import { EvenHubStoreDetailLayer, type EvenHubStoreDetailOptions } from "./store
import { cleanError, installStoreApp } from "./store-install";
import { checkForEvenHubUpdates, describeUpdate, type EvenHubAppUpdate } from "./updates";
import { lineStep } from "../../ui/metrics";
import { isEvenHubStoreAvailable } from "./glasses-compat";
const LIST_X = 18;
/** Horizontal gap between tab labels. */
@@ -145,6 +146,11 @@ export type EvenHubStoreLayerOptions = {
* missing). The tab row is its own focus level above the list: double-click
* in the list focuses the tabs, scrolling (or a watch swipe in any direction)
* there switches tabs, and a click returns to the list.
*
* With glasses that can't use the store (a RayNeo iO; see glasses-compat.ts)
* it shows only a notice saying so, and loads nothing. That is checked on
* every paint and input, so a window open across a re-pair follows the
* glasses either way.
*/
export class EvenHubStoreLayer implements Layer {
/** Swipes left/right switch tabs on the tab strip; elsewhere they get the usual fallback. */
@@ -168,12 +174,15 @@ export class EvenHubStoreLayer implements Layer {
private updatingAll = false;
/** An app page requested while the login form was up; opened once signed in. */
private pendingPackage: InstalledEvenHubApp | null = null;
/** An app page requested while the store was unavailable, named on its notice. */
private unavailablePackageName: string | null = null;
constructor(private readonly options: EvenHubStoreLayerOptions) {
if (this.showingLogin) resetEvenHubLoginForm();
}
paint(ctx: LayerContext): GrayImage {
if (!isEvenHubStoreAvailable()) return this.paintUnavailable(ctx);
if (!this.started) {
this.started = true;
// Do NOT open the phone credential editor here. This runs on the first
@@ -233,6 +242,23 @@ export class EvenHubStoreLayer implements Layer {
return image;
}
/** The notice that replaces the store when the paired glasses can't use it. */
private paintUnavailable(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
image.drawText(font, LIST_X, 8, "EvenHub", 220);
if (this.unavailablePackageName) {
const status = `${this.unavailablePackageName}'s package is missing.`;
image.drawText(font, LIST_X, 8 + lineStep(font), truncateText(font, status, width - LIST_X * 2), 125);
}
const message = "Using the Even Realities app store requires Even Realities glasses.";
for (const [index, line] of wrapText(font, message, width - LIST_X * 2).entries()) {
image.drawText(font, LIST_X, headerHeight(font) + 16 + index * lineStep(font), line, 190);
}
return image;
}
/** Tab labels to the right of the title; the active one is bright and underlined. */
private paintTabs(image: GrayImage, font: UiFont, ctx: LayerContext): void {
const tabsFocused = ctx.stack.isFocused() && this.focus === "tabs";
@@ -294,6 +320,10 @@ export class EvenHubStoreLayer implements Layer {
}
async handleInput(rawEvent: InputEvent, ctx: LayerContext): Promise<void> {
if (!isEvenHubStoreAvailable()) {
if (directionalFallback(rawEvent).type === "double-click") shell.yieldFocusToSidebar();
return;
}
const tabSwipe = !this.showingLogin && this.focus === "tabs"
&& (rawEvent.type === "swipe-left" || rawEvent.type === "swipe-right");
const event = isDirectionalInput(rawEvent) && !tabSwipe ? directionalFallback(rawEvent) : rawEvent;
@@ -396,6 +426,12 @@ export class EvenHubStoreLayer implements Layer {
* placeholder built from the registry entry stands in.
*/
showInstalledPackage(stack: LayerStack, installed: InstalledEvenHubApp): void {
if (!isEvenHubStoreAvailable()) {
this.unavailablePackageName = installed.name;
stack.clearToBase();
return;
}
this.unavailablePackageName = null;
if (this.showingLogin) {
this.pendingPackage = installed;
return;
@@ -407,7 +443,7 @@ export class EvenHubStoreLayer implements Layer {
/** Dictated text becomes a search (the shell's "Type Into App" / voice input). */
receiveTextInput(text: string, ctx: LayerContext): void {
if (this.showingLogin) return;
if (this.showingLogin || !isEvenHubStoreAvailable()) return;
const query = evenHubSearchQuerySetting.set(text);
if (!query) return;
this.closePhoneEditor(ctx.actions, "search");
@@ -417,7 +453,7 @@ export class EvenHubStoreLayer implements Layer {
}
buildMenuItems(): MenuItem[] {
if (this.showingLogin) return [];
if (this.showingLogin || !isEvenHubStoreAvailable()) return [];
const items: MenuItem[] = [];
if (this.activeTab === "search") {
items.push({
+2 -1
View File
@@ -18,6 +18,7 @@ import {
batteryIndicatorVisible,
ConfigSettingBoolean,
glassesBatteryVisibilitySetting,
glassesModelName,
onAnySettingChanged,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
@@ -328,7 +329,7 @@ function collectBatteryItems(): BatteryItem[] {
push(phoneBatteryVisibilitySetting.get(), "Phone", "phone", phone.battery, phone.charging);
const levels = shell.getBatteryLevels();
push(watchBatteryVisibilitySetting.get(), "Watch", "watch", levels.watch, levels.watchCharging);
push(glassesBatteryVisibilitySetting.get(), "G2", "glasses", levels.headset, levels.headsetCharging);
push(glassesBatteryVisibilitySetting.get(), glassesModelName(), "glasses", levels.headset, levels.headsetCharging);
if (levels.ring !== null && Number.isInteger(levels.ring) && levels.ring >= 0 && levels.ring <= 100) {
push(ringBatteryVisibilitySetting.get(), "R1", "ring", levels.ring, levels.ringCharging);
}
+13 -2
View File
@@ -1,6 +1,7 @@
/**
* Finding a G1's arms by listening for them. That's how an install knows what each arm runs before connecting to it,
* and how it finds an arm again afterwards: an arm coming off Even's firmware has a new address.
* and how it finds an arm again afterwards, when it advertises what it runs now (and, coming from g1v0 before 0.5.66, at
* a new address).
*/
import { classifyAdvertisement, type EvenAdvertisement } from "../g2/even-advertisement";
import { DiscoveryAggregator, type GlassesPairCandidate } from "../g2/pairing-candidates";
@@ -27,11 +28,21 @@ export class G1ArmScanner {
/** Resolves when an arm of this side on g1v0 is heard, or null after [timeoutMs]. */
waitForG1v0Arm(side: G1Side, serial: string | null | undefined, timeoutMs: number): Promise<EvenAdvertisement | null> {
return this.waitForArm(side, serial, timeoutMs, (arm) => arm.g1Firmware !== "stock");
}
/** Resolves when an arm of this side is heard that [accept] takes, on any firmware, or null after [timeoutMs]. */
waitForArm(
side: G1Side,
serial: string | null | undefined,
timeoutMs: number,
accept: (arm: EvenAdvertisement) => boolean,
): Promise<EvenAdvertisement | null> {
const startedAt = Date.now();
const others = new Map<string, EvenAdvertisement>();
return this.listen<EvenAdvertisement>(timeoutMs, (raw, done) => {
const arm = classifyAdvertisement(raw);
if (!arm || arm.role !== side || !arm.g1Firmware || arm.g1Firmware === "stock") return;
if (!arm || arm.role !== side || !arm.g1Firmware || !accept(arm)) return;
if (!serial || sameG1Serial(arm.serial, serial)) {
done(arm);
return;
+21
View File
@@ -0,0 +1,21 @@
/**
* Even's official G1 firmware, which an uninstall puts back: both images of one public release, the application core's
* and the network core's (the Bluetooth controller), as Even's own update installs them, so the two always match.
* From Even's CDN, checked against these SHA-256 sums (scouter_kit g1_firmware/stock_images.txt). Every public image
* says 0.0.0 in its MCUboot header, so the hashes are the only way to tell releases apart.
*/
export type EvenG1Release = {
version: string;
zipUrl: string;
zipSha256: string;
appSha256: string;
netCoreSha256: string;
};
export const EVEN_G1_RESTORE: EvenG1Release = {
version: "1.6.6",
zipUrl: "https://cdn.evenreal.co/firmware/dcfa510c090e476c10a6f6c348a22415.zip",
zipSha256: "748836f2d9d092b0783cbb7672fdccec4f730051cad27f095bbb156ac3e5d316",
appSha256: "ae032838e27037156da98e19de90df78f5406715751f3b38adf50498db3010c1",
netCoreSha256: "c277749be97a2763742db399afeb10ca6916059abd60d41bbc05c8892c002c77",
};
+26 -5
View File
@@ -1,29 +1,34 @@
/**
* Prepares the g1v0 image on the phone, as app/g2/firmware-builder.ts does for a G2: downloads Even's public firmware,
* checks it, and puts the parts this firmware embeds back into what the app ships. The result is byte for byte the
* image that was built, tested and signed, and it is checked to be. It does not touch the glasses.
* image that was built, tested and signed, and it is checked to be. Also prepares Even's own images for an uninstall.
* It does not touch the glasses.
*/
import { knownFolders } from "@nativescript/core";
import { firmwareSha256, writeFirmwareFile } from "../native/firmware-files";
import { decodeBase64 } from "../util/base64";
import { fetchWithUserAgent } from "../util/http";
import { EVEN_G1_RESTORE } from "./even-firmware";
import { G1V0_IMAGE } from "./firmware/g1v0-image";
import { G1V0_OWN_BYTES_BASE64 } from "./firmware/g1v0-own-bytes";
import { assembleG1Image, decodeG1OwnBytes, G1FirmwareError, readZipEntry } from "./firmware-image";
import { assembleG1Image, decodeG1OwnBytes, extractEvenG1Images, G1FirmwareError, readZipEntry } from "./firmware-image";
export type G1BuildProgress = "downloading" | "verifying" | "assembling" | "writing";
export type BuiltG1Firmware = { path: string; bytes: number; version: string };
/** Even's release for an uninstall: the application core's image and the network core's. */
export type BuiltEvenG1Firmware = { appPath: string; netCorePath: string; bytes: number; version: string };
function sha256(bytes: Uint8Array): string {
return firmwareSha256(bytes.slice().buffer);
}
async function downloadStockZip(): Promise<Uint8Array> {
async function downloadStockZip(url: string): Promise<Uint8Array> {
let response: Response;
try {
response = await fetchWithUserAgent(G1V0_IMAGE.stockZipUrl);
response = await fetchWithUserAgent(url);
} catch (error) {
throw new G1FirmwareError(`Could not reach Even's firmware server: ${(error as Error)?.message ?? error}`);
}
@@ -33,7 +38,7 @@ async function downloadStockZip(): Promise<Uint8Array> {
export async function buildG1Firmware(onProgress?: (progress: G1BuildProgress) => void): Promise<BuiltG1Firmware> {
onProgress?.("downloading");
const zip = await downloadStockZip();
const zip = await downloadStockZip(G1V0_IMAGE.stockZipUrl);
onProgress?.("verifying");
const zipHash = sha256(zip);
@@ -50,3 +55,19 @@ export async function buildG1Firmware(onProgress?: (progress: G1BuildProgress) =
writeFirmwareFile(path, image.slice().buffer);
return { path, bytes: image.length, version: G1V0_IMAGE.version };
}
export async function buildEvenG1Firmware(onProgress?: (progress: G1BuildProgress) => void): Promise<BuiltEvenG1Firmware> {
onProgress?.("downloading");
const zip = await downloadStockZip(EVEN_G1_RESTORE.zipUrl);
onProgress?.("verifying");
const { app, netCore } = extractEvenG1Images(zip, EVEN_G1_RESTORE, sha256);
onProgress?.("writing");
const folder = knownFolders.documents().path;
const appPath = `${folder}/even_g1_${EVEN_G1_RESTORE.version}_app.bin`;
const netCorePath = `${folder}/even_g1_${EVEN_G1_RESTORE.version}_net.bin`;
writeFirmwareFile(appPath, app.slice().buffer);
writeFirmwareFile(netCorePath, netCore.slice().buffer);
return { appPath, netCorePath, bytes: app.length + netCore.length, version: EVEN_G1_RESTORE.version };
}
+26
View File
@@ -4,6 +4,7 @@
*/
import { inflate, inflateRaw } from "pako";
import type { EvenG1Release } from "./even-firmware";
import type { G1FirmwareImage } from "./firmware/g1v0-image";
export class G1FirmwareError extends Error {}
@@ -41,6 +42,31 @@ export function readZipEntry(zip: Uint8Array, name: string): Uint8Array {
throw new G1FirmwareError(`The firmware download has no ${name}.`);
}
/**
* The two images of Even's release from its download, each checked by its own SHA-256 as well as the zip's, so what
* goes to the arms is byte for byte what Even published.
*/
export function extractEvenG1Images(
zip: Uint8Array,
release: EvenG1Release,
sha256: (bytes: Uint8Array) => string,
): { app: Uint8Array; netCore: Uint8Array } {
const zipHash = sha256(zip);
if (zipHash !== release.zipSha256) {
throw new G1FirmwareError(`Even's firmware download failed verification.\nexpected ${release.zipSha256}\ngot ${zipHash}`);
}
const checked = (name: string, want: string) => {
const bytes = readZipEntry(zip, name);
const got = sha256(bytes);
if (got !== want) throw new G1FirmwareError(`${name} in Even's download failed verification.\nexpected ${want}\ngot ${got}`);
return bytes;
};
return {
app: checked("app_update.bin", release.appSha256),
netCore: checked("net_core_app_update.bin", release.netCoreSha256),
};
}
export function decodeG1OwnBytes(base64: string, decode: (text: string) => Uint8Array): Uint8Array {
return inflate(decode(base64));
}
+16 -5
View File
@@ -1,11 +1,15 @@
/** What installing firmware on a G1 has to decide. No I/O. */
import type { GlassesPairCandidate } from "../g2/pairing-candidates";
import { EVEN_G1_RESTORE } from "./even-firmware";
export type G1Side = "left" | "right";
/** Left first: a right arm on g1v0 next to a left arm on Even's firmware would leave the left eye dark. */
export const G1_SIDES: readonly G1Side[] = ["left", "right"];
/** Going back, right first, for the same reason: halfway, the pair is as halfway through an install. */
export const G1_UNINSTALL_SIDES: readonly G1Side[] = ["right", "left"];
export const G1_CASE_INSTRUCTIONS =
"Put the glasses in their charging case with the lid open, and plug the case in. Stay nearby, and leave Faceclaw open.";
@@ -14,13 +18,20 @@ export const G1_CASE_DELAY_HINT =
"A fully charged arm can take up to 5 minutes to notice it's in the case, so this may take a while.";
export const G1_INSTALL_NOTICE =
"This replaces the firmware on both arms, about two minutes each. Going back to Even's firmware later takes a computer, and " +
"may not be the version you have now. Installing custom firmware is not covered by warranty.";
"This replaces the firmware on both arms, about two minutes each. Faceclaw can put Even's firmware back later, but as version " +
`${EVEN_G1_RESTORE.version}, which may not be the version you have now. Installing custom firmware is not covered by warranty.`;
export const G1_UNINSTALL_NOTICE =
`This puts Even's official firmware ${EVEN_G1_RESTORE.version} back on both arms, Bluetooth controller included, a few minutes ` +
"each. It may not be the version they came with. Afterwards they work with Even's app again, and not with Faceclaw until you " +
"install its firmware again.";
/** What the native flow says when it finishes (G1ArmFlashFlow). */
export type G1FlashResult = {
flashed?: boolean;
firmware?: "g1v0" | "stock";
/** A restore erased g1v0's asset store, where Even's fonts and pictures were. */
wiped?: boolean;
version?: string;
safeMode?: boolean;
inCase?: boolean;
@@ -102,8 +113,8 @@ export function g1StateFromAdvertising(
return { state: compareG1Versions(lowest, shipped) < 0 ? "older" : "current", version: lowest };
}
/** Each arm counts for half of the bar. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number): number {
/** Each arm counts for half of the bar, in the order they're done. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number, order: readonly G1Side[] = G1_SIDES): number {
const within = bytesTotal > 0 ? Math.min(1, bytesSent / bytesTotal) : 0;
return ((side === "right" ? 1 + within : within) / 2) * 100;
return ((order.indexOf(side) + within) / 2) * 100;
}
+1 -14
View File
@@ -27,7 +27,7 @@
*
* It is **not** a measurement. A hand over the temple, a pocket, or a body
* between phone and glasses moves the estimate by metres. The wearer therefore
* only ever sees a coarse zone (glyph + label), never a number in metres they
* only ever sees a coarse zone (a signal-strength glyph), never a number in metres they
* might over-trust; the metres value exists purely to rank and bucket.
*
* This module is pure (no NativeScript imports) so it can run under node tests.
@@ -75,19 +75,6 @@ export function zoneFromMeters(meters: number): ProximityZone {
return "distant";
}
export function zoneLabel(zone: ProximityZone): string {
switch (zone) {
case "immediate":
return "In your hand";
case "near":
return "Nearby";
case "far":
return "Across the room";
case "distant":
return "Far away";
}
}
/** A glyph for the zone; SF Symbols have no Android equivalent, so plain text. */
export function zoneGlyph(zone: ProximityZone): string {
switch (zone) {
+2 -1
View File
@@ -77,7 +77,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
import { appViewportRect, isOnSwitcherEdge, screenHeight, screenWidth, sidebarStripVisible, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry";
import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { appSwitcherPositionSetting, glassesTypeSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, effectiveRingConnectionMode, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, shouldPopUpNewNotification, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { appSwitcherPositionSetting, glassesModelName, glassesTypeSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, effectiveRingConnectionMode, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, shouldPopUpNewNotification, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -1267,6 +1267,7 @@ class DashboardController {
silentMode: this.silentMode,
screenOn: shell.isScreenOn(),
battery: this.lastHeadsetBattery,
glassesModel: glassesModelName(),
caseBattery: batteries.case,
caseCharging: batteries.caseCharging,
foregroundTitle: shell.getForegroundApp()?.title ?? null,
+10 -8
View File
@@ -3,6 +3,8 @@ export type GlassesDisplayState = {
silentMode: boolean;
screenOn: boolean;
battery: number | null;
/** The paired glasses' model, e.g. "G2" (glassesModelName). */
glassesModel: string;
/**
* The charging case's last-known level, and whether it is on USB (null
* while the glasses are out of the case). Shown only while charging, when
@@ -20,7 +22,7 @@ export function glassesDisplayLabel(state: GlassesDisplayState): string {
// Charging wins over every session-local state: the glasses are in their
// case, so neither the lock screen nor the foreground window is visible.
if (state.phase === "charging") {
return chargingDisplayLabel(state.battery);
return chargingDisplayLabel(state.battery, state.glassesModel);
}
// Preview mode has a live (simulated) screen despite the disconnected
// phase, so fall through to the screen-state/foreground labels.
@@ -63,8 +65,8 @@ export function glassesDisplayAsleep(state: GlassesDisplayState): boolean {
);
}
export function chargingDisplayLabel(battery: number | null): string {
return validBatteryLevel(battery) ? `Charging · G2 ${battery}%` : "Charging";
export function chargingDisplayLabel(battery: number | null, glassesModel: string): string {
return validBatteryLevel(battery) ? `Charging: ${glassesModel} ${battery}%` : "Charging";
}
/** The shell's last-known battery levels (ShellChromeState["battery"]), as far as the phone shows them. */
@@ -81,13 +83,13 @@ export type BatteryLevels = {
* The phone Settings tab's battery row: each device whose level is known,
* e.g. "G2 100% · Case 98% ⚡ · R1 72%" (⚡ = charging), or "" when none
* is. Levels are the last known ones (the case only reports while the glasses
* are docked), so ⚡ appears only while it is live: G2 and Case only with a
* link to the glasses (`glassesLinked`: connected or charging), and Case only
* while they are docked (caseCharging is null otherwise).
* are docked), so ⚡ appears only while it is live: the glasses and Case only
* with a link to the glasses (`glassesLinked`: connected or charging), and Case
* only while they are docked (caseCharging is null otherwise).
*/
export function formatBatteryLine(levels: BatteryLevels, glassesLinked: boolean): string {
export function formatBatteryLine(levels: BatteryLevels, glassesLinked: boolean, glassesModel: string): string {
const devices: Array<[string, number | null, boolean | null]> = [
["G2", levels.headset, glassesLinked && levels.headsetCharging],
[glassesModel, levels.headset, glassesLinked && levels.headsetCharging],
["Case", levels.case, glassesLinked && levels.caseCharging],
["R1", levels.ring, levels.ringCharging],
];
+1 -4
View File
@@ -16,7 +16,6 @@ import {
RING_CALIBRATION,
sortedByProximity,
zoneGlyph,
zoneLabel,
type ProximityEstimate,
type ProximityZone,
} from "./ble-proximity";
@@ -329,7 +328,6 @@ export type PairingRowPresentation = {
isPreviouslyPaired: boolean;
/** "Yours" / "Closest" / "". */
badge: string;
proximitySummary: string;
proximityGlyph: string;
zone: ProximityZone | null;
/** "Left + right arms found", "Only the left arm has been seen", …; "" when there is nothing worth a line (an unbonded ring). */
@@ -355,12 +353,11 @@ function presentationBase(
isNearest: boolean,
isPaired: boolean,
warnings: readonly string[],
): Pick<PairingRowPresentation, "isNearest" | "isPreviouslyPaired" | "badge" | "proximitySummary" | "proximityGlyph" | "zone" | "warning"> {
): Pick<PairingRowPresentation, "isNearest" | "isPreviouslyPaired" | "badge" | "proximityGlyph" | "zone" | "warning"> {
return {
isNearest,
isPreviouslyPaired: isPaired,
badge: isPaired ? "Yours" : isNearest ? "Closest" : "",
proximitySummary: proximity ? zoneLabel(proximity.zone) : "Signal unknown",
proximityGlyph: proximity ? zoneGlyph(proximity.zone) : "○○○○",
zone: proximity?.zone ?? null,
warning: warnings.join(" "),
+2
View File
@@ -32,6 +32,7 @@ import { type AppDefinition } from "../apps/app-definition";
import { getInstalledEvenHubApps, installedEvenHubAppId } from "../apps/evenhub/installed-apps";
import { WEAR_PATHS, wearBridge, type WearMessage } from "../native/wear-bridge";
import {
glassesModelName,
onAnySettingChanged,
watchCanUnlockSetting,
watchCrownClockwiseNextSetting,
@@ -294,6 +295,7 @@ export class WearRemote {
worn: state.glassesWorn,
listening: voiceActivity.isActive(),
battery: state.lastHeadsetBattery,
glassesModel: glassesModelName(),
charging: state.phase === "charging" || battery.headsetCharging === true,
caseBattery: battery.case,
caseCharging: battery.caseCharging,
+6 -4
View File
@@ -7,8 +7,10 @@ export type { G1FlashMode, G1FlasherOptions } from './g1-flasher'
declare const FaceclawKitIosG1Flasher: any, FaceclawKitFaceclawFirmwareFlasherListener: any
/** CoreBluetooth has no way to remove a pairing; iOS Settings does it, and a stale one does no harm. */
export function forgetG1Pairing(_address: string): void {}
/** CoreBluetooth has no way to remove a pairing; iOS Settings does it. */
export function forgetG1Pairing(_address: string): boolean {
return false
}
/**
* iOS twin of the Android G1Flasher: the shared Kotlin G1ArmFlashFlow over a CoreBluetooth central. As with the G2's
@@ -47,8 +49,8 @@ export class G1Flasher {
return new Promise<G1FlashResult>((resolve, reject) => {
const identifier = iosBluetooth().peripheralIdentifier(this.options.address, this.options.side)
if (!identifier) throw new Error(`Could not find the ${this.options.side} arm. Keep the glasses in the case with the lid open.`)
this.flasher = FaceclawKitIosG1Flasher.alloc().initWithAddressSideFirmwarePathModeConnectWindowMs(
identifier, this.options.side, this.options.firmwarePath, this.options.mode, this.options.connectWindowMs)
this.flasher = FaceclawKitIosG1Flasher.alloc().initWithAddressSideFirmwarePathNetCorePathModeConnectWindowMs(
identifier, this.options.side, this.options.firmwarePath, this.options.netCorePath ?? '', this.options.mode, this.options.connectWindowMs)
this.listenerProxy = kotlinListener(FaceclawKitFaceclawFirmwareFlasherListener, {
onLogLine: (line: string) => this.logListener?.(String(line ?? '')),
onProgressLensComponentIndexComponentCountBlockIndexBlockCountBytesSentBytesTotal: (
+12 -6
View File
@@ -4,24 +4,30 @@ import { parseG1FlashResult, type G1FlashResult, type G1Side } from "../g1/flash
declare const com: any;
export type G1FlashMode = "stock" | "update" | "probe";
/** "restore": Even's firmware back on an arm running g1v0, both of its images. */
export type G1FlashMode = "stock" | "update" | "probe" | "restore";
export type G1FlasherOptions = {
address: string;
side: G1Side;
/** The application core's image. */
firmwarePath: string;
/** A restore's network-core image. */
netCorePath?: string;
mode: G1FlashMode;
/** How long to keep trying to reach the arm and pair with it. */
connectWindowMs: number;
};
/** Removes the phone's pairing with an address the glasses no longer use. */
export function forgetG1Pairing(address: string): void {
/** Removes the phone's pairing with an address, which the glasses no longer use or no longer share. False: this phone can't. */
export function forgetG1Pairing(address: string): boolean {
const context = Utils.android.getApplicationContext();
if (context) com.faceclaw.app.FaceclawG1Flasher.forgetPairing(context, address);
if (!context) return false;
com.faceclaw.app.FaceclawG1Flasher.forgetPairing(context, address);
return true;
}
/** TS wrapper around FaceclawG1Flasher: one arm's install, or a question about what it runs. */
/** TS wrapper around FaceclawG1Flasher: one arm's install, its restore to Even's firmware, or a question about what it runs. */
export class G1Flasher {
private readonly flasher: any;
private readonly listenerProxy: any;
@@ -34,7 +40,7 @@ export class G1Flasher {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.flasher = new com.faceclaw.app.FaceclawG1Flasher(
context, options.address, options.side, options.firmwarePath, options.mode, options.connectWindowMs,
context, options.address, options.side, options.firmwarePath, options.netCorePath ?? "", options.mode, options.connectWindowMs,
);
this.listenerProxy = new com.faceclaw.app.FaceclawFirmwareFlasherListener({
onLog: (line: string) => this.logListener?.(String(line)),
+10 -4
View File
@@ -7,6 +7,8 @@ declare const FaceclawKitIosBleCentral: any, FaceclawKitIosProtocolPlatform: any
/** CBManagerState raw values reported by the Kotlin central. */
export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_POWERED_OFF = 4, BLE_STATE_POWERED_ON = 5
/** CBManagerAuthorization.allowedAlways. */
const BLE_AUTHORIZATION_ALLOWED = 3
export type BluetoothEvent =
| { kind: 'state'; state: number; authorization: number }
@@ -50,17 +52,21 @@ export class IosBluetooth {
}
},
})
this.native.setScanListenerListener(this.scanListener)
}
onEvent(listener: (event: BluetoothEvent) => void): () => void {
this.listeners.add(listener); return () => { this.listeners.delete(listener) }
}
private emit(event: BluetoothEvent): void { for (const listener of [...this.listeners]) listener(event) }
/**
* Whether the user has allowed Bluetooth. Unlike `state` this is accurate before the
* central exists, and reading it never shows the permission prompt.
*/
isAuthorized(): boolean { return Number(this.native.authorization()) === BLE_AUTHORIZATION_ALLOWED }
/** Creates the central (first use shows the Bluetooth permission prompt) without blocking the JS thread. */
private ensureCentral(): void {
// A zero timeout returns immediately after creating the central; the state arrives
// through the scan listener on the main queue.
this.native.waitForPoweredOnTimeoutMs(0)
// Registering the listener creates the central, or has an existing one re-report its
// state; the state arrives through the listener on the main queue.
this.native.setScanListenerListener(this.scanListener)
}
ensureReady(): Promise<void> {
if (this.state === BLE_STATE_POWERED_ON) return Promise.resolve()
+158 -27
View File
@@ -1,14 +1,23 @@
import { Frame, Observable } from "@nativescript/core";
import { G1ArmScanner } from "../g1/arm-scanner";
import { EVEN_G1_RESTORE } from "../g1/even-firmware";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { buildG1Firmware, type BuiltG1Firmware, type G1BuildProgress } from "../g1/firmware-builder";
import {
buildEvenG1Firmware,
buildG1Firmware,
type BuiltEvenG1Firmware,
type BuiltG1Firmware,
type G1BuildProgress,
} from "../g1/firmware-builder";
import { saveG1Arm, saveG1Pair } from "../g1/addresses";
import {
G1_CASE_DELAY_HINT,
G1_CASE_INSTRUCTIONS,
G1_INSTALL_NOTICE,
G1_SIDES,
G1_UNINSTALL_NOTICE,
G1_UNINSTALL_SIDES,
g1FlashPercent,
type G1FlashResult,
type G1Side,
@@ -23,19 +32,27 @@ import { formatErrorMessage } from "../util/format-error";
import { finishOnboardingNavigation } from "./onboarding-navigation";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
type Phase = "intro" | "preparing" | "flashing" | "flashed" | "error" | "unavailable";
type Phase = "intro" | "preparing" | "flashing" | "flashed" | "error";
const LOCATE_MS = 45_000;
/** An arm takes about 20 s to copy the image, and a hung boot resets itself within two minutes. */
const RETURN_MS = 240_000;
/** Even's image is larger than g1v0, and MCUboot first installs the network core's. */
const RESTORE_RETURN_MS = 300_000;
/**
* Just after its reset an arm may still be heard on g1v0. Later than this, one heard on g1v0 has booted it again:
* MCUboot didn't take Even's firmware.
*/
const OLD_FIRMWARE_GRACE_MS = 15_000;
const CONNECT_MS = 60_000;
/** A new arm pairs only once it knows it's in the case, which a full case can take a while to tell it. */
const FIRST_PAIRING_MS = 120_000;
/**
* The install page on a G1, in place of OnboardingFlashViewModel. The two arms are separate devices that each take the
* image over MCUmgr (G1ArmFlashFlow), left first. There is nothing on the lens to confirm with before g1v0 is on the arm,
* so the confirmation is on the phone: the page before, or this one's intro.
* The install and uninstall page on a G1, in place of OnboardingFlashViewModel. The two arms are separate devices that
* each take the image over MCUmgr (G1ArmFlashFlow), left first; an uninstall goes right first and puts back both of
* Even's images, the network core's too. There is nothing on the lens to confirm with while an arm runs Even's
* firmware, so the confirmation is on the phone: the page before, or this one's intro.
*
* Every run starts by listening for what each arm runs now, so a retry picks up wherever the last one stopped. An arm's
* new address is saved as soon as it's known.
@@ -43,12 +60,18 @@ const FIRST_PAIRING_MS = 120_000;
export class G1FlashViewModel extends Observable {
private phase: Phase = "intro";
private readonly fromOnboarding: boolean;
private readonly uninstalling: boolean;
private readonly scanner = new G1ArmScanner();
private image: BuiltG1Firmware | null = null;
private evenImage: BuiltEvenG1Firmware | null = null;
private flasher: G1Flasher | null = null;
private generation = 0;
private disposed = false;
private unpairedArm = false;
/** An uninstall's outcome, for the last page: an arm's store erased, a pairing this phone couldn't remove, an arm done. */
private wiped = false;
private pairingLeft = false;
private restoredArm = false;
headline = "Install Faceclaw's Firmware";
status = "";
@@ -59,17 +82,14 @@ export class G1FlashViewModel extends Observable {
constructor(options?: { mode?: "install" | "uninstall"; fromOnboarding?: boolean; autoStart?: boolean }) {
super();
this.fromOnboarding = options?.fromOnboarding ?? true;
if (options?.mode === "uninstall") {
// Restoring Even's firmware has never been run on a real arm, and an arm whose network core is older than the
// image may not come back, so the phone doesn't offer it yet.
this.phase = "unavailable";
this.headline = "Back to Even's Firmware";
this.status = "Faceclaw can't restore Even's firmware on a G1 yet. It takes a computer: see \"Restore Even's firmware\" in " +
"the ScouterKit firmware's README.";
return;
}
this.uninstalling = options?.mode === "uninstall";
suppressAutoReconnect();
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
if (this.uninstalling) {
this.headline = "Back to Even's Firmware";
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_UNINSTALL_NOTICE}`;
} else {
this.status = `${G1_CASE_INSTRUCTIONS}\n\n${G1_INSTALL_NOTICE}`;
}
if (options?.autoStart) void this.run();
}
@@ -90,7 +110,7 @@ export class G1FlashViewModel extends Observable {
get primaryLabel(): string {
switch (this.phase) {
case "intro":
return "Install";
return this.uninstalling ? "Uninstall" : "Install";
case "flashed":
return "Finish";
case "error":
@@ -119,7 +139,7 @@ export class G1FlashViewModel extends Observable {
}
onSecondaryTap(): void {
if (this.phase === "intro" || this.phase === "error" || this.phase === "unavailable") this.leave();
if (this.phase === "intro" || this.phase === "error") this.leave();
}
// --- the install ----------------------------------------------------------
@@ -129,21 +149,30 @@ export class G1FlashViewModel extends Observable {
const live = () => !this.disposed && generation === this.generation;
this.setPhase("preparing");
this.setBusy(true);
this.setText("Preparing Firmware", "Getting the firmware ready...");
this.setText("Preparing Firmware", this.uninstalling ? "Getting Even's firmware ready..." : "Getting the firmware ready...");
try {
await ensureBlePermissions();
if (!live()) return;
if (!this.image) {
this.image = await buildG1Firmware((progress) => {
if (live()) this.setStatus(describeBuild(progress));
});
this.appendLog(`firmware ${this.image.version} prepared and verified (${this.image.bytes.toLocaleString()} bytes)`);
if (this.uninstalling) {
if (!this.evenImage) {
this.evenImage = await buildEvenG1Firmware((progress) => {
if (live()) this.setStatus(describeEvenBuild(progress));
});
this.appendLog(`Even's firmware ${this.evenImage.version} downloaded and verified (${this.evenImage.bytes.toLocaleString()} bytes)`);
}
} else {
if (!this.image) {
this.image = await buildG1Firmware((progress) => {
if (live()) this.setStatus(describeBuild(progress));
});
this.appendLog(`firmware ${this.image.version} prepared and verified (${this.image.bytes.toLocaleString()} bytes)`);
}
await this.prepareFonts(live);
}
await this.prepareFonts(live);
if (!live()) return;
this.setPhase("flashing");
this.setText("Installing Firmware", "Listening for your glasses...");
this.setText(this.uninstalling ? "Restoring Even's Firmware" : "Installing Firmware", "Listening for your glasses...");
const identity = loadPairedGlassesIdentity();
const stored = loadDeviceAddresses();
const pair = await this.scanner.waitForPair({ serial: identity?.serial, left: stored.left, right: stored.right }, LOCATE_MS);
@@ -154,6 +183,14 @@ export class G1FlashViewModel extends Observable {
}
saveG1Pair(pair);
if (this.uninstalling) {
for (const side of G1_UNINSTALL_SIDES) {
await this.restoreArm(side, pair, live);
if (!live()) return;
}
this.restored();
return;
}
this.unpairedArm = false;
for (const side of G1_SIDES) {
await this.installArm(side, pair, live);
@@ -231,6 +268,65 @@ export class G1FlashViewModel extends Observable {
this.appendLog(`${side} arm runs ${running.version}`);
}
/**
* Even's firmware back on one arm, then a wait for it to advertise as Even's. An arm already on Even's firmware is
* left alone: a retry goes on from there.
*/
private async restoreArm(side: G1Side, pair: GlassesPairCandidate, live: () => boolean): Promise<void> {
const arm = pair[side]!;
if (arm.g1Firmware === "stock") {
this.appendLog(`${side} arm already runs Even's firmware`);
this.setProgress(g1FlashPercent(side, 1, 1, G1_UNINSTALL_SIDES));
return;
}
const even = this.evenImage!;
this.setProgress(g1FlashPercent(side, 0, 1, G1_UNINSTALL_SIDES));
this.setStatus(`Connecting to the ${side} arm...`);
const result = await this.flash({
address: arm.address,
side,
firmwarePath: even.appPath,
netCorePath: even.netCorePath,
mode: "restore",
connectWindowMs: CONNECT_MS,
}, (state) => {
if (state === "pairing") this.setStatus(`Pairing with the ${side} arm. If your phone asks, accept it.`);
else if (state === "checking") this.setStatus(`Checking the ${side} arm...`);
else if (state === "wiping") {
this.setStatus(`Erasing Faceclaw's storage on the ${side} arm, where Even's fonts were. This can take several minutes; keep the ` +
"glasses in the case. Nothing else has changed yet.");
} else if (state === "flashing") this.setStatus(`Sending Even's firmware to the ${side} arm. Its firmware hasn't changed yet.`);
else if (state === "committing") this.setStatus(`Installing on the ${side} arm. Keep the glasses in the case.`);
}, (sent, total) => this.setProgress(g1FlashPercent(side, sent, total, G1_UNINSTALL_SIDES)));
if (!live()) return;
if (result.wiped) this.wiped = true;
this.setProgress(g1FlashPercent(side, 1, 1, G1_UNINSTALL_SIDES));
this.setStatus(`The ${side} arm is restarting into Even's firmware. This takes a minute or two; keep it in the case.`);
const resetAt = Date.now();
const identity = loadPairedGlassesIdentity();
const back = await this.scanner.waitForArm(side, identity?.serial ?? pair.serial, RESTORE_RETURN_MS,
(heard) => heard.g1Firmware === "stock" || Date.now() - resetAt >= OLD_FIRMWARE_GRACE_MS);
if (!live()) return;
if (!back) {
throw new Error(`The ${side} arm hasn't come back yet. Leave the glasses in the plugged-in case for a few minutes, with the lid ` +
"open: an interrupted install finishes by itself. Then retry.");
}
if (back.g1Firmware !== "stock") {
throw new Error(`The ${side} arm came back on Faceclaw's firmware: it didn't take Even's. Retry to try again.`);
}
saveG1Arm(side, back);
this.restoredArm = true;
// Even's app makes its own pairing with Even's firmware; the one this phone made with g1v0 would only be in its way.
this.forgetPairing(back.address);
if (back.address !== arm.address) this.forgetPairing(arm.address);
this.appendLog(`${side} arm runs Even's firmware`);
}
private forgetPairing(address: string): void {
if (!forgetG1Pairing(address)) this.pairingLeft = true;
}
private async flash(
options: G1FlasherOptions,
onState?: (state: string) => void,
@@ -271,6 +367,28 @@ export class G1FlashViewModel extends Observable {
: ""));
}
private restored(): void {
// Stays manually disconnected: Faceclaw would only find firmware it can't run.
this.setBusy(false);
this.setProgress(100);
this.setPhase("flashed");
if (!this.restoredArm) {
this.setText("All Done", "Both arms already run Even's firmware.");
return;
}
const steps = [`Both arms run Even's firmware ${EVEN_G1_RESTORE.version}.`];
if (this.pairingLeft) {
steps.push("Before pairing them in Even's app, remove both arms in this phone's Bluetooth settings (\"Forget This Device\"): " +
"Faceclaw's firmware made that pairing, and Even's firmware makes its own.");
} else {
steps.push("To use them, pair them in Even's app.");
}
if (this.wiped) {
steps.push("Even's Chinese, Japanese and Korean text and its demo pictures were erased with Faceclaw's storage, and don't come back.");
}
this.setText("All Done", steps.join("\n\n"));
}
private failed(message: string): void {
this.setBusy(false);
this.setPhase("error");
@@ -278,8 +396,10 @@ export class G1FlashViewModel extends Observable {
}
private finish(): void {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
if (!this.uninstalling) {
setPreviewOnlyMode(false);
setOnboardingCompleted(true);
}
this.teardown();
finishOnboardingNavigation();
}
@@ -344,6 +464,17 @@ export class G1FlashViewModel extends Observable {
}
}
function describeEvenBuild(progress: G1BuildProgress): string {
switch (progress) {
case "downloading":
return "Downloading Even's firmware from Even's firmware server...";
case "verifying":
return "Verifying the download...";
default:
return "Saving the firmware...";
}
}
function describeBuild(progress: G1BuildProgress): string {
switch (progress) {
case "downloading":
+2 -2
View File
@@ -7,7 +7,7 @@ import { IosPreviewController } from '../g2/ios-preview-controller'
import { PhoneGestureRecognizer } from './phone-gestures'
import { BleBandwidthMeter } from './ble-bandwidth-meter'
import { sampleBleTraffic } from '../native/ble-traffic'
import { onAnySettingChanged, mirrorTouchSetting, showBleBandwidthSetting } from '../ui/dashboard-settings'
import { glassesModelName, onAnySettingChanged, mirrorTouchSetting, showBleBandwidthSetting } from '../ui/dashboard-settings'
import { loadDeviceAddresses } from '../g2/device-addresses'
import { deviceAddressError } from '../g2/ios-peripheral-identity'
import { formatBatteryLine } from '../g2/glasses-display-state'
@@ -75,7 +75,7 @@ export function createMainPage(): Page {
// The Settings tab's battery row. iOS reports charging sessions as
// connected, so "connected" is the whole live-link condition here.
let glassesLinked = false
const refreshBatteryLine = () => { model.batteryLine = formatBatteryLine(shell.getBatteryLevels(), glassesLinked) }
const refreshBatteryLine = () => { model.batteryLine = formatBatteryLine(shell.getBatteryLevels(), glassesLinked, glassesModelName()) }
const keyboardField = () => keyboardPanel.getViewById<TextView>('keyboardInputField')
const controller = new IosPreviewController((image, label) => {
mirror.imageSource = image; model.set('padFocusLine', label)
+2
View File
@@ -17,6 +17,7 @@ import {
import { dashboardController, type MirrorTouchKind } from "../g2/dashboard-controller";
import { formatBatteryLine } from "../g2/glasses-display-state";
import {
glassesModelName,
mirrorTouchSetting,
onAnySettingChanged,
showBleBandwidthSetting,
@@ -97,6 +98,7 @@ export class MainViewModel extends RemoteControlsViewModel {
this.batteryLine = formatBatteryLine(
snapshot.batteries,
snapshot.phase === "connected" || snapshot.phase === "charging",
glassesModelName(),
);
this.activeTextSettingId = snapshot.activeTextSettingId;
this.activeTextEditorTitle = snapshot.activeTextEditorTitle;
@@ -13,6 +13,9 @@ const GLASSES_OPTIONS: { choice: GlassesChoice; label: string; description?: str
{ choice: "rayneo-io", label: "RayNeo iO" },
];
/** RayNeo iO support isn't ready to offer in a release yet; set this to show its row again. */
const OFFER_RAYNEO_IO = false;
/** Why this choice can't be made on this phone, or "" when it can. */
function unavailableReason(choice: GlassesChoice): string {
// FaceclawCommunicatorBridge refuses to start a session with one on iOS.
@@ -48,7 +51,8 @@ export class OnboardingDevicesViewModel extends Observable {
get glassesOptions(): GlassesOptionItem[] {
const selected = this.selected;
return GLASSES_OPTIONS.map(({ choice, label, description }) => {
const options = OFFER_RAYNEO_IO ? GLASSES_OPTIONS : GLASSES_OPTIONS.filter(({ choice }) => choice !== "rayneo-io");
return options.map(({ choice, label, description }) => {
const reason = unavailableReason(choice);
const note = reason || description || "";
const isSelected = choice === selected;
+2 -1
View File
@@ -1,4 +1,5 @@
import { Frame, Observable, Screen } from "@nativescript/core";
import { EVEN_G1_RESTORE } from "../g1/even-firmware";
import { glassesTypeSetting, type GlassesType } from "../ui/dashboard-settings";
import { isPreviewOnlyMode } from "./onboarding-state";
@@ -38,7 +39,7 @@ function firmwareBody(glasses: GlassesType): string {
return `Faceclaw only runs on a RayNeo iO that has Faceclaw's custom firmware installed. This app can't install it on an iO, so that has to be done separately before you pair your glasses. ${WARRANTY_NOTE}\n\n${PREVIEW_HINT}`;
}
const restore = glasses === "g1"
? "Returning to the official firmware later takes a computer."
? `You can return to the official firmware later from Faceclaw, as version ${EVEN_G1_RESTORE.version}.`
: "You can uninstall and return to the official firmware later, by reconnecting the official Even Realities app.";
return `Faceclaw only runs on ${GLASSES_MAKER[glasses].product} glasses that have Faceclaw's custom firmware installed. Next, Faceclaw will pair with your glasses, check their firmware, and install the custom firmware if it isn't there yet.\n\nFlashing replaces the official firmware. ${restore} ${WARRANTY_NOTE}\n\n${PREVIEW_HINT}`;
}
+3 -13
View File
@@ -293,7 +293,7 @@ export class PairingViewModel extends Observable {
}
if (this.selectedPair) {
const identity = this.selectedPair.identity;
const label = identity ? identity.displayName : "Even Realities G2";
const label = identity ? identity.displayName : this.selectedPair.g1Firmware ? "Even Realities G1" : "Even Realities G2";
parts.push(
`${label} · serial ${this.selectedPair.serial ?? "unknown"}\n` +
`Left ${this.selectedPair.left?.address ?? "?"} · Right ${this.selectedPair.right?.address ?? "?"}`,
@@ -504,22 +504,12 @@ export class PairingViewModel extends Observable {
),
);
const complete = pairs.filter((pair) => pair.completeness === "complete").length;
const partial = pairs.length - complete;
if (this.scanFailure) {
this.status = `Scan failed: ${this.scanFailure}`;
} else if (!this._scanning) {
this.status = "Scan paused.";
} else if (!pairs.length && !rings.length && !rayneos.length) {
this.status = "Scanning…";
} else {
const bits = [
complete ? `${complete} ${complete === 1 ? "pair" : "pairs"} ready` : null,
partial ? `${partial} with one arm heard` : null,
rings.length ? `${rings.length} ${rings.length === 1 ? "ring" : "rings"}` : null,
rayneos.length ? `${rayneos.length} RayNeo iO` : null,
].filter(Boolean);
this.status = `Scanning… ${bits.join(" · ")}. Tap a pair to select it.`;
this.status = "Scanning…";
}
for (const property of [
@@ -554,7 +544,7 @@ function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (ar
colorwayLabel: colorwayLabel(row.colorway),
badgeVisibility: row.badge ? "visible" : "collapse",
variantVisibility: row.variantSummary ? "visible" : "collapse",
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
proximityLine: row.proximityGlyph,
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
armsVisibility: row.armsSummary ? "visible" : "collapse",
warningVisibility: row.warning ? "visible" : "collapse",
+7
View File
@@ -236,3 +236,10 @@ Button.permissions-primary-dimmed {
.ns-dark .permissions-check {
color: #7bc47f;
}
/* Onboarding splash (phone-ui/onboarding-page). The logo art is
* black-on-transparent; tint it white in dark mode so it doesn't vanish into
* the dark page background. */
.ns-dark .onboarding-logo {
tint-color: #ffffff;
}
+12 -2
View File
@@ -107,7 +107,7 @@ const ANDROID_PERMISSIONS: PermissionDefinition[] = [
const PERMISSIONS: PermissionDefinition[] = global.isIOS ? [{
id: "nearby-devices", title: "Nearby Devices",
description: "Needed to communicate with your smart glasses over Bluetooth.", optional: false,
isGranted: () => iosBluetooth().state === 5,
isGranted: () => iosBluetooth().isAuthorized(),
request: () => iosBluetooth().ensureReady(),
}, {
id: "calendar", title: "Calendar",
@@ -143,6 +143,7 @@ export class PermissionsViewModel extends Observable {
private readonly onboarding: boolean;
private _cards: PermissionCardItem[] = [];
private requesting = false;
private stopWatchingBluetooth: (() => void) | null = null;
constructor(options?: { onboarding?: boolean }) {
super();
@@ -159,11 +160,20 @@ export class PermissionsViewModel extends Observable {
onPageLoaded(): void {
Application.on(Application.resumeEvent, this.onAppResume);
// The answer to the Bluetooth prompt can arrive after request() has stopped
// waiting for it, and with no resume to re-check on.
if (global.isIOS) {
this.stopWatchingBluetooth = iosBluetooth().onEvent((event) => {
if (event.kind === "state") this.refresh();
});
}
this.refresh();
}
onPageUnloaded(): void {
Application.off(Application.resumeEvent, this.onAppResume);
this.stopWatchingBluetooth?.();
this.stopWatchingBluetooth = null;
}
// --- observable properties -------------------------------------------------
@@ -177,7 +187,7 @@ export class PermissionsViewModel extends Observable {
}
get instructions(): string {
if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Calendar and Apple Music access are optional. Tap a card to allow access; a checkmark means it is ready.";
if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Calendar and Apple Music access are optional. Tap a card to allow access; a checkmark means access is allowed.";
return this.onboarding
? `Faceclaw uses these ${global.isIOS ? "iOS" : "Android"} permissions. Tap a card to grant one; a checkmark means it is already granted. ` +
"Optional permissions can also be granted later, from the Permissions item in the main-screen menu."
+1 -1
View File
@@ -116,7 +116,7 @@
color: #6a6a6a;
margin-top: 4;
}
/* The charging case's level under "Charging · G2 n%". */
/* The charging case's level under "Charging: G2 n%". */
.pad-detail {
font-size: 15;
color: #b0b0b0;
+8 -1
View File
@@ -313,7 +313,7 @@ export const phoneBatteryVisibilitySetting = batteryVisibilitySetting(
"phoneBatteryVisibility", "Phone", "display.battery.phoneVisibility",
);
export const glassesBatteryVisibilitySetting = batteryVisibilitySetting(
"glassesBatteryVisibility", "G2", "display.battery.glassesVisibility",
"glassesBatteryVisibility", "Glasses", "display.battery.glassesVisibility",
);
export const ringBatteryVisibilitySetting = batteryVisibilitySetting(
"ringBatteryVisibility", "R1", "display.battery.ringVisibility",
@@ -408,6 +408,13 @@ export function glassesHaveCompass(): boolean {
return glassesTypeSetting.get() === "g2";
}
const GLASSES_MODEL_NAMES: Record<GlassesType, string> = { g2: "G2", g1: "G1", "rayneo-io": "iO" };
/** The paired glasses' model without the brand, short enough for battery labels and a watch's one-line charging status. */
export function glassesModelName(): string {
return GLASSES_MODEL_NAMES[glassesTypeSetting.get()];
}
const APP_SWITCHER_POSITION_LABELS: Record<AppSwitcherPosition, string> = {
left: "Left",
right: "Right",
+3 -1
View File
@@ -54,6 +54,7 @@ import {
dataCollectionSetting,
distanceUnitSetting,
glassesBatteryVisibilitySetting,
glassesModelName,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
watchBatteryVisibilitySetting,
@@ -387,7 +388,8 @@ function batteryIndicatorsMenuItem(): MenuItem {
enumSettingMenuItem(batteryDisplayModeSetting),
enumSettingMenuItem(phoneBatteryVisibilitySetting),
enumSettingMenuItem(watchBatteryVisibilitySetting),
enumSettingMenuItem(glassesBatteryVisibilitySetting),
// Named as the top bar names this indicator.
enumSettingMenuItem(glassesBatteryVisibilitySetting, { label: glassesModelName() }),
enumSettingMenuItem(ringBatteryVisibilitySetting),
]);
},
+6 -4
View File
@@ -4,7 +4,7 @@ import { wrapText } from "../../graphics/textwrap";
import { InputEvent } from "../gestures";
import { Layer, LayerContext, PaintBelow } from "../layers";
import { isMenuItemDisabled, MenuItem, MenuLayer, openModalMenu } from "../menu";
import { Menu } from "../menu-core";
import { Menu, drawMenuLabel } from "../menu-core";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../metrics";
import { shell } from "../shell/shell";
@@ -66,8 +66,9 @@ export class SettingsPanelLayer implements Layer {
rowGap: ROW_GAP,
highlight: { radius: 6 },
getHeight: () => listRowHeight(getDefaultSmallFont()),
draw: ({ image, item, x, y, selected }) => {
image.drawText(getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label, selected ? 255 : 200);
draw: ({ image, item, x, y, width, selected }) => {
drawMenuLabel(image, getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET,
width - ROW_TEXT_X - 8, item.label, selected ? 255 : 200);
},
});
this.rightMenu = new Menu<MenuItem>({
@@ -92,7 +93,8 @@ export class SettingsPanelLayer implements Layer {
ctx: this.paintCtx!,
});
} else {
image.drawText(getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET, item.label,
drawMenuLabel(image, getDefaultSmallFont(), x + ROW_TEXT_X, y + LIST_ROW_TEXT_INSET,
width - ROW_TEXT_X - 8, item.label,
disabled ? 70 : selected ? 255 : 200);
}
},
+46 -4
View File
@@ -2,6 +2,8 @@ import { DrawExpression as E } from "../graphics/draw-expression";
import { GrayImage } from "../graphics/image";
import { menuScrollList, slidingHighlightY, type MenuScrollHighlight } from "../graphics/menu-scroll-list";
import type { InputEvent } from "./gestures";
import { MenuLabelMotion, type MenuLabelPainter } from "./menu-label";
export { drawMenuLabel } from "./menu-label";
import { MenuHighlightMotion } from "./menu-highlight-motion";
import { MenuScrollMotion, scrollOffsetExpression, type MenuScrollAnimation } from "./menu-scroll-motion";
@@ -39,6 +41,8 @@ export type MenuDrawArgs<T> = {
selected: boolean;
/** Whether the menu owns input right now: the `focused` flag the host passed to paint. */
focused: boolean;
/** Clipped label; overflowing selected/focused labels get a retained reading pass. */
drawLabel: MenuLabelPainter;
};
export type MenuHighlightStyle = {
@@ -110,6 +114,7 @@ export class Menu<T> {
private lastBox: MenuBox | null = null;
private readonly motion = new MenuHighlightMotion();
private readonly scrollMotion = new MenuScrollMotion();
private readonly labelMotion = new MenuLabelMotion();
constructor(private readonly options: MenuOptions<T>) {
this.itemList = options.items ?? [];
@@ -160,7 +165,9 @@ export class Menu<T> {
: null;
this.itemList = items;
if (selectedIndex !== undefined) this.deselected = selectedIndex === null;
const previousSelection = this.selected;
this.selected = this.settle(selectedIndex === undefined ? this.selected : selectedIndex);
if (this.selected !== previousSelection) this.labelMotion.reset();
if (before !== null && this.selected !== null && width !== undefined) {
this.scrollY = Math.max(0, this.layout(width).tops[this.selected]! - before);
}
@@ -173,7 +180,9 @@ export class Menu<T> {
*/
select(index: number | null): void {
this.deselected = index === null;
this.selected = this.settle(index);
const next = this.settle(index);
if (next !== this.selected) this.labelMotion.reset();
this.selected = next;
}
/** Step the selection by one selectable row; handles wrap and the exit callbacks. */
@@ -184,6 +193,7 @@ export class Menu<T> {
if (next !== null) {
if (from !== null) this.motion.navigate(from, false);
this.scrollMotion.navigate(false);
this.labelMotion.reset();
this.selected = next;
this.deselected = false;
return;
@@ -194,6 +204,7 @@ export class Menu<T> {
if (wrapped !== null && wrapped !== from) {
if (from !== null) this.motion.navigate(from, true);
this.scrollMotion.navigate(true);
this.labelMotion.reset();
this.selected = wrapped;
this.deselected = false;
} else if (from === null && this.lastBox) {
@@ -247,6 +258,7 @@ export class Menu<T> {
paint(image: GrayImage, box: MenuBox, focused: boolean): void {
this.lastBox = box;
this.reconcile();
if (!focused || this.selected === null) this.labelMotion.reset();
const layout = this.layout(box.width);
this.ensureVisible(layout, box.height);
const now = Date.now();
@@ -277,9 +289,10 @@ export class Menu<T> {
}
// A selected row taller than the box is drawn whole, from its top.
const row = new GrayImage(box.width, height, 0);
this.options.draw({ image: row, item, index, x: 0, y: 0, width: box.width, height, selected, focused });
this.draw({ image: row, item, index, x: 0, y: 0, width: box.width, height, selected, focused });
image.drawMenuSelection(row, box.x, rowY, background, MENU_HIGHLIGHT_STROKE,
highlight?.radius ?? 8, highlight?.depth ?? 0, animation);
this.copyRowPresentations(row, image, box.x, rowY, box.y, box.y + box.height, highlight?.depth ?? 0);
} else {
this.drawRow(image, index, box.x, rowY, box.width, height, focused, box.y, box.y + box.height);
}
@@ -293,6 +306,31 @@ export class Menu<T> {
}
}
/** Retain row-local animations, intersecting their clips with the row and viewport. */
private copyRowPresentations(row: GrayImage, target: GrayImage, x: number, y: number,
clipTop: number, clipBottom: number, depth: number): void {
for (const draw of row.draws) {
if (draw.kind !== "image" || !draw.presentation?.displayList) continue;
const left = Math.max(0, -draw.x), right = Math.min(draw.source.width, row.width - draw.x);
const top = Math.max(0, -draw.y, clipTop - y - draw.y);
const bottom = Math.min(draw.source.height, row.height - draw.y, clipBottom - y - draw.y);
if (right <= left || bottom <= top) continue;
const list = draw.presentation.displayList;
target.drawDisplayList({ ...list, calls: list.calls.map(call => {
const c = call.clip ?? { x: 0, y: 0, width: draw.source.width, height: draw.source.height };
const cx = Math.max(left, c.x), cy = Math.max(top, c.y);
return { ...call, clip: { x: cx, y: cy,
width: Math.max(0, Math.min(right, c.x + c.width) - cx),
height: Math.max(0, Math.min(bottom, c.y + c.height) - cy) } };
}) }, x + draw.x, y + draw.y, draw.source.width, draw.source.height, depth);
}
}
private draw(args: Omit<MenuDrawArgs<T>, "drawLabel">): void {
this.labelMotion.row(args.image, args.index, args.selected && args.focused,
drawLabel => this.options.draw({ ...args, drawLabel }));
}
/** Draw a vertical scrollbar for the last painted box (no-op unless the content overflows it). */
drawScrollbar(image: GrayImage, x: number, y: number, height: number): void {
const box = this.lastBox;
@@ -317,11 +355,12 @@ export class Menu<T> {
const selected = index === this.selected;
const scratch = selected && this.options.highlight !== false;
if (!scratch && y >= clipTop && y + height <= clipBottom) {
this.options.draw({ image: target, item, index, x, y, width, height, selected, focused });
this.draw({ image: target, item, index, x, y, width, height, selected, focused });
return;
}
const row = new GrayImage(width, height, 0);
this.options.draw({ image: row, item, index, x: 0, y: 0, width, height, selected, focused });
this.draw({ image: row, item, index, x: 0, y: 0, width, height, selected, focused });
this.copyRowPresentations(row, target, x, y, clipTop, clipBottom, 0);
const skip = Math.max(0, clipTop - y);
target.bitBlt(row.withDrawsBaked(), x, y + skip,
{ sy: skip, height: Math.min(height, clipBottom - y) - skip, transparentZero: true });
@@ -352,6 +391,9 @@ export class Menu<T> {
if (rowTop + height <= top || rowTop >= bottom) continue;
this.drawRow(strip, index, 0, rowTop - top, box.width, height, focused, 0, strip.height);
}
// A reading pass has its own clipped timeline. Snap vertical motion rather
// than baking that pass into a strip or leaving it at the wrong row position.
if (strip.draws.some(d => d.kind === "image" && d.presentation)) return null;
// Crop to the columns with ink; the static paint shows the rest unchanged.
const baked = strip.withDrawsBaked();
let left = baked.width, right = -1;
+71
View File
@@ -0,0 +1,71 @@
import { DrawExpression as E } from "../graphics/draw-expression";
import { DrawOp, type ListCall } from "../graphics/display-list";
import { GrayImage, type UiFont } from "../graphics/image";
import { menuAnimationDurationMs } from "./menu-animation-pref";
export type MenuLabelPainter = (font: UiFont, x: number, y: number, width: number, text: string, value: number) => void;
const contexts = new WeakMap<GrayImage, { motion: MenuLabelMotion; index: number; active: boolean }>();
let nextToken = 0x40000000;
/** Shared row builders inherit their menu's focus and timeline without changing their public signature. */
export function drawMenuLabel(image: GrayImage, font: UiFont, x: number, y: number, width: number, text: string, value: number): void {
const context = contexts.get(image);
if (context) context.motion.draw(image, font, x, y, width, text, value, context.index, context.active);
else drawStatic(image, font, x, y, width, text, value);
}
function drawStatic(image: GrayImage, font: UiFont, x: number, y: number, width: number, text: string, value: number): void {
if (width <= 0) return;
if (font.measureText(text) <= width) image.drawText(font, x, y, text, value);
else {
const clip = new GrayImage(width, font.lineHeight);
clip.drawText(font, 0, 0, text, value);
image.bitBlt(clip.withDrawsBaked(), x, y, { transparentZero: true });
}
}
/** One bounded, firmware-driven reading pass per selection/content/geometry/focus change. No JS timers. */
export class MenuLabelMotion {
private key = "";
private timeline = { token: 0, startedAt: 0 };
row(image: GrayImage, index: number, active: boolean, draw: (drawLabel: MenuLabelPainter) => void): void {
contexts.set(image, { motion: this, index, active });
try { draw((font, x, y, width, text, value) => drawMenuLabel(image, font, x, y, width, text, value)); }
finally { contexts.delete(image); }
}
reset(): void { this.key = ""; }
draw(image: GrayImage, font: UiFont, x: number, y: number, width: number, text: string, value: number, index: number, active: boolean): void {
width = Math.max(0, Math.floor(width));
const measured = Math.ceil(font.measureText(text));
drawStatic(image, font, x, y, width, text, value);
if (!active) return;
const travel = menuAnimationDurationMs(Math.max(600, Math.ceil((measured - width) * 1000 / 30)));
if (!width || measured <= width || !travel || font.lineHeight > 480) { this.reset(); return; }
// Bounded tiles, never a label-wide BLE image. Extreme labels use the static fallback.
const tileWidth = Math.min(640, Math.floor(65530 / font.lineHeight) * 2);
if (tileWidth <= 0 || Math.ceil(measured / tileWidth) > 32) return;
const key = JSON.stringify([index, text, width, font.lineHeight, measured, x, y, value, travel]);
if (this.key !== key) {
this.key = key;
this.timeline = { token: nextToken++, startedAt: Date.now() };
}
const distance = measured - width;
// Hold the beginning, traverse at reading speed, hold the end, then return and stop.
const offset = E.progress(travel, 900).mul(E.f32(distance))
.sub(E.progress(travel, 1800 + travel).mul(E.f32(distance))).toInt();
const resources: GrayImage[] = [];
const calls: ListCall[] = [];
for (let left = 0; left < measured; left += tileWidth) {
const tile = new GrayImage(Math.min(tileWidth, measured - left), font.lineHeight, 16);
tile.drawText(font, -left, 0, text, value);
resources.push(tile.withDrawsBaked());
calls.push({ op: DrawOp.RECT_COPY, resource: resources.length - 1, x: 0, y: 0,
width: tile.width, height: tile.height, dx: E.i32(left).sub(offset), dy: 0,
clip: { x: 0, y: 0, width, height: font.lineHeight } });
}
image.drawDisplayList({ resources, calls, timeline: this.timeline }, x, y, width, font.lineHeight);
}
}
+6 -5
View File
@@ -7,7 +7,7 @@ import { clamp } from "../util/numeric-util";
import { normalizeAnimationSpeed } from "./animation-speed";
import { Layer, LayerContext, PaintBelow } from "./layers";
import { MENU_ANIMATION_KEY, setMenuAnimationReader } from "./menu-animation-pref";
import { Menu, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE } from "./menu-core";
import { Menu, drawMenuLabel, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE } from "./menu-core";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import { LIST_ROW_TEXT_INSET, centeredTextY, lineStep, listRowHeight, menuTitleHeight } from "./metrics";
@@ -179,7 +179,7 @@ export function submenuItem(
render: ({ image, x, y, width, height, selected, disabled, text }) => {
const font = getDefaultSmallFont();
const value = disabled ? 70 : selected ? 255 : 200;
image.drawText(font, x, y + LIST_ROW_TEXT_INSET, text, value);
drawMenuLabel(image, font, x, y + LIST_ROW_TEXT_INSET, width - font.measureText("▶") - 12, text, value);
drawSubmenuIndicator(image, font, x, y, width, height, value);
},
};
@@ -200,7 +200,7 @@ export function drawToggleMenuItem(
const switchX = x + width - switchWidth - 2;
// Center the switch on the row's line box (legacy y+1 at the 12px default).
const switchY = y + Math.max(1, Math.round((listRowHeight(font) - 2 - switchHeight) / 2));
image.drawText(font, x, y + LIST_ROW_TEXT_INSET, label, 200);
drawMenuLabel(image, font, x, y + LIST_ROW_TEXT_INSET, switchX - x - 8, label, 200);
const offFill = selected ? 1 : 18;
image.fillRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 70 : offFill, 8);
image.drawRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 130 : 55, 8);
@@ -218,8 +218,8 @@ export function drawRightValueMenuItem(
label: string,
value: string,
): void {
image.drawText(font, x, y + LIST_ROW_TEXT_INSET, label, 200);
const valueX = x + width - font.measureText(value) - 2;
drawMenuLabel(image, font, x, y + LIST_ROW_TEXT_INSET, valueX - x - 8, label, 200);
image.drawText(font, valueX, y + LIST_ROW_TEXT_INSET, value, 220);
}
@@ -268,7 +268,8 @@ export class MenuLayer implements Layer {
ctx: this.paintCtx!,
});
} else {
image.drawText(font, x + MENU_ROW_TEXT_INSET, y + LIST_ROW_TEXT_INSET, item.label,
drawMenuLabel(image, font, x + MENU_ROW_TEXT_INSET, y + LIST_ROW_TEXT_INSET,
width - 2 * MENU_ROW_TEXT_INSET, item.label,
disabled ? 70 : selected ? 255 : 200);
}
},
+2 -1
View File
@@ -15,6 +15,7 @@ import {
batteryDisplayModeSetting,
batteryIndicatorVisible,
glassesBatteryVisibilitySetting,
glassesModelName,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
watchBatteryVisibilitySetting,
@@ -1089,7 +1090,7 @@ function batteryItems(state: ShellChromeState): BatteryItem[] {
Boolean(state.battery.watchCharging));
}
if (state.battery.headset !== null && Number.isFinite(state.battery.headset)) {
pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), "G2", "glasses", state.battery.headset,
pushBatteryItem(items, glassesBatteryVisibilitySetting.get(), glassesModelName(), "glasses", state.battery.headset,
Boolean(state.battery.headsetCharging));
}
if (state.battery.ring !== null && Number.isInteger(state.battery.ring)
+33 -7
View File
@@ -1,11 +1,12 @@
import { GrayImage } from "../../graphics/image";
import { DrawOp } from "../../graphics/display-list";
import { flattenPlanes } from "../../graphics/plane";
import { InputEvent } from "../gestures";
import { Layer, LayerActions, LayerContext, LayerStack, PaintBelow } from "../layers";
import { appViewportRect, appViewportSize, SHELL_OPAQUE_BLACK } from "./geometry";
// The modal covers most of the min-height app viewport, leaving a little of
// the foreground app visible around the edges. Both its size and position are
// The modal box covers most of the min-height app viewport. Retained vector
// clears optionally hide the app outside its opaque rect. Size and position are
// computed per paint: the display-mode setting changes the viewport size at
// runtime, and the vertical position setting moves the band.
const MODAL_MARGIN = 14;
@@ -33,9 +34,11 @@ export function modalRect(): { x: number; y: number; width: number; height: numb
/**
* A shell overlay hosting an inner layer stack in a bordered box over the
* app viewport (used for new-notification popups). The inner stack paints at
* the modal's interior size; its pixels blit onto an opaque black backdrop,
* so inner value-0 pixels read as black, not transparent.
* app viewport (used for new-notification popups). Normally the shell's lower
* layers stay visible. For a wake popup, only the box is opaque (keeping its
* image within 64 KiB), and a resource-free retained list clears the outside
* margins over separate app surfaces. The inner stack paints at the modal's interior
* size; inner value-0 pixels read as black, not transparent.
*/
export class ShellModalLayer implements Layer {
private readonly stack: LayerStack;
@@ -44,6 +47,8 @@ export class ShellModalLayer implements Layer {
baseLayer: Layer,
actions: LayerActions,
private readonly hooks: {
/** Arrival-time screen state: mask the background only for a wake popup. */
hideBackground?: boolean;
/** The modal left the shell stack, however it went. */
removed?: () => void;
/** Input reached the modal (before its inner stack handles it). */
@@ -57,8 +62,15 @@ export class ShellModalLayer implements Layer {
this.hooks.removed?.();
}
paint(_ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const image = paintBelow();
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
// Wake popups omit lower chrome, but ordinary popups keep the usual overlay.
if (!this.hooks.hideBackground) paintBelow();
// Leave the outer margins transparent so the
// scene encoder crops to the resource-sized modal, not the whole display.
// Native dim=0 still preserves a 1/0 halftone; clipped CLEAR calls below
// instead produce literal black without changing shared dimming semantics.
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height);
// Track a display-mode switch while the modal is up, so the inner stack
// paints at the same size the box below is drawn with.
const interior = modalInterior();
@@ -78,6 +90,20 @@ export class ShellModalLayer implements Layer {
image.drawRect(rect.x, rect.y, rect.width, rect.height, 110);
image.bitBlt(inner, innerX, innerY, { transparentZero: true });
top.image.copyPresentationsInto(image, innerX + top.x, innerY + top.y);
if (!this.hooks.hideBackground) return image;
// ShellScene replays retained calls after the opaque box. Clear only the
// complement of that box, keeping the inner menu's presentation order.
// These are vector clips, not tiled image resources; no full-screen image
// is uploaded. Clips move with the scene's stereo depth just like the box.
const margins = [
{ x: 0, y: 0, width, height: rect.y },
{ x: 0, y: rect.y + rect.height, width, height: height - rect.y - rect.height },
{ x: 0, y: rect.y, width: rect.x, height: rect.height },
{ x: rect.x + rect.width, y: rect.y, width: width - rect.x - rect.width, height: rect.height },
];
image.drawDisplayList({ resources: [], calls: margins
.filter(clip => clip.width > 0 && clip.height > 0)
.map(clip => ({ op: DrawOp.CLEAR, color: 0, clip })) }, 0, 0, width, height);
return image;
}
+13 -4
View File
@@ -9,7 +9,7 @@
*/
export interface NotificationModalHost<M> {
/** Create and stack a modal showing this notification. */
open(notificationKey: string): M;
open(notificationKey: string, hideBackground: boolean): M;
/** Whether a queued notification is still worth opening (not dismissed, popups still on). */
isAvailable(notificationKey: string): boolean;
/** Put the screen back to sleep. */
@@ -20,6 +20,8 @@ interface Entry {
readonly notificationKey: string;
/** Whether this notification woke the screen, so closing the last modal sleeps again. */
readonly wokeScreen: boolean;
/** Arrival-time state, independent of the inherited return-to-sleep flag. */
readonly hideBackground: boolean;
}
export class NotificationModalQueue<M> {
@@ -37,11 +39,14 @@ export class NotificationModalQueue<M> {
if (this.current) {
if (this.current.notificationKey !== notificationKey
&& !this.queued.some((entry) => entry.notificationKey === notificationKey)) {
this.queued.push({ notificationKey, wokeScreen });
this.queued.push({ notificationKey, wokeScreen, hideBackground: wokeScreen });
}
return;
}
this.current = { modal: this.host.open(notificationKey), notificationKey, wokeScreen };
this.current = {
modal: this.host.open(notificationKey, wokeScreen),
notificationKey, wokeScreen, hideBackground: wokeScreen,
};
}
/**
@@ -94,7 +99,11 @@ export class NotificationModalQueue<M> {
while (this.queued.length > 0) {
const next = this.queued.shift()!;
if (!this.host.isAvailable(next.notificationKey)) continue;
this.post(next.notificationKey, wokeScreen || next.wokeScreen);
this.current = {
...next,
wokeScreen: wokeScreen || next.wokeScreen,
modal: this.host.open(next.notificationKey, next.hideBackground),
};
return true;
}
return false;
+3 -2
View File
@@ -482,7 +482,7 @@ class Shell {
// App-posted notifications that are open or queued, by key.
private readonly appNotifications = new Map<string, AppNotification>();
private readonly notificationModals = new NotificationModalQueue<NotificationPopup>({
open: (notificationKey) => this.pushNotificationModal(notificationKey),
open: (notificationKey, hideBackground) => this.pushNotificationModal(notificationKey, hideBackground),
isAvailable: (notificationKey) => {
if (this.appNotifications.has(notificationKey)) return true;
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
@@ -926,7 +926,7 @@ class Shell {
this.openNotificationModal(notification.key, wokeScreen);
}
private pushNotificationModal(notificationKey: string): NotificationPopup {
private pushNotificationModal(notificationKey: string, hideBackground: boolean): NotificationPopup {
const appNotification = this.appNotifications.get(notificationKey);
const close = () => this.closeNotificationModal(popup, notificationKey);
const content = appNotification
@@ -951,6 +951,7 @@ class Shell {
appNotification ? appNotification.createLayer(close) : content!,
this.config.actions,
{
hideBackground,
removed: () => {
timeout.stop();
this.appNotifications.delete(notificationKey);
+1 -1
View File
@@ -1,2 +1,2 @@
export const FACECLAW_VERSION = "0.8.6";
export const FACECLAW_VERSION = "0.9.0";
export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;
@@ -224,12 +224,12 @@
INFOPLIST_KEY_CFBundleDisplayName = Faceclaw;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = "$(FACECLAW_IOS_BUNDLE_ID)";
INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = YES;
INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = NO;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchkitapp";
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchremote";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -245,12 +245,12 @@
INFOPLIST_KEY_CFBundleDisplayName = Faceclaw;
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
INFOPLIST_KEY_WKCompanionAppBundleIdentifier = "$(FACECLAW_IOS_BUNDLE_ID)";
INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = YES;
INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp = NO;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchkitapp";
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchremote";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -261,7 +261,7 @@
isa = XCBuildConfiguration;
buildSettings = {
GENERATE_INFOPLIST_FILE = YES;
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchkitapp.uitests";
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchremote.uitests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TEST_TARGET_NAME = Faceclaw;
@@ -272,7 +272,7 @@
isa = XCBuildConfiguration;
buildSettings = {
GENERATE_INFOPLIST_FILE = YES;
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchkitapp.uitests";
PRODUCT_BUNDLE_IDENTIFIER = "$(FACECLAW_IOS_BUNDLE_ID).watchremote.uitests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TEST_TARGET_NAME = Faceclaw;
+3 -3
View File
@@ -42,7 +42,7 @@ func padLine(state: PhoneState?, link: LinkStatus) -> StatusLine {
if !state.remoteEnabled { return StatusLine(text: "Watch control off", tone: .problem) }
if state.connected {
if state.charging || state.phase == "charging" {
return StatusLine(text: chargingLine(state.battery), tone: .busy, detail: caseLine(state))
return StatusLine(text: chargingLine(state), tone: .busy, detail: caseLine(state))
}
if state.silentMode { return StatusLine(text: "Silent mode", tone: .off) }
if state.locked { return StatusLine(text: "Locked", tone: .off) }
@@ -64,8 +64,8 @@ func padLine(state: PhoneState?, link: LinkStatus) -> StatusLine {
return StatusLine(text: "Disconnected", tone: .off)
}
private func chargingLine(_ battery: Int?) -> String {
battery.map { "Charging · G2 \($0)%" } ?? "Charging"
private func chargingLine(_ state: PhoneState) -> String {
state.battery.map { "Charging: \(state.glassesModel) \($0)%" } ?? "Charging"
}
/**
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<!-- Crown sensitivity is stored in the watch app's own preferences. -->
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array><string>CA92.1</string></array>
</dict>
<dict>
<!-- The monotonic clock measures touch durations and gesture deadlines. -->
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array><string>35F9.1</string></array>
</dict>
</array>
</dict>
</plist>
+4 -1
View File
@@ -103,8 +103,10 @@ struct PhoneState: Equatable {
var locked = false
var worn: Bool?
var listening = false
/** Current or last-known G2 charge percentage. */
/** The glasses' current or last-known charge percentage. */
var battery: Int?
/** The paired glasses' model, as the charging line names it. */
var glassesModel = "G2"
var charging = false
/** Last-known charging-case percentage; live only while the glasses are docked. */
var caseBattery: Int?
@@ -139,6 +141,7 @@ struct PhoneState: Equatable {
state.worn = o["worn"] as? Bool
state.listening = o["listening"] as? Bool ?? false
state.battery = percent(o["battery"])
state.glassesModel = o["glassesModel"] as? String ?? "G2"
state.charging = o["charging"] as? Bool ?? false
state.caseBattery = percent(o["caseBattery"])
state.caseCharging = o["caseCharging"] as? Bool
+29 -1
View File
@@ -112,9 +112,37 @@ xcrun devicectl device capture screenshot --device <watch-udid> --destination wa
A hook (`scripts/apple-watch-embed.cjs`) adds the watch project to the generated iOS
project after each prepare, and takes it back out if the setting is removed. The
bundle ID follows `IOS_BUNDLE_ID` (the watch app's is `<that>.watchkitapp`) and the
bundle ID follows `IOS_BUNDLE_ID` (the watch app's is `<that>.watchremote`) and the
version follows `app/version.ts`.
### TestFlight releases
Build the iPhone release with embedding enabled:
```bash
FACECLAW_EMBED_WATCH=1 npm run build:ios -- --release
```
Keep `FACECLAW_EMBED_WATCH=1` in `build_paths.sh` if that file sets the option.
Distribute the resulting `platforms/ios/build/Release-iphoneos/faceclaw.xcarchive`
through Xcode Organizer using App Store Connect. The watch companion travels inside
the iOS archive; do not upload the standalone watch development build.
Before uploading, check that `Products/Applications/faceclaw.app/Watch/Faceclaw.app`
exists in the archive. Its bundle ID must be `com.faceclaw.app.watchremote` for the
public release, with `WKCompanionAppBundleIdentifier` set to `com.faceclaw.app`.
Both apps must have the same version and build number; the hook copies the build
number from `App_Resources/iOS/Info.plist`. The watch app is dependent on the phone
app, and includes its own privacy manifest for preferences and gesture timing.
Include UUID-matching debug symbols for both apps and their embedded frameworks in
the archive's `dSYMs` directory. Name the watch symbol bundle
`FaceclawWatch.app.dSYM` when copying it from `Release-watchos/Faceclaw.app.dSYM`,
so it doesn't overwrite the phone's `faceclaw.app.dSYM` on a case-insensitive disk.
After Apple processes the upload, verify that
TestFlight's build metadata recognizes the Apple Watch companion before adding it
to Public Beta.
## Testing
```bash
@@ -0,0 +1,70 @@
# Notification focus and selected-label readability
Feature branch: `feat/notification-focus-marquee`.
## Notification backdrop
Notification popups hide the whole glasses interface only when the notification
arrived with the screen off and woke it. If the screen was already on, the usual
overlay keeps the app and chrome visible behind the box. This arrival-time choice
is preserved per queued notification, separately from the existing inherited
return-to-sleep state. For wake popups the shell omits lower chrome layers. The
box is an opaque cropped image below the firmware's 64 KiB resource limit;
resource-free retained CLEAR calls black out its outside margins over separate
app surfaces. No oversized full-screen image is uploaded. The notification's
contents and retained inner selection animations remain visible. Closing the
modal restores the existing interface; apps are not closed. The mask follows
display-size and window-band changes rather than assuming G2 dimensions.
Automated coverage crosses the real shell scene encoder and presentation replay,
checking external app pixels, chrome, margins, resource bounds, content, dismissal
restoration, resizing, band position and retained selection order.
## Selected menu labels
Common menu rows, submenu labels, toggle labels, right-value labels and Settings
panel section/option labels scroll when selected, focused and too wide. A reading
pass pauses for 900 ms, moves at approximately 30 pixels/second at Normal animation
speed, pauses at the end, returns, then stays still. Reselecting or changing the
label/geometry restarts the pass. No JavaScript frame timers are used.
The label is clipped to the available space; right-side values, arrows and toggles
stay fixed. Disabled menu animations use a static clipped fallback. Oversized
labels requiring more than 32 bounded image tiles also use the static fallback.
Custom application renderers that draw text directly are not automatically covered.
## Test baseline
The unmodified source branch at `b4a2b293` was tested separately with `npm test`:
1,218 tests, 1,213 passed, 2 failed, 3 skipped. Both existing failures are in
`tests/onboarding-devices.test.cjs`: its expectations still include the RayNeo iO
picker entry that upstream intentionally hid. Keep this independent feature free
of unrelated onboarding changes. The combined build integration updates those
assertions to the actual upstream UI.
## Feature validation
- Full standalone suite: 1,233 tests, 1,228 passed, 2 failed, 3 skipped. The only
failures are the same two independently reproduced onboarding baseline failures.
- New behavioral tests: 11 marquee tests and 4 production-encoding notification
backdrop tests passed.
- Existing menu display-list regression suite: 11 passed.
- TypeScript (`tsc --noEmit`) and lint passed; existing lint warnings remain.
## Wake-only backdrop correction
- A screen-off arrival masks app/chrome; an already-on arrival preserves them.
- Queued arrivals preserve their own mask flag, while the original wake still
restores sleep after the last popup. Closing a popup does not close its app.
- RED: the new overlay and queue assertions failed before implementation.
- GREEN: all 24 focused queue/backdrop/menu display-list tests passed.
- Full standalone suite: 1,235 tests, 1,230 passed, 2 known onboarding failures,
3 skipped. No new failures. TypeScript and lint passed.
- Combined build: 1,332 tests, 1,329 passed, 0 failed, 3 skipped; TypeScript and
lint passed. Independent review found no blocking issues.
## Hardware limitation
No phone, glasses or ring is attached to this development environment. No firmware
is flashed and no APK is installed. Automated renderer tests cannot establish
physical-glasses performance or perceived animation smoothness.
@@ -21,22 +21,31 @@ class G1FlashTimings(
@JvmField val heartbeatMs: Int = 8_000,
@JvmField val pollMs: Int = 200,
@JvmField val uploadRetries: Int = 40,
/** How often a store job's state is asked for while its notice hasn't come. */
@JvmField val storePollMs: Int = 2_000,
/** Erasing the store over Even's old fonts and pictures takes minutes. */
@JvmField val wipeMs: Int = 1_800_000,
@JvmField val crcMs: Int = 30_000,
)
/**
* Installs an MCUboot image on one G1 arm through MCUmgr SMP, or asks an arm what it runs; a port of scouter_kit's
* g1_firmware/flash.py. The caller handles one arm at a time, left first, and looks for the arm again afterwards: it
* restarts, and coming off Even's firmware it has a new address.
* g1_firmware/flash.py. The caller handles one arm at a time and looks for the arm again afterwards: it restarts, and
* coming off firmware older than g1v0 0.5.66 it has a new address.
*
* Nothing changes on the arm until the confirm, which comes only after the arm's image list shows that its second slot
* holds exactly this image. MCUboot then overwrites the running firmware with no way back. [run] blocks; the worker thread
* is the host's.
*
* [Mode.RESTORE] puts Even's firmware back on an arm running g1v0: both of a release's images, the application core's
* ([firmwarePath]) and the network core's ([netCorePath]), as Even's own update does, so the two always match.
*/
class G1ArmFlashFlow(
private val link: StockLink,
private val address: String,
private val side: String,
private val firmwarePath: String,
private val netCorePath: String,
private val mode: Mode,
/** How long to keep trying to reach the arm and pair with it. */
private val connectWindowMs: Int,
@@ -52,20 +61,30 @@ class G1ArmFlashFlow(
UPDATE,
/** Only say what the arm runs, and pair with it. */
PROBE,
/** The arm runs g1v0 and gets Even's firmware back. */
RESTORE,
}
companion object {
const val TAG = "FaceclawG1Flash"
private const val MIN_BATTERY_PERCENT = 30
private const val ANY_STORE_JOB = -1
private const val STORE_JOB_INTERRUPTED = -1
fun mode(name: String): Mode = when (name) {
"stock" -> Mode.STOCK
"update" -> Mode.UPDATE
"probe" -> Mode.PROBE
"restore" -> Mode.RESTORE
else -> throw IllegalArgumentException("unknown mode $name")
}
}
/** One image of an install: MCUboot's number for it, its bytes and the hash its slot is checked against. */
private class Part(val imageIndex: Int, val bytes: ByteArray, val label: String) {
val hash: ByteArray = G1Smp.imageHash(bytes)
}
private class LinkLostException(message: String) : Exception(message)
/** The arm has no g1v0 service. */
@@ -89,6 +108,9 @@ class G1ArmFlashFlow(
private var stockBattery: Int? = null
private var stockBatteryLatch: Latch? = null
/** `NOTICE` 8s since the store job now waited for was asked for. */
private val storeNotices = ArrayList<G1Protocol.StoreNotice>()
/** The OS's half of a stale pairing goes once per run: a second failure isn't that. */
private var bondRemoved = false
@@ -111,7 +133,11 @@ class G1ArmFlashFlow(
fun run() {
link.setListener(this)
try {
if (mode == Mode.PROBE) probe() else install()
when (mode) {
Mode.PROBE -> probe()
Mode.RESTORE -> restore()
else -> install()
}
} catch (e: Exception) {
val message = if (cancelled) "Cancelled." else StockLinkSession.messageOf(e)
log("failed: $message")
@@ -135,13 +161,15 @@ class G1ArmFlashFlow(
listener.onComplete(true, """{"firmware":"g1v0","version":"${hello.version}","safeMode":${hello.safeMode},"inCase":${hello.inCase},"battery":${batteryPercent()}}""")
}
private fun readFirmware(path: String): ByteArray = try {
readImage(path)
} catch (e: Exception) {
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
}
private fun install() {
listener.onState("validating", side)
val image = try {
readImage(firmwarePath)
} catch (e: Exception) {
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
}
val image = readFirmware(firmwarePath)
val version = G1Smp.imageVersion(image)
val hash = G1Smp.imageHash(image)
log("image $version, ${image.size} bytes, hash ${BinaryEncoding.bytesToHex(hash.copyOf(8))}")
@@ -166,15 +194,15 @@ class G1ArmFlashFlow(
val slots = retrying { images() }
for (slot in slots) log(slot.toString())
listener.onState("flashing", side)
if (holdsImage(slots, hash)) {
if (holdsImage(slots, G1Smp.IMAGE_APP, hash)) {
log("the second slot already holds this image")
listener.onProgress(side, 1, 1, image.size, image.size, image.size.toLong(), image.size.toLong())
} else {
val startedAt = now()
upload(image)
upload(image, G1Smp.IMAGE_APP)
log("uploaded in ${(now() - startedAt) / 1000} s")
}
if (!holdsImage(retrying { images() }, hash)) {
if (!holdsImage(retrying { images() }, G1Smp.IMAGE_APP, hash)) {
throw IllegalStateException("The $side arm's second slot doesn't hold the image after the upload. Nothing was installed.")
}
throwIfCancelled()
@@ -184,6 +212,82 @@ class G1ArmFlashFlow(
val code = G1Smp.replyCode(confirm)
if (code != 0) throw IllegalStateException("The $side arm refused the image (error $code). Nothing was installed.")
log("confirmed: MCUboot installs it at the next boot")
reset()
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
/**
* Even's firmware back on an arm running g1v0: the store cleared if g1v0 ever wrote to it, then both images uploaded
* and checked, and only then marked for MCUboot, the network core first. MCUboot installs both at the reset, the
* network core through its own path to that core, as at every update from Even.
*/
private fun restore() {
listener.onState("validating", side)
val parts = listOf(
Part(G1Smp.IMAGE_NET_CORE, readFirmware(netCorePath), "network core"),
Part(G1Smp.IMAGE_APP, readFirmware(firmwarePath), "application"),
)
for (part in parts) log("${part.label} image: ${part.bytes.size} bytes, hash ${BinaryEncoding.bytesToHex(part.hash.copyOf(8))}")
listener.onState("connecting", side)
bringUp()
listener.onState("checking", side)
val hello = hello()
log("runs g1v0 ${hello.version}, safe mode ${hello.safeMode}, in the case ${hello.inCase}, encrypted ${hello.encrypted}")
requireBattery(batteryPercent())
val wiped = clearStore(hello)
val slots = retrying { images() }
for (slot in slots) log(slot.toString())
listener.onState("flashing", side)
val total = parts.sumOf { it.bytes.size }
var before = 0
for ((index, part) in parts.withIndex()) {
if (holdsImage(slots, part.imageIndex, part.hash)) {
log("the ${part.label}'s second slot already holds Even's image")
listener.onProgress(side, index + 1, parts.size, part.bytes.size, part.bytes.size, (before + part.bytes.size).toLong(), total.toLong())
} else {
val startedAt = now()
upload(part.bytes, part.imageIndex, index + 1, parts.size, before, total)
log("${part.label} uploaded in ${(now() - startedAt) / 1000} s")
}
before += part.bytes.size
}
val uploaded = retrying { images() }
for (part in parts) {
if (!holdsImage(uploaded, part.imageIndex, part.hash)) {
throw IllegalStateException("The $side arm's slot for its ${part.label} doesn't hold Even's image after the upload. Nothing was installed.")
}
}
throwIfCancelled()
listener.onState("committing", side)
// The network core first. If the second request fails, what's left pending is Even's network core under g1v0,
// which g1v0 works with (its fallback installs this very image); Even's application over the older network core
// is the combination that has never been tried.
for (part in parts) {
val permanent = part.imageIndex == G1Smp.IMAGE_APP
val reply = smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(part.hash, permanent), timings.smpReplyMs)
val code = G1Smp.replyCode(reply)
if (code != 0) {
throw IllegalStateException("The $side arm refused Even's ${part.label} image (error $code). The arm wasn't restarted; retry to try again.")
}
}
val marked = retrying { images() }
for (slot in marked) log(slot.toString())
for (part in parts) {
if (!marked.any { it.image == part.imageIndex && it.slot == 1 && it.hash.contentEquals(part.hash) && "pending" in it.flags }) {
throw IllegalStateException("The $side arm didn't mark Even's ${part.label} image for installing. The arm wasn't restarted; retry to try again.")
}
}
log("both images marked: MCUboot installs them at the next boot")
reset()
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"firmware":"stock","wiped":$wiped}""")
}
private fun reset() {
try {
smp(G1Smp.OP_WRITE, G1Smp.GROUP_OS, G1Smp.CMD_OS_RESET, emptyMap(), timings.resetReplyMs)
} catch (e: StockTimeoutException) {
@@ -191,8 +295,144 @@ class G1ArmFlashFlow(
} catch (e: LinkLostException) {
log("the link went down with the reset")
}
listener.onState("rebooting", side)
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
// ---- the asset store ---------------------------------------------------------
/**
* Before Even's firmware goes back: g1v0's asset store took the flash where Even's fonts and pictures were, so if it
* ever wrote there, Even's firmware must meet erased flash (flash.py's `wipe_store`). A store that was never written
* is left alone, and Even's data with it. True when it was erased.
*/
private fun clearStore(hello: G1Protocol.Hello): Boolean {
repeat(3) {
val info = assetInfo()
if (info == null) {
log("no asset store: this firmware never wrote where Even's data is")
return false
}
if (!info.available) {
log("the asset store is unavailable, so nothing was written to it")
return false
}
if (info.running) {
// A retried request can find its own job running, as can a retry after a link lost during a wipe.
log("a storage job is running: waiting for it to end")
clearStoreNotices()
waitStoreJob(ANY_STORE_JOB, timings.wipeMs.toLong())
return@repeat
}
if (!storeWritten(info, hello)) {
log("the asset store was never written: Even's fonts and pictures stay as they are")
return false
}
if (hello.safeMode) throw IllegalStateException(safeModeMessage())
listener.onState("wiping", side)
log("erasing the asset store (${info.assets} assets, commit ${info.seq})")
val startedAt = now()
clearStoreNotices()
when (val status = control(G1Protocol.OP_ASSET_FORMAT, G1Protocol.assetFormatRequest(wipe = true)).status) {
0 -> {
val result = waitStoreJob(G1Protocol.STORE_JOB_FORMAT, timings.wipeMs.toLong())
if (result == STORE_JOB_INTERRUPTED) {
throw IllegalStateException("The $side arm restarted while erasing Faceclaw's storage. Nothing was installed; retry to finish it.")
}
if (result != 0) {
throw IllegalStateException("The $side arm couldn't erase Faceclaw's storage (error $result). Nothing was installed.")
}
log("asset store erased in ${(now() - startedAt) / 1000} s")
return true
}
G1Protocol.STATUS_SAFE_MODE -> throw IllegalStateException(safeModeMessage())
// A job runs: the next round waits for it.
G1Protocol.STATUS_ASSET -> {}
else -> throw IllegalStateException("The $side arm refused to erase Faceclaw's storage (error $status). Nothing was installed.")
}
}
throw IllegalStateException("The $side arm's storage couldn't be erased. Nothing was installed.")
}
private fun safeModeMessage(): String =
"The $side arm is in safe mode (its firmware restarted repeatedly), where it can't erase Faceclaw's storage, and that has to " +
"happen before Even's firmware goes back. Install Faceclaw's firmware again, then uninstall it. Nothing was installed."
/**
* Whether g1v0 ever wrote to the store. It only reads it at boot, so with no assets and no commit nothing was written,
* unless a format erased the directory's two sectors (a format resets the commit count), which their fingerprint shows.
*/
private fun storeWritten(info: G1Protocol.AssetInfo, hello: G1Protocol.Hello): Boolean {
if (info.assets > 0 || info.seq != 0L) return true
if (hello.safeMode) {
log("safe mode: the directory can't be checked")
return true
}
val nonErased = flashNonErased(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES)
log("the store's directory sectors: ${nonErased ?: "unknown"} bytes not erased")
return nonErased == null || nonErased == 0L
}
/** How many bytes of flash [from]…[from] + [n] - 1 aren't 0xFF, or null when the arm didn't say. */
private fun flashNonErased(from: Int, n: Int): Long? {
clearStoreNotices()
val status = try {
control(G1Protocol.OP_FLASH_CRC, G1Protocol.flashCrcRequest(from, n)).status
} catch (e: StockTimeoutException) {
return null
}
// 13: a crc job runs, which a retried request finds when the first one's reply was lost; its notice says the same.
if (status != 0 && status != G1Protocol.STATUS_ASSET) return null
val deadline = now() + timings.crcMs
while (now() < deadline) {
throwIfCancelled()
val notice = lock.withLock {
storeNotices.firstOrNull { it.job == G1Protocol.STORE_JOB_CRC && it.address == from && it.n == n }
}
if (notice != null) return if (notice.result == 0) notice.nonErased else null
if (!link.isConnected(address)) return null
sleeper.sleep(timings.pollMs.toLong())
}
return null
}
private fun assetInfo(): G1Protocol.AssetInfo? {
val reply = control(G1Protocol.OP_ASSET_INFO)
return if (reply.status == 0) G1Protocol.parseAssetInfo(reply.body) else null
}
private fun clearStoreNotices() = lock.withLock { storeNotices.clear() }
/**
* The result of the store job running now: its `NOTICE` 8, or `ASSET_INFO`'s state once it has ended (a notice is lost
* with the link, and the job goes on without it). [STORE_JOB_INTERRUPTED] when the arm restarted meanwhile, which ends
* a job unfinished.
*/
private fun waitStoreJob(job: Int, timeoutMs: Long): Int {
val deadline = now() + timeoutMs
var askAt = now() + timings.storePollMs
while (true) {
throwIfCancelled()
val notice = lock.withLock { storeNotices.firstOrNull { job == ANY_STORE_JOB || it.job == job } }
if (notice != null) return notice.result
if (now() >= deadline) throw StockTimeoutException("the $side arm's storage job didn't end within ${timeoutMs / 60_000} minutes")
if (now() >= askAt) {
askAt = now() + timings.storePollMs
val info = try {
assetInfo()
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
log("no answer while the storage job runs (${e.message})")
reconnectIfNeeded()
null
}
when (info?.state) {
G1Protocol.STORE_DONE -> return info.lastError
G1Protocol.STORE_FAILED -> return if (info.lastError != 0) info.lastError else G1Protocol.STATUS_ASSET
// A job leaves the state at done or failed until the next boot.
G1Protocol.STORE_IDLE -> return STORE_JOB_INTERRUPTED
}
}
sleeper.sleep(timings.pollMs.toLong())
}
}
private fun requireBattery(percent: Int?) {
@@ -202,21 +442,24 @@ class G1ArmFlashFlow(
}
}
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
private fun holdsImage(slots: List<G1Smp.Slot>, imageIndex: Int, hash: ByteArray): Boolean =
slots.any { it.image == imageIndex && it.slot == 1 && it.hash.contentEquals(hash) }
private fun images(): List<G1Smp.Slot> =
G1Smp.parseSlots(smp(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, emptyMap(), timings.smpReplyMs))
/** MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. */
private fun upload(image: ByteArray) {
/**
* MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. Progress counts
* [before] bytes of earlier parts out of [total].
*/
private fun upload(image: ByteArray, imageIndex: Int, part: Int = 1, parts: Int = 1, before: Int = 0, total: Int = image.size) {
val fileSha = sha256(image)
var offset = 0
var failures = 0
while (offset < image.size) {
throwIfCancelled()
val reply = try {
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha), timings.uploadReplyMs)
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha, imageIndex), timings.uploadReplyMs)
} catch (e: Exception) {
if (e !is StockTimeoutException && e !is LinkLostException) throw e
failures++
@@ -231,7 +474,7 @@ class G1ArmFlashFlow(
throw IllegalStateException("The $side arm refused the upload at $offset (error $code). Nothing was installed.")
}
offset = next
listener.onProgress(side, 1, 1, offset, image.size, offset.toLong(), image.size.toLong())
listener.onProgress(side, part, parts, offset, image.size, (before + offset).toLong(), total.toLong())
}
}
@@ -525,6 +768,11 @@ class G1ArmFlashFlow(
stockBatteryLatch?.countDown()
}
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
val notice = G1Protocol.parseStoreNotice(data)
if (notice != null) {
lock.withLock { storeNotices.add(notice) }
return
}
val reply = G1Protocol.parseReply(data) ?: return
lock.withLock {
if (reply.tag == controlTag) {
@@ -39,9 +39,17 @@ object G1Protocol {
const val OP_PROPS = 0x0A
const val OP_MIC = 0x13
const val OP_EVENTS = 0x14
const val OP_ASSET_INFO = 0x17
const val OP_ASSET_FORMAT = 0x1B
const val OP_FLASH_CRC = 0x1C
const val OP_FC_INFO = 0x1D
const val OP_PROP_SET = 0x1E
/** Control statuses (VM.md §1). */
const val STATUS_SAFE_MODE = 7
/** A store request: a job runs, no space, no store. */
const val STATUS_ASSET = 13
const val EV_NOTICE = 0x05
const val EV_MIC_DATA = 0x06
const val EV_INPUT = 0x07
@@ -65,6 +73,18 @@ object G1Protocol {
const val NOTICE_MIC_STOPPED = 5
const val MIC_STOPPED_LEASE = 3
const val NOTICE_GUARD = 7
/** A store job ended (VM.md §6.10). */
const val NOTICE_STORE_JOB = 8
const val STORE_JOB_FORMAT = 3
const val STORE_JOB_CRC = 4
/** `ASSET_INFO`'s job states. */
const val STORE_IDLE = 0
const val STORE_DONE = 4
const val STORE_FAILED = 5
/** The asset store's partition in the arm's QSPI flash, where Even's fonts and pictures were; its first two sectors hold its directory. */
const val STORE_ADDRESS = 0x140000
const val STORE_DIRECTORY_BYTES = 2 * 4096
const val PROP_BATT_PCT = 0x11
const val PROP_CHARGE = 0x12
@@ -156,6 +176,50 @@ object G1Protocol {
return Notice(data[EVENT_HEADER].toInt() and 255, data.copyOfRange(EVENT_HEADER + 1, data.size))
}
/** `ASSET_FORMAT` frees the whole store; with [wipe] it also erases every sector that isn't erased already. */
fun assetFormatRequest(wipe: Boolean): ByteArray =
le32(0x534B4153) + if (wipe) le32(0x50570000) else ByteArray(0)
/** `FLASH_CRC`: a read-only fingerprint of flash bytes address…address + n - 1, given in `NOTICE` 8. */
fun flashCrcRequest(address: Int, n: Int): ByteArray = le32(address) + le32(n)
class AssetInfo(
@JvmField val assets: Int,
@JvmField val state: Int,
@JvmField val lastError: Int,
/** Without a usable flash there is no store, and nothing was ever written to it. */
@JvmField val available: Boolean,
/** The directory's commit count: 0 for a store that is empty and never was written, or was formatted since. */
@JvmField val seq: Long,
) {
val running: Boolean get() = state in 1..3
}
fun parseAssetInfo(body: ByteArray): AssetInfo? {
if (body.size < 20) return null
return AssetInfo(body[12].toInt() and 255, body[13].toInt() and 255, body[14].toInt() and 255, body[15].toInt() and 1 != 0,
u32(body, 16).toLong() and 0xffffffffL)
}
class StoreNotice(
@JvmField val job: Int,
@JvmField val result: Int,
/** A crc job's range, crc32 and how many of its bytes are not 0xFF; 0 for the other jobs. */
@JvmField val address: Int,
@JvmField val n: Int,
@JvmField val nonErased: Long,
)
fun parseStoreNotice(data: ByteArray): StoreNotice? {
val notice = parseNotice(data) ?: return null
val body = notice.body
if (notice.kind != NOTICE_STORE_JOB || body.size < 18) return null
return StoreNotice(body[0].toInt() and 255, body[1].toInt() and 255, u32(body, 2), u32(body, 6), u32(body, 14).toLong() and 0xffffffffL)
}
private fun le32(value: Int): ByteArray =
byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
/**
* What the arm's light reading looks like to [BrightnessPolicy] and the Developer app: a live passive poll in the
* G2 custom firmware's report (settings field 105), whose value counts tenths of a lux.
@@ -197,17 +197,28 @@ object G1Smp {
return (frame.indices step size).map { frame.copyOfRange(it, minOf(it + size, frame.size)) }
}
/** The first chunk also says what is coming, which lets the arm resume an upload of the same file. */
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray): Map<String, Any?> {
/** MCUboot's image numbers on an nRF5340: the application core, and the network core (the Bluetooth controller). */
const val IMAGE_APP = 0
const val IMAGE_NET_CORE = 1
/**
* The first chunk also says what is coming, which lets the arm resume an upload of the same file, and which image it
* is: each has its own second slot.
*/
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray, imageIndex: Int = IMAGE_APP): Map<String, Any?> {
val data = image.copyOfRange(offset, minOf(offset + UPLOAD_CHUNK, image.size))
return if (offset == 0) {
mapOf("image" to 0, "len" to image.size, "off" to 0, "sha" to fileSha256, "data" to data, "upgrade" to false)
mapOf("image" to imageIndex, "len" to image.size, "off" to 0, "sha" to fileSha256, "data" to data, "upgrade" to false)
} else {
mapOf("off" to offset, "data" to data)
}
}
fun confirmRequest(imageHash: ByteArray): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to true)
/**
* Marks the image with this hash for MCUboot's next boot. [permanent] false is a test install, which is what Even's app
* and g1v0's own network-core fallback ask for on image 1; the network core has no copy to go back to either way.
*/
fun confirmRequest(imageHash: ByteArray, permanent: Boolean = true): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to permanent)
/** Joins notifications into replies; [feed] gives each complete one as sequence number and body. */
class Assembler {
@@ -172,8 +172,8 @@ class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath
}
}
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, or a question about what it runs. */
class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: String, connectWindowMs: Int) {
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, its restore to Even's firmware, or a question about what it runs. */
class IosG1Flasher(address: String, side: String, firmwarePath: String, netCorePath: String, mode: String, connectWindowMs: Int) {
private val link = IosBleCentral()
private val lock = IosProtocolPlatform.createLock()
private var started = false
@@ -184,6 +184,7 @@ class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: St
address,
side,
firmwarePath,
netCorePath,
G1ArmFlashFlow.mode(mode),
connectWindowMs,
object : FaceclawFirmwareFlasherListener {
+4
View File
@@ -26,10 +26,14 @@ function embedEnabled() {
/** Xcode's own builds of the watch project read this too, so they sign the same way. */
function writeLocalConfig() {
const version = /FACECLAW_VERSION = "(.*)"/.exec(fs.readFileSync(path.join(root, 'app/version.ts'), 'utf8'))[1];
const build = execFileSync('/usr/libexec/PlistBuddy', [
'-c', 'Print :CFBundleVersion', path.join(root, 'App_Resources/iOS/Info.plist'),
], { encoding: 'utf8' }).trim();
const lines = [
`FACECLAW_IOS_BUNDLE_ID = ${process.env.IOS_BUNDLE_ID || 'com.faceclaw.app'}`,
// An embedded watch app has to carry the phone app's version.
`MARKETING_VERSION = ${version}`,
`CURRENT_PROJECT_VERSION = ${build}`,
];
if (process.env.IOS_TEAM_ID) lines.push(`DEVELOPMENT_TEAM = ${process.env.IOS_TEAM_ID}`);
fs.writeFileSync(path.join(root, 'apple-watch/Local.xcconfig'), `${lines.join('\n')}\n`);
+13 -4
View File
@@ -429,8 +429,9 @@ const shellScene = require('../.test-build/app/graphics/shell-scene.js');
const displayList = require('../.test-build/app/graphics/display-list.js');
const notificationTypes = require('../.test-build/app/native/notification-types.js');
const ICON = notificationTypes.NOTIFICATION_ICON_SIZE;
function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, trayIcons = [] } = {}) {
const font = { lineHeight: 12, ascent: 10, measureText: (text) => text.length * 4,
function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, trayIcons = [], glassesModel = 'G2' } = {}) {
const measuredText = [];
const font = { lineHeight: 12, ascent: 10, measureText: (text) => { measuredText.push(text); return text.length * 4; },
drawText: (image, x, y, text, value) => { for (let i = 0; i < text.length; i++) image.fillRect(x + i * 4, y + 2, 2, 6, value); } };
let nextKey = 100;
const requested = [];
@@ -451,7 +452,7 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t
'../../native/phone-battery': { readPhoneBatteryState: () => ({ battery: phoneBattery, charging: false }) },
'../../util/render-freshness': { renderPassAllowsStaleData: () => false },
'../dashboard-settings': { batteryDisplayModeSetting: { get: () => 'icon' }, phoneBatteryVisibilitySetting: settings,
batteryIndicatorVisible: () => true },
glassesBatteryVisibilitySetting: settings, glassesModelName: () => glassesModel, batteryIndicatorVisible: () => true },
'../clock-format': { formatClockDate: () => 'Thu Oct 2', formatClockTime: () => '9:41' },
'../layers': { LayerStack: { allocateShellKey: () => nextKey++ } },
// As in menu.ts.
@@ -469,11 +470,19 @@ function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, t
};
let heightChanges = 0;
const chrome = new context.exports.ShellChromeLayer(() => state, () => heightChanges++);
return { chrome, state, requested, planBottomBar: context.exports.planBottomBar, heightChanges: () => heightChanges };
return { chrome, state, requested, measuredText, planBottomBar: context.exports.planBottomBar, heightChanges: () => heightChanges };
}
const notification = (key) => ({ kind: 'notification', key });
const keysOf = (items) => Array.from(items, (item) => item.key);
test('the top bar labels the glasses battery with the paired model', () => {
const { chrome, state, measuredText } = chromeLayer(geometry(), { glassesModel: 'G1' });
state.battery.headset = 72;
chrome.paintParts();
assert.ok(measuredText.includes('G1'));
assert.ok(!measuredText.includes('G2'));
});
test('a bottom app switcher frames the foreground window\'s content in a rounded border', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
@@ -60,7 +60,6 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
deleteAsrModel() {}, startAsrModelDownload() {}, onAsrModelStateChanged: () => () => {},
},
'../../apps/files/text-viewer': { TextViewerLayer: class {} },
'../../analytics/privacy-disclosure': { IOS_PRIVACY_NOTICE: '' },
'../menu': {
drawRightValueMenuItem() {}, openModalMenu() {},
submenuItem: label => ({ label, onSelect() {} }),
-2
View File
@@ -12,7 +12,6 @@ const {
MINIMUM_METERS,
MAXIMUM_METERS,
zoneFromMeters,
zoneLabel,
sortedByProximity,
} = require("../.test-build/app/g2/ble-proximity.js");
@@ -59,7 +58,6 @@ test("zones and their boundaries", () => {
assert.equal(zoneFromMeters(3), "far");
assert.equal(zoneFromMeters(9.9), "far");
assert.equal(zoneFromMeters(10), "distant");
assert.equal(zoneLabel("immediate"), "In your hand");
});
test("weak signals carry lower confidence", () => {
+1 -1
View File
@@ -33,7 +33,7 @@ const menu = load('app/ui/menu.ts', {
'../graphics/image': graphics, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
'./menu-core': load('app/ui/menu-core.ts', {
'../graphics/image': graphics, './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'../graphics/image': graphics, './menu-label': require('../.test-build/app/ui/menu-label.js'), './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
}),
});
+8
View File
@@ -35,6 +35,14 @@ test('the display mode starts as the middle band, or carries over the old mode a
assert.equal(api.displayLayoutSetting.get(), 'band-bottom');
});
test('the glasses model name follows the paired glasses type', () => {
const model = (entries) => settingsFixture(new Map(entries)).glassesModelName();
assert.equal(model([]), 'G2');
assert.equal(model([['deviceType', 'g2']]), 'G2');
assert.equal(model([['deviceType', 'g1']]), 'G1');
assert.equal(model([['deviceType', 'rayneo-io']]), 'iO');
});
test('per-app display modes carry over their old mode and position where the merged values can say it', () => {
const app = (appId, entries) => settingsFixture(new Map(entries))[`${appId}DisplayLayoutSetting`].get();
assert.equal(app('navigate', []), 'global');
+299
View File
@@ -0,0 +1,299 @@
// EvenHub with a RayNeo iO paired: the store shows only a notice (and loads
// nothing), and each sideloaded app warns once that it won't display
// correctly. The real layers run with their dependencies mocked; what they
// paint is collected as text.
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const gestures = loader({}, {})('app/ui/gestures.ts');
const font = { lineHeight: 10, measureText: (text) => text.length * 6 };
/** Records drawn text; every other drawing call is a no-op. */
const makeImageClass = (drawn) => class {
drawText(_font, _x, _y, text) { drawn.push(text); }
fillRect() {}
fillRoundedRect() {}
drawRoundedRect() {}
};
const settle = () => new Promise((resolve) => setImmediate(resolve));
// ---- the store -----------------------------------------------------------
const emptyPage = { apps: [], total: 0, page: 1, pageSize: 20 };
class FakeMenu {
constructor(options) { this.options = options; this.items = options.items; this.selectedIndex = 0; }
setItems(items) { this.items = items; }
get selectedItem() { return this.items[this.selectedIndex] ?? null; }
handleInput() {}
paint(image, box) { this.items.forEach((item, index) => this.options.draw({ image, item, index, x: box.x, y: box.y, width: box.width })); }
drawScrollbar() {}
}
const loadStore = () => {
const drawn = [];
const glasses = { available: false };
const calls = { listApps: 0, yields: 0 };
const setting = { get: () => '', set() {} };
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: makeImageClass(drawn) },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] },
'../../ui/gestures': { ...gestures, GESTURE_CLICK: 'click' },
'../../ui/menu': { drawSelectionHighlight() {} },
'../../ui/menu-core': { Menu: FakeMenu },
'../../ui/shell/shell': { shell: { yieldFocusToSidebar() { calls.yields++; } } },
'../../ui/metrics': { lineStep: () => 12 },
'../../ui/dashboard-settings': {
ConfigSettingString: class { constructor(options) { this.value = options.defaultValue ?? ''; }
get() { return this.value; } set(next) { this.value = next; return next; } },
},
'./even-api': {
evenHubApi: {
listApps: async () => { calls.listApps++; return emptyPage; },
listNewApps: async () => emptyPage,
searchApps: async () => emptyPage,
},
EvenHubAuthenticationError: class extends Error {},
isEvenHubStoreConfigured: () => true,
},
'./credentials': {
evenHubLoginEmailSetting: setting, evenHubLoginPasswordSetting: setting, evenHubRememberMeSetting: setting,
clearEvenHubLoginForm() {}, resetEvenHubLoginForm() {}, clearEvenHubSession() {}, clearTransientEvenHubSession() {},
},
'./installed-apps': { getInstalledEvenHubApps: () => [], uninstallEvenHubPackage: () => true },
'./store-detail-layer': { EvenHubStoreDetailLayer: class {} },
'./store-install': { cleanError: (error) => String(error), installStoreApp: async () => ({}) },
'./updates': { checkForEvenHubUpdates: async () => [], describeUpdate: () => ({}) },
'./glasses-compat': { isEvenHubStoreAvailable: () => glasses.available },
});
const { EvenHubStoreLayer } = load('app/apps/evenhub/store-layer.ts');
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
const stackCalls = { push: 0, clearToBase: 0 };
const ctx = {
stack: {
getBaseSize: () => ({ width: 476, height: 180 }),
isFocused: () => true,
clearToBase() { stackCalls.clearToBase++; },
push() { stackCalls.push++; },
pop() {},
},
actions: { requestRender() {}, endTextSettingEdit() {}, startTextSettingsEdit() {} },
};
const repaint = () => {
drawn.length = 0;
layer.paint(ctx);
return [...drawn];
};
return { layer, ctx, glasses, calls, stackCalls, repaint };
};
const NOTICE = 'Using the Even Realities app store requires Even Realities glasses.';
test('with a RayNeo iO the store shows the notice and loads nothing', async () => {
const { layer, ctx, calls, repaint } = loadStore();
const painted = repaint();
assert.ok(painted.includes(NOTICE), JSON.stringify(painted));
assert.ok(!painted.includes('Top'), 'no tabs');
await settle();
assert.equal(calls.listApps, 0, 'no request to the store');
assert.equal(layer.buildMenuItems().length, 0, 'no store actions in the window menu');
await layer.handleInput({ type: 'click', source: 'ring' }, ctx);
await layer.handleInput({ type: 'scroll-down' }, ctx);
layer.receiveTextInput('chess', ctx);
await settle();
assert.equal(calls.listApps, 0, 'input and dictation do nothing');
assert.ok(repaint().includes(NOTICE));
await layer.handleInput({ type: 'double-click', source: 'ring' }, ctx);
await layer.handleInput({ type: 'swipe-left', source: 'watch', timestampMs: 0 }, ctx);
assert.equal(calls.yields, 2, 'double-click and a back swipe leave the window');
});
test('an installed app\'s store page opens to the notice, naming the app', () => {
const { layer, ctx, stackCalls, repaint } = loadStore();
layer.showInstalledPackage(ctx.stack, { packageId: 'com.example.alpha', name: 'Alpha', version: '1' });
assert.equal(stackCalls.push, 0, 'no store page is opened');
assert.equal(stackCalls.clearToBase, 1, 'pages above the notice are closed');
const painted = repaint();
assert.ok(painted.includes("Alpha's package is missing."), JSON.stringify(painted));
assert.ok(painted.includes(NOTICE));
});
test('the store comes back once Even Realities glasses are paired', async () => {
const { glasses, calls, repaint } = loadStore();
repaint();
glasses.available = true;
repaint();
await settle();
assert.equal(calls.listApps, 1, 'the Top tab loads on the first paint it gets');
const painted = repaint();
assert.ok(!painted.includes(NOTICE));
assert.ok(painted.includes('Public apps by popularity'), JSON.stringify(painted));
});
// ---- the display warning ---------------------------------------------------
const loadWarning = () => {
const drawn = [];
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: makeImageClass(drawn) },
'../../graphics/textwrap': { wrapText: (_f, text) => [text] },
'../../ui/gestures': gestures,
'../../ui/layers': {},
'../../ui/menu': { drawListScrollbar() {}, drawSelectionHighlight() {} },
'../../ui/metrics': { lineStep: () => 12, listRowHeight: () => 20 },
});
const { EvenHubDisplayWarningLayer } = load('app/apps/evenhub/display-warning-dialog.ts');
const ImageClass = makeImageClass(drawn);
const outcome = { answered: 0, closed: 0, popped: 0 };
const dialog = new EvenHubDisplayWarningLayer(
'Demo',
() => { outcome.answered++; },
() => { outcome.closed++; },
);
// The real stack calls onRemoved as it pops.
const ctx = {
stack: {
getBaseSize: () => ({ width: 476, height: 180 }),
isFocused: () => true,
pop() { outcome.popped++; dialog.onRemoved(); },
},
};
const paint = () => {
drawn.length = 0;
dialog.paint(ctx, () => new ImageClass());
return [...drawn];
};
return { dialog, ctx, paint, outcome };
};
test('the display warning names the app and the reason', () => {
const { paint } = loadWarning();
const painted = paint();
assert.ok(painted.includes('Compatibility warning'));
const message = painted.find((text) => text.includes('Demo'));
assert.ok(message, JSON.stringify(painted));
assert.match(message, /will not display correctly on the RayNeo iO/);
assert.match(message, /different resolution/);
assert.ok(painted.includes('Continue') && painted.includes('Close app'));
});
test('Continue dismisses the warning and leaves the app running', () => {
const { dialog, ctx, paint, outcome } = loadWarning();
paint();
dialog.handleInput({ type: 'click', source: 'ring' }, ctx);
assert.deepEqual(outcome, { answered: 1, closed: 0, popped: 1 });
});
test('Close app dismisses the warning and closes the app', () => {
const { dialog, ctx, paint, outcome } = loadWarning();
paint();
dialog.handleInput({ type: 'scroll-down' }, ctx);
dialog.handleInput({ type: 'click', source: 'ring' }, ctx);
assert.deepEqual(outcome, { answered: 1, closed: 1, popped: 1 });
});
test('double-click dismisses the warning; closing the window under it does not count', () => {
const backedOut = loadWarning();
backedOut.paint();
backedOut.dialog.handleInput({ type: 'double-click', source: 'ring' }, backedOut.ctx);
assert.deepEqual(backedOut.outcome, { answered: 1, closed: 0, popped: 1 });
const abandoned = loadWarning();
abandoned.paint();
abandoned.dialog.onRemoved();
assert.deepEqual(abandoned.outcome, { answered: 0, closed: 0, popped: 0 }, 'shown again next launch');
});
// ---- which launches warn -------------------------------------------------
const loadCompat = (glassesType) => {
const store = new Map();
const glasses = { type: glassesType };
const compat = loader({}, {
'../../ui/dashboard-settings': { glassesTypeSetting: { get: () => glasses.type } },
'../../native/settings-store': {
getStringSetting: (key, fallback) => (store.has(key) ? store.get(key) : fallback),
setStringSetting: (key, value) => { store.set(key, value); },
},
})('app/apps/evenhub/glasses-compat.ts');
return { compat, glasses };
};
test('each app warns once with a RayNeo iO paired, and never with Even glasses', () => {
const { compat, glasses } = loadCompat('rayneo-io');
assert.equal(compat.isEvenHubStoreAvailable(), false);
assert.equal(compat.needsDisplayWarning('com.example.a'), true);
compat.markDisplayWarningShown('com.example.a');
compat.markDisplayWarningShown('com.example.a');
assert.equal(compat.needsDisplayWarning('com.example.a'), false, 'answered once');
assert.equal(compat.needsDisplayWarning('com.example.b'), true, 'another app still warns');
glasses.type = 'g2';
assert.equal(compat.isEvenHubStoreAvailable(), true);
assert.equal(compat.needsDisplayWarning('com.example.b'), false);
glasses.type = 'g1';
assert.equal(compat.isEvenHubStoreAvailable(), true);
assert.equal(compat.needsDisplayWarning('com.example.b'), false);
});
// ---- the app window ------------------------------------------------------
const loadWindow = (needsWarning) => {
const pushed = [];
const closed = [];
const marked = [];
class FakeWarning { constructor(appName, onAnswered, closeApp) { Object.assign(this, { appName, onAnswered, closeApp }); } }
const load = loader({}, {
'../../graphics/image': { GrayImage: class {} },
'./compositor': { EVENHUB_SCREEN_WIDTH: 576 },
'../../ui/gestures': gestures,
'../../ui/layers': {},
'../../ui/shell/in-process-window': {
createInProcessWindow: () => ({
stack: { push: (layer) => pushed.push(layer) },
window: { handleInput: async () => {} },
requestRender() {},
setHeightMode() {},
}),
},
'../../ui/shell/shell': { shell: { closeWindow: (id) => closed.push(id), foregroundWindow: () => null } },
'../../ui/shell/chrome-layer': { makeImageWindowIcon: () => () => {}, windowIcon: () => () => {} },
'./session': { EvenHubSession: class {} },
'./installed-apps': { renderInstalledEvenHubIcon: () => null },
'./glasses-compat': {
needsDisplayWarning: () => needsWarning,
markDisplayWarningShown: (id) => marked.push(id),
},
'./display-warning-dialog': { EvenHubDisplayWarningLayer: FakeWarning },
});
const { createEvenHubWindow } = load('app/apps/evenhub/evenhub-window.ts');
const session = {
manifest: { packageId: 'com.example.demo', name: 'Demo' },
attachWindow() {},
};
const options = { actions: {}, submitFrame() {}, setSurfaceVisible() {}, removeSurface() {}, onClosed() {} };
createEvenHubWindow('evenhub:app:7', 'evenhub', session, options, () => {}, () => {});
return { pushed, closed, marked, FakeWarning };
};
test('an EvenHub window opens under the warning when the app needs one', () => {
const { pushed, closed, marked, FakeWarning } = loadWindow(true);
assert.equal(pushed.length, 1);
const warning = pushed[0];
assert.ok(warning instanceof FakeWarning);
assert.equal(warning.appName, 'Demo');
warning.onAnswered();
assert.deepEqual(marked, ['com.example.demo']);
warning.closeApp();
assert.deepEqual(closed, ['evenhub:app:7']);
});
test('an EvenHub window opens straight to the app otherwise', () => {
assert.equal(loadWindow(false).pushed.length, 0);
});
+1
View File
@@ -62,6 +62,7 @@ const loadStoreLayer = ({ configured = false, api = {} } = {}) => {
'./store-detail-layer': { EvenHubStoreDetailLayer: class { constructor(_app, options) { detailOptions.push(options); } } },
'./store-install': { cleanError: (error) => String(error?.message ?? error), installStoreApp: async () => {} },
'./updates': { checkForEvenHubUpdates: async () => [], describeUpdate: () => '' },
'./glasses-compat': { isEvenHubStoreAvailable: () => true },
});
const { EvenHubStoreLayer } = load('app/apps/evenhub/store-layer.ts');
return { EvenHubStoreLayer, email, password, drawn, detailOptions };
+1
View File
@@ -86,6 +86,7 @@ const loadStore = ({ updates = [] } = {}) => {
checkForEvenHubUpdates: async () => updates,
describeUpdate: () => ({ updateAvailable: false, packageMissing: false }),
},
'./glasses-compat': { isEvenHubStoreAvailable: () => true },
});
const { EvenHubStoreLayer } = load('app/apps/evenhub/store-layer.ts');
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
+1
View File
@@ -22,6 +22,7 @@ const bdf = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app
const font = bdf(14);
const textwrap = load('app/graphics/textwrap.ts', {});
const coreDeps = {
'./menu-label': build('ui/menu-label'),
'../graphics/image': graphics, './menu-highlight-motion': build('ui/menu-highlight-motion'),
'../graphics/menu-scroll-list': build('graphics/menu-scroll-list'), './menu-scroll-motion': build('ui/menu-scroll-motion'),
'../graphics/draw-expression': build('graphics/draw-expression'),
+34 -1
View File
@@ -3,7 +3,8 @@ const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const zlib = require('node:zlib');
const { readZipEntry, assembleG1Image, decodeG1OwnBytes, G1FirmwareError } = require('../.test-build/app/g1/firmware-image.js');
const { readZipEntry, assembleG1Image, decodeG1OwnBytes, extractEvenG1Images, G1FirmwareError } = require('../.test-build/app/g1/firmware-image.js');
const { EVEN_G1_RESTORE } = require('../.test-build/app/g1/even-firmware.js');
const plan = require('../.test-build/app/g1/flash-plan.js');
const { G1V0_IMAGE } = require('../.test-build/app/g1/firmware/g1v0-image.js');
const { G1V0_OWN_BYTES_BASE64 } = require('../.test-build/app/g1/firmware/g1v0-own-bytes.js');
@@ -178,6 +179,38 @@ test('the native flow\'s answer is read, and nonsense is no answer', () => {
assert.deepEqual(plan.parseG1FlashResult('null'), {});
});
test('an uninstall goes right first, and its bar follows that order', () => {
assert.deepEqual([...plan.G1_UNINSTALL_SIDES], ['right', 'left']);
assert.equal(plan.g1FlashPercent('right', 0, 100, plan.G1_UNINSTALL_SIDES), 0);
assert.equal(plan.g1FlashPercent('right', 100, 100, plan.G1_UNINSTALL_SIDES), 50);
assert.equal(plan.g1FlashPercent('left', 50, 100, plan.G1_UNINSTALL_SIDES), 75);
});
test('Even\'s two images come out of its download only when each is the one published', () => {
const app = noise(9000, 7);
const netCore = noise(4000, 8);
const zip = zipOf([
{ name: 'app_update.bin', data: app },
{ name: 'net_core_app_update.bin', data: netCore, deflate: true },
{ name: 'manifest.json', data: noise(100, 9) },
]);
const release = { version: '9.9.9', zipUrl: 'u', zipSha256: sha(zip), appSha256: sha(app), netCoreSha256: sha(netCore) };
const out = extractEvenG1Images(zip, release, sha);
assert.deepEqual(Buffer.from(out.app), Buffer.from(app));
assert.deepEqual(Buffer.from(out.netCore), Buffer.from(netCore));
assert.throws(() => extractEvenG1Images(zip, { ...release, zipSha256: sha(app) }, sha), (e) => e instanceof G1FirmwareError && /download failed/.test(e.message));
assert.throws(() => extractEvenG1Images(zip, { ...release, netCoreSha256: sha(app) }, sha), /net_core_app_update\.bin in Even's download/);
});
test('the release an uninstall puts back is the one the bundled firmware was built from', () => {
// g1v0 embeds Even's network core from this same download, which the bundle's manifest checks by hash.
assert.equal(EVEN_G1_RESTORE.version, G1V0_IMAGE.stockVersion);
assert.equal(EVEN_G1_RESTORE.zipUrl, G1V0_IMAGE.stockZipUrl);
assert.equal(EVEN_G1_RESTORE.zipSha256, G1V0_IMAGE.stockZipSha256);
const net = G1V0_IMAGE.parts.find((part) => part.file === 'net_core_app_update.bin' && part.fileOffset === 0);
assert.equal(net?.sha256, EVEN_G1_RESTORE.netCoreSha256);
});
test('each arm counts for half of the bar', () => {
assert.equal(plan.g1FlashPercent('left', 0, 100), 0);
assert.equal(plan.g1FlashPercent('left', 100, 100), 50);
+19 -12
View File
@@ -15,6 +15,7 @@ const connected = {
silentMode: false,
screenOn: true,
battery: 72,
glassesModel: "G2",
caseBattery: null,
caseCharging: null,
foregroundTitle: "Music",
@@ -37,22 +38,23 @@ test("only the Display off state counts as asleep (the watch face's wake hint)",
assert.equal(glassesDisplayAsleep({ ...connected, phase: "disconnected", screenOn: false }), false);
});
test("charging takes precedence and includes the last-known G2 battery", () => {
test("charging takes precedence and includes the glasses' model and last-known battery", () => {
assert.equal(
glassesDisplayLabel({ ...connected, phase: "charging", silentMode: true, screenOn: false }),
"Charging · G2 72%",
"Charging: G2 72%",
);
assert.equal(chargingDisplayLabel(null), "Charging");
assert.equal(chargingDisplayLabel(-1), "Charging");
assert.equal(chargingDisplayLabel(101), "Charging");
assert.equal(glassesDisplayLabel({ ...connected, phase: "charging", glassesModel: "G1" }), "Charging: G1 72%");
assert.equal(chargingDisplayLabel(null, "G2"), "Charging");
assert.equal(chargingDisplayLabel(-1, "G2"), "Charging");
assert.equal(chargingDisplayLabel(101, "G2"), "Charging");
});
test("while charging, the case level is the watch face's second line and joins the mirror's message", () => {
const charging = { ...connected, phase: "charging", caseBattery: 64, caseCharging: false };
assert.equal(glassesDisplayLabel(charging), "Charging · G2 72%");
assert.equal(glassesDisplayLabel(charging), "Charging: G2 72%");
assert.equal(glassesDisplayDetail(charging), "Case 64%");
assert.equal(glassesDisplayDetail({ ...charging, caseCharging: true }), "Case 64% ⚡");
assert.equal(chargingPreviewMessage(charging), "Charging · G2 72% · Case 64%");
assert.equal(chargingPreviewMessage(charging), "Charging: G2 72% · Case 64%");
// No case level yet: the label alone.
assert.equal(glassesDisplayDetail({ ...charging, caseBattery: null }), "");
assert.equal(chargingPreviewMessage({ ...charging, caseBattery: null, battery: null }), "Charging");
@@ -65,14 +67,19 @@ const levels = {
};
test("the Settings battery line lists each known level, with ⚡ only while the reading is live", () => {
assert.equal(formatBatteryLine(levels, true), "G2 87% ⚡ · Case 64% ⚡ · R1 72%");
assert.equal(formatBatteryLine(levels, true, "G2"), "G2 87% ⚡ · Case 64% ⚡ · R1 72%");
// Without a link to the glasses their charging state and the case's are stale.
assert.equal(formatBatteryLine({ ...levels, ringCharging: true }, false), "G2 87% · Case 64% · R1 72% ⚡");
assert.equal(formatBatteryLine({ ...levels, ringCharging: true }, false, "G2"), "G2 87% · Case 64% · R1 72% ⚡");
// caseCharging is null while the glasses are out of the case.
assert.equal(formatBatteryLine({ ...levels, caseCharging: null }, true), "G2 87% ⚡ · Case 64% · R1 72%");
assert.equal(formatBatteryLine({ ...levels, case: null, ring: null }, true), "G2 87% ⚡");
assert.equal(formatBatteryLine({ ...levels, caseCharging: null }, true, "G2"), "G2 87% ⚡ · Case 64% · R1 72%");
assert.equal(formatBatteryLine({ ...levels, case: null, ring: null }, true, "G2"), "G2 87% ⚡");
assert.equal(
formatBatteryLine({ headset: null, headsetCharging: null, case: null, caseCharging: null, ring: null, ringCharging: null }, true),
formatBatteryLine({ headset: null, headsetCharging: null, case: null, caseCharging: null, ring: null, ringCharging: null }, true, "G2"),
"",
);
});
test("the Settings battery line names the paired glasses", () => {
assert.equal(formatBatteryLine({ ...levels, case: null, ring: null }, true, "G1"), "G1 87% ⚡");
assert.equal(formatBatteryLine({ ...levels, case: null, ring: null }, true, "iO"), "iO 87% ⚡");
});
+1 -1
View File
@@ -212,7 +212,7 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
'./phone-gestures': { PhoneGestureRecognizer: class { cancel() {} } },
'./ble-bandwidth-meter': require('../.test-build/app/phone-ui/ble-bandwidth-meter.js'),
'../native/ble-traffic': { sampleBleTraffic: () => totals },
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, displayLayoutSetting: { displayValue: () => 'Tall' }, showBleBandwidthSetting: { get: () => enabled },
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, displayLayoutSetting: { displayValue: () => 'Tall' }, showBleBandwidthSetting: { get: () => enabled }, glassesModelName: () => 'G2',
onAnySettingChanged: fn => { settingListeners.add(fn); return () => settingListeners.delete(fn); } },
'../g2/device-addresses': { loadDeviceAddresses: () => ({}) },
'../g2/ios-peripheral-identity': { deviceAddressError: () => 'no test devices' },
+131
View File
@@ -0,0 +1,131 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const NOT_DETERMINED = 0, DENIED = 2, ALLOWED = 3;
const STATE_UNAUTHORIZED = 3, STATE_POWERED_ON = 5;
/**
* The Permissions page and the real scan layer over a fake Kotlin central. As in
* IosBleCentral, registering the scan listener is what creates the CBCentralManager, so
* `registrations` counting up from 0 is the moment iOS would show its permission prompt.
*/
function harness({ authorization = NOT_DETERMINED, onboarding = true } = {}) {
const central = {
authorizationValue: authorization,
listener: null,
registrations: 0,
authorization() { return this.authorizationValue; },
setScanListenerListener(listener) { this.registrations++; this.listener = listener; },
// CoreBluetooth answering: the state arrives some time after the central is created.
report(state, value) {
this.authorizationValue = value;
this.listener.onBluetoothStateStateAuthorization(state, value);
},
};
const alerts = [];
const timers = [];
const appListeners = new Set();
const load = loader({
global: { isIOS: true },
setTimeout: (fn, delay) => { timers.push({ fn, delay }); return timers.length; },
clearTimeout: id => { timers[id - 1].cleared = true; },
FaceclawKitIosBleCentral: { alloc: () => ({ initWithPlatform: () => central }) },
FaceclawKitIosProtocolPlatform: { shared: {} },
FaceclawKitIosBleScanListener: {},
}, {
'@nativescript/core': {
Application: { resumeEvent: 'resume', on: (_name, fn) => appListeners.add(fn), off: (_name, fn) => appListeners.delete(fn) },
ApplicationSettings: { getString: (_key, fallback) => fallback, setString() {}, remove() {} },
Dialogs: { alert: async options => { alerts.push(options.message); }, confirm: async () => true },
Frame: { topmost: () => null },
Observable: class { notifyPropertyChange() {} },
},
'../g2/ios-peripheral-identity': {},
'../util/hex-util': { hexToBytes() {} },
'./kotlin-listener.ios': { kotlinListener: (_protocol, methods) => methods },
'../g2/android-permissions': {},
'../native/calendar-permissions': { hasCalendarPermission: () => false, ensureCalendarPermission: async () => false },
'../native/battery-optimization': {},
'../native/file-access': {},
'../native/notification-access': {},
'../native/media-controller': { mediaControllerBridge: { hasAccess: () => false, requestAccess: async () => false } },
});
const { PermissionsViewModel } = load('app/phone-ui/permissions-view-model.ts');
const model = new PermissionsViewModel({ onboarding });
const card = () => model.cards.find(item => item.id === 'nearby-devices');
return {
central, alerts, timers, appListeners, model, card,
checked: () => card().checkVisibility === 'visible',
tap: () => card().onCardTap({ object: { bindingContext: card() } }),
flush: () => new Promise(resolve => setImmediate(resolve)),
};
}
test('opening the page does not prompt; tapping the card does, and allowing checks it', async () => {
const page = harness();
page.model.onPageLoaded();
assert.equal(page.central.registrations, 0, 'rendering the card must not create the central');
assert.equal(page.checked(), false);
assert.match(page.model.primaryClass, /dimmed/);
page.tap();
assert.equal(page.central.registrations, 1, 'the tap creates the central, which shows the prompt');
page.central.report(STATE_POWERED_ON, ALLOWED);
await page.flush();
assert.equal(page.checked(), true);
assert.equal(page.model.primaryClass, '-primary');
assert.equal(page.alerts.length, 0);
});
test('Bluetooth already allowed is checked on the first render, with no central and no prompt', () => {
// A central's state arrives asynchronously, which is why a card reading it rendered unchecked
// and then had its tap ignored once the state said granted.
const page = harness({ authorization: ALLOWED });
assert.equal(page.checked(), true);
assert.equal(page.model.primaryClass, '-primary');
page.tap();
assert.equal(page.central.registrations, 0);
});
test('an answer arriving after the wait timed out still updates the page', async () => {
const page = harness();
page.model.onPageLoaded();
page.tap();
page.timers.find(timer => timer.delay === 30_000).fn();
await page.flush();
assert.match(page.alerts[0], /timed out/);
assert.equal(page.checked(), false);
page.central.report(STATE_POWERED_ON, ALLOWED);
assert.equal(page.checked(), true);
assert.equal(page.model.primaryClass, '-primary');
});
test('denied stays unchecked, and tapping again re-reads the state and explains', async () => {
const page = harness();
page.model.onPageLoaded();
page.tap();
page.central.report(STATE_UNAUTHORIZED, DENIED);
await page.flush();
assert.equal(page.checked(), false);
assert.match(page.alerts[0], /iPhone Settings/);
page.tap();
assert.equal(page.central.registrations, 2, 'an existing central re-reports its state when registered again');
page.central.report(STATE_UNAUTHORIZED, DENIED);
await page.flush();
assert.equal(page.alerts.length, 2);
});
test('leaving the page stops watching Bluetooth', () => {
const page = harness();
page.model.onPageLoaded();
page.tap();
page.model.onPageUnloaded();
assert.equal(page.appListeners.size, 0);
const before = page.model.cards;
page.central.report(STATE_POWERED_ON, ALLOWED);
assert.equal(page.model.cards, before, 'no refresh once unloaded');
});
-57
View File
@@ -1,57 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function harness(width, height) {
const font = { lineHeight: 20, measureText: text => text.length * 10, getGlyph: () => ({ dwidthX: 10 }) };
const load = loader({}, { './onboarding-fonts': { onboardingFont: () => font } });
const { IosPrivacyPage } = load('app/apps/onboarding/ios-privacy-page.ts');
const { IOS_PRIVACY_NOTICE } = load('app/analytics/privacy-disclosure.ts');
const page = new IosPrivacyPage();
let next = 0;
return {
page, notice: IOS_PRIVACY_NOTICE, get next() { return next; },
input(type) { page.handleInput({ type }, { next: () => next++ }); },
paint() {
const rows = [];
page.paint({ width, height, drawText(font, x, y, text) {
assert.ok(x + font.measureText(text) <= width, `horizontal overflow: ${text}`);
assert.ok(y >= 0 && y + font.lineHeight <= height, `vertical overflow: ${text}`);
rows.push({ y, text });
} });
return rows;
},
};
}
for (const [width, height] of [[576, 188], [576, 260], [640, 432]]) {
test(`entire iOS notice is readable before continuing at ${width}x${height}`, () => {
const h = harness(width, height);
const shown = [];
for (let i = 0; !h.next && i < 30; i++) {
const rows = h.paint();
const footer = rows.at(-1);
for (const row of rows.slice(1, -1)) {
assert.ok(row.y + 20 <= footer.y, 'body must not overlap navigation');
shown.push(row.text);
}
h.input('click');
}
assert.equal(h.next, 1);
// Line breaking may also split after punctuation (e.g. device/app).
assert.equal(shown.join('').replace(/\s+/g, ''), h.notice.replace(/\s+/g, ''));
});
}
test('scrolling stays inside the notice; revisiting starts at the beginning', () => {
const h = harness(576, 188);
const first = h.paint().map(row => row.text);
h.input('scroll-up');
assert.deepEqual(h.paint().map(row => row.text), first);
h.input('scroll-down');
assert.notDeepEqual(h.paint().map(row => row.text), first);
for (let i = 0; i < 30; i++) h.input('scroll-down');
assert.equal(h.next, 0, 'scrolling must not accept the notice');
h.page.enter();
assert.deepEqual(h.paint().map(row => row.text), first);
});
+5
View File
@@ -125,6 +125,7 @@ function loadRemote({ phase = 'disconnected', preview = false, now = 1_800_000_0
'../apps/evenhub/installed-apps': { getInstalledEvenHubApps: () => [], installedEvenHubAppId: id => id },
'../native/wear-bridge': { wearBridge: bridge, WEAR_PATHS: types().WEAR_PATHS },
'../ui/dashboard-settings': {
glassesModelName: () => 'G1',
onAnySettingChanged() {}, watchCanUnlockSetting: setting(true), watchCrownClockwiseNextSetting: setting(false),
watchMirrorAssistantSetting: setting(true), watchRemoteEnabledSetting: setting(true),
watchVibrateOnInputSetting: setting(true), watchSoundEffectsSetting: setting(false),
@@ -214,6 +215,10 @@ test('the mirrored state carries the Apple Watch feedback settings', () => {
assert.equal(state.soundEffects, false);
});
test('the mirrored state names the glasses for the charging line', () => {
assert.equal(loadRemote({ phase: 'charging' }).remote.buildState().glassesModel, 'G1');
});
test('the mirrored state says when gestures are landing on the preview', () => {
const state = loadRemote({ preview: true }).remote.buildState();
assert.equal(state.preview, true);
@@ -42,10 +42,11 @@ private fun testImage(version: Triple<Int, Int, Int> = Triple(0, 5, 64), payload
}
/**
* One arm behind the StockLink port: MCUmgr's image and OS groups as flash.py meets them on real arms, and g1v0's HELLO
* and PROPS. Requests are answered synchronously, from the write.
* One arm behind the StockLink port: MCUmgr's image and OS groups as flash.py meets them on real arms, and g1v0's HELLO,
* PROPS and asset store. Requests are answered synchronously, from the write. [netImage] is what a restore puts in image
* 1's slot.
*/
private class FakeArm(private val image: ByteArray, var stock: Boolean = false) : StockLink {
private class FakeArm(private val image: ByteArray, var stock: Boolean = false, private val netImage: ByteArray? = null) : StockLink {
var inbound: StockLinkListener? = null
var connected = false
var bond = BondState.BONDED
@@ -59,13 +60,44 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
var safeMode = false
var battery = 80
var slot1Hash: ByteArray? = null
/** The hash in each image's second slot. */
val slotHashes = HashMap<Int, ByteArray>()
var slot1Hash: ByteArray?
get() = slotHashes[0]
set(value) {
if (value == null) slotHashes.remove(0) else slotHashes[0] = value
}
/** Images marked for the next boot, and whether permanently. */
val pending = HashMap<Int, Boolean>()
val confirms = ArrayList<Pair<Int, Boolean>>()
/** The image of the upload in progress, and what each image's last whole upload was. */
var uploadImage = -1
val uploads = HashMap<Int, ByteArray>()
var uploaded = ByteArray(0)
var uploadOffset = 0
var uploadRefusal = 0
/** After the upload the list shows this instead of the image's hash. */
var corruptAfterUpload = false
var confirmRefusal = 0
/** Only this image's confirm is refused; -1: any. */
var confirmRefusalImage = -1
/** This image's confirm is answered, and the list doesn't show it pending. */
var unmarkedImage = -1
/** No `ASSET_INFO`, as before 0.5.56. */
var storeSupported = true
var storeAvailable = true
var storeAssets = 0
var storeSeq = 0L
var storeState = 0
var storeError = 0
/** Bytes that aren't 0xFF in the store's directory sectors: Even's data, until a format. */
var directoryNonErased = 4096L
/** The format's NOTICE 8 never comes. */
var loseStoreNotice = false
/** The arm restarts during the wipe: no notice, and the job state back to idle. */
var wipeInterrupted = false
val formats = ArrayList<Boolean>()
var dropAtOffset = -1
var silentRequests = 0
/** The chunk at this offset gets no answer, once. */
@@ -157,6 +189,9 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
private fun control(request: ByteArray) {
val op = request[0].toInt() and 0xff
val tag = request[1]
val args = request.copyOfRange(2, request.size)
var status = 0
var after: (() -> Unit)? = null
val body = when (op) {
G1Protocol.OP_HELLO -> {
val parts = runningVersion.split(".").map { it.toInt().toByte() }
@@ -164,11 +199,67 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
byteArrayOf(5, parts[0], parts[1], parts[2], 1, flags.toByte(), 0)
}
G1Protocol.OP_PROPS -> byteArrayOf(battery.toByte(), 0, 0, 0)
G1Protocol.OP_ASSET_INFO -> {
if (!storeSupported) {
status = 2
ByteArray(0)
} else {
ByteArray(12) + byteArrayOf(storeAssets.toByte(), storeState.toByte(), storeError.toByte(), if (storeAvailable) 1 else 0) +
le32(storeSeq.toInt())
}
}
G1Protocol.OP_FLASH_CRC -> {
calls.add("crc")
assertContentEquals(G1Protocol.flashCrcRequest(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES), args)
if (safeMode) {
status = 7
} else {
after = { storeNotice(G1Protocol.STORE_JOB_CRC, 0, args + le32(0x1234) + le32(directoryNonErased.toInt())) }
}
ByteArray(0)
}
G1Protocol.OP_ASSET_FORMAT -> {
calls.add("format")
assertContentEquals(G1Protocol.assetFormatRequest(wipe = true), args)
when {
safeMode -> status = 7
storeState in 1..3 -> status = 13
else -> {
formats.add(true)
storeAssets = 0
storeSeq = 0
directoryNonErased = 0
if (wipeInterrupted) {
storeState = 0
} else {
storeState = 4
storeError = 0
if (!loseStoreNotice) after = { storeNotice(G1Protocol.STORE_JOB_FORMAT, 0, ByteArray(16)) }
}
}
}
ByteArray(0)
}
else -> ByteArray(0)
}
val event = ByteArray(9) + byteArrayOf(tag, 0) + body
val event = ByteArray(9) + byteArrayOf(tag, status.toByte()) + body
event[0] = (0x80 or op).toByte()
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
after?.invoke()
}
private fun storeNotice(job: Int, result: Int, detail: ByteArray) {
val event = ByteArray(9) + byteArrayOf(G1Protocol.NOTICE_STORE_JOB.toByte(), job.toByte(), result.toByte()) + detail
event[0] = G1Protocol.EV_NOTICE.toByte()
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
}
private fun le32(value: Int): ByteArray = byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
private fun imageOf(index: Int): ByteArray = when (index) {
0 -> image
1 -> netImage ?: throw AssertionError("an upload to image 1")
else -> throw AssertionError("an upload to image $index")
}
private fun smp(frame: ByteArray) {
@@ -191,17 +282,26 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
return
}
if (uploadRefusal != 0) return reply(op, group, seq, cmd, mapOf("rc" to uploadRefusal))
if (off == uploadOffset) {
val data = body["data"] as ByteArray
if (off == 0) {
assertEquals(image.size.toLong(), body["len"])
assertContentEquals(sha256(image), body["sha"] as ByteArray)
assertEquals(0L, body["image"])
if (off == 0) {
// A first chunk names the image; the same file again resumes where it stopped, as MCUmgr does.
val index = (body["image"] as Long).toInt()
val expected = imageOf(index)
assertEquals(expected.size.toLong(), body["len"])
assertContentEquals(sha256(expected), body["sha"] as ByteArray)
if (index != uploadImage || uploadOffset >= expected.size) {
uploadImage = index
uploadOffset = 0
uploaded = ByteArray(0)
}
}
if (off == uploadOffset) {
val data = body["data"] as ByteArray
uploaded += data
uploadOffset += data.size
if (uploadOffset == image.size) slot1Hash = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
if (uploadOffset == imageOf(uploadImage).size) {
uploads[uploadImage] = uploaded
slotHashes[uploadImage] = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
}
}
if (uploadOffset >= dropAtOffset && dropAtOffset >= 0) {
dropAtOffset = -1
@@ -214,14 +314,31 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
calls.add("list")
val images = ArrayList<Map<String, Any?>>()
images.add(mapOf("image" to 0, "slot" to 0, "version" to runningVersion, "hash" to ByteArray(32), "active" to true, "confirmed" to true, "bootable" to true))
slot1Hash?.let { images.add(mapOf("image" to 0, "slot" to 1, "version" to "0.5.64", "hash" to it, "bootable" to true)) }
for ((index, hash) in slotHashes.toSortedMap()) {
val marked = pending[index]
val entry = mutableMapOf<String, Any?>("image" to index, "slot" to 1, "version" to "0.5.64", "hash" to hash, "bootable" to true)
if (marked != null && index != unmarkedImage) {
entry["pending"] = true
if (marked) entry["permanent"] = true
}
images.add(entry)
}
reply(op, group, seq, cmd, mapOf("images" to images))
}
group == 1 && cmd == 0 -> {
calls.add("confirm")
assertEquals(true, body["confirm"])
assertContentEquals(wantHash, body["hash"] as ByteArray)
reply(op, group, seq, cmd, mapOf("rc" to confirmRefusal))
val hash = body["hash"] as ByteArray
val index = slotHashes.entries.firstOrNull { it.value.contentEquals(hash) }?.key
assertNotNull(index, "a confirm for a hash no slot holds")
if (index == 0 && netImage == null) {
assertEquals(true, body["confirm"])
assertContentEquals(wantHash, hash)
}
val permanent = body["confirm"] as Boolean
confirms.add(index to permanent)
val refused = if (confirmRefusalImage < 0 || confirmRefusalImage == index) confirmRefusal else 0
if (refused == 0) pending[index] = permanent
reply(op, group, seq, cmd, mapOf("rc" to refused))
}
group == 0 && cmd == 5 -> {
calls.add("reset")
@@ -262,6 +379,7 @@ private class Recorder : FaceclawFirmwareFlasherListener {
private val FAST = G1FlashTimings(
connectTimeoutMs = 50, servicesTimeoutMs = 50, descriptorTimeoutMs = 50, writeTimeoutMs = 50, pairingMs = 200, retryDelayMs = 1,
controlReplyMs = 20, controlTries = 2, uploadReplyMs = 150, smpReplyMs = 150, resetReplyMs = 50, heartbeatMs = 30, pollMs = 5, uploadRetries = 5,
storePollMs = 10, wipeMs = 2_000, crcMs = 200,
)
class G1SmpStockTest {
@@ -370,7 +488,7 @@ class G1ArmFlashFlowTest {
private val image = testImage()
private fun flow(arm: FakeArm, listener: Recorder, mode: G1ArmFlashFlow.Mode, window: Int = 100) =
G1ArmFlashFlow(arm, ARM, "left", "image.bin", mode, window, listener, FAST, testPlatform(), { image })
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", mode, window, listener, FAST, testPlatform(), { image })
private fun run(arm: FakeArm, mode: G1ArmFlashFlow.Mode, window: Int = 100): Recorder {
val listener = Recorder()
@@ -464,7 +582,7 @@ class G1ArmFlashFlowTest {
fun aDamagedImageFailsBeforeTheLinkIsTouched() {
val listener = Recorder()
val arm = FakeArm(image)
G1ArmFlashFlow(arm, ARM, "left", "image.bin", G1ArmFlashFlow.Mode.UPDATE, 100, listener, FAST, testPlatform(), { ByteArray(100) }).run()
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", G1ArmFlashFlow.Mode.UPDATE, 100, listener, FAST, testPlatform(), { ByteArray(100) }).run()
assertEquals(false, listener.success)
assertEquals(0, arm.connects)
}
@@ -473,7 +591,7 @@ class G1ArmFlashFlowTest {
fun anUnreadableImageIsAClearFailure() {
val listener = Recorder()
val arm = FakeArm(image)
G1ArmFlashFlow(arm, ARM, "left", "image.bin", G1ArmFlashFlow.Mode.STOCK, 100, listener, FAST, testPlatform(), { throw IllegalStateException("gone") }).run()
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", G1ArmFlashFlow.Mode.STOCK, 100, listener, FAST, testPlatform(), { throw IllegalStateException("gone") }).run()
assertEquals(false, listener.success)
assertTrue("could not read the firmware" in listener.detail, listener.detail)
}
@@ -653,6 +771,169 @@ class G1ArmFlashFlowTest {
assertEquals(0, arm.bondRequests)
}
// ---- back to Even's firmware ----
private val evenApp = testImage(Triple(0, 0, 0), payloadSize = 7000)
private val evenNet = testImage(Triple(0, 0, 1), payloadSize = 3000)
private fun restoreArm(): FakeArm = FakeArm(evenApp, netImage = evenNet).also { it.runningVersion = "0.5.66" }
private fun restore(arm: FakeArm, window: Int = 100): Recorder {
val listener = Recorder()
G1ArmFlashFlow(arm, ARM, "right", "app.bin", "net.bin", G1ArmFlashFlow.Mode.RESTORE, window, listener, FAST, testPlatform(), { path ->
when (path) {
"app.bin" -> evenApp
"net.bin" -> evenNet
else -> throw IllegalStateException("no $path")
}
}).run()
assertNotNull(listener.success, "the flow must always finish")
return listener
}
@Test
fun aRestoreUploadsBothImagesThenMarksTheNetworkCoreFirst() {
val arm = restoreArm()
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"firmware":"stock","wiped":false}""", result.detail)
assertContentEquals(evenNet, arm.uploads[1])
assertContentEquals(evenApp, arm.uploads[0])
// Image 1 as a test install, as Even's app and g1v0's fallback do; the application for good.
assertEquals(listOf(1 to false, 0 to true), arm.confirms)
assertEquals(listOf("confirm", "confirm", "list", "reset"), arm.calls.takeLast(4))
assertEquals((evenApp.size + evenNet.size).toLong(), result.total)
assertEquals(result.total, result.progress)
assertTrue("rebooting" in result.states)
}
@Test
fun aStoreNeverWrittenKeepsEvensData() {
val arm = restoreArm()
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals(listOf("crc"), arm.calls.filter { it == "crc" || it == "format" })
assertTrue(arm.formats.isEmpty())
assertFalse("wiping" in result.states)
}
@Test
fun aStoreThatHoldsAssetsIsWipedBeforeAnyUpload() {
val arm = restoreArm()
arm.storeAssets = 2
arm.storeSeq = 5
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"firmware":"stock","wiped":true}""", result.detail)
assertEquals(listOf(true), arm.formats)
assertTrue(arm.calls.indexOf("format") < arm.calls.indexOf("upload"))
assertFalse("crc" in arm.calls, "a store with assets needs no fingerprint")
assertTrue("wiping" in result.states)
}
@Test
fun anEmptyStoreWhoseDirectoryWasErasedIsWiped() {
// A format resets the commit count, and erased the two directory sectors over Even's data.
val arm = restoreArm()
arm.directoryNonErased = 0
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertEquals(listOf("crc", "format"), arm.calls.filter { it == "crc" || it == "format" })
}
@Test
fun firmwareWithoutTheStoreIsNotWiped() {
val arm = restoreArm()
arm.storeSupported = false
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertFalse("crc" in arm.calls)
assertFalse("format" in arm.calls)
}
@Test
fun aLostWipeNoticeIsReadFromTheStoreState() {
val arm = restoreArm()
arm.storeAssets = 1
arm.storeSeq = 1
arm.loseStoreNotice = true
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertTrue("\"wiped\":true" in result.detail, result.detail)
}
@Test
fun anArmThatRestartsDuringTheWipeGetsNothingInstalled() {
val arm = restoreArm()
arm.storeAssets = 1
arm.storeSeq = 1
arm.wipeInterrupted = true
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("restarted while erasing" in result.detail, result.detail)
assertFalse("upload" in arm.calls)
assertFalse("confirm" in arm.calls)
}
@Test
fun safeModeWithAWrittenStoreInstallsNothing() {
val arm = restoreArm()
arm.safeMode = true
arm.storeAssets = 1
arm.storeSeq = 1
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("safe mode" in result.detail, result.detail)
assertFalse("format" in arm.calls)
assertFalse("upload" in arm.calls)
}
@Test
fun aLowBatteryStopsARestoreBeforeTheWipe() {
val arm = restoreArm()
arm.battery = 12
arm.storeAssets = 1
arm.storeSeq = 1
val result = restore(arm)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertFalse("format" in arm.calls)
assertFalse("upload" in arm.calls)
}
@Test
fun aRefusedNetworkCoreNeverLeavesTheApplicationMarked() {
val arm = restoreArm()
arm.confirmRefusal = 3
arm.confirmRefusalImage = 1
val result = restore(arm)
assertEquals(false, result.success)
assertEquals(listOf(1 to false), arm.confirms)
assertFalse(0 in arm.pending)
assertFalse("reset" in arm.calls)
assertTrue("network core" in result.detail, result.detail)
}
@Test
fun anImageTheArmDidNotMarkIsNoReset() {
val arm = restoreArm()
arm.unmarkedImage = 0
val result = restore(arm)
assertEquals(false, result.success)
assertFalse("reset" in arm.calls)
assertTrue("didn't mark" in result.detail, result.detail)
}
@Test
fun aLostLinkResumesARestoreUpload() {
val arm = restoreArm()
arm.dropAtOffset = 2048
val result = restore(arm)
assertEquals(true, result.success, result.detail)
assertContentEquals(evenNet, arm.uploads[1])
assertContentEquals(evenApp, arm.uploads[0])
}
@Test
fun cancellingDuringTheUploadStopsBeforeTheConfirm() {
val arm = FakeArm(image)
@@ -665,3 +946,41 @@ class G1ArmFlashFlowTest {
assertFalse("confirm" in arm.calls)
}
}
class G1StoreProtocolTest {
/** The bytes of scouter_kit's tools/g1host.py: `struct.pack("<II", FORMAT_MAGIC, WIPE_MAGIC)`. */
@Test
fun requestsMatchThePythonTool() {
assertEquals("53414b5300005750", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = true)))
assertEquals("53414b53", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = false)))
assertEquals("0000140000200000", BinaryEncoding.bytesToHex(G1Protocol.flashCrcRequest(0x140000, 8192)))
}
@Test
fun assetInfoIsRead() {
// data 10, free 20, largest 30, 2 assets, state 4, error 0, flags 1, seq 0x01020304
val info = G1Protocol.parseAssetInfo(hex("0a000000140000001e00000002040001" + "04030201"))
assertNotNull(info)
assertEquals(2, info.assets)
assertEquals(4, info.state)
assertTrue(info.available)
assertFalse(info.running)
assertEquals(0x01020304L, info.seq)
assertEquals(null, G1Protocol.parseAssetInfo(ByteArray(19)))
}
@Test
fun aStoreJobsNoticeIsRead() {
val crc = hex("05" + "0000000000000000" + "08" + "0400" + "00001400" + "00200000" + "78563412" + "00100000")
val notice = G1Protocol.parseStoreNotice(crc)
assertNotNull(notice)
assertEquals(G1Protocol.STORE_JOB_CRC, notice.job)
assertEquals(0, notice.result)
assertEquals(0x140000, notice.address)
assertEquals(8192, notice.n)
assertEquals(4096L, notice.nonErased)
// Another notice kind, or a short one, is none.
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "07" + "2a2a")))
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "08" + "0300")))
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ function load(file,modules) {
const font={lineHeight:12,ascent:10,descent:2,measureText:text=>text.length*4,
drawText:(image,x,y,text,value)=>{for(let i=0;i<text.length;i++) image.fillRect(x+i*4,y+2,2,6,value);}};
const menuCore=load('app/ui/menu-core.ts',{
'../graphics/image':graphics,'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'../graphics/image':graphics,'./menu-label': require('../.test-build/app/ui/menu-label.js'), './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
});
const {MenuLayer,TextPageLayer}=load('app/ui/menu.ts',{
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback }, '../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
@@ -121,13 +121,13 @@ test('unselected sidebar icons retain -2 depth through shell cropping, including
});
test('shell modal carries its inner menu highlight animation instead of baking its first frame',async()=>{
const {ShellModalLayer}=load('app/ui/shell/modal-layer.ts',{
'../../graphics/image':graphics,'../../graphics/plane':planes,'../gestures':{},'../layers':load('app/ui/layers.ts',{
'../../graphics/image':graphics,'../../graphics/display-list':require('../.test-build/app/graphics/display-list.js'),'../../graphics/plane':planes,'../gestures':{},'../layers':load('app/ui/layers.ts',{
'../graphics/image':graphics,'../graphics/plane':planes,'../native/frame-timings':{spanCurrent:(_name,fn)=>fn()},'../graphics/screen-size':{screenWidth:()=>640,screenHeight:()=>480},
'./gestures':{isDirectionalInput:()=>false},
}),
'./geometry':{appViewportSize:()=>({width:120,height:110}),appViewportRect:()=>({x:10,y:20,width:120,height:110}),SHELL_OPAQUE_BLACK:1},
});
const modal=new ShellModalLayer(menu().layer,noopLayerActions),paint=()=>modal.paint({},()=>new graphics.GrayImage(200,200));
const modal=new ShellModalLayer(menu().layer,noopLayerActions),paint=()=>modal.paint({stack:{getBaseSize:()=>({width:200,height:200})}},()=>new graphics.GrayImage(200,200));
const bare=menu().paint().draws.find(d=>d.presentation),before=paint().draws.find(d=>d.presentation);
assert.equal(before.x,bare.x+28);assert.equal(before.y,bare.y+38); // translated into the box interior
await modal.handleInput({type:'scroll-down'},{});
+218
View File
@@ -0,0 +1,218 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { GrayImage } = require('../.test-build/app/graphics/image.js');
const { Menu } = require('../.test-build/app/ui/menu-core.js');
const { paintDisplayList } = require('../.test-build/app/graphics/display-list.js');
const pref = require('../.test-build/app/ui/menu-animation-pref.js');
// Distinctive ink at the tail proves the full label, not an ellipsis, is rasterized.
const font = { lineHeight: 8, measureText: s => s.length * 4,
drawText(image, x, y, text, value) {
for (let i = 0; i < text.length; i++) image.fillRect(x + i * 4, y, text[i] === 'Z' ? 3 : 1, 4, value);
} };
function fixture() {
const labels = ['abcdefghijkZ', 'short'];
const menu = new Menu({ items: labels, getHeight: () => 12,
draw: ({ image, item, x, y, width, drawLabel }) => {
if (drawLabel) drawLabel(font, x + 3, y + 2, width - 6, item, 240);
else image.drawText(font, x + 3, y + 2, item, 240);
} });
return { menu, labels, paint(focused = true, width = 30) {
const image = new GrayImage(50, 30); menu.paint(image, { x: 2, y: 1, width, height: 24 }, focused); return image;
} };
}
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules) {
const context = { exports: {}, require: name => { assert.ok(name in modules, name); return modules[name]; } };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const menuModule = load('app/ui/menu.ts', {
'../graphics/image': { GrayImage }, '../graphics/screen-size': { screenHeight: () => 480 },
'../graphics/textwrap': {}, '../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'./animation-speed': require('../.test-build/app/ui/animation-speed.js'), './layers': {}, './gestures': {},
'./menu-animation-pref': pref, './menu-core': require('../.test-build/app/ui/menu-core.js'),
'./metrics': require('../.test-build/app/ui/metrics.js'),
});
const lists = image => image.draws.filter(d => d.presentation?.displayList?.timeline);
test('selected overflowing label is retained, initially paused, then reveals its tail inside its clip', () => {
const f = fixture();
const image = f.paint();
const moving = lists(image);
assert.equal(moving.length, 1);
const d = moving[0], list = d.presentation.displayList;
const render = ms => {
const pixels = new Uint8Array(50 * 30).fill(64);
paintDisplayList(pixels, pixels.slice(), 50, 30,
{ displayList: { ...list, presentedAt: list.timeline.startedAt }, x: d.x, y: d.y, width: d.source.width, height: d.source.height, depth: 0 }, false, list.timeline.startedAt + ms);
return pixels;
};
assert.deepEqual(render(0), render(700));
assert.notDeepEqual(render(0), render(1800));
assert.equal(render(1800)[3 * 50 + 27], 240, 'tail Z reaches the right edge');
assert.equal(render(1800)[3 * 50 + 29], 64, 'right inset is untouched');
assert.equal(render(1800)[13 * 50 + 8], 64, 'next row is untouched');
});
test('short, unselected, unfocused and disabled-animation labels stay clipped and static', () => {
const f = fixture();
assert.equal(lists(f.paint(false)).length, 0);
f.menu.select(1);
assert.equal(lists(f.paint()).length, 0);
pref.setMenuAnimationReader(() => 'disabled');
try {
f.menu.select(0);
const image = f.paint();
assert.equal(lists(image).length, 0);
const row = image.draws.find(d => d.presentation).source;
assert.ok(row.pixels.some(v => v === 240), 'static label remains readable');
for (let y = 0; y < row.height; y++) assert.equal(row.getPixel(28, y), 0, 'right inset stays clear');
} finally { pref.setMenuAnimationReader(() => 'normal'); }
});
test('same retained presentation keeps its clock across paints and resets on content, width and focus', () => {
const original = Date.now;
let now = 1000;
Date.now = () => now;
try {
const f = fixture();
const timeline = () => lists(f.paint())[0].presentation.displayList.timeline;
const first = timeline();
now = 1500;
assert.deepEqual(timeline(), first);
f.labels[0] += 'Z';
const content = timeline();
assert.equal(content.startedAt, 1500);
assert.notEqual(content.token, first.token);
const resized = lists(f.paint(true, 28))[0].presentation.displayList.timeline;
assert.notEqual(resized.token, content.token);
f.paint(false);
assert.notEqual(timeline().token, resized.token);
} finally { Date.now = original; }
});
test('retained label pauses at the end, returns, stops scheduling, and survives a later PRESENT', () => {
const { evaluate } = require('../.test-build/app/graphics/draw-expression.js');
const { encodeDisplayList, readDisplayList } = require('../.test-build/app/graphics/display-list.js');
const d = lists(fixture().paint())[0];
const list = d.presentation.displayList;
const offset = ms => evaluate(list.calls[0].dx, 0, ms);
assert.equal(offset(1700).value, -24);
assert.equal(offset(2400).value, -24);
assert.equal(offset(3400).value, 0);
assert.equal(offset(100000).pending, false, 'native refresh becomes idle after the bounded pass');
const placed = { displayList: list, x: d.x, y: d.y, width: d.source.width, height: d.source.height, depth: 0 };
const start = list.timeline.startedAt;
const bytes = encodeDisplayList(placed, start + 1400);
const replay = readDisplayList(bytes, 0, 10000).placed;
assert.equal(evaluate(replay.displayList.calls[0].dx, 1400, 0).value, offset(1400).value);
});
test('very long labels are tiled into firmware-valid resources rather than giant images', () => {
const { encodeDisplayList } = require('../.test-build/app/graphics/display-list.js');
const f = fixture(); f.labels[0] = 'a'.repeat(1000) + 'Z';
const d = lists(f.paint())[0];
const list = d.presentation.displayList;
assert.ok(list.resources.length > 1);
assert.equal(list.resources.reduce((n, r) => n + r.width, 0), 4004, 'the entire label is retained');
for (const r of list.resources) {
assert.ok(r.width <= 640);
assert.ok(5 + Math.ceil(r.width / 2) * r.height <= 65536);
}
assert.doesNotThrow(() => encodeDisplayList({ displayList: list, x: d.x, y: d.y, width: d.source.width, height: d.source.height, depth: 0 }));
});
test('selected marquee clips to a short menu viewport rather than painting below it', () => {
const f = fixture();
const image = new GrayImage(50, 30);
f.menu.paint(image, { x: 2, y: 1, width: 30, height: 5 }, true);
const d = lists(image)[0];
assert.ok(d);
const clip = d.presentation.displayList.calls[0].clip;
assert.ok(d.y + clip.y + clip.height <= 6);
});
test('setItems changing selection restarts the pass without restarting unchanged settings repaints', () => {
const f = fixture();
const first = lists(f.paint())[0].presentation.displayList.timeline.token;
f.menu.setItems(f.labels);
assert.equal(lists(f.paint())[0].presentation.displayList.timeline.token, first);
f.menu.setItems(f.labels, 1);
f.menu.setItems(f.labels, 0);
assert.notEqual(lists(f.paint())[0].presentation.displayList.timeline.token, first);
});
test('selection away and back restarts the reading pass even without an intermediate paint', () => {
const f = fixture();
const before = lists(f.paint())[0].presentation.displayList.timeline;
f.menu.select(1);
f.menu.select(0);
const after = lists(f.paint())[0].presentation.displayList.timeline;
assert.notEqual(after.token, before.token);
});
test('common row builders scroll only the label and reserve fixed right decorations', () => {
const label = 'abcdefghijklmnopqrstuvwxyzZ';
const items = [
menuModule.submenuItem(label, () => {}),
{ label, onSelect() {}, render: a => menuModule.drawToggleMenuItem(a.image, font, a.x, a.y, a.width, a.text, true, a.selected) },
{ label, onSelect() {}, render: a => menuModule.drawRightValueMenuItem(a.image, font, a.x, a.y, a.width, a.text, '42') },
];
for (const [i, item] of items.entries()) {
const layer = new menuModule.MenuLayer(null, [item], { x: 0, y: 0, width: 140, minHeight: 40, maxHeight: 50 });
const image = layer.paint({ stack: { getBaseSize: () => ({ width: 140, height: 60 }), isFocused: () => true } }, () => new GrayImage(140, 60));
const scrolling = lists(image);
assert.equal(scrolling.length, 1, `builder ${i}`);
assert.ok(scrolling[0].source.width < 140 - 44, 'right decoration has reserved space');
const render = ms => {
const pixels = image.withDrawsBaked(false).pixels.slice();
for (const d of image.draws) {
const list = d.presentation?.displayList;
if (!list) continue;
const origin = list.timeline?.startedAt ?? 0;
paintDisplayList(pixels, pixels.slice(), 140, 60,
{ displayList: { ...list, presentedAt: origin }, x: d.x, y: d.y,
width: d.source.width, height: d.source.height, depth: 0 }, false, origin + ms);
}
return pixels;
};
const before = render(0), during = render(1800);
assert.notDeepEqual(before, during, 'the selected label actually moves');
const decorationX = [110, 82, 108][i];
const decoration = pixels => Array.from({ length: 60 }, (_, y) =>
Array.from(pixels.slice(y * 140 + decorationX, y * 140 + 119))).flat();
assert.deepEqual(decoration(before), decoration(during), 'right decoration never moves or gets overwritten');
assert.ok(decoration(before).some(v => v > 100), 'the fixed decoration is visible');
}
});
test('SettingsPanel labels animate only in the focused column', async () => {
const { SettingsPanelLayer } = load('app/ui/dashboard/settings-panel.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font }, '../../graphics/image': { GrayImage },
'../../graphics/textwrap': { wrapText: () => [] }, '../gestures': {}, '../layers': {},
'../menu': menuModule, '../menu-core': require('../.test-build/app/ui/menu-core.js'),
'../metrics': require('../.test-build/app/ui/metrics.js'), '../shell/shell': { shell: {} },
});
const layer = new SettingsPanelLayer([{ label: 'very long section label beyond column width',
items: [{ label: 'very long option label beyond the right column width', onSelect() {} }] }]);
const ctx = { stack: { getBaseSize: () => ({ width: 360, height: 100 }), isFocused: () => true } };
const left = lists(layer.paint(ctx));
assert.equal(left.length, 1);
assert.ok(left[0].x < 150);
await layer.handleInput({ type: 'click' }, ctx);
const right = lists(layer.paint(ctx));
assert.equal(right.length, 1);
assert.ok(right[0].x > 150);
});
test('common MenuLayer default row retains the full overflowing label', () => {
const layer = new menuModule.MenuLayer(null, [{ label: 'abcdefghijklmnopZ', onSelect() {} }],
{ x: 0, y: 0, width: 80, minHeight: 40, maxHeight: 50 });
const image = layer.paint({ stack: { getBaseSize: () => ({ width: 80, height: 60 }), isFocused: () => true } }, () => new GrayImage(80, 60));
assert.equal(lists(image).length, 1);
});
+1 -1
View File
@@ -159,7 +159,7 @@ test('Music settings keeps toggles and selection when a new app arrives and supp
'../graphics/textwrap': textwrap,
'../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./menu-label': require('../.test-build/app/ui/menu-label.js'), './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'), './gestures': {},
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback }, '../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
};
+1 -1
View File
@@ -199,7 +199,7 @@ do {
state.battery = 50
state.caseBattery = 64
state.caseCharging = true
check(padLine(state: state, link: up) == StatusLine(text: "Charging · G2 50%", tone: .busy, detail: "Case 64% ⚡"), "charging")
check(padLine(state: state, link: up) == StatusLine(text: "Charging: G2 50%", tone: .busy, detail: "Case 64% ⚡"), "charging")
var off = PhoneState()
check(padLine(state: off, link: up).text == "Disconnected", "disconnected")
+150
View File
@@ -0,0 +1,150 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const graphics = require('../.test-build/app/graphics/image.js');
const planes = require('../.test-build/app/graphics/plane.js');
const { encodeShellScene } = require('../.test-build/app/graphics/shell-scene.js');
const { readPresentation, paintPresentation } = require('../.test-build/app/graphics/presentation-wire.js');
const { DrawOp } = require('../.test-build/app/graphics/display-list.js');
function fixture(width = 640, height = 480, retained = false, hideBackground = true) {
const screen = { width, height, top: 0 };
const load = loader({}, {
'../graphics/image': graphics, '../graphics/plane': planes,
'../graphics/screen-size': { screenWidth: () => screen.width, screenHeight: () => screen.height },
'../native/frame-timings': { spanCurrent: (_name, action) => action() },
'./gestures': { isDirectionalInput: () => false },
'../../graphics/image': graphics, '../../graphics/plane': planes, '../gestures': {},
'./geometry': {
appViewportSize: () => ({ width: screen.width - 64, height: Math.min(288, screen.height) }),
appViewportRect: () => ({ x: 32, y: screen.top, width: screen.width - 64, height: Math.min(288, screen.height) }),
SHELL_OPAQUE_BLACK: 1,
},
});
const { LayerStack, noopLayerActions } = load('app/ui/layers.ts');
const { ShellModalLayer, modalRect } = load('app/ui/shell/modal-layer.ts');
let lowerPaints = 0, innerSize, removed = 0;
const background = { paint() {
lowerPaints++;
const image = new graphics.GrayImage(screen.width, screen.height);
image.fillRect(0, 0, 24, 100, 170);
return image;
} };
const stack = new LayerStack(background, noopLayerActions);
const inner = {
paint(ctx) {
innerSize = ctx.stack.getBaseSize();
const image = new graphics.GrayImage(innerSize.width, innerSize.height);
image.fillRect(6, 6, 8, 8, 240);
if (retained) image.drawMenuSelection(new graphics.GrayImage(20, 12, 255), 20, 18, 60, 120, 3, 0);
return image;
},
handleInput() {},
};
const modal = new ShellModalLayer(inner, noopLayerActions, { hideBackground, removed() { removed++; } });
return { screen, stack, modal, modalRect, innerSize: () => innerSize, lowerPaints: () => lowerPaints, removed: () => removed };
}
// Real shell encoder and presentation decoder, replayed over a separate app
// in native ShellScene.calls order: opaque cropped surface, then retained calls.
function sceneFrame(f, appValue = 200) {
const bytes = encodeShellScene(f.stack.paintUndimmed());
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const frame = new graphics.GrayImage(f.screen.width, f.screen.height, appValue);
const original = frame.pixels.slice(), layers = [];
let p = 2;
for (let i = 0; i < view.getUint16(0, true); i++) {
const x = view.getInt16(p + 2, true), y = view.getInt16(p + 4, true);
const width = view.getUint16(p + 6, true), height = view.getUint16(p + 8, true);
const count = view.getUint16(p + 12, true);
assert.ok(5 + Math.ceil(width / 2) * height <= 65536);
assert.equal(view.getUint16(p + 10, true), 256, 'vector mask does not rely on zero dim keeping no halftone');
const image = new graphics.GrayImage(width, height);
image.pixels.set(bytes.subarray(p + 16, p + 16 + width * height));
frame.bitBlt(image, x, y);
p += 16 + width * height;
const selections = [];
for (let j = 0; j < count; j++) {
const record = readPresentation(bytes, p);
selections.push(record.selection);
paintPresentation(frame.pixels, original, frame.width, frame.height, record.selection);
p = record.end;
}
layers.push({ x, y, width, height, selections });
}
assert.equal(p + 2, bytes.length, 'complete scene decoded');
return { frame, layers, bytes };
}
test('G2 notification serializes through the production shell scene within one 64 KiB surface', () => {
const f = fixture();
f.stack.push(f.modal);
const { layers } = sceneFrame(f);
assert.equal(layers.length, 1);
assert.deepEqual({ ...layers[0], selections: undefined }, { ...f.modalRect(), selections: undefined });
assert.equal(f.lowerPaints(), 0, 'chrome must not enter the scene');
const mask = layers[0].selections[0].displayList;
assert.equal(mask.resources.length, 0, 'no full-screen image or image tiles');
assert.ok(mask.calls.every(call => call.op === DrawOp.CLEAR && call.color === 0 && call.clip));
});
test('an already-awake notification keeps app and chrome visible with no blackout presentation', () => {
const f = fixture(640, 480, false, false);
f.stack.push(f.modal);
const { frame, layers } = sceneFrame(f);
assert.equal(f.lowerPaints(), 1, 'chrome is painted underneath the popup');
assert.equal(layers.length, 2);
assert.equal(frame.getPixel(639, 479), 200, 'app is visible outside the popup');
assert.equal(frame.getPixel(0, 0), 170, 'chrome remains visible');
assert.ok(frame.pixels.includes(240), 'popup still appears above the app');
assert.ok(layers.every(layer => layer.selections.length === 0), 'no margin mask for an already-on screen');
});
test('notification omits chrome and blacks out a separate app until dismissed', () => {
const f = fixture(), before = sceneFrame(f).frame;
assert.equal(f.lowerPaints(), 1);
f.stack.push(f.modal);
const { frame, layers } = sceneFrame(f);
assert.equal(f.lowerPaints(), 1);
assert.equal(layers.length, 1);
assert.equal(frame.getPixel(0, 0), 0);
assert.equal(frame.getPixel(639, 479), 0);
assert.ok(!frame.pixels.includes(200), 'margins hide separate app surface');
assert.ok(!frame.pixels.includes(170), 'status bar and switcher hidden');
assert.ok(frame.pixels.includes(240), 'notification remains visible');
f.stack.pop();
assert.equal(f.removed(), 1);
const closed = sceneFrame(f);
assert.deepEqual(closed.frame.pixels, before.pixels);
assert.equal(closed.layers[0].selections.length, 0, 'dismiss removes blackout');
});
test('notification mask follows resize, band position and restore without covering content', () => {
const f = fixture();
f.stack.push(f.modal);
for (const [width, height, top] of [[640, 480, 0], [540, 220, 0], [640, 480, 192], [640, 480, 0]]) {
Object.assign(f.screen, { width, height, top });
const { frame, layers } = sceneFrame(f), rect = f.modalRect();
assert.equal(frame.getPixel(width - 1, height - 1), 0);
assert.equal(frame.getPixel(rect.x, rect.y), 110);
assert.equal(frame.getPixel(rect.x + 2, rect.y + 2), 1, 'interior opaque black');
assert.equal(frame.getPixel(rect.x + 10, rect.y + 10), 240);
assert.ok(!frame.pixels.includes(200), 'no app pixels survive');
assert.equal(layers[0].height, rect.height);
assert.deepEqual({ ...f.innerSize() }, { width: rect.width - 8, height: rect.height - 8 });
}
});
test('notification retains inner menu presentations after blackout with correct offsets', () => {
const f = fixture(640, 480, true);
f.stack.push(f.modal);
const { layers, frame } = sceneFrame(f), rect = f.modalRect();
const { selections } = layers[0];
assert.equal(selections.length, 2, 'mask and selection both cross real encoder');
const row = selections[0];
assert.ok(row.displayList, 'selection is retained, not a frozen raster');
assert.equal(row.x, rect.x + 4 + 20);
assert.equal(row.y, rect.y + 4 + 18);
assert.equal(frame.getPixel(row.x + 10, row.y + 6), 240);
assert.equal(frame.getPixel(0, 0), 0);
});
+1 -1
View File
@@ -120,7 +120,7 @@ function ui(fontSize = 12) {
'../native/notification-types': require('../.test-build/app/native/notification-types.js'),
'../native/notification-access': { isNotificationListenerEnabled: () => true },
'../util/render-freshness': { renderPassAllowsStaleData: () => false },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./menu-label': require('../.test-build/app/ui/menu-label.js'), './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'),
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback }, '../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
'./gestures': {},
+16 -2
View File
@@ -3,13 +3,27 @@ const assert = require("node:assert/strict");
const { NotificationModalQueue } = require("../.test-build/app/ui/shell/notification-modal-queue.js");
test('background visibility follows each arrival, independently of inherited return-to-sleep state', () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post('wake', true);
queue.post('already-on', false);
assert.equal(host.opened[0].hideBackground, true);
queue.closed(host.opened[0]);
assert.equal(host.opened[1].hideBackground, false, 'queued arrivals must not inherit the first popup mask');
queue.closed(host.opened[1]);
assert.equal(host.sleeps, 1, 'sleep restoration is still inherited across the queue');
queue.post('normal', false);
assert.equal(host.opened[2].hideBackground, false);
});
/** A host that records opened modals (one handle object each) and sleeps. */
function makeHost(unavailable = new Set()) {
const host = {
opened: [],
sleeps: 0,
open(notificationKey) {
const modal = { notificationKey };
open(notificationKey, hideBackground) {
const modal = { notificationKey, hideBackground };
host.opened.push(modal);
return modal;
},
+3 -3
View File
@@ -33,7 +33,7 @@ function fixture({ glasses = 'g2', ios = false, completed = false, ring = false,
const modules = {
'@nativescript/core': core, './onboarding-state': onboardingState, '../ui/dashboard-settings': settings,
'./onboarding-navigation': { finishOnboardingNavigation: () => state.navigations.push('finish') },
'../analytics/privacy-disclosure': { IOS_PRIVACY_NOTICE: 'privacy' },
'../g1/even-firmware': { EVEN_G1_RESTORE: { version: '1.6.6' } },
'../native/even-app-conflict': { openEvenAppSettings() {} },
'../native/ble-permissions': { ensureBlePermissions: async () => {} },
'../g2/device-addresses': {
@@ -143,8 +143,8 @@ test('the disclaimer and firmware steps name only the chosen glasses', () => {
assert.doesNotMatch(io.disclaimer.body, /Even/);
assert.match(g2.firmware.body, /reconnecting the official Even Realities app/);
assert.doesNotMatch(g2.firmware.body, /computer|G1/);
assert.match(g1.firmware.body, /takes a computer/);
assert.doesNotMatch(g2.firmware.body, /from Faceclaw|1\.6\.6|G1/);
assert.match(g1.firmware.body, /return to the official firmware later from Faceclaw, as version 1\.6\.6\./);
assert.doesNotMatch(g1.firmware.body, /reconnecting|G2/);
assert.equal(g2.firmware.primaryLabel, 'Flash Firmware');
assert.equal(g1.firmware.primaryLabel, 'Flash Firmware');
+1 -1
View File
@@ -231,7 +231,7 @@ test('the flow switches immersive mode per page and skips pages that do not appl
const load = loader({}, {
'../../graphics/image': { GrayImage: class {} },
'../../ui/shell/in-process-window': {}, '../../ui/shell/shell': { shell }, '../../ui/sound-effects': {},
'./data-collection-page': {}, './depth-page': {}, './display-mode-page': {}, './ios-privacy-page': {}, './layout-page': {},
'./data-collection-page': {}, './depth-page': {}, './display-mode-page': {}, './layout-page': {},
'./onboarding-progress': {}, './text-size-page': {}, './welcome-page': {},
});
const { OnboardingLayer } = load('app/apps/onboarding/onboarding-app.ts');
+1 -1
View File
@@ -189,7 +189,7 @@ test("scan row carries the decoded variant, artwork, and proximity", () => {
assert.equal(row.colorway, "brown");
assert.equal(row.imagePath, "~/images/glasses/glasses_g2_b_brown.png");
assert.equal(row.hasVariantImage, true);
assert.match(row.proximitySummary, /In your hand|Nearby/);
assert.match(row.proximityGlyph, /^●●●[●○]$/);
assert.match(row.armsSummary, /serials match/);
assert.equal(row.canSelect, true);
assert.equal(row.isNearest, false);
+1
View File
@@ -15,6 +15,7 @@ function fakeImageModule() {
this.width = width;
this.height = height;
this.texts = [];
this.draws = [];
return new Proxy(this, { get: (target, key) => (key in target ? target[key] : () => {}) });
}
drawText(_font, _x, _y, text) { this.texts.push(text); }
+1
View File
@@ -46,6 +46,7 @@
"../app/g1/pako.d.ts",
"../app/g1/firmware-image.ts",
"../app/g1/flash-plan.ts",
"../app/g1/even-firmware.ts",
"../app/g1/firmware/g1v0-image.ts",
"../app/g1/firmware/g1v0-own-bytes.ts",
"../app/apps/calculator/math/*.ts",
+6 -4
View File
@@ -62,7 +62,7 @@ dashboard state, re-sent whenever it changes (and at least every 30 s):
"protocol": 1, "version": "…",
"phase": "connected", "status": "…", "connected": true, "preview": false,
"screenOn": true, "locked": false, "worn": true, "listening": false,
"battery": 78, "charging": false, "silentMode": false,
"battery": 78, "glassesModel": "G2", "charging": false, "silentMode": false,
"caseBattery": 64, "caseCharging": true,
"foreground": {"appId": "music", "title": "Music"},
"windows": [{"windowId": "…", "title": "…", "appId": "…", "focused": true, "closeable": true, "acceptsText": false}],
@@ -74,9 +74,11 @@ dashboard state, re-sent whenever it changes (and at least every 30 s):
}
```
`battery` is the current or last-known G2 percentage. `charging` and
`silentMode` identify the two states in which the glasses display is not
visible even though the BLE session remains available.
`battery` is the glasses' current or last-known percentage, and `glassesModel`
is what the charging line calls them: `G2`, `G1` or `iO` (a watch treats a
missing one, from an older phone app, as `G2`). `charging` and `silentMode`
identify the two states in which the glasses display is not visible even though
the BLE session remains available.
`caseBattery` is the last-known charging-case percentage, or null until the
glasses have reported one; the case only reports while the glasses are docked,
@@ -92,8 +92,10 @@ data class PhoneState(
val locked: Boolean,
val worn: Boolean?,
val listening: Boolean,
/** Current or last-known G2 charge percentage. */
/** The glasses' current or last-known charge percentage. */
val battery: Int?,
/** The paired glasses' model, as the charging line names it. */
val glassesModel: String,
val charging: Boolean,
/** Last-known charging-case percentage; live only while the glasses are docked. */
val caseBattery: Int?,
@@ -126,6 +128,7 @@ data class PhoneState(
worn = if (o.isNull("worn")) null else o.optBoolean("worn"),
listening = o.optBoolean("listening", false),
battery = if (o.isNull("battery")) null else o.optInt("battery", -1).takeIf { it in 0..100 },
glassesModel = o.optString("glassesModel", "G2"),
charging = o.optBoolean("charging", false),
caseBattery = if (o.isNull("caseBattery")) null else o.optInt("caseBattery", -1).takeIf { it in 0..100 },
caseCharging = if (o.isNull("caseCharging")) null else o.optBoolean("caseCharging"),
@@ -81,7 +81,7 @@ fun padLine(state: PhoneState?, link: LinkStatus): StatusLine = when {
state.remoteEnabled == false -> StatusLine("Watch control off", StatusTone.PROBLEM)
state.connected -> when {
state.charging || state.phase == "charging" ->
StatusLine(chargingLine(state.battery), StatusTone.BUSY, caseLine(state))
StatusLine(chargingLine(state), StatusTone.BUSY, caseLine(state))
state.silentMode -> StatusLine("Silent mode", StatusTone.OFF)
state.locked -> StatusLine("Locked", StatusTone.OFF)
!state.screenOn -> StatusLine("●● Wake", StatusTone.OFF)
@@ -93,8 +93,8 @@ fun padLine(state: PhoneState?, link: LinkStatus): StatusLine = when {
else -> StatusLine("Disconnected", StatusTone.OFF)
}
private fun chargingLine(battery: Int?): String =
if (battery != null) "Charging · G2 $battery%" else "Charging"
private fun chargingLine(state: PhoneState): String =
state.battery?.let { "Charging: ${state.glassesModel} $it%" } ?: "Charging"
/**
* "Case 64%", with ⚡ while the case is on USB; null when the level is