Merge upstream main preserving custom feature integrations

This commit is contained in:
MasterControl committed 2026-11-10 17:08:15 +00:00
commit 6150a1ac57
228 files changed
+16844 -1388

No files matched your search

+3
View File
@@ -258,6 +258,7 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
const layers = load('app/ui/layers.ts', {
'../graphics/image': images, '../graphics/plane': { dimPlanes: (planes) => planes },
'../native/frame-timings': timings, './gestures': gestures,
'../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
});
class Menu {
constructor(title, items) { this.title = title; this.items = items; this.selectedIndex = 0; }
@@ -285,9 +286,11 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
'../notifications': {}, '../dashboard-settings': settings, './ambient-cards': {},
'./chrome-layer': { ShellChromeLayer: class {} }, './modal-layer': {}, './tool-debug-layer': {},
'./brightness-picker-layer': {}, './notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts', {}),
'./notification-popup-timeout': {},
'../../native/notification-icons': {}, '../../native/notification-sources': {},
'../../assistant/tool-registry': {}, './geometry': {
sidebarWidth: () => 64, minWindowTop: () => 96, switcherPosition: () => 'left', uiDepth: () => 0,
screenWidth: () => 640, screenHeight: () => 480,
appViewportRect: () => ({ x: 64, y: 124, width: 576, height: 260 }),
},
});
+11
View File
@@ -32,6 +32,17 @@ test('receives fragmented UTF-8 notifications; pre-existing and modified items d
x.source(8,0,4);x.feed(3,[]);x.details(8);x.feed(3,[]);x.metadata(8);assert.equal(x.changed.at(-1)[1],false)
assert.ok(x.sent.every(p=>p.length<=20))
})
test('a phone that is not sharing ANCS says so and is asked again, and an unknown status restarts',t=>{
const x=setup(t);x.client.stop()
const sent=[],c=new AncsClient(async b=>sent.push([...b]),()=>{})
t.after(()=>c.stop());c.start(5,20)
c.receive(new Uint8Array([65,78,1,0,...le(5),0,0,3,0]))
c.receive(new Uint8Array([65,78,1,0,...le(5),1,0,3,3]))
assert.equal(c.state,'unavailable');assert.match(c.statusMessage,/Share System Notifications/)
const d=new AncsClient(async()=>{},()=>{});t.after(()=>d.stop());d.start(6,20)
d.receive(new Uint8Array([65,78,1,0,...le(6),0,0,3,4]))
assert.equal(d.state,'unavailable');assert.doesNotMatch(d.statusMessage,/Share System Notifications/)
})
test('removal during retrieval cannot resurrect notification',t=>{
const x=setup(t);x.source(7);x.source(7,2);x.details(7);x.feed(3,[])
assert.deepEqual(x.client.read(),[])
+90 -8
View File
@@ -9,7 +9,8 @@ const js = (source) => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
function geometry() {
// The shell geometry over a G2's 640x480 screen, or `screen` (a RayNeo iO is 540x220).
function geometry(screen = { width: 640, height: 480 }) {
const settings = Object.fromEntries(Object.entries({
displayLayoutSetting: 'band-middle', navigateDisplayLayoutSetting: 'global', terminalDisplayLayoutSetting: 'default',
appSwitcherPositionSetting: 'left', uiDepthSetting: '0', statusBarPositionSetting: 'top',
@@ -18,13 +19,13 @@ function geometry() {
const fullscreen = new Map();
settings.appFullscreenSetting = id => ({ get: () => fullscreen.get(id) ?? false, set: value => fullscreen.set(id, value) });
const context = { exports: {}, require: (name) => {
if (name === '../../graphics/image') return { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 };
if (name === '../../graphics/screen-size') return { screenWidth: () => screen.width, screenHeight: () => screen.height };
assert.equal(name, '../dashboard-settings');
return settings;
} };
vm.runInNewContext(js(read('app/ui/shell/geometry.ts')), context);
const rect = (mode, appId) => ({ ...context.exports.appViewportRect(mode, appId) });
return { ...context.exports, settings, rect };
return { ...context.exports, settings, screen, rect };
}
const LAYOUTS = ['band-top', 'band-high', 'band-middle', 'band-low', 'band-bottom', 'tall', 'fullscreen'];
@@ -284,6 +285,78 @@ test('an immersive app fills the panel without chrome rows, frame or depth, in a
}
});
test('on a RayNeo iO\'s 540x220 screen windows take every row under the bar, beside the strip or over the row', () => {
const g = geometry({ width: 540, height: 220 });
const panel = { x: 0, y: 0, width: 540, height: 220 };
// A band is the whole screen's height, so every band position is the same.
for (const layout of LAYOUTS) {
g.settings.displayLayoutSetting.value = layout;
g.settings.appSwitcherPositionSetting.value = 'left';
assert.equal(g.minWindowHeight(), 220);
assert.equal(g.minWindowTop(), 0);
for (const mode of ['min', 'medium', 'max']) assert.deepEqual(g.rect(mode), { x: 64, y: 28, width: 476, height: 192 }, layout);
assert.deepEqual({ ...g.switcherRect('min') }, { x: 0, y: 0, width: 64, height: 220 });
g.settings.appSwitcherPositionSetting.value = 'right';
assert.deepEqual(g.rect('min'), { x: 0, y: 28, width: 476, height: 192 });
assert.deepEqual({ ...g.switcherRect('min') }, { x: 476, y: 0, width: 64, height: 220 });
}
assert.equal(g.isOnSwitcherEdge(500, 10, 'min'), true);
assert.equal(g.screenCenterInViewportX(), 270);
// A bottom row: the window centred above it, its sides room for the deepest shift.
g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.displayLayoutSetting.value = 'band-middle';
assert.deepEqual(g.rect('min'), { x: 32, y: 28, width: 476, height: 156 });
assert.deepEqual({ ...g.switcherRect('min') }, { x: 32, y: 184, width: 476, height: 36 });
g.settings.displayLayoutSetting.value = 'fullscreen';
assert.deepEqual(g.rect('min'), { x: 0, y: 28, width: 540, height: 156 });
// The phone mirror shows the whole screen, at its 27:11.
g.settings.displayLayoutSetting.value = 'band-middle';
for (const position of ['left', 'bottom', 'popup']) {
g.settings.appSwitcherPositionSetting.value = position;
assert.deepEqual({ ...g.phonePreviewRect({ ...g.usedScreenRect('min') }) }, panel, position);
}
// Every layout stays on the screen.
g.settings.uiDepthSetting.value = '62';
for (const switcher of ['left', 'right', 'bottom', 'popup']) {
g.settings.appSwitcherPositionSetting.value = switcher;
for (const statusBar of ['top', 'bottom']) {
g.settings.statusBarPositionSetting.value = statusBar;
for (const layout of LAYOUTS) {
g.settings.displayLayoutSetting.value = layout;
for (const mode of ['min', 'medium', 'max']) {
const rect = g.rect(mode), row = g.switcherRect(mode);
const where = `${switcher} ${statusBar} ${layout} ${mode}`;
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 540 && rect.y + rect.height <= 220, where);
assert.ok(row.y >= 0 && row.y + row.height <= 220, where);
if (g.windowFramed()) assert.ok(rect.x - 1 - 31 >= 0 && rect.x + rect.width + 31 < 540, where);
}
}
}
}
// The G2's band is unchanged.
assert.equal(geometry().minWindowHeight(), 288);
});
test('on a RayNeo iO the chrome paints the screen\'s size, its strip and row within it', () => {
for (const position of ['left', 'right', 'bottom', 'popup']) {
const g = geometry({ width: 540, height: 220 });
g.settings.appSwitcherPositionSetting.value = position;
const { chrome, state } = chromeLayer(g, { windows: 3, notifications: 2, phoneBattery: 80 });
state.focus = 'sidebar';
const image = chrome.paint();
assert.deepEqual([image.width, image.height], [540, 220], position);
const parts = chrome.paintParts();
assert.ok(parts.length > 0, position);
for (const part of parts) {
assert.ok(part.x >= 0 && part.y >= 0 && part.x + part.image.width <= 540 && part.y + part.image.height <= 220,
`${position} part ${part.shellKey} at ${[part.x, part.y, part.image.width, part.image.height]}`);
}
// And it draws something there.
const lit = (x0, y0, w, h) => { for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) if (image.pixels[y * 540 + x]) return true; return false; };
assert.ok(lit(0, 0, 540, 220), position);
}
});
test('the phone mirror zooms to the area the shell uses, centred at the panel\'s 4:3', () => {
const g = geometry();
const preview = (mode, appId) => {
@@ -377,8 +450,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 = [];
@@ -399,7 +473,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.
@@ -417,11 +491,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';
@@ -932,7 +1014,7 @@ test('Terminal resize keeps the view identity, negotiates its grid and skips pos
client: { stop: () => calls.push('stop'), setViewport: (...size) => calls.push(size) },
};
const resize = resizeHandler('app/apps/terminal/terminal-app.worker.ts', {
windows: new Map([['test', window]]), clearTimeout: (timer) => calls.push(timer),
windows: new Map([['test', window]]), pendingHeightChanges: new Map(), clearTimeout: (timer) => calls.push(timer),
TerminalEmulator: class { constructor(cols, rows) { this.cols = cols; this.rows = rows; } },
reconnectView: (view) => { assert.equal(view, window); calls.push('reconnect'); },
scheduleRender: () => calls.push('paint'),
+1 -1
View File
@@ -62,7 +62,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() {} }),
@@ -75,6 +74,7 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
openSettingsSubMenu() {},
},
'../font-picker': { uiFontPickerMenuItem: () => ({ label: 'Font' }) },
'../notification-filter': { NotificationFilterLayer: class {} },
'../openai-compatible-model-picker': {
compatibleModelDiscoveryMenuItem: () => ({ label: 'Discover models' }),
},
-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", () => {
+16 -1
View File
@@ -1,6 +1,6 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { normalizeBrightnessCurve, brightnessCurveError, DEFAULT_BRIGHTNESS_CURVE } = require('../.test-build/app/g2/brightness-curve.js');
const { normalizeBrightnessCurve, brightnessCurveError, DEFAULT_BRIGHTNESS_CURVE, G1_BRIGHTNESS_CURVE, RAYNEO_IO_BRIGHTNESS_CURVE } = require('../.test-build/app/g2/brightness-curve.js');
test('brightness curve accepts monotone knots and canonicalizes spacing', () => {
assert.equal(normalizeBrightnessCurve(' 0:0, 2.5:20,1000:100 '), '0:0,2.5:20,1000:100');
});
@@ -44,6 +44,21 @@ test('the screen fade speed scales the 280 ms on/off fade, or makes it instant',
const fadeAt = (speed) => { api.screenFadeSetting.set(speed); return api.getBrightnessPreferences().fadeMs; };
assert.deepEqual(['very-fast', 'fast', 'normal', 'slow', 'disabled'].map(fadeAt), [56, 140, 280, 560, 0]);
});
test('an unset curve follows the paired glasses; a chosen one stays', () => {
const store = new Map();
const api = settingsFixture(store);
assert.equal(api.getBrightnessPreferences().curve, DEFAULT_BRIGHTNESS_CURVE);
store.set('deviceType', 'rayneo-io');
assert.equal(api.getBrightnessPreferences().curve, RAYNEO_IO_BRIGHTNESS_CURVE);
assert.equal(brightnessCurveError(RAYNEO_IO_BRIGHTNESS_CURVE), null);
store.set('deviceType', 'g1');
assert.equal(api.getBrightnessPreferences().curve, G1_BRIGHTNESS_CURVE);
assert.equal(brightnessCurveError(G1_BRIGHTNESS_CURVE), null);
api.autoBrightnessCurveSetting.set('0:0,2:50,8:100');
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
store.set('deviceType', 'g2');
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
});
test('curve drafts preview exactly while brightness keeps the previous valid saved curve', () => {
const store = new Map([['display.autoBrightnessCurve', '0:0,2:50,8:100']]);
let api = settingsFixture(store), curve = api.autoBrightnessCurveSetting;
+18 -1
View File
@@ -25,9 +25,10 @@ const fonts = { getDefaultSmallFont: () => font };
const layers = load('app/ui/layers.ts', {
'../graphics/image': graphics, '../graphics/plane': plane, './gestures': gestures,
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
'../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
});
const menu = 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 },
'./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 },
'./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, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
@@ -112,6 +113,22 @@ test('the thin bar fills upward in proportion to brightness in each viewport', (
}
});
test('in a short window (a RayNeo iO\'s) the bar shrinks so the dialog stays inside it', () => {
for (const viewport of [{ x: 64, y: 28, width: 476, height: 192 }, { x: 32, y: 1, width: 476, height: 155 }]) {
const f = fixture('100', viewport);
const image = f.stack.paint().at(-1).image;
// The dialog's border (110) and the full bar (255), all within the window.
let top = Infinity, bottom = -1, fill = 0;
for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
const value = image.getPixel(x, y);
if (value === 110) { top = Math.min(top, y); bottom = Math.max(bottom, y); }
if (value === 255) fill++;
}
assert.ok(top >= viewport.y && bottom < viewport.y + viewport.height, `dialog ${top}..${bottom} in ${JSON.stringify(viewport)}`);
assert.ok(fill > 0 && fill < 12 * 100, 'a shorter bar, still drawn');
}
});
test('system menu hides brightness in Auto and opens its picker between Voice input and Debug', async () => {
const f = fixture('auto');
const { shell } = load('app/ui/shell/shell.ts', {
+13 -1
View File
@@ -23,7 +23,7 @@ const font = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../ap
const small = font(18), large = font(32);
const diagnostics = { magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 0x8c, sampleTimeMs: 1234 };
function compass(width = 576, height = 260) {
function compass(width = 576, height = 260, glasses = 'g2') {
let listener, window;
class RecordingImage extends graphics.GrayImage {
texts = [];
@@ -55,6 +55,7 @@ function compass(width = 576, height = 260) {
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../native/location-permissions': { hasLocationPermission: () => false },
'../../ui/dashboard-settings': { glassesHaveCompass: () => glasses === 'g2' },
'./calibration': calibration,
'./calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
@@ -63,6 +64,7 @@ function compass(width = 576, height = 260) {
app.createCompassAppWindow({ onClosed() {} });
return { menu: () => window.menuItems(),
paint: () => window.baseLayer.paint(ctx),
tap: () => window.baseLayer.handleInput({ type: 'click' }, ctx),
heading: (info) => listener({ command: 15, headingDegrees: 359, diagnostics: info }) };
}
@@ -110,3 +112,13 @@ test('calibration readout fits the viewport without overlapping the heading or s
}
}
});
test('glasses without a magnetometer say so and offer no calibration', () => {
const app = compass(576, 260, 'g1');
const image = app.paint();
assert.ok(image.texts.some((t) => t.text === 'These glasses have no compass sensor'));
assert.equal(calibrationText(image), undefined);
assert.equal(app.menu().length, 0);
// ctx.stack has no push or topMatches here, so opening calibration would throw.
app.tap();
});
+1
View File
@@ -44,6 +44,7 @@ const compass = load('app/apps/compass/compass-app.ts', {
'../../ui/shell/in-process-window': {},
'../../ui/shell/shell': {},
'../../native/location-permissions': {},
'../../ui/dashboard-settings': { glassesHaveCompass: () => true },
'./calibration': calibration,
'./calibration-layer': {},
'./compass-rose': rose,
+7
View File
@@ -41,6 +41,13 @@ with tempfile.TemporaryDirectory() as d:
try: m.read_document(p)
except (ValueError, m.ET.ParseError): pass
else: raise AssertionError(f'accepted invalid config {invalid!r}')
pulled = {'schema': 2, 'platform': 'ios', 'settings': {'onboarding.lookalike': True, 'display.timeFormat': '24h'}, 'platformSettings': {
'onboarding.complete': True, 'onboarding.previewOnly': False, 'onboarding.glassesFinishedVersion': '0.8.6', 'onboarding.step': 3, 'deviceAddress.left': 'AA'}}
reset = json.loads(ios.onboarding_reset_document(json.dumps(pulled)))
assert reset == {'schema': 2, 'platform': 'ios', 'settings': {}, 'platformSettings': {
'onboarding.complete': False, 'onboarding.glassesFinishedVersion': '', 'onboarding.step': 0}}, reset
assert m.check_document(json.dumps(reset)) == (2, 'ios', 3)
assert ios.onboarding_reset_document(json.dumps({**pulled, 'platformSettings': {'onboarding.complete': False, 'onboarding.glassesFinishedVersion': '', 'deviceAddress.left': 'AA'}})) is None
`], { stdio: 'inherit' });
});
+6 -3
View File
@@ -7,7 +7,7 @@ test('Notifications menu dismisses all, including beyond the visible list, and l
let dismissals = 0, renders = 0, pops = 0;
const load = loader({}, {
'../../ui/notifications': { NotificationsListLayer: class {} },
'../../ui/notification-filter': { NotificationFilterLayer: class {} },
'../../ui/dashboard/settings-menus': { NOTIFICATIONS_SETTINGS_SECTION: 'notifications' },
'../../native/notification-icons': {
ALL_NOTIFICATIONS: 0x7fffffff,
readActiveNotifications(max) { assert.equal(max, 0x7fffffff); return active; },
@@ -19,9 +19,12 @@ test('Notifications menu dismisses all, including beyond the visible list, and l
createInProcessWindow(value) { options = value; return { requestRender() { renders++; } }; },
},
});
load('app/apps/notifications/notifications-app.ts').createNotificationsAppWindow({});
const sections = [];
load('app/apps/notifications/notifications-app.ts').createNotificationsAppWindow({}, section => sections.push(section));
const items = options.menuItems();
assert.equal(items[0].label, 'Notification filter');
assert.equal(items[0].label, 'Settings');
items[0].onSelect({ stack: { pop() {} } });
assert.deepEqual(sections, ['notifications']);
const action = items.find(x => x.label === 'Dismiss all notifications');
assert.equal(action.disabled(), false);
assert.equal(dismissals, 0);
+54
View File
@@ -36,6 +36,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');
@@ -94,3 +102,49 @@ test('keep awake persists per app independently of full screen, including existi
prefs = settingsFixture(store);
assert.equal(prefs.appKeepAwakeSetting('terminal').get(), false);
});
test('a RayNeo iO defaults the app switcher to the left, and keeps a chosen position and the band', () => {
const store = new Map();
const api = settingsFixture(store);
assert.equal(api.appSwitcherPositionSetting.get(), 'bottom');
api.glassesTypeSetting.set('rayneo-io');
assert.equal(api.appSwitcherPositionSetting.get(), 'left');
assert.equal(api.displayLayoutSetting.get(), 'band-middle');
assert.equal(store.has('display.appSwitcherPosition'), false);
// A stored position is the user's, on either glasses.
api.appSwitcherPositionSetting.set('right');
assert.equal(api.appSwitcherPositionSetting.get(), 'right');
api.glassesTypeSetting.set('g2');
assert.equal(api.appSwitcherPositionSetting.get(), 'right');
store.delete('display.appSwitcherPosition');
assert.equal(api.appSwitcherPositionSetting.get(), 'bottom');
// An unknown stored value falls back to the glasses' default.
store.set('display.appSwitcherPosition', 'sideways');
api.glassesTypeSetting.set('rayneo-io');
assert.equal(api.appSwitcherPositionSetting.get(), 'left');
});
test('a RayNeo iO always takes the R1 directly, leaving the G2\'s ring connection setting alone', () => {
const store = new Map();
const api = settingsFixture(store);
assert.equal(api.effectiveRingConnectionMode(), 'glasses');
api.ringConnectionModeSetting.set('health');
assert.equal(api.effectiveRingConnectionMode(), 'health');
api.glassesTypeSetting.set('rayneo-io');
assert.equal(api.effectiveRingConnectionMode(), 'direct');
assert.equal(api.ringConnectionModeSetting.get(), 'health');
api.glassesTypeSetting.set('g2');
assert.equal(api.effectiveRingConnectionMode(), 'health');
});
test('only a G2 has a compass', () => {
const api = settingsFixture();
assert.equal(api.glassesHaveCompass(), true);
api.glassesTypeSetting.set('g1');
assert.equal(api.glassesHaveCompass(), false);
api.glassesTypeSetting.set('rayneo-io');
assert.equal(api.glassesHaveCompass(), false);
api.glassesTypeSetting.set('g2');
assert.equal(api.glassesHaveCompass(), true);
});
+113
View File
@@ -162,3 +162,116 @@ test("a bare R1 substring is not a ring — only the stock EVEN R1 prefix is", (
const ad = classifyAdvertisement(raw({ address: "DA:7F:D2:B5:6E:E2", name: "EVEN R1_B56EE2", manufacturerData: "" }));
assert.equal(ad.role, "ring");
});
// RayNeo iO-2229 as captured 2026-11-01: company 0x5716 + [07][MAC]; pairing mode omits the data.
test("RayNeo iO advertisements classify as one device with its MAC", () => {
const io = classifyAdvertisement(raw({
address: "00:6A:5E:5F:33:C2",
name: "RayNeo iO-2229",
manufacturerData: "1657" + "07006a5e5f33c2130000000000000001",
}));
assert.equal(io.role, "rayneo-io");
assert.equal(io.embeddedMac, "00:6A:5E:5F:33:C2");
assert.equal(io.embeddedMacMismatch, false);
assert.equal(io.serial, null);
const pairing = classifyAdvertisement(raw({ address: "00:6A:5E:5F:33:C2", name: "RayNeo iO-2229", manufacturerData: "" }));
assert.equal(pairing.role, "rayneo-io");
assert.equal(pairing.embeddedMac, null);
// G2 advertisements are untouched
assert.equal(classifyAdvertisement(raw({})).role, "left");
});
// ---------------------------------------------------------------------------
// Even G1
// ---------------------------------------------------------------------------
const g1Ascii = (text) => Array.from(text).map((c) => c.charCodeAt(0).toString(16).padStart(2, "0")).join("");
const g1Raw = (name, manufacturerData, address = "F4:27:E9:CA:E8:3F") => ({
address,
name,
manufacturerData,
rssi: -50,
txPower: null,
connectable: true,
bonded: false,
source: "scan",
seenAtMs: 1000,
});
test("a G1 arm on Even's firmware: side from the name, serial after the side byte", () => {
const ad = classifyAdvertisement(g1Raw("Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139") + "0000000000"));
assert.equal(ad.role, "left");
assert.equal(ad.g1Firmware, "stock");
assert.equal(ad.serial, "S110LABC030139");
assert.equal(ad.embeddedMac, null);
});
test("a G1 arm on g1v0: the name says all, the serial is in the 0xFFFF record", () => {
const ad = classifyAdvertisement(g1Raw("G1v0_R", "ffff" + "01" + "04" + g1Ascii("S110LABC030139")));
assert.equal(ad.role, "right");
assert.equal(ad.g1Firmware, "g1v0");
assert.equal(ad.serial, "S110LABC030139");
assert.equal(classifyAdvertisement(g1Raw("G1v0S_L", "")).g1Firmware, "g1v0-safe");
assert.equal(classifyAdvertisement(g1Raw("G1v0S_L", "")).serial, null);
});
const g1Record = (flags, version, serial = "S110LABC030139") => "ffff" + "02" + flags + version + g1Ascii(serial);
test("a G1 arm on g1v0 0.5.66+: its name tells pairs apart, its record says what it runs", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", g1Record("05", "000542")));
assert.equal(ad.role, "left");
assert.equal(ad.g1Firmware, "g1v0");
assert.equal(ad.g1Version, "0.5.66");
assert.equal(ad.serial, "S110LABC030139");
assert.equal(classifyAdvertisement(g1Raw("G1CFW_R_CBE689", g1Record("04", "000542"))).role, "right");
});
test("a G1 arm in safe mode says so in its record, not its name", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", g1Record("0d", "000542")));
assert.equal(ad.g1Firmware, "g1v0-safe");
assert.equal(ad.g1Version, "0.5.66");
});
test("a G1 arm whose record hasn't arrived yet still shows, without a version or serial", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", ""));
assert.equal(ad.g1Firmware, "g1v0");
assert.equal(ad.g1Version, undefined);
assert.equal(ad.serial, null);
});
test("g1v0 before 0.5.66 and Even's firmware advertise no version", () => {
assert.equal(classifyAdvertisement(g1Raw("G1v0_R", "ffff" + "01" + "04" + g1Ascii("S110LABC030139"))).g1Version, undefined);
assert.equal(classifyAdvertisement(g1Raw("Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139"))).g1Version, undefined);
});
test("a G1 pair joins on its serial across firmware, so an install in progress stays one pair", () => {
const stock = classifyAdvertisement(g1Raw("Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139") + "0000000000"));
const custom = classifyAdvertisement(g1Raw("G1CFW_R_CBE689", g1Record("04", "000542")));
assert.equal(stock.serial, custom.serial);
});
test("on iOS a G1 arm gets an address from its peripheral identifier, and is found at all", () => {
const { identifyIosPeripheral, g1IosAddress } = require("../.test-build/app/g2/ios-peripheral-identity.js");
const identifier = "14b99254-0798-d1a8-3eec-b141bdabfae8";
assert.equal(g1IosAddress(identifier), "14:B9:92:54:07:98");
for (const [name, manufacturerData, firmware] of [
["G1CFW_L_EF50E5", g1Record("05", "000542"), "g1v0"],
["Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139"), "stock"],
["G1v0_L", "ffff" + "01" + "05" + g1Ascii("S110LABC030139"), "g1v0"],
]) {
const device = identifyIosPeripheral({ identifier, name, manufacturerData, rssi: -50, connectable: true });
assert.ok(device, name);
assert.equal(device.address, "14:B9:92:54:07:98", name);
assert.equal(device.identifier, identifier.toUpperCase(), name);
assert.equal(device.role, "left", name);
assert.equal(device.g1Firmware, firmware, name);
assert.equal(device.serial, "S110LABC030139", name);
}
assert.equal(identifyIosPeripheral({ identifier: "not-a-uuid", name: "G1CFW_L_EF50E5", manufacturerData: "", rssi: 0, connectable: true }), null);
});
test("names that only look like a G1 are not admitted", () => {
for (const name of ["G1v0_X", "G1v0", "G1 Tracker", "Even G1", "Pixel G1v0_L", "G1CFW_L", "G1CFW_X_EF50E5", "G1CFW_L_EF50E", "Pixel G1CFW_L_EF50E5"]) {
assert.equal(classifyAdvertisement(g1Raw(name, "")), null, name);
}
});
+1 -1
View File
@@ -130,9 +130,9 @@ test("a layout font is the default for text and list containers, which override
page.containers.map((c) => [c.name, c.font]),
[
["l", { family: "Inter", size: 24, weight: 700 }],
["i", undefined],
["t", { family: "Inter", size: 24 }],
["u", { family: "Terminus", size: 24 }],
["i", undefined],
],
);
});
+126
View File
@@ -0,0 +1,126 @@
// updateImageRawData conversion (app/apps/evenhub/image-pipeline.ts), checked
// against what the Even phone app's decompiled _prepare / _prepareLegacyRaw do.
const test = require("node:test");
const assert = require("node:assert/strict");
const UPNG = require("upng-js");
const {
IMAGE_EXCEPTION,
IMAGE_SEND_FAILED,
IMAGE_SIZE_INVALID,
IMAGE_SUCCESS,
detectImageFormat,
grayLevel,
prepareImageUpdate,
resizeRgbaCover,
} = require("../.test-build/app/apps/evenhub/image-pipeline.js");
const noNative = () => null;
const request = (over) => ({
imageData: [],
compressMode: 2,
requestWidth: 0,
requestHeight: 0,
geometry: { width: 20, height: 20 },
decodeNative: noNative,
stockLimits: true,
...over,
});
/** A PNG of the given RGBA pixels. */
function png(width, height, rgba) {
return Array.from(new Uint8Array(UPNG.encode([Uint8Array.from(rgba).buffer], width, height, 0)));
}
test("imageData must be an array of integers", () => {
assert.equal(prepareImageUpdate(request({ imageData: "AAAA" })).result, IMAGE_SEND_FAILED);
assert.equal(prepareImageUpdate(request({ imageData: { 0: 1, 1: 2 } })).result, IMAGE_SEND_FAILED);
assert.equal(prepareImageUpdate(request({ imageData: [1, 2.5] })).result, IMAGE_SEND_FAILED);
});
test("formats are recognized by their magic bytes", () => {
assert.equal(detectImageFormat(Uint8Array.from(png(1, 1, [0, 0, 0, 255]))), "png");
assert.equal(detectImageFormat(Uint8Array.from([0xff, 0xd8, 0xff, 0xe0])), "jpeg");
assert.equal(detectImageFormat(Uint8Array.from([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50])), "webp");
assert.equal(detectImageFormat(Uint8Array.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])), "gif");
assert.equal(detectImageFormat(Uint8Array.from([0x42, 0x4d, 0, 0])), "bmp");
assert.equal(detectImageFormat(Uint8Array.from([1, 2, 3])), "raw");
});
test("grey uses 299/587/114 weights rounded to 16 levels, ignoring alpha", () => {
assert.equal(grayLevel(255, 0, 0), 4);
assert.equal(grayLevel(255, 255, 255), 15);
assert.equal(grayLevel(0, 0, 0), 0);
// A transparent white pixel is white: the phone app never looks at alpha.
const result = prepareImageUpdate(request({ imageData: png(20, 20, new Array(20 * 20).fill([255, 255, 255, 0]).flat()) }));
assert.equal(result.result, IMAGE_SUCCESS);
assert.ok(result.levels.every((level) => level === 15));
});
test("an encoded image is scaled to cover the container and centre-cropped", () => {
// 4x2: columns 0..3 lit 0, 85, 170, 255. Covering 20x20 scales by 10 to
// 40x20 and crops 10px a side, so only columns 1 and 2 survive.
const row = [0, 85, 170, 255].flatMap((v) => [v, v, v, 255]);
const result = prepareImageUpdate(request({ imageData: png(4, 2, [...row, ...row]) }));
assert.equal(result.result, IMAGE_SUCCESS);
assert.deepEqual([result.width, result.height], [20, 20]);
assert.deepEqual(Array.from(result.levels.slice(0, 20)), [...new Array(10).fill(grayLevel(85, 85, 85)), ...new Array(10).fill(grayLevel(170, 170, 170))]);
});
test("the cover resize samples source pixel centres", () => {
const source = { width: 3, height: 1, rgba: Uint8Array.from([10, 0, 0, 0, 20, 0, 0, 0, 30, 0, 0, 0]) };
const wide = resizeRgbaCover(source, 6, 2);
assert.deepEqual(Array.from(wide.rgba.filter((_, i) => i % 4 === 0)), [10, 10, 20, 20, 30, 30, 10, 10, 20, 20, 30, 30]);
});
test("width and height sent with the update replace the container's", () => {
const black = new Array(30 * 30).fill([0, 0, 0, 255]).flat();
const result = prepareImageUpdate(request({ imageData: png(30, 30, black), requestWidth: 40, requestHeight: 25 }));
assert.deepEqual([result.width, result.height], [40, 25]);
});
test("without a usable container size, the decoded size must itself be in range", () => {
const tiny = new Array(10 * 10).fill([0, 0, 0, 255]).flat();
assert.equal(prepareImageUpdate(request({ imageData: png(10, 10, tiny), geometry: null })).result, IMAGE_SIZE_INVALID);
});
test("JPEG, WebP and GIF go to the native decoder; a failed decode is an exception", () => {
const jpeg = [0xff, 0xd8, 0xff, 0xe0];
const decoded = prepareImageUpdate(request({
imageData: jpeg,
decodeNative: () => ({ width: 20, height: 20, rgba: new Uint8Array(20 * 20 * 4).fill(255) }),
}));
assert.equal(decoded.result, IMAGE_SUCCESS);
assert.equal(decoded.format, "jpeg");
assert.equal(prepareImageUpdate(request({ imageData: jpeg })).result, IMAGE_EXCEPTION);
});
test("raw pixels need compressMode 2 and exactly the container's size", () => {
const raw = new Array(400).fill(0);
assert.equal(prepareImageUpdate(request({ imageData: raw })).result, IMAGE_SUCCESS);
assert.equal(prepareImageUpdate(request({ imageData: raw, compressMode: 0 })).result, IMAGE_EXCEPTION);
assert.equal(prepareImageUpdate(request({ imageData: raw.slice(1) })).result, IMAGE_EXCEPTION);
assert.equal(prepareImageUpdate(request({ imageData: raw, geometry: { width: 400, height: 1 } })).result, IMAGE_SIZE_INVALID);
});
test("raw bytes up to 15 are already 4-bit levels; larger ones are 8-bit grey", () => {
const raw = new Array(400).fill(0);
raw.splice(0, 4, 15, 16, 128, 255);
const { levels } = prepareImageUpdate(request({ imageData: raw }));
assert.deepEqual(Array.from(levels.slice(0, 4)), [15, 1, 8, 15]);
});
test("4-bit raw rows are padded to whole bytes", () => {
// 21 wide: 11 bytes a row, high nibble first, the last low nibble unused.
const rows = [];
for (let y = 0; y < 20; y++) rows.push(0xf0, ...new Array(9).fill(0), 0x0f << 4);
const { result, levels } = prepareImageUpdate(request({ imageData: rows, geometry: { width: 21, height: 20 } }));
assert.equal(result, IMAGE_SUCCESS);
assert.deepEqual([levels[0], levels[1], levels[20], levels[21]], [15, 0, 15, 15]);
});
test("extended layouts skip the stock size and compressMode rules", () => {
const big = new Array(400 * 200).fill(0);
const result = prepareImageUpdate(request({ imageData: big, compressMode: 0, geometry: { width: 400, height: 200 }, stockLimits: false }));
assert.equal(result.result, IMAGE_SUCCESS);
});
+63
View File
@@ -0,0 +1,63 @@
// The EvenHub layout debug log (app/apps/evenhub/layout-debug.ts): page notes
// and the per-update lines it writes to logcat.
const test = require("node:test");
const assert = require("node:assert/strict");
const { parsePage } = require("../.test-build/app/apps/evenhub/containers.js");
const { describeImageUpdate, describePage, pageNotes } = require("../.test-build/app/apps/evenhub/layout-debug.js");
const iconOverBody = (extra = {}) =>
parsePage({
containerTotalNum: 2,
textObject: [{ containerID: 1, containerName: "body", xPosition: 0, yPosition: 0, width: 576, height: 288, isEventCapture: 1, ...extra.text }],
imageObject: [{ containerID: 2, containerName: "icon", xPosition: 8, yPosition: 8, width: 24, height: 24, ...extra.image }],
});
test("describePage lists containers bottom to top and ends with the raw payload", () => {
const lines = describePage("rebuildPageContainer", iconOverBody(), { containerTotalNum: 2 });
assert.match(lines[0], /^rebuildPageContainer: 2 containers \(0 list, 1 text, 1 image\), containerTotalNum=2/);
assert.match(lines[1], /^ {2}0: text#1 "body" @0,0 576x288 capture len=0 ""$/);
assert.match(lines[2], /^ {2}1: image#2 "icon" @8,8 24x24 no pixels yet$/);
assert.equal(lines.at(-1), ' raw: {"containerTotalNum":2}');
});
test("a shared container id is noted with the container it resolves to", () => {
assert.ok(pageNotes(iconOverBody({ image: { containerID: 1 } })).includes(
'id 1 is shared by text#1 "body", image#1 "icon"; updates and events resolve to text#1 "body" only',
));
});
test("capture-container problems and a wrong containerTotalNum are noted", () => {
assert.ok(pageNotes(iconOverBody({ text: { isEventCapture: 0 } })).some((n) => n.startsWith("no event-capture container")));
assert.ok(pageNotes(iconOverBody(), 3).some((n) => n.startsWith("containerTotalNum is 3 but 2")));
assert.deepEqual(pageNotes(iconOverBody(), 2), []);
});
const prepared = (over = {}) => ({ result: 0, levels: null, width: 0, height: 0, format: "raw", reason: "", ...over });
test("an update lists payload, size, lit pixels and outcome", () => {
const page = iconOverBody();
const levels = new Uint8Array(24 * 24);
levels[24 * 3 + 5] = 9;
levels[24 * 10 + 7] = 15;
const [line] = describeImageUpdate({
sentId: 2, sentName: "icon", raw: Array.from(levels), target: page.containers[1],
prepared: prepared({ levels, width: 24, height: 24 }), shown: true, result: 0,
});
assert.equal(line, 'updateImageRawData id=2 "icon" -> image#2 "icon" payload=number[576] format=raw 24x24 lit=2px max=15/15 bbox=5,3-7,10 result=0 shown');
});
test("an update says why it wasn't shown", () => {
const page = iconOverBody({ image: { containerID: 1 } });
const toText = describeImageUpdate({
sentId: 1, sentName: "", raw: [], target: page.containers[0],
prepared: prepared({ levels: new Uint8Array(1), width: 1, height: 1 }), shown: false, result: 4,
});
assert.ok(toText.some((line) => line.includes('resolves to text#1 "body", so the glasses refuse')));
const failed = describeImageUpdate({
sentId: 2, sentName: "", raw: "AAAA", target: undefined,
prepared: prepared({ result: 4, format: null, reason: "imageData is not an array of integers" }), shown: false, result: 4,
});
assert.match(failed[0], /payload=string\(4 chars\) result=4 not shown$/);
assert.equal(failed[1], " imageData is not an array of integers");
});
+61
View File
@@ -0,0 +1,61 @@
// The Even phone app's checks before it sends a page or text upgrade to the
// glasses (app/apps/evenhub/payload-validation.ts).
const test = require("node:test");
const assert = require("node:assert/strict");
const { stockPayloadError } = require("../.test-build/app/apps/evenhub/payload-validation.js");
// What SDK 0.0.16 sends for a small page (captured with a stub bridge).
const sdkPage = () => ({
containerTotalNum: 2,
textObject: [{ containerID: 1, containerName: "t", xPosition: 0, yPosition: 0, width: 200, height: 100, content: "hi", isEventCapture: 1, borderWidth: 2 }],
imageObject: [{ containerID: 2, containerName: "i", xPosition: 0, yPosition: 0, width: 40, height: 40 }],
listObject: [{ containerID: 3, containerName: "l", itemContainer: { itemCount: 2, itemName: ["a", "b"], isItemSelectBorderEn: 1 } }],
menuObject: { menuItems: [{ itemName: "Pause", itemID: 1 }] },
});
test("SDK-shaped payloads pass", () => {
assert.equal(stockPayloadError("create", sdkPage()), null);
assert.equal(stockPayloadError("rebuild", sdkPage()), null);
assert.equal(stockPayloadError("textUpgrade", { containerID: 1, containerName: "t", contentOffset: 2, contentLength: 3, content: "abc" }), null);
});
test("unknown keys fail, numeric tag keys pass", () => {
const page = sdkPage();
page.textObject[0].Container_ID = 1;
assert.match(stockPayloadError("create", page), /unknown key textObject\[0\]\.Container_ID/);
assert.match(stockPayloadError("rebuild", { ...sdkPage(), widgetId: 1 }), /unknown key widgetId/);
assert.equal(stockPayloadError("create", { ...sdkPage(), 7: 1 }), null);
});
test("numeric fields take integers or numeric strings only", () => {
const withField = (value) => {
const page = sdkPage();
page.textObject[0].xPosition = value;
return stockPayloadError("create", page);
};
assert.equal(withField(-10), null, "negative values wrap rather than fail");
assert.equal(withField("12"), null);
assert.match(withField(10.5), /must be an integer/);
assert.match(withField(true), /must be an integer/);
assert.match(withField(null), /is null/);
assert.match(withField("left"), /must be an integer/);
});
test("string and repeated fields are type-checked", () => {
const page = sdkPage();
page.textObject[0].content = 5;
assert.match(stockPayloadError("create", page), /content must be a string/);
const list = sdkPage();
list.listObject[0].itemContainer.itemName = "a";
assert.match(stockPayloadError("create", list), /itemName must be an array/);
});
test("textColor must be an integer 0..4 wherever it appears", () => {
const page = sdkPage();
page.textObject[0].textColor = 4;
assert.equal(stockPayloadError("create", page), null);
page.textObject[0].textColor = 15;
assert.match(stockPayloadError("create", page), /textColor must be an integer from 0 to 4/);
assert.match(stockPayloadError("textUpgrade", { containerID: 1, content: "x", textColor: "3" }), /textColor/);
});
+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);
});
+161
View File
@@ -0,0 +1,161 @@
// EvenHubSession behaviors that follow stock (the Even phone app plus
// firmware 2.2.9.22, as decompiled and run in the firmware emulator): text
// scrolling and its boundary events, text upgrades, image routing, and what a
// page the firmware can't build does.
const test = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const { loader } = require('./helpers/load-typescript.cjs');
// A face with 10px characters and 27px lines, wrapping only at '\n'.
const face = {
lineHeight: 27,
measureLine: text => text.length * 10,
wrap: text => text.split('\n'),
drawText() {},
drawTextWrapped() {},
};
function harness() {
const timers = [];
const load = loader({ global: { isIOS: true }, setTimeout: fn => { timers.push(fn); return timers.length; }, clearTimeout() {}, Promise }, {
'@nativescript/core': { ApplicationSettings: { getString: (_k, d) => d, setString() {} } },
'upng-js': require('upng-js'),
'../../graphics/evenhub-font': { EvenHubFont: { get: () => face } },
'./fonts': { containerFace: () => face, availableFontFamilies: () => [], measureContainerText: () => ({ width: 0, lineHeight: 27 }) },
'../../ui/dashboard-settings': {}, '../../ui/sound-effects': {}, './api-key-dialog': {},
'./mic-router': { evenHubMicRouter: {} }, './imu-router': { evenHubImuRouter: {} },
'./compass-router': { evenHubCompassRouter: {} }, '../../assistant/tool-registry': {},
'../../native/location': {}, '../../native/location-tracker': {}, '../../native/location-permissions': {},
'../../native/image-rgba': { decodeImageRgba: () => null },
});
const api = load('app/apps/evenhub/session.ts');
const session = new api.EvenHubSession({ name: 'Probe', packageId: 'test.stock', permissions: [] }, '/test/dist', () => {}, '');
let windowClosed = false;
session.attachWindow({ requestRender() {}, windowId: 'probe', closeWindow: () => { windowClosed = true; } });
const web = vm.createContext({ Promise, Map, Date, console });
web.window = web;
web.__faceclawEvenHub = { postMessage: (name, args, id) => session.handleBridgeCall(name, args, id) };
session.attachWebView({ evaluateJs: script => vm.runInContext(script, web), destroy() {} });
vm.runInContext(api.EVENHUB_BRIDGE_INJECT_SCRIPT, web);
const events = [];
web._listenEvenAppMessage = value => {
const message = typeof value === 'string' ? JSON.parse(value) : value;
if (message.method === 'evenHubEvent') events.push(JSON.parse(JSON.stringify(message.data)));
};
const call = (method, data = {}) => web.flutter_inappwebview.callHandler('evenAppMessage', JSON.stringify({ method, data }));
const runTimers = () => { for (const fn of timers.splice(0)) fn(); };
return { session, call, events, runTimers, windowClosed: () => windowClosed };
}
const lines = n => Array.from({ length: n }, (_, i) => `line ${i}`).join('\n');
const textPage = (content, extra = {}) => ({
containerTotalNum: 1,
textObject: [{ containerID: 1, containerName: 'body', xPosition: 0, yPosition: 0, width: 300, height: 100, content, isEventCapture: 1, ...extra }],
});
const swipe = (h, direction) => h.session.handleGesture({ type: direction === 'down' ? 'scroll-down' : 'scroll-up' });
test('an overflowing capture text container scrolls itself and reports only at its ends', async () => {
const h = harness();
// 6 lines = 162px in a 100px window: 62px to scroll, three 28px swipes.
assert.equal(await h.call('createStartUpPageContainer', textPage(lines(6))), 0);
h.events.length = 0;
swipe(h, 'down'); swipe(h, 'down'); swipe(h, 'down');
assert.deepEqual(h.events, [], 'no events while scrolling, nor for the swipe that reaches the end');
swipe(h, 'down');
assert.deepEqual(h.events, [{ type: 'textEvent', jsonData: { containerID: 1, containerName: 'body', eventType: 2 } }]);
h.events.length = 0;
swipe(h, 'up'); swipe(h, 'up'); swipe(h, 'up');
assert.deepEqual(h.events, []);
swipe(h, 'up');
assert.deepEqual(h.events, [{ type: 'textEvent', jsonData: { containerID: 1, containerName: 'body', eventType: 1 } }]);
});
test('text that fits reports every swipe as reaching an end', async () => {
const h = harness();
await h.call('createStartUpPageContainer', textPage('short'));
h.events.length = 0;
swipe(h, 'down'); swipe(h, 'down');
assert.equal(h.events.filter(e => e.type === 'textEvent' && e.jsonData.eventType === 2).length, 2);
});
test('text upgrades replace the whole text by id, ignore offsets, and keep old text when emptied', async () => {
const h = harness();
await h.call('createStartUpPageContainer', textPage('Hello world'));
const body = () => h.session.page.containers[0];
assert.equal(await h.call('textContainerUpgrade', { containerID: 1, containerName: 'other name', contentOffset: 3, contentLength: 2, content: 'XY' }), true);
assert.equal(body().content, 'XY');
assert.equal(await h.call('textContainerUpgrade', { containerID: 1, content: '' }), true);
assert.equal(body().content, 'XY', 'an empty upgrade leaves the old text showing');
assert.equal(await h.call('textContainerUpgrade', { containerID: 9, content: 'nope' }), false);
assert.equal(await h.call('textContainerUpgrade', { containerID: 1, content: 'x', junk: 1 }), false, 'unknown keys are refused');
});
test('an upgrade scrolls the text back to the top', async () => {
const h = harness();
await h.call('createStartUpPageContainer', textPage(lines(6)));
swipe(h, 'down');
assert.equal(h.session.page.containers[0].scrollY, 28);
await h.call('textContainerUpgrade', { containerID: 1, content: lines(7) });
assert.equal(h.session.page.containers[0].scrollY, 0);
});
test('image updates need a page, an image at that id, and a usable payload', async () => {
const h = harness();
const raw = new Array(400).fill(0);
assert.equal(await h.call('updateImageRawData', { containerID: 2, imageData: raw, compressMode: 2 }), 4, 'no page yet');
await h.call('createStartUpPageContainer', {
containerTotalNum: 3,
textObject: [{ containerID: 1, containerName: 'body', width: 300, height: 100, content: 'x', isEventCapture: 1 },
{ containerID: 3, containerName: 'label', width: 50, height: 30, content: 'y' }],
imageObject: [{ containerID: 2, containerName: 'icon', width: 20, height: 20 }, { containerID: 3, containerName: 'shadowed', width: 20, height: 20 }],
});
assert.equal(await h.call('updateImageRawData', { containerID: 2, imageData: raw, compressMode: 2 }), 0);
assert.equal(await h.call('updateImageRawData', { containerID: 2, imageData: 'AAAA', compressMode: 2 }), 4, 'base64 is refused');
assert.equal(await h.call('updateImageRawData', { containerID: 3, imageData: raw, compressMode: 2 }), 4, 'id 3 resolves to the text container');
// With no image at that id the Even app has no size for raw pixels: 0x0 is out of range.
assert.equal(await h.call('updateImageRawData', { containerID: 7, imageData: raw, compressMode: 2 }), 2);
});
test('a page the firmware cannot build fails create, and a failed rebuild closes the app', async () => {
const h = harness();
const tinyImage = { ...textPage('x'), imageObject: [{ containerID: 2, containerName: 'dot', width: 10, height: 10 }] };
assert.equal(await h.call('createStartUpPageContainer', tinyImage), 1);
assert.equal(await h.call('rebuildPageContainer', textPage('x')), false, 'nothing to rebuild before a page exists');
assert.equal(await h.call('createStartUpPageContainer', textPage('x')), 0);
h.events.length = 0;
assert.equal(await h.call('rebuildPageContainer', tinyImage), false);
assert.equal(h.session.page.containers.length, 0);
assert.ok(h.events.some(e => e.type === 'sysEvent' && e.jsonData.eventType === 6), 'ABNORMAL_EXIT');
h.runTimers();
assert.equal(h.windowClosed(), true);
});
test('the Even app refuses malformed pages before they reach the glasses', async () => {
const h = harness();
assert.equal(await h.call('createStartUpPageContainer', textPage('x', { isEventCapture: true })), 1);
assert.equal(await h.call('createStartUpPageContainer', textPage('x', { textColor: 7 })), 1);
assert.equal(await h.call('createStartUpPageContainer', textPage('x')), 0);
assert.equal(await h.call('rebuildPageContainer', { ...textPage('y'), Container_Total_Num: 1 }), false);
assert.equal(h.session.page.containers[0].content, 'x', 'a refused rebuild leaves the page alone');
});
test('borders use the colour index, overflowing text gets a scrollbar, and images cover text', async () => {
const h = harness();
// 300x100 with a 2px border of colour 3; 6 lines overflow the 96px window by 66px.
await h.call('createStartUpPageContainer', {
containerTotalNum: 2,
textObject: [{ containerID: 1, containerName: 'body', xPosition: 0, yPosition: 0, width: 300, height: 100, content: lines(6), isEventCapture: 1, borderWidth: 2, borderColor: 3 }],
imageObject: [{ containerID: 2, containerName: 'icon', xPosition: 0, yPosition: 40, width: 20, height: 20 }],
});
await h.call('updateImageRawData', { containerID: 2, imageData: new Array(400).fill(0), compressMode: 2 });
const image = h.session.paint({ width: 576, height: 288 }, true);
const at = (x, y) => image.pixels[y * 576 + x];
assert.equal(at(150, 0), 3 * 17, 'border grey');
assert.equal(at(0, 50), 0, 'the black image covers the border under it');
// Track 6..94 (88px); length floor(88 * 100 / 166) = 53; x 290..293.
assert.deepEqual([at(290, 7), at(291, 7), at(293, 7), at(289, 7), at(294, 7)], [187, 187, 187, 0, 0]);
assert.deepEqual([at(290, 6), at(291, 6), at(292, 6), at(293, 6)], [0, 187, 187, 0], 'chamfered top row');
assert.equal(at(291, 58), 187);
assert.equal(at(291, 59), 0, 'bar ends after 53 rows');
});
+4 -1
View File
@@ -17,6 +17,8 @@ const setting = (initial = '') => {
class AuthError extends Error {}
const gestures = loader({}, {})('app/ui/gestures.ts');
/**
* Load the store layer, by default with a signed-out account and no stored
* credentials. `api` overrides evenHubApi methods; text the layer paints is
@@ -34,7 +36,7 @@ const loadStoreLayer = ({ configured = false, api = {} } = {}) => {
'../../graphics/image': { GrayImage: class { drawText(_f, _x, _y, text) { drawn.push(text); } fillRect() {} } },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] },
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.min(hi, Math.max(lo, v)) },
'../../ui/gestures': { GESTURE_CLICK: 'click' },
'../../ui/gestures': { ...gestures, GESTURE_CLICK: 'click' },
'../../ui/menu': { drawSelectionHighlight() {} },
'../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'),
'../../ui/shell/shell': { shell: { yieldFocusToSidebar() {} } },
@@ -60,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 };
+81
View File
@@ -0,0 +1,81 @@
// Stock container-model rules the EvenHub emulation follows: stacking order,
// which container captures input, id resolution, firmware clamps and border
// greys. Source: the evenRealities-openCFW reconstruction of firmware 2.2.6.10
// (evenhub_ui_containers.c, evenhub_ui_page.c, common_text/list_container.c).
const test = require("node:test");
const assert = require("node:assert/strict");
const {
borderGrey,
clampToStockLimits,
containerById,
eventCaptureContainer,
paintOrder,
parsePage,
} = require("../.test-build/app/apps/evenhub/containers.js");
const names = (containers) => containers.map((c) => c.name);
test("without zOrderIndex containers stack lists, then texts, then images", () => {
const page = parsePage({
imageObject: [{ containerID: 1, containerName: "img" }],
textObject: [{ containerID: 2, containerName: "txt" }],
listObject: [{ containerID: 3, containerName: "lst" }],
});
assert.deepEqual(names(paintOrder(page.containers)), ["lst", "txt", "img"]);
});
test("zOrderIndex sorts only when every container has one", () => {
const all = parsePage({
textObject: [{ containerID: 1, containerName: "body", zOrderIndex: 2 }],
imageObject: [{ containerID: 2, containerName: "icon", zOrderIndex: 1 }],
});
assert.deepEqual(names(paintOrder(all.containers)), ["icon", "body"]);
const some = parsePage({
textObject: [{ containerID: 1, containerName: "body", zOrderIndex: 2 }],
imageObject: [{ containerID: 2, containerName: "icon" }],
});
assert.deepEqual(names(paintOrder(some.containers)), ["body", "icon"]);
});
test("the first capture container in stacking order owns input", () => {
const page = parsePage({
textObject: [
{ containerID: 1, containerName: "a", isEventCapture: 1, zOrderIndex: 5 },
{ containerID: 2, containerName: "b", isEventCapture: 1, zOrderIndex: 3 },
],
});
assert.equal(eventCaptureContainer(page).name, "b");
});
test("an id resolves to its first container in stacking order, whatever the kind", () => {
const page = parsePage({
textObject: [{ containerID: 7, containerName: "label" }],
imageObject: [{ containerID: 7, containerName: "icon" }],
});
assert.equal(containerById(page, 7).kind, "text");
assert.equal(containerById(page, 8), undefined);
});
test("stock clamps text and list geometry but leaves image sizes alone", () => {
const page = parsePage({
textObject: [{ containerID: 1, containerName: "t", xPosition: 900, yPosition: 400, width: 800, height: 400, borderColor: 40, borderRadius: 30, paddingLength: 50 }],
listObject: [{ containerID: 2, containerName: "l", itemContainer: { itemName: Array.from({ length: 25 }, (_, i) => `item ${i}`) } }],
imageObject: [{ containerID: 3, containerName: "i", xPosition: 600, width: 400, height: 200 }],
});
clampToStockLimits(page);
const [list, text, image] = page.containers;
assert.deepEqual([text.x, text.y, text.width, text.height], [576, 288, 576, 288]);
assert.deepEqual([text.borderColor, text.borderRadius, text.paddingLength], [16, 10, 32]);
assert.equal(list.itemNames.length, 20);
assert.deepEqual([image.x, image.width, image.height], [576, 400, 200]);
});
test("border color indices are 16 grey steps, with 16 meaning white", () => {
assert.equal(borderGrey(0), 0);
assert.equal(borderGrey(3), 0x33);
assert.equal(borderGrey(15), 0xff);
assert.equal(borderGrey(16), 0xff);
const page = parsePage({ textObject: [{ containerID: 1, containerName: "t", borderWidth: 2 }] });
assert.equal(page.containers[0].borderColor, 0, "an omitted borderColor is the protobuf default, black");
});
+263
View File
@@ -0,0 +1,263 @@
// EvenHub store navigation: watch swipes on the tab strip, the Updates tab's
// Update All row, and page-at-a-time scrolling in the permission dialog.
//
// The real layers run with their dependencies mocked; what they paint is
// collected as text, so these assert what the user would see.
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() {}
};
/** Stand-in for ui/menu-core's Menu: draws every row in order, scrolls the selection by one. */
class FakeMenu {
constructor(options) {
this.options = options;
this.items = options.items;
this.selectedIndex = 0;
this.scrollTop = 0;
}
setItems(items, selectedIndex) {
this.items = items;
if (selectedIndex !== undefined) this.selectedIndex = selectedIndex;
this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, items.length - 1));
}
get selectedItem() { return this.items[this.selectedIndex] ?? null; }
handleInput(event) {
if (event.type === 'scroll-down') this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1);
if (event.type === 'scroll-up') this.selectedIndex = Math.max(0, this.selectedIndex - 1);
}
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 storeApp = (packageId, name, version) => ({
id: 1, packageId, name, version, creatorName: '', tagline: '', description: '', categories: [],
installCount: 0, likeCount: 0, firstPublishedAt: '', iconPath: '', changelog: '', fileSize: 0,
});
const emptyPage = { apps: [], total: 0, page: 1, pageSize: 20 };
/** A signed-in store layer; `updates` is what the update check reports. */
const loadStore = ({ updates = [] } = {}) => {
const drawn = [];
const installs = [];
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() {} } },
'../../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 () => 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: () => updates.map((update) => update.installed), uninstallEvenHubPackage: () => true },
'./store-detail-layer': { EvenHubStoreDetailLayer: class {} },
'./store-install': {
cleanError: (error) => String(error?.message ?? error),
installStoreApp: async (_ctx, app) => { installs.push(app.packageId); return { packageId: app.packageId }; },
},
'./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: () => {} });
return { layer, drawn, installs };
};
const makeCtx = () => ({
stack: {
getBaseSize: () => ({ width: 576, height: 288 }),
isFocused: () => true,
clearToBase() {},
push() {},
pop() {},
},
actions: { requestRender() {}, endTextSettingEdit() {}, startTextSettingsEdit() {} },
});
const settle = () => new Promise((resolve) => setImmediate(resolve));
/** Repaint and return the drawn text. */
const repaint = (layer, drawn, ctx) => {
drawn.length = 0;
layer.paint(ctx);
return [...drawn];
};
const watch = (type) => ({ type, source: 'watch', timestampMs: 0 });
test('watch swipes left and right switch tabs while the tab strip is focused', async () => {
const { layer, drawn } = loadStore();
const ctx = makeCtx();
layer.paint(ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'));
// In the list, a right swipe is "select" and must not change tabs.
await layer.handleInput(watch('swipe-right'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'), 'still on Top');
// A left swipe in the list is "back", which focuses the tab strip.
await layer.handleInput(watch('swipe-left'), ctx);
await layer.handleInput(watch('swipe-right'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Recently published apps'), 'right moved to New');
await layer.handleInput(watch('swipe-left'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Public apps by popularity'), 'left moved back to Top');
// Up/down still switch tabs too.
await layer.handleInput(watch('swipe-down'), ctx);
await settle();
assert.ok(repaint(layer, drawn, ctx).includes('Recently published apps'), 'down moved to New');
});
/** Open the store and move to the Updates tab, with focus back in its list. */
const openUpdatesTab = async (layer, ctx) => {
layer.paint(ctx);
await settle();
await layer.handleInput({ type: 'double-click', source: 'ring' }, ctx);
for (let i = 0; i < 3; i++) await layer.handleInput({ type: 'scroll-down' }, ctx);
await settle();
await layer.handleInput({ type: 'click', source: 'ring' }, ctx);
};
test('the Updates tab lists Update All first and it installs every update', async () => {
const updates = [
{ installed: { packageId: 'a', name: 'Alpha', version: '1' }, latest: storeApp('a', 'Alpha', '2'), packageMissing: false },
{ installed: { packageId: 'b', name: 'Beta', version: '1' }, latest: storeApp('b', 'Beta', '3'), packageMissing: false },
{ installed: { packageId: 'c', name: 'Gamma', version: '1' } },
];
const { layer, drawn, installs } = loadStore({ updates });
const ctx = makeCtx();
await openUpdatesTab(layer, ctx);
const painted = repaint(layer, drawn, ctx);
assert.ok(painted.includes('Updates (3)'), `the tab count is apps, not rows: ${JSON.stringify(painted)}`);
assert.ok(painted.includes('3 apps need attention'));
const updateAll = painted.indexOf('Update All');
assert.ok(updateAll >= 0, `painted: ${JSON.stringify(painted)}`);
assert.ok(painted.includes('Install all 2 available updates'), 'the orphan is not counted');
assert.ok(updateAll < painted.indexOf('Alpha') && updateAll < painted.indexOf('Gamma'), 'Update All is the first row');
// The list opens on Update All; clicking it installs both updatable apps.
await layer.handleInput({ type: 'click', source: 'ring' }, ctx);
await settle();
assert.deepEqual(installs, ['a', 'b']);
const after = repaint(layer, drawn, ctx);
assert.ok(!after.includes('Update All'), 'nothing left to update, so the row goes');
assert.ok(after.includes('Gamma'), 'the missing package stays listed');
assert.ok(after.includes('Updated 2 apps.'));
});
test('the Updates tab has no Update All row when nothing can be installed', async () => {
const updates = [{ installed: { packageId: 'c', name: 'Gamma', version: '1' } }];
const { layer, drawn } = loadStore({ updates });
const ctx = makeCtx();
await openUpdatesTab(layer, ctx);
const painted = repaint(layer, drawn, ctx);
assert.ok(painted.includes('Gamma'));
assert.ok(!painted.includes('Update All'));
});
// ---- permission dialog ---------------------------------------------------
const loadDialog = (detailLines) => {
const drawn = [];
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: makeImageClass(drawn) },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => text.split('|') },
'../../ui/gestures': gestures,
'../../ui/layers': {},
'../../ui/menu': { drawListScrollbar() {}, drawSelectionHighlight() {} },
'./permissions': { permissionDetail: (permission) => permission.detail, permissionLabel: (name) => name },
'./privacy-policy': { openPrivacyPolicyOnPhone() {} },
'../../ui/metrics': { lineStep: () => 12, listRowHeight: () => 20 },
});
const { EvenHubPermissionDialogLayer } = load('app/apps/evenhub/permission-dialog.ts');
const ImageClass = makeImageClass(drawn);
const outcome = { confirmed: null };
const dialog = new EvenHubPermissionDialogLayer(
'Demo',
[{ name: 'network', detail: detailLines.join('|') }],
'',
() => { outcome.confirmed = true; },
() => { outcome.confirmed = false; },
);
const ctx = { stack: { getBaseSize: () => ({ width: 576, height: 136 }), isFocused: () => true, pop() {} } };
const paint = () => {
drawn.length = 0;
dialog.paint(ctx, () => new ImageClass());
return [...drawn];
};
return { dialog, ctx, paint, outcome };
};
test('the permission dialog scrolls a page at a time with one line of overlap', () => {
const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);
const { dialog, ctx, paint, outcome } = loadDialog(lines);
const pages = [paint()];
while (!pages[pages.length - 1].includes('Allow')) {
assert.ok(pages.length < 20, 'paging reaches the actions');
dialog.handleInput({ type: 'scroll-down' }, ctx);
pages.push(paint());
}
assert.ok(pages.length >= 3, `the list is long enough to need several pages (${pages.length})`);
// Every page but the last (which stops at the bottom) starts on the line the previous one ended on.
for (let page = 1; page < pages.length - 1; page++) {
const previous = pages[page - 1];
assert.equal(pages[page][0], previous[previous.length - 1], `page ${page + 1} overlaps page ${page} by one line`);
assert.ok(pages[page].length > 2, 'a page moves by more than one line');
}
// Every line was on screen on some page.
for (const line of lines) assert.ok(pages.some((page) => page.includes(line)), `${line} was shown`);
// Paging up from the bottom: the old first line becomes the new last one.
const bottom = pages[pages.length - 1];
dialog.handleInput({ type: 'scroll-up' }, ctx);
const up = paint();
assert.equal(up[up.length - 1], bottom[0], 'one line of overlap going up');
assert.ok(up.length > 2);
for (let i = 0; i < pages.length; i++) dialog.handleInput({ type: 'scroll-up' }, ctx);
assert.deepEqual(paint(), pages[0], 'back at the top');
// A click before the bottom pages down rather than allowing; scrolling up returns.
dialog.handleInput({ type: 'click', source: 'ring' }, ctx);
assert.deepEqual(paint(), pages[1]);
assert.equal(outcome.confirmed, null);
dialog.handleInput({ type: 'scroll-up' }, ctx);
assert.deepEqual(paint(), pages[0]);
});
+2
View File
@@ -28,6 +28,8 @@ function fixture() {
'../../ui/gestures': {}, '../../ui/shell/shell': { shell: {} }, './session': {},
'../../ui/shell/chrome-layer': { windowIcon: () => () => null, makeImageWindowIcon: () => () => null },
'./installed-apps': {},
'./glasses-compat': { needsDisplayWarning: () => false },
'./display-warning-dialog': {},
'../../ui/shell/in-process-window': { createInProcessWindow(value) {
options = value;
return { window: {}, stack: {}, requestRender() {}, setHeightMode(mode) { heights.push(mode); } };
+14
View File
@@ -74,3 +74,17 @@ test("reportedFirmwareVersion picks the higher arm", () => {
assert.equal(compat.reportedFirmwareVersion(info("", "", "2.2.9.22")), "2.2.9.22");
assert.equal(compat.reportedFirmwareVersion(info("", "", "")), "");
});
test("a G1's report names what the arms run and offers the install, stock or too old", () => {
const stock = compat.firmwareIncompatibilityMessage(info("", "Even's firmware", "Even's firmware"));
assert.match(stock, /G1/);
assert.match(stock, /Even's firmware/);
assert.match(stock, /install/);
assert.doesNotMatch(stock, /revision/);
const older = compat.firmwareIncompatibilityMessage(info("", "g1v0 0.5.62", "g1v0 0.5.63"));
assert.match(older, /L=g1v0 0\.5\.62 R=g1v0 0\.5\.63/);
assert.match(older, /install/);
// A compatible G1 reports the extension, and a G2's stock report is unchanged.
assert.equal(compat.firmwareIncompatibilityMessage(info(`Faceclaw/${REQUIRED}`, "g1v0 0.5.63", "g1v0 0.5.63")), null);
assert.match(compat.firmwareIncompatibilityMessage(info("")), /stock firmware/);
});
+88
View File
@@ -0,0 +1,88 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, console, require(name) { assert.ok(name in modules, `${file}: ${name}`); return modules[name]; } };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const build = (name) => require(`../.test-build/app/${name}.js`);
const graphics = build('graphics/image');
const metrics = build('ui/metrics');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const bdf = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
const font = bdf(14);
const textwrap = load('app/graphics/textwrap.ts', {});
const coreDeps = {
'../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'),
};
const menuCore = load('app/ui/menu-core.ts', coreDeps);
const menu = load('app/ui/menu.ts', {
...coreDeps, './menu-animation-pref': build('ui/menu-animation-pref'), './animation-speed': build('ui/animation-speed'),
'../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'../graphics/screen-size': { screenWidth: () => 540, screenHeight: () => 220 },
'../graphics/textwrap': textwrap, '../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {}, './metrics': metrics, './menu-core': menuCore,
});
// The UI font picker on Roboto Light 20, drawn in Terminus (TTF rendering is native).
const preview = bdf(20);
const picker = load('app/ui/font-picker.ts', {
'../graphics/bdffont': { getFont: () => font }, '../graphics/image': graphics, '../graphics/textwrap': textwrap,
'../graphics/ttf-font': { TtfFont: { load: () => preview } },
'../graphics/installed-fonts': { listInstalledFonts: () => [{ path: '/fonts/Roboto-Light.ttf', fileName: 'Roboto-Light.ttf',
family: 'Roboto', style: 'Light', weightOrder: 300, monospace: false }] },
'../graphics/ui-fonts': { fontSelectionLabel: () => 'Roboto Light 20', getDefaultSmallFont: () => font, uiFontSizeAllowed: () => true,
getTerminalFontSelection: () => null, getUiFontSelection: () => ({ kind: 'ttf', file: 'Roboto-Light.ttf', size: 20 }),
setTerminalFontSelection() {}, setUiFontSelection() {} },
'./gestures': {}, './menu': menu, './menu-core': menuCore, './metrics': metrics,
});
function stackOf(size) {
const layers = [];
return { layers, ctx: { stack: { getBaseSize: () => size, isFocused: () => true, push: (layer) => layers.push(layer) } } };
}
const glyphRuns = (image, f) => image.draws.filter((d) => d.kind === 'glyph' && d.font === f);
test('the font picker previews under its rows where they fit, else beside them, on the window either way', () => {
// At 192 rows either fits, by the font's metrics: only the bounds are checked.
for (const [size, beside] of [[{ width: 576, height: 260 }, false], [{ width: 476, height: 192 }, null], [{ width: 476, height: 155 }, true]]) {
const { layers, ctx } = stackOf(size);
picker.uiFontPickerMenuItem().onSelect(ctx);
const image = layers[0].paint(ctx);
const sample = glyphRuns(image, preview);
// The rows' labels and values (255 selected, 200 not; the title is 220, the info line 110).
const rows = glyphRuns(image, font).filter((d) => d.value === 255 || d.value === 200);
assert.ok(sample.length > 20, `the sample is drawn at ${size.height}`);
for (const d of image.draws) {
if (d.kind !== 'glyph') continue;
assert.ok(d.x >= 0 && d.y >= 0 && d.x + d.glyph.bbxWidth <= size.width && d.y + d.font.lineHeight <= size.height,
`glyph at ${d.x},${d.y} outside ${size.width}x${size.height}`);
}
const rowsRight = Math.max(...rows.map((d) => d.x)), rowsBottom = Math.max(...rows.map((d) => d.y));
if (beside === true) assert.ok(Math.min(...sample.map((d) => d.x)) > rowsRight, 'the sample right of the rows');
if (beside === false) assert.ok(Math.min(...sample.map((d) => d.y)) > rowsBottom, 'the sample under the rows');
}
});
test('a modal menu in a short window (a RayNeo iO\'s) keeps narrow margins, so four choices all show', () => {
const items = ['Left', 'Right', 'Bottom', 'Popup'].map((label) => ({ label, onSelect() {} }));
for (const [size, margin] of [[{ width: 576, height: 260 }, 20], [{ width: 476, height: 155 }, 8]]) {
const { layers, ctx } = stackOf(size);
menu.openModalMenu(ctx, 'App switcher position', items, 0);
const { layout } = layers[0];
assert.ok(layout.y >= margin && layout.y + layout.maxHeight <= size.height - margin, `${size.height}: ${layout.y}+${layout.maxHeight}`);
// Title, body padding (8 above and below) and the four rows.
const natural = metrics.menuTitleHeight(font) + 2 * 8 + items.length * metrics.listRowHeight(font);
assert.equal(layout.maxHeight, natural, `${size.height}: every row fits`);
}
});
+220
View File
@@ -0,0 +1,220 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const zlib = require('node:zlib');
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');
const sha = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
const noise = (length, seed) => Uint8Array.from({ length }, (_, i) => (i * 31 + seed * 17 + (i >> 3)) & 0xff);
const fromBase64 = (text) => new Uint8Array(Buffer.from(text, 'base64'));
/** A zip the way Even's are made: one entry stored, the others deflated, under a folder. */
function zipOf(entries) {
const locals = [];
const directory = [];
let offset = 0;
for (const { name, data, deflate } of entries) {
const packed = deflate ? zlib.deflateRawSync(data) : Buffer.from(data);
const nameBytes = Buffer.from(name);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(deflate ? 8 : 0, 8);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(deflate ? 8 : 0, 10);
central.writeUInt32LE(packed.length, 20);
central.writeUInt32LE(data.length, 24);
central.writeUInt16LE(nameBytes.length, 28);
central.writeUInt32LE(offset, 42);
locals.push(local, nameBytes, packed);
directory.push(central, nameBytes);
offset += local.length + nameBytes.length + packed.length;
}
const centralBytes = Buffer.concat(directory);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(centralBytes.length, 12);
end.writeUInt32LE(offset, 16);
return new Uint8Array(Buffer.concat([...locals, centralBytes, end]));
}
function fixture() {
const net = noise(5000, 1);
const app = noise(9000, 2);
const image = noise(20000, 3);
const table = app.subarray(4000, 4352);
image.set(net, 3000);
image.set(table, 12000);
const parts = [
{ offset: 3000, length: net.length, file: 'net.bin', fileOffset: 0, sha256: sha(net) },
{ offset: 12000, length: table.length, file: 'app.bin', fileOffset: 4000, sha256: sha(table) },
];
const own = Buffer.concat([image.subarray(0, 3000), image.subarray(8000, 12000), image.subarray(12352)]);
const manifest = { version: '0.0.1', sha256: sha(image), size: image.length, source: 't', stockVersion: 's', stockZipUrl: 'u', stockZipSha256: 'z', parts };
return { net, app, image, own: new Uint8Array(own), manifest };
}
test('a zip entry is found, deflated or stored, also under a folder', () => {
const stored = noise(300, 4);
const packed = noise(70000, 5);
const zip = zipOf([{ name: 'manifest.json', data: stored }, { name: 'firmware/app.bin', data: packed, deflate: true }]);
assert.deepEqual(readZipEntry(zip, 'manifest.json'), stored);
assert.deepEqual(Buffer.from(readZipEntry(zip, 'app.bin')), Buffer.from(packed));
assert.throws(() => readZipEntry(zip, 'missing.bin'), /no missing\.bin/);
assert.throws(() => readZipEntry(noise(100, 6), 'x'), /not a zip/);
});
test('the parts go back where they were, byte for byte', () => {
const { net, app, image, own, manifest } = fixture();
const files = { 'net.bin': net, 'app.bin': app };
const out = assembleG1Image(manifest, own, (name) => files[name], sha);
assert.deepEqual(Buffer.from(out), Buffer.from(image));
});
test('a part that is not the one it was built with is refused', () => {
const { net, app, own, manifest } = fixture();
const bad = net.slice();
bad[100] ^= 1;
const files = { 'net.bin': bad, 'app.bin': app };
assert.throws(() => assembleG1Image(manifest, own, (name) => files[name], sha), G1FirmwareError);
const short = { 'net.bin': net.subarray(0, 100), 'app.bin': app };
assert.throws(() => assembleG1Image(manifest, own, (name) => short[name], sha), /not the one/);
});
test('damaged bundled bytes never pass as an image', () => {
const { net, app, own, manifest } = fixture();
const files = { 'net.bin': net, 'app.bin': app };
const flipped = own.slice();
flipped[10] ^= 1;
assert.throws(() => assembleG1Image(manifest, flipped, (name) => files[name], sha), /failed verification/);
assert.throws(() => assembleG1Image(manifest, own.subarray(0, own.length - 1), (name) => files[name], sha), G1FirmwareError);
});
test('the bundled firmware is whole and carries none of Even\'s bytes in its manifest ranges', () => {
const own = decodeG1OwnBytes(G1V0_OWN_BYTES_BASE64, fromBase64);
const taken = G1V0_IMAGE.parts.reduce((sum, part) => sum + part.length, 0);
assert.equal(own.length + taken, G1V0_IMAGE.size);
// MCUboot's magic and the version in its header, ahead of the first part.
assert.equal(Buffer.from(own.subarray(0, 4)).toString('hex'), '3db8f396');
assert.equal(`${own[20]}.${own[21]}.${own[22] | (own[23] << 8)}`, G1V0_IMAGE.version);
assert.match(G1V0_IMAGE.stockZipUrl, /^https:\/\/cdn\.evenreal\.co\//);
assert.match(G1V0_IMAGE.sha256, /^[0-9a-f]{64}$/);
const sorted = [...G1V0_IMAGE.parts].sort((a, b) => a.offset - b.offset);
assert.ok(sorted[0].offset > 512 && sorted.at(-1).offset + sorted.at(-1).length < G1V0_IMAGE.size);
assert.doesNotMatch(G1V0_IMAGE.source, /uncommitted/, 'ship only a firmware that was committed');
});
test('versions compare by number, not by text', () => {
assert.ok(plan.compareG1Versions('0.5.100', '0.5.63') > 0);
assert.ok(plan.compareG1Versions('0.5.9', '0.5.63') < 0);
assert.equal(plan.compareG1Versions('0.5.63', '0.5.63'), 0);
assert.equal(plan.compareG1Versions('0.5', '0.5.0'), 0);
assert.ok(plan.compareG1Versions('', '0.5.63') < 0);
});
test('a pair is chosen by serial, then address, and never guessed between two', () => {
const g1 = (serial, left, right) => ({ g1Firmware: 'g1v0', serial, left: left && { address: left }, right: right && { address: right } });
const ours = g1('S1', 'L1', 'R1');
const theirs = g1('S2', 'L2', 'R2');
assert.equal(plan.pickG1Pair([theirs, ours], { serial: 's1' }), ours);
assert.equal(plan.pickG1Pair([theirs, ours], { left: 'L1' }), ours);
assert.equal(plan.pickG1Pair([theirs, ours], { right: 'R2' }), theirs);
assert.equal(plan.pickG1Pair([theirs, ours], {}), null);
assert.equal(plan.pickG1Pair([ours], {}), ours);
// A flash changed the addresses: the serial still finds it.
assert.equal(plan.pickG1Pair([g1('S1', 'NEW', 'NEW2'), theirs], { serial: 'S1', left: 'OLD', right: 'OLD2' }).left.address, 'NEW');
// Our serial with one arm heard so far: wait, even if another pair is complete.
assert.equal(plan.pickG1Pair([g1('S1', 'L1', null), theirs], { serial: 'S1' }), null);
// The wanted glasses weren't heard: another pair is never a stand-in, even the only one around.
assert.equal(plan.pickG1Pair([theirs], { serial: 'S1' }), null);
assert.equal(plan.pickG1Pair([theirs], { left: 'L1', right: 'R1' }), null);
// A wanted address on one side doesn't match a pair for lacking the other.
assert.equal(plan.pickG1Pair([g1('S2', 'L2', null)], { left: 'L1' }), null);
// G2 pairs don't count.
assert.equal(plan.pickG1Pair([{ serial: 'S9', left: { address: 'a' }, right: { address: 'b' } }], {}), null);
});
test('the state of the two arms is that of the arm that needs the most', () => {
const on = (version, extra = {}) => ({ firmware: 'g1v0', version, safeMode: false, ...extra });
const state = (...arms) => plan.g1FirmwareState(arms, '0.5.63');
assert.equal(state(on('0.5.63'), on('0.5.63')), 'current');
assert.equal(state(on('0.5.64'), on('0.5.63')), 'current');
assert.equal(state(on('0.5.62'), on('0.5.63')), 'older');
assert.equal(state(on('0.5.63', { safeMode: true }), on('0.5.62')), 'safe-mode');
assert.equal(state({ firmware: 'stock' }, on('0.5.63', { safeMode: true })), 'stock');
});
test('what the advertising alone says about the arms', () => {
const arm = (g1Firmware, g1Version) => ({ g1Firmware, g1Version });
const state = (left, right) => plan.g1StateFromAdvertising({ left, right }, '0.5.66');
assert.deepEqual(state(arm('g1v0', '0.5.66'), arm('g1v0', '0.5.66')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('g1v0', '0.5.67'), arm('g1v0', '0.5.66')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('g1v0', '0.5.66'), arm('g1v0', '0.5.100')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('stock'), arm('g1v0', '0.5.66')), { state: 'stock', version: '' });
assert.deepEqual(state(arm('g1v0-safe', '0.5.66'), arm('g1v0', '0.5.66')), { state: 'safe-mode', version: '' });
// Firmware before 0.5.66, or a record that hasn't arrived: an arm has to be asked.
assert.equal(state(arm('g1v0'), arm('g1v0', '0.5.66')), null);
assert.equal(state(arm('g1v0'), arm('g1v0')), null);
});
test('an older arm wins over a newer one', () => {
const arm = (g1Version) => ({ g1Firmware: 'g1v0', g1Version });
assert.deepEqual(plan.g1StateFromAdvertising({ left: arm('0.5.67'), right: arm('0.5.65') }, '0.5.66'), { state: 'older', version: '0.5.65' });
});
test('the native flow\'s answer is read, and nonsense is no answer', () => {
assert.deepEqual(plan.parseG1FlashResult('{"flashed":true,"version":"0.5.64"}'), { flashed: true, version: '0.5.64' });
assert.deepEqual(plan.parseG1FlashResult('nonsense'), {});
assert.deepEqual(plan.parseG1FlashResult(''), {});
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);
assert.equal(plan.g1FlashPercent('right', 0, 100), 50);
assert.equal(plan.g1FlashPercent('right', 100, 100), 100);
assert.equal(plan.g1FlashPercent('right', 5, 0), 50);
});
+46 -3
View File
@@ -20,18 +20,26 @@ function load(file, dependencies) {
function harness() {
const values = new Map();
const listeners = new Set();
const live = new Set();
const glasses = { haveCompass: true };
class Setting {
constructor(options) { Object.assign(this, options); }
get() { return values.get(this.storageKey) ?? this.defaultValue; }
get() {
const value = values.get(this.storageKey) ?? this.defaultValue;
return this.normalize ? this.normalize(value) : value;
}
set(value) { values.set(this.storageKey, value); }
}
const config = {
ConfigSettingBoolean: Setting, ConfigSettingEnum: Setting,
glassesHaveCompass: () => glasses.haveCompass,
onAnySettingChanged: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
};
const widgets = {
glanceWidgetSpans: (choice) => choice === 'calendar' || choice === 'terminal',
findGlanceWidget: () => ({ create: () => ({ start() {}, stop() {}, paint() {} }) }),
findGlanceWidget: (choice) => ({ create: () => ({
start() { live.add(choice); }, stop() { live.delete(choice); }, paint() {},
}) }),
};
const settings = load('app/apps/glanceboard/glanceboard-settings.ts', {
'../../ui/dashboard-settings': config, './layout': layout, './widgets': widgets,
@@ -45,7 +53,7 @@ function harness() {
'../../graphics/image': { GrayImage }, '../../ui/dashboard-settings': config,
'./glanceboard-settings': settings, './layout': layout, './widgets': widgets,
});
return { settings, GlanceBoard, values, listeners, notify: () => [...listeners].forEach((listener) => listener()) };
return { settings, GlanceBoard, values, listeners, live, glasses, notify: () => [...listeners].forEach((listener) => listener()) };
}
test('layout defaults to 2x2; expanding preserves stored slots and remembers the extra row', () => {
@@ -97,3 +105,38 @@ test('an active empty board resizes and requests a frame when the layout changes
board.stop();
assert.equal(h.listeners.size, 0);
});
test('glasses without a compass: no compass in the picker, and a stored one reads as Empty until a G2 returns', () => {
const h = harness();
h.values.set('glanceboard.quadrants.slot.0', 'compass');
assert.ok(h.settings.glanceSlotSettings()[0].values.includes('compass'));
assert.equal(h.settings.glanceSlotSettings()[0].get(), 'compass');
h.glasses.haveCompass = false;
const [slot] = h.settings.glanceSlotSettings();
assert.ok(!slot.values.includes('compass'));
// Empty, not the slot's default: System card may already be elsewhere on the board.
assert.equal(slot.get(), 'none');
assert.equal(h.values.get('glanceboard.quadrants.slot.0'), 'compass');
h.glasses.haveCompass = true;
assert.equal(h.settings.glanceSlotSettings()[0].get(), 'compass');
});
test('an unknown stored slot value still falls back to the slot default', () => {
const { settings: s, values } = harness();
values.set('glanceboard.quadrants.slot.0', 'removed-widget');
assert.equal(s.glanceSlotSettings()[0].get(), 'system-card');
});
test('a live board drops the compass widget when the paired glasses have no compass', () => {
const h = harness();
h.values.set('glanceboard.quadrants.slot.0', 'compass');
const board = new h.GlanceBoard(() => {});
board.start();
assert.ok(h.live.has('compass'));
h.glasses.haveCompass = false;
h.notify();
assert.ok(!h.live.has('compass'));
board.stop();
});
+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% ⚡");
});
+23
View File
@@ -0,0 +1,23 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { GrayImage } = require('../.test-build/app/graphics/image.js');
test('a non-integer size rounds up, warns, and leaves every pixel addressable', t => {
const warn = t.mock.method(console, 'warn', () => {});
const image = new GrayImage(78.625, 23.5, 7);
assert.deepEqual([image.width, image.height, image.pixels.length], [79, 24, 79 * 24]);
assert.ok(image.pixels.every(value => value === 7));
for (let y = 0; y < image.height; y++) {
image.setPixel(78, y, 200);
assert.equal(image.getPixel(78, y), 200, `row ${y}`);
}
assert.equal(warn.mock.callCount(), 1);
assert.match(warn.mock.calls[0].arguments[0], /78\.625x23\.5/);
});
test('a whole-number size is kept as given, without a warning', t => {
const warn = t.mock.method(console, 'warn', () => {});
const image = new GrayImage(79, 24);
assert.deepEqual([image.width, image.height], [79, 24]);
assert.equal(warn.mock.callCount(), 0);
});
+85 -1
View File
@@ -53,7 +53,7 @@ test('controller skips unset preferences, deduplicates changes and forces reconn
const method = controller.members.find(node => node.name?.getText(file) === 'pushHeadUpPreferences').getText(file);
let prefs = { enabled: -1, angle: -1 };
const { Harness } = evaluate(`export class Harness { ${method} }`, {
global: { isAndroid: true }, getHeadUpPreferences: () => prefs,
global: { isAndroid: true }, glassesTypeSetting: { get: () => 'g2' }, getHeadUpPreferences: () => prefs,
});
const h = new Harness(), calls = [];
h.communicator = { configureHeadUpWake: async (...args) => calls.push(args) };
@@ -74,3 +74,87 @@ test('controller skips unset preferences, deduplicates changes and forces reconn
const connect = controller.members.find(node => node.name?.getText(file) === 'connect').getText(file);
assert.match(connect, /pushHeadUpPreferences\(true\)/);
});
function settingsMenuHarness(isIOS, model) {
const file = ts.createSourceFile('settings-menus.ts', source('app/ui/dashboard/settings-menus.ts'), ts.ScriptTarget.Latest, true);
const actual = new Set(['settingsSections', 'ringConnectionMenuItem', 'notificationFilterMenuItem']);
const globals = { global: { isIOS }, NOTIFICATIONS_SETTINGS_SECTION: 'Notifications' };
// Isolate the real menu construction from unrelated rendering/native dependencies.
for (const node of file.statements) {
if (ts.isImportDeclaration(node)) {
for (const binding of node.importClause?.namedBindings?.elements ?? []) {
const name = binding.name.text;
globals[name] = Object.assign(() => ({}), { label: name, get: () => '' });
}
} else if (ts.isFunctionDeclaration(node) && !actual.has(node.name.text)) {
globals[node.name.text] = () => ({});
}
}
const row = setting => ({ label: setting.label });
Object.assign(globals, {
enumSettingMenuItem: row, toggleSettingMenuItem: row, textSettingMenuItem: row,
glassesTypeSetting: { get: () => model },
customizationRows: () => () => [], whisperServerMenuItems: () => [],
submenuItem: (label, onSelect, options) => ({ label, onSelect, ...options }),
});
const code = file.statements.filter(node => ts.isFunctionDeclaration(node) && actual.has(node.name.text))
.map(node => `export ${node.getText(file)}`).join('\n');
return evaluate(code, globals);
}
test('head-up controls are offered only for Android G2 model selection', () => {
for (const isIOS of [false, true]) {
for (const model of ['g2', 'g1', 'rayneo-io']) {
const display = settingsMenuHarness(isIOS, model).settingsSections().find(section => section.label === 'Display');
for (const label of ['headUpWakeSetting', 'headUpAngleSetting']) {
assert.equal(display.items.some(item => item.label === label), !isIOS && model === 'g2', `${isIOS ? 'iOS' : 'Android'} ${model} ${label}`);
}
}
}
});
test('notification filter description matches glasses-wide filtering while keeping phone notifications', () => {
const item = settingsMenuHarness(false, 'g2').notificationFilterMenuItem();
assert.equal(item.description, 'Disabled apps are hidden from glasses popups, the notification list, and the tray. Their notifications remain on your phone.');
});
test('Developer ring connection stays model-aware on iOS and Android', () => {
for (const isIOS of [false, true]) {
for (const model of ['g2', 'g1', 'rayneo-io']) {
const section = settingsMenuHarness(isIOS, model).settingsSections().find(section => section.label === 'Developer');
const ring = section.items.find(item => item.label === 'ringConnectionModeSetting');
assert.equal(typeof ring.disabled, 'function', 'use the model-aware ring helper');
assert.equal(ring.disabled(), model !== 'g2', `${isIOS ? 'iOS' : 'Android'} ${model}`);
}
}
});
function controllerForModel(getModel, isAndroid, preferences) {
const file = ts.createSourceFile('controller.ts', source('app/g2/dashboard-controller.ts'), ts.ScriptTarget.Latest, true);
const controller = file.statements.find(node => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
const method = controller.members.find(node => node.name?.getText(file) === 'pushHeadUpPreferences').getText(file);
const { Harness } = evaluate(`export class Harness { ${method} }`, {
global: { isAndroid }, glassesTypeSetting: { get: getModel }, getHeadUpPreferences: () => preferences,
});
return new Harness();
}
test('controller sends stored head-up choices only to Android G2, including forced reconnects', () => {
for (const isAndroid of [true, false]) {
let model = 'g1';
const preferences = { enabled: 1, angle: 35 };
const h = controllerForModel(() => model, isAndroid, preferences);
const calls = [];
h.communicator = { configureHeadUpWake: async (...args) => calls.push(args) };
for (model of ['g1', 'rayneo-io']) {
h.pushHeadUpPreferences();
h.pushHeadUpPreferences(true);
assert.equal(calls.length, 0, `${isAndroid ? 'Android' : 'iOS'} ${model}`);
assert.equal(h.lastPushedHeadUp, undefined, 'skipped models must not consume dedup state');
}
model = 'g2';
h.pushHeadUpPreferences();
assert.deepEqual(calls, isAndroid ? [[1, 35]] : []);
assert.deepEqual(preferences, { enabled: 1, angle: 35 }, 'model changes preserve stored choices');
}
});
+1
View File
@@ -65,6 +65,7 @@ function loadIconGrid({ lastInputWasWatch = false } = {}) {
'./menu-animation-pref': build('ui/menu-animation-pref'),
'./animation-speed': build('ui/animation-speed'),
'../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
});
const grid = load('app/ui/icon-grid.ts', {
...common,
+1 -1
View File
@@ -214,7 +214,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' },
+7 -4
View File
@@ -87,7 +87,8 @@ function sessionHarness(overrides = {}, playBuzzer = () => {}, { packageId = 'te
'../../ui/dashboard-settings': {}, '../../ui/sound-effects': {}, './api-key-dialog': {},
'./mic-router': { evenHubMicRouter: {} }, './imu-router': { evenHubImuRouter: {} },
'./compass-router': { evenHubCompassRouter: {} }, '../../assistant/tool-registry': {},
'../../native/location': {}, '../../native/location-tracker': {}, '../../native/location-permissions': {}, ...overrides,
'../../native/location': {}, '../../native/location-tracker': {}, '../../native/location-permissions': {},
'../../native/image-rgba': { decodeImageRgba: () => null }, ...overrides,
});
const api = load('app/apps/evenhub/session.ts');
const session = new api.EvenHubSession({ name: 'Probe', packageId, permissions: [] }, '/test/dist', line => logs.push(line), '', playBuzzer);
@@ -105,10 +106,12 @@ function sessionHarness(overrides = {}, playBuzzer = () => {}, { packageId = 'te
test('injected EvenHub RPC creates, updates and composites an image page with no Android globals', async () => {
const h = sessionHarness();
assert.equal(await h.call('createStartUpPageContainer', { containerTotalNum: 1,
imageObject: [{ containerID: 1, containerName: 'board', xPosition: 0, yPosition: 0, width: 2, height: 2 }] }), 0);
assert.equal(await h.call('updateImageRawData', { containerID: 1, containerName: 'board', imageData: [0, 80, 160, 255] }), 0);
imageObject: [{ containerID: 1, containerName: 'board', xPosition: 0, yPosition: 0, width: 20, height: 20 }] }), 0);
// Raw 8-bit grey as the SDK sends it (compressMode 2), quantized to 4-bit levels as the Even app does.
const raw = new Array(400).fill(0); raw.splice(0, 4, 0, 80, 160, 255);
assert.equal(await h.call('updateImageRawData', { containerID: 1, containerName: 'board', imageData: raw, compressMode: 2 }), 0);
const painted = h.session.paint({ width: 576, height: 288 }, true);
assert.deepEqual([painted.pixels[0], painted.pixels[1], painted.pixels[576], painted.pixels[577]], [0, 80, 160, 255]);
assert.deepEqual(Array.from(painted.pixels.slice(0, 4)), [0, 5 * 17, 9 * 17, 255]);
assert.equal(await h.call('setLocalStorage', { key: 'score', value: '42' }), true);
assert.equal(await h.call('getLocalStorage', { key: 'score' }), '42');
const events = [];
+43 -6
View File
@@ -21,7 +21,10 @@ const planes = load('app/graphics/plane.ts', { './image': images });
const timings = load('app/native/frame-timings.ts', {});
const LAUNCHER_GRAY = 75;
let glassesType = 'g2';
function fixture() {
const relay = { available: true, starts: 0, client: null, message: undefined };
const observers = new Map(), phoneState = { protectedDataAvailable: true };
let settingsChanged, remoteHost, controller, bridge = null;
let now = 1000, nextTask = 0, screenOn = true, shellOptions;
@@ -104,12 +107,12 @@ function fixture() {
const noop = () => () => {};
class FaceclawCommunicatorBridge extends Display {
phase = 'disconnected'; listeners = {};
constructor() { super(); bridge = this; }
constructor(addresses) { super(); bridge = this; this.addresses = addresses; }
on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; }
onStateChange(fn) { return this.on('state', fn); } onRingEvent(fn) { return this.on('ring', fn); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo() { return noop(); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo(fn) { return this.on('firmware', fn); }
onFrameMetrics() { return noop(); } onPreviewAnimationFrame() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
onAncsAuthorization() { return noop(); } setRequiresAncs() {} ancsRelayAvailable() { return relay.available; } rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
emitState(phase, status = phase) { if (phase === 'connected' || phase === 'disconnected') this.phase = phase; this.listeners.state?.({ phase, status }); }
emitRing(input) { this.listeners.ring?.(input); }
@@ -148,7 +151,10 @@ function fixture() {
'../ui/shell/voice-activity': { voiceActivity: { setActive() {}, isActive: () => false, subscribe: () => () => {} } },
'../native/faceclaw-communicator.ios': { FaceclawCommunicatorBridge, resolveIosPeripherals: async addresses => addresses },
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../g1/firmware/g1v0-image': { G1V0_IMAGE: { version: '0.5.65' } },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; constructor() { relay.client = this; }
start() { this.state = 'starting'; relay.starts++; } stop(message) { this.state = 'disconnected'; relay.message = message; }
stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
'../native/weather': { weatherBridge: { setSessionActive() {} } },
'./glance-host': { GlanceHost }, './events': events,
@@ -172,7 +178,7 @@ function fixture() {
'../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] },
'../apps/onboarding/onboarding-progress': { claimGlassesOnboardingAutoLaunch: () => false },
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, ringConnectionModeSetting: { get: () => 'glasses' }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../ui/dashboard-settings': { glassesTypeSetting: { get: () => glassesType }, brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, ringConnectionModeSetting: { get: () => 'glasses' }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
@@ -214,10 +220,41 @@ function fixture() {
}
async function phone(type, origin = 'ring') { controller.gesture(type, origin); await render(); }
async function connect() { await controller.connect(); await render(); }
return { controller, shell, battery, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
return { relay, controller, shell, battery, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
get shellOptions() { return shellOptions; }, registered, inProcessApps,
get bridge() { return bridge; }, connect, wear: wearing => bridge.emitWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
}
test('the session is told which glasses it drives, as a G2 session gets nowhere on a G1', async () => {
for (const type of ['g1', 'g2']) {
glassesType = type;
const f = fixture();
await f.connect();
assert.equal(f.bridge.addresses.glassesType, type);
assert.ok('right' in f.bridge.addresses && 'left' in f.bridge.addresses, 'the arms still come with it');
}
glassesType = 'g2';
});
test('a link that comes back asks for the notification relay again; a G1 without one is told to update', async () => {
const f = fixture();
await f.connect();
const firmware = { leftVersion: 'g1v0 0.5.65', rightVersion: 'g1v0 0.5.65', extension: 'Faceclaw/38' };
f.bridge.listeners.firmware(firmware);
assert.equal(f.relay.starts, 1);
// Connected and running: nothing to do.
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 1);
// The firmware's relay ended with the link, so the client must not go on thinking it's ready.
f.bridge.emitState('retrying', 'Reconnecting');
assert.equal(f.relay.client.state, 'disconnected');
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 2);
f.bridge.emitState('retrying', 'Reconnecting');
f.relay.available = false;
f.bridge.emitState('connected');
assert.equal(f.relay.starts, 2);
assert.match(f.relay.message, /firmware 0\.5\.65/);
});
const assertBlank = pixels => assert.ok(pixels.every(p => p === 0));
const assertBoard = pixels => {
assert.equal(pixels[48 * 640 + 270], 200);
+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);
});
+10
View File
@@ -57,6 +57,16 @@ function alsRecord(alsValue) {
return body;
}
test('only a G1 session runs the G1 connect path', () => {
for (const [glassesType, expected] of [['g1', 1], ['g2', 0], [undefined, 0]]) {
const { session, FaceclawCommunicatorBridge } = harness();
let used = 0;
session.useG1 = () => { used++; };
new FaceclawCommunicatorBridge({ right: 'r', left: 'l', glassesType });
assert.equal(used, expected, String(glassesType));
}
});
test('the bridge is the active session from start() until close()', async () => {
const h = harness();
const bridge = new h.FaceclawCommunicatorBridge({ right: 'r', left: 'l' });
+6 -1
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),
@@ -135,7 +136,7 @@ function loadRemote({ phase = 'disconnected', preview = false, now = 1_800_000_0
})[id] ?? {},
});
const remote = new WearRemote({
apps: [{ appId: 'timer', title: 'Timer' }],
apps: () => [{ appId: 'timer', title: 'Timer' }],
injectInput: async kind => { inputs.push(kind); },
launchApp: async () => {}, connect: async () => {}, disconnect: async () => {},
setGlassesLocked() {}, requestShellRender() {},
@@ -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);
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.test.*
class ColorGlyphArtTest {
private val size = 16
private val clear = 0
private val white = argb(255, 255, 255, 255)
private val yellow = argb(255, 255, 204, 50)
private val brown = argb(255, 90, 50, 20)
private val darkGray = argb(255, 60, 60, 60)
private val green = argb(255, 120, 170, 60)
private val red = argb(255, 230, 60, 50)
private val lightRed = argb(255, 250, 140, 130)
private fun argb(a: Int, r: Int, g: Int, b: Int): Int = (a shl 24) or (r shl 16) or (g shl 8) or b
private fun glyph(pixel: (x: Int, y: Int) -> Int): IntArray = IntArray(size * size) { pixel(it % size, it / size) }
private fun inDisc(x: Int, y: Int): Boolean {
val dx = x + 0.5 - size / 2.0
val dy = y + 0.5 - size / 2.0
return dx * dx + dy * dy <= 7.0 * 7.0
}
private fun at(shade: ByteArray, x: Int, y: Int): Int = shade[y * size + x].toInt() and 0xff
private fun lit(level: Double): Int = (255 * level.pow(NotificationIconArt.GAMMA)).roundToInt()
@Test fun whiteGlyphIsItsAlpha() {
// An ordinary glyph drawn in white: antialiased edges, no color anywhere.
val pixels = glyph { x, y -> if (x in 4..11) argb(if (x == 4 || x == 11) 90 else 255, 255, 255, 255) else clear }
assertFalse(ColorGlyphArt.isColor(pixels))
assertContentEquals(ByteArray(pixels.size) { ((pixels[it] ushr 24) and 0xff).toByte() }, ColorGlyphArt.coverage(pixels))
}
@Test fun faintColorFringeIsNotColor() {
// Unpremultiplying a nearly transparent pixel can land anywhere; only real ink counts.
val pixels = glyph { x, _ -> if (x == 3) argb(8, 0, 0, 0) else if (x in 4..11) white else clear }
assertFalse(ColorGlyphArt.isColor(pixels))
}
@Test fun oneColorGlyphLightsFully() {
// 🖤: dark by lightness, but its shape is what matters.
val pixels = glyph { x, y -> if (inDisc(x, y)) darkGray else clear }
assertTrue(ColorGlyphArt.isColor(pixels))
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(0, at(shade, 0, 0))
}
@Test fun darkDetailOnALightBodyStaysVisibleButDim() {
// 😀: a yellow disc with dark eyes and mouth; the body stays full, the features dim.
val pixels = glyph { x, y ->
when {
!inDisc(x, y) -> clear
(y in 5..6 && (x == 5 || x == 10)) || (y == 11 && x in 5..10) -> brown
else -> yellow
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(lit(0.3), at(shade, 5, 5))
assertTrue(at(shade, 5, 5) > 0)
}
@Test fun lightDetailOnADarkerBodyDimsTheBody() {
// ✅: a green tile with a large white check; the check lights fully above a dimmer tile.
val pixels = glyph { x, y ->
when {
x !in 1..14 || y !in 1..14 -> clear
(x in 4..7 && y in 9..11) || (x in 7..12 && y in 4..8) -> white
else -> green
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 9, 6))
assertEquals(lit(0.6), at(shade, 2, 2))
}
@Test fun smallHighlightLeavesTheBodyFull() {
// ❤️: a red body with a small glint; the glint is not detail worth dimming the body for.
val pixels = glyph { x, y ->
when {
!inDisc(x, y) -> clear
x in 4..5 && y in 4..5 -> lightRed
else -> red
}
}
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(255, at(shade, 8, 8))
assertEquals(255, at(shade, 4, 4))
}
@Test fun edgeAlphaScalesTheShade() {
val pixels = glyph { x, y -> if (x == 2) argb(128, 60, 60, 60) else if (x in 3..12 && y in 3..12) darkGray else clear }
val shade = ColorGlyphArt.coverage(pixels)
assertEquals(128, at(shade, 2, 8))
assertEquals(0, at(shade, 1, 8))
}
@Test fun emptyGlyphIsEmpty() {
assertTrue(ColorGlyphArt.shade(IntArray(size * size)).all { it.toInt() == 0 })
}
}
@@ -0,0 +1,986 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
private const val ARM = "F4:27:E9:CA:E8:3F"
private fun hex(text: String): ByteArray = ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
/** An image the way MCUboot lays one out: header, payload, then a TLV area with its SHA-256. */
private fun testImage(version: Triple<Int, Int, Int> = Triple(0, 5, 64), payloadSize: Int = 5000): ByteArray {
val headerSize = 512
val hash = ByteArray(32) { (it * 3 + version.third).toByte() }
val image = ByteArray(headerSize + payloadSize + 4 + 4 + 32)
fun put16(at: Int, value: Int) {
image[at] = value.toByte()
image[at + 1] = (value ushr 8).toByte()
}
fun put32(at: Int, value: Int) {
put16(at, value and 0xffff)
put16(at + 2, value ushr 16)
}
put32(0, 0x96f3b83d.toInt())
put16(8, headerSize)
put32(12, payloadSize)
image[20] = version.first.toByte()
image[21] = version.second.toByte()
put16(22, version.third)
for (i in 0 until payloadSize) image[headerSize + i] = (i * 7).toByte()
val tlv = headerSize + payloadSize
put16(tlv, 0x6907)
put16(tlv + 2, 4 + 4 + 32)
put16(tlv + 4, 0x10)
put16(tlv + 6, 32)
hash.copyInto(image, tlv + 8)
return image
}
/**
* 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, private val netImage: ByteArray? = null) : StockLink {
var inbound: StockLinkListener? = null
var connected = false
var bond = BondState.BONDED
var bondRequests = 0
var bondResult = BondState.BONDED
val subscribed = ArrayList<String>()
val heartbeats = ArrayList<ByteArray>()
val calls = ArrayList<String>()
var runningVersion = "0.5.63"
var safeMode = false
var battery = 80
/** 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. */
var silentAtOffset = -1
var onChunk: (() -> Unit)? = null
var connects = 0
/** The OS remembers a table without g1v0's services, as after an install at the same address. */
var staleTable = false
var refreshes = 0
/** Android says bonded and the arm has lost its half. */
var staleBond = false
var removedBonds = 0
var inCase = false
/** Even's firmware's answer to its battery query; null: it says nothing. */
var stockBatteryReply: ByteArray? = null
val wantHash = G1Smp.imageHash(image)
override fun setListener(listener: StockLinkListener?) { inbound = listener }
override fun connect(address: String, timeoutMs: Int): Boolean {
connects++
connected = true
return true
}
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
override fun discoverServices(address: String, timeoutMs: Int): Boolean = connected
/** As FaceclawBleManager: a characteristic the table lacks throws, a refused one (no encryption) returns false. */
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean {
if (!connected) throw IllegalStateException("Not connected")
if (!hasCharacteristic(address, characteristicUuid)) throw IllegalStateException("Characteristic not found: $characteristicUuid")
if (stock && staleBond && characteristicUuid == G1Smp.NUS_TX_UUID) return false
subscribed.add(characteristicUuid)
return true
}
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = when (characteristicUuid) {
G1Ble.EVT_CHAR_UUID -> !stock && !staleTable
G1Smp.NUS_TX_UUID -> stock
else -> true
}
override fun refreshServices(address: String, timeoutMs: Int): Boolean {
refreshes++
staleTable = false
return connected
}
override fun removeBond(address: String): Boolean {
removedBonds++
bond = BondState.NONE
staleBond = false
connected = false
return true
}
override fun isConnected(address: String): Boolean = connected
override fun bondState(address: String): BondState = bond
override fun requestBond(address: String) {
bondRequests++
bond = bondResult
}
override fun negotiatedMtu(address: String): Int = 100
override fun disconnect(address: String) { connected = false }
override fun close() { connected = false }
fun drop() {
connected = false
inbound?.onConnectionStateChange(ARM, false)
}
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (!connected) throw IllegalStateException("Not connected")
when (characteristicUuid) {
G1Smp.NUS_RX_UUID -> {
val frame = frames.single()
if (frame[0].toInt() == 0x2c) {
stockBatteryReply?.let { inbound?.onNotification(ARM, G1Smp.NUS_TX_UUID, it) }
} else {
heartbeats.add(frame)
}
}
G1Ble.PAIR_CHAR_UUID -> return bond == BondState.BONDED && !staleBond
G1Ble.CTRL_CHAR_UUID -> control(frames.single())
G1Smp.SMP_CHAR_UUID -> {
for (frame in frames) assertTrue(frame.size <= 97, "a write longer than the MTU allows")
smp(frames.reduce { a, b -> a + b })
}
else -> throw IllegalStateException("write to $characteristicUuid")
}
return true
}
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() }
val flags = (if (safeMode) 1 else 0) or 2 or (if (staleBond) 0 else 64) or (if (inCase) 128 else 0)
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, 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) {
val op = frame[0].toInt()
val group = frame[5].toInt()
val seq = frame[6].toInt() and 0xff
val cmd = frame[7].toInt()
val body = G1Cbor.decode(frame, 8) as Map<*, *>
if (silentRequests > 0) {
silentRequests--
return
}
when {
group == 1 && cmd == 1 -> {
calls.add("upload")
val off = (body["off"] as Long).toInt()
onChunk?.invoke()
if (off == silentAtOffset) {
silentAtOffset = -1
return
}
if (uploadRefusal != 0) return reply(op, group, seq, cmd, mapOf("rc" to uploadRefusal))
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 == imageOf(uploadImage).size) {
uploads[uploadImage] = uploaded
slotHashes[uploadImage] = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
}
}
if (uploadOffset >= dropAtOffset && dropAtOffset >= 0) {
dropAtOffset = -1
drop()
return
}
reply(op, group, seq, cmd, mapOf("rc" to 0, "off" to uploadOffset))
}
group == 1 && cmd == 0 && op == G1Smp.OP_READ -> {
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))
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")
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")
reply(op, group, seq, cmd, emptyMap())
drop()
}
else -> throw IllegalStateException("SMP $group/$cmd")
}
}
/** The reply comes in pieces, as notifications do. */
private fun reply(op: Int, group: Int, seq: Int, cmd: Int, body: Map<String, Any?>) {
val frame = G1Smp.frame(op or 1, group, seq, cmd, body)
for (piece in G1Smp.split(frame, 23)) inbound?.onNotification(ARM, G1Smp.SMP_CHAR_UUID, piece)
}
}
private class Recorder : FaceclawFirmwareFlasherListener {
val states = ArrayList<String>()
val logs = ArrayList<String>()
var progress = 0L
var total = 0L
var success: Boolean? = null
var detail = ""
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) {
progress = bytesSent
total = bytesTotal
}
override fun onState(state: String?, detail: String?) { states.add(state ?: "") }
override fun onComplete(success: Boolean, detail: String?) {
this.success = success
this.detail = detail ?: ""
}
}
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 {
@Test
fun stocksBatteryReplyIsReadOnlyWhenItIsOne() {
// What the real firmware answered in emulation (g1-fw BLE_COMMAND_SET_REPORT), first bytes.
assertEquals(100, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0x64, 0x64, 0xf9.toByte(), 0x80.toByte())))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 101)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0xc9.toByte(), 50)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x25, 0x66, 50)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66)))
}
}
class G1SmpTest {
private val sha = ByteArray(32) { it.toByte() }
/** The expected bytes come from scouter_kit's tools/g1host.py, whose requests were proven on real arms. */
@Test
fun requestsMatchTheProvenPythonTool() {
val image = ByteArray(574408)
image[0] = 1
image[1] = 2
image[2] = 3
val first = G1Smp.uploadRequest(image, 0, sha).toMutableMap()
first["data"] = byteArrayOf(1, 2, 3)
assertEquals(
"0200004e00010001a665696d61676500636c656e1a0008c3c8636f666600637368615820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f6464617461430102036775706772616465f4",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 0, G1Smp.CMD_IMAGE_UPLOAD, first)),
)
assertEquals(
"0200001100010101a2636f6666190800646461746143010203",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 1, G1Smp.CMD_IMAGE_UPLOAD, mapOf("off" to 2048, "data" to byteArrayOf(1, 2, 3)))),
)
assertEquals(
"0200003100010500a264686173685820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f67636f6e6669726df5",
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 5, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(sha))),
)
assertEquals("0000000100010700a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, 7, G1Smp.CMD_IMAGE_STATE, emptyMap())))
assertEquals("020000010000ff05a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_OS, 255, G1Smp.CMD_OS_RESET, emptyMap())))
}
@Test
fun cborMatchesPythonAndRoundTrips() {
val value = mapOf("n" to -5, "big" to 70000, "huge" to 5000000000L, "t" to true, "s" to "ab")
val encoded = G1Cbor.encode(value)
assertEquals("a5616e24636269671a0001117064687567651b000000012a05f2006174f56173626162", BinaryEncoding.bytesToHex(encoded))
val decoded = G1Cbor.decode(encoded) as Map<*, *>
assertEquals(-5L, decoded["n"])
assertEquals(70000L, decoded["big"])
assertEquals(5000000000L, decoded["huge"])
assertEquals(true, decoded["t"])
assertEquals("ab", decoded["s"])
}
@Test
fun cborReadsTheIndefiniteLengthsOfAnImageList() {
// {"images": [{"slot": 1, "active": true}]}, each container of indefinite length.
val data = hex("bf66696d616765739fbf64736c6f74016661637469766" + "5f5ffffff")
val slots = (G1Cbor.decode(data) as Map<*, *>)["images"] as List<*>
val slot = slots.single() as Map<*, *>
assertEquals(1L, slot["slot"])
assertEquals(true, slot["active"])
}
@Test
fun malformedCborIsAnErrorNotAWrongValue() {
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("5820")) }
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("bf")) }
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(ByteArray(0)) }
}
@Test
fun repliesAreJoinedAcrossNotifications() {
val assembler = G1Smp.Assembler()
val one = G1Smp.frame(3, 1, 7, 1, mapOf("off" to 2048, "rc" to 0))
val two = G1Smp.frame(3, 1, 8, 0, emptyMap())
val all = one + two
val replies = ArrayList<Pair<Int, Map<*, *>>>()
for (start in all.indices step 5) replies += assembler.feed(all.copyOfRange(start, minOf(start + 5, all.size)))
assertEquals(listOf(7, 8), replies.map { it.first })
assertEquals(2048, G1Smp.replyOffset(replies[0].second))
assertEquals(0, G1Smp.replyCode(replies[1].second))
}
@Test
fun anImageSaysWhatItIs() {
val image = testImage(Triple(0, 5, 300))
assertEquals("0.5.300", G1Smp.imageVersion(image))
assertContentEquals(ByteArray(32) { (it * 3 + 300).toByte() }, G1Smp.imageHash(image))
assertFailsWith<IllegalArgumentException> { G1Smp.imageVersion(ByteArray(100)) }
val cut = image.copyOf(image.size - 20)
assertFailsWith<IllegalArgumentException> { G1Smp.imageHash(cut) }
}
@Test
fun writesFitTheMtu() {
val pieces = G1Smp.split(ByteArray(1000), 247)
assertTrue(pieces.all { it.size <= 244 })
assertEquals(1000, pieces.sumOf { it.size })
}
}
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 })
private fun run(arm: FakeArm, mode: G1ArmFlashFlow.Mode, window: Int = 100): Recorder {
val listener = Recorder()
flow(arm, listener, mode, window).run()
assertNotNull(listener.success, "the flow must always finish")
return listener
}
private fun confirmIsLast(arm: FakeArm) {
assertEquals(listOf("confirm", "reset"), arm.calls.takeLast(2))
assertEquals(1, arm.calls.count { it == "confirm" })
}
@Test
fun anUpdateUploadsChecksThenConfirmsAndResets() {
val arm = FakeArm(image)
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
assertContentEquals(image, arm.uploaded)
assertEquals(image.size.toLong(), result.progress)
assertEquals(image.size.toLong(), result.total)
confirmIsLast(arm)
// The list before the confirm is what proves the slot holds this image.
assertEquals("list", arm.calls[arm.calls.indexOf("confirm") - 1])
assertTrue(arm.heartbeats.isEmpty(), "g1v0 has no heartbeat")
assertTrue("rebooting" in result.states)
}
@Test
fun anArmAlreadyOnThisVersionIsLeftAlone() {
val arm = FakeArm(image)
arm.runningVersion = "0.5.64"
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success)
assertEquals("""{"flashed":false,"version":"0.5.64"}""", result.detail)
assertTrue(arm.calls.isEmpty(), "nothing goes to the update service")
}
@Test
fun anArmInSafeModeOnThisVersionIsInstalledAgain() {
val arm = FakeArm(image)
arm.runningVersion = "0.5.64"
arm.safeMode = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
confirmIsLast(arm)
}
@Test
fun aSlotThatDoesNotHoldTheImageIsNeverConfirmed() {
val arm = FakeArm(image)
arm.corruptAfterUpload = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
assertFalse("reset" in arm.calls)
assertTrue("Nothing was installed" in result.detail, result.detail)
}
@Test
fun aRefusedUploadIsNeverConfirmed() {
val arm = FakeArm(image)
arm.uploadRefusal = 9
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
assertTrue("error 9" in result.detail, result.detail)
}
@Test
fun aRefusedConfirmIsNotAReset() {
val arm = FakeArm(image)
arm.confirmRefusal = 2
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("reset" in arm.calls)
}
@Test
fun aLowBatteryStopsAnUpdateBeforeAnyUpload() {
val arm = FakeArm(image)
arm.battery = 12
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertTrue(arm.calls.isEmpty())
}
@Test
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()
assertEquals(false, listener.success)
assertEquals(0, arm.connects)
}
@Test
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()
assertEquals(false, listener.success)
assertTrue("could not read the firmware" in listener.detail, listener.detail)
}
@Test
fun aLostLinkResumesTheUpload() {
val arm = FakeArm(image)
arm.dropAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertContentEquals(image, arm.uploaded)
assertTrue(arm.connects >= 2, "it connected again")
confirmIsLast(arm)
}
@Test
fun aChunkThatGetsNoAnswerIsSentAgain() {
val arm = FakeArm(image)
arm.silentAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertContentEquals(image, arm.uploaded)
confirmIsLast(arm)
}
@Test
fun anUploadThatNeverGetsAnswersGivesUpWithoutConfirming() {
val arm = FakeArm(image)
arm.silentRequests = 1000
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(false, result.success)
assertFalse("confirm" in arm.calls)
}
@Test
fun aSlotAlreadyHoldingTheImageSkipsTheUpload() {
val arm = FakeArm(image)
arm.slot1Hash = arm.wantHash
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertFalse("upload" in arm.calls)
confirmIsLast(arm)
}
@Test
fun stockGetsAHeartbeatEvenWhileAChunkWaits() {
val arm = FakeArm(image, stock = true)
// A chunk can wait a long time, as the first does while the arm erases its slot: the heartbeat has to keep going.
arm.silentAtOffset = 2048
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(arm.heartbeats.size >= 3, "heartbeats: ${arm.heartbeats.size}")
assertTrue(G1Smp.NUS_TX_UUID in arm.subscribed)
assertEquals(0x25, arm.heartbeats[0][0].toInt())
assertEquals(arm.heartbeats[1][3], 1.toByte())
assertEquals(arm.heartbeats[1][5], 1.toByte())
confirmIsLast(arm)
}
@Test
fun stockIsPairedWithFirst() {
val arm = FakeArm(image, stock = true)
arm.bond = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.bondRequests)
assertTrue("pairing" in result.states)
}
@Test
fun aRefusedBondIsRetriedThenReported() {
val arm = FakeArm(image)
arm.bond = BondState.NONE
arm.bondResult = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
assertEquals(false, result.success)
assertTrue(arm.calls.isEmpty())
assertTrue("Couldn't reach the left arm" in result.detail, result.detail)
}
@Test
fun aPlatformThatCannotSeeBondsReliesOnTheEncryptedWrite() {
val arm = FakeArm(image)
arm.bond = BondState.UNKNOWN
val listener = Recorder()
// The write to PAIR fails on an unknown bond in this fake, as on an arm out of the case: no encrypted link.
flow(arm, listener, G1ArmFlashFlow.Mode.PROBE, 1).run()
assertEquals(false, listener.success)
assertEquals(0, arm.bondRequests)
assertTrue("an arm pairs only in its case" in listener.detail, listener.detail)
}
@Test
fun aStaleBondInTheCaseIsRemovedAndMadeAgain() {
val arm = FakeArm(image)
arm.staleBond = true
arm.inCase = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.removedBonds)
assertEquals(1, arm.bondRequests)
confirmIsLast(arm)
}
@Test
fun aBondIsNeverGivenUpOutOfTheCase() {
val arm = FakeArm(image)
arm.staleBond = true
arm.inCase = false
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
assertEquals(false, result.success)
assertEquals(0, arm.removedBonds, "no new bond can be made out of the case")
}
@Test
fun aStaleBondOnStockIsRemovedAndMadeAgain() {
val arm = FakeArm(image, stock = true)
arm.staleBond = true
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.removedBonds)
assertEquals(1, arm.bondRequests)
}
@Test
fun anOldServiceTableIsReadAgainBeforeItIsBelieved() {
val arm = FakeArm(image)
arm.staleTable = true
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.refreshes)
assertTrue("\"firmware\":\"g1v0\"" in result.detail, result.detail)
}
@Test
fun aLowBatteryOnStockStopsBeforeAnyUpload() {
val arm = FakeArm(image, stock = true)
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 12, 12)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertFalse("upload" in arm.calls)
}
@Test
fun aChargedArmOnStockGoesOn() {
val arm = FakeArm(image, stock = true)
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 100, 100)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(result.logs.any { "battery 100%" in it }, result.logs.toString())
}
@Test
fun aStockArmThatSaysNothingAboutItsBatteryGoesOn() {
val arm = FakeArm(image, stock = true)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(result.logs.any { "battery unknown" in it }, result.logs.toString())
}
@Test
fun aProbeSaysWhatAnArmRuns() {
val arm = FakeArm(image)
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals(true, result.success, result.detail)
assertEquals("""{"firmware":"g1v0","version":"0.5.63","safeMode":false,"inCase":false,"battery":80}""", result.detail)
assertTrue(arm.calls.isEmpty())
}
@Test
fun aProbeOfEvensFirmwareNeedsNoPairing() {
val arm = FakeArm(image, stock = true)
arm.bond = BondState.NONE
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals("""{"firmware":"stock"}""", result.detail)
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)
val listener = Recorder()
val flow = flow(arm, listener, G1ArmFlashFlow.Mode.UPDATE)
arm.onChunk = { flow.cancel() }
flow.run()
assertEquals(false, listener.success)
assertEquals("Cancelled.", listener.detail)
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")))
}
}
File diff suppressed because it is too large. Load diff
@@ -316,6 +316,24 @@ private class Session {
}
class GlassesSessionCoreTest {
@Test fun headUpEnqueueIsG2OnlyAndPreservesPreferencesForOtherModels() {
for (model in listOf(GlassesType.G2, GlassesType.G1, GlassesType.RAYNEO_IO)) {
val s = Session()
try {
s.core.monitor.withLock {
s.core.glassesType = model
s.core.sessionReady = true
s.core.headUpPreferences = 1 to 35
s.core.enqueueHeadUpPreferencesLocked()
val writes = s.core.pendingMessages.filter { it.kind == "head-up-control" }
assertEquals(if (model == GlassesType.G2) 4 else 0, writes.size, "$model")
assertEquals(1 to 35, s.core.headUpPreferences, "keep stored choices for $model")
assertEquals(if (model == GlassesType.G2) 1 to 35 else null, s.core.headUpSent, "$model")
}
} finally { s.core.close() }
}
}
@Test fun headUpWritesOnlyExplicitFieldsToBothArmsAndResendsAfterReconnect() {
val s = Session()
try {
@@ -0,0 +1,167 @@
package com.faceclaw.app
import kotlin.test.*
/** Vectors are bytes captured from a RayNeo iO (Strix OS 1.0.5.12 / 1.0.4.12 + CFW) on 2026-11-01. */
class RayNeoIoProtocolTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private val phoneId = hex("fac582dfa91e")
private val glassesId = hex("006a5e5f33c2")
@Test
fun crcAndFrames() {
assertEquals(0x31c3, RayNeoIoProtocol.crc16Xmodem("123456789".encodeToByteArray()))
val payload = hex("100001")
val frame = RayNeoIoProtocol.encodeFrame(0x1234, RayNeoIoProtocol.BUSINESS_CFW, payload)
assertEquals(13, frame.size)
assertContentEquals(hex("aa55000712340" + "0f0100001"), frame.copyOfRange(0, 11))
val decoded = RayNeoIoProtocol.decodeFrame(frame)!!
assertEquals(0x1234, decoded.messageNumber)
assertEquals(0xf0, decoded.business)
assertContentEquals(payload, decoded.payload)
frame[9] = 9
assertNull(RayNeoIoProtocol.decodeFrame(frame))
}
@Test
fun reassemblerSpansNotificationsAndSkipsJunk() {
val a = RayNeoIoProtocol.encodeFrame(1, 15, ByteArray(300) { it.toByte() })
val b = RayNeoIoProtocol.encodeFrame(2, 0xf0, hex("0195000001070024cf"))
val stream = hex("0102") + a + b
val r = RayNeoIoProtocol.FrameReassembler()
val frames = RayNeoIoProtocol.writes(stream, 23).flatMap { r.ingest(it) }
assertEquals(listOf(1, 2), frames.map { it.messageNumber })
assertEquals(300, frames[0].payload.size)
assertEquals(0, r.pendingBytes)
// a corrupt head is skipped, the next good frame still decodes
val bad = a.copyOf().also { it[20] = (it[20] + 1).toByte() }
assertEquals(listOf(2), r.ingest(bad + b).map { it.messageNumber })
}
@Test
fun handshakeMatchesCapture() {
// the Mac harness's request (iOS platform byte, name "Amoli", model "Mac")
assertContentEquals(
hex("11002810000101110006fac582dfa91e120005416d6f6c69130001011600066950686f6e651700034d6163"),
RayNeoIoProtocol.versionRequest(phoneId, "Amoli", "iPhone", "Mac", RayNeoIoProtocol.PLATFORM_IOS),
)
val reply = RayNeoIoProtocol.parseVersionReply(
hex("11004a10000102110006006a5e5f33c212000e5261794e656f20694f2d323232391300010514000f3030364135453546333343323232391500010518000f303036413545354633334332323239"),
)!!
assertContentEquals(glassesId, reply.glassesId)
assertEquals(2, reply.protocolVersion)
assertEquals("006A5E5F33C2229", reply.serial)
assertFalse(reply.accountBound)
assertContentEquals(
hex("18002a100004875e2013110020efed651a6aacd1834e8023891eaf80ec4a25814db5222e42655b71fdd373ab96"),
RayNeoIoProtocol.guestAuthRequest(hex("875e2013"), phoneId, glassesId),
)
val authReply = hex("19002a1000042316e62111002082289251b37c1ddb76694d5a4bb4e911a79ad8f2867d7379bb8125f36ae6acac")
assertTrue(RayNeoIoProtocol.isGuestAuthReply(authReply))
assertTrue(RayNeoIoProtocol.verifyGuestAuthReply(authReply, phoneId, glassesId))
assertFalse(RayNeoIoProtocol.verifyGuestAuthReply(authReply, hex("fac582dfa91f"), glassesId))
}
@Test
fun envelopes() {
assertContentEquals(
hex("080110011a027b7d"),
RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(RayNeoIoProtocol.OTA_VERSION, "{}")),
)
val status = RayNeoIoProtocol.decodeEnvelope(hex(GENERAL_STATUS))!!
assertEquals(1, status.type)
assertEquals(98, RayNeoIoProtocol.batteryFromLauncherJson(status.json))
assertEquals(100, RayNeoIoProtocol.batteryFromLauncherJson("""{"cmd":"battery_change","payload":{"value":100,"mode":1}}"""))
assertEquals(-1, RayNeoIoProtocol.batteryFromLauncherJson("""{"cmd":"screen_status","payload":{"value":1}}"""))
val request = RayNeoIoProtocol.Envelope(1, RayNeoIoProtocol.GENERAL_STATUS_REQUEST, sequence = 300, mode = RayNeoIoProtocol.MODE_REQUEST)
val back = RayNeoIoProtocol.decodeEnvelope(RayNeoIoProtocol.encodeEnvelope(request))!!
assertEquals(300, back.sequence)
assertEquals(RayNeoIoProtocol.MODE_REQUEST, back.mode)
assertEquals(request.json, back.json)
}
@Test
fun cfwLink() {
assertContentEquals(hex("100001"), RayNeoIoProtocol.controlPacket(RayNeoIoProtocol.CTRL_QUERY))
val record = ByteArray(500) { it.toByte() }
val packets = RayNeoIoProtocol.cfwPackets(record, 0x95, 240)
assertEquals(listOf(0x81, 0x01, 0x41), packets.map { it[0].toInt() and 255 })
assertTrue(packets.all { it[1] == 0x95.toByte() })
assertContentEquals(record, packets.flatMap { it.drop(2) }.toByteArray())
assertEquals(0xc1, RayNeoIoProtocol.cfwPackets(ByteArray(5), 1)[0][0].toInt() and 255)
val ack = RayNeoIoProtocol.parseCfwAck(hex("0195000001070024cf"))!!
assertFalse(ack.nack)
assertEquals(0x95, ack.streamId)
assertEquals(0, ack.messageId)
assertEquals(1, ack.lens)
assertEquals(7, ack.size)
assertEquals(0xcf24, ack.checksum)
assertTrue(RayNeoIoProtocol.parseCfwAck(hex("0395000002070024cf"))!!.nack)
assertNull(RayNeoIoProtocol.parseCfwAck(hex("0195000003070024cf")))
// Glassly v13 IDENT, then the Faceclaw fork's with the revision string appended
val v13 = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d007f474c4153534c594346572d494f2f31330019"))!!
assertEquals(540, v13.width)
assertEquals(220, v13.height)
assertEquals(240, v13.maxChunk)
assertEquals(13, v13.revision)
assertEquals("GLASSLYCFW-IO/13", v13.name)
assertFalse(v13.faceclaw)
val fc = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d00ff474c4153534c594346572d494f2f3133001946616365636c61772f333800"))!!
assertTrue(fc.faceclaw)
assertEquals(38, fc.faceclawRevision)
assertFalse(fc.brightnessControl)
val bright = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d00ff474c4153534c594346572d494f2f3133001946616365636c61772f33380062726967687433302061" + "6c73313600"))!!
assertEquals(listOf("bright30", "als16"), bright.features)
assertEquals(38, bright.faceclawRevision)
assertTrue(bright.brightnessControl)
// a Glassly build with no display lists has no brightness control, whatever else it says
assertFalse(RayNeoIoProtocol.Ident(540, 220, 240, 13, 0x7f, "x", -1, listOf("bright30", "als16")).brightnessControl)
val als = ByteArray(25)
als[0] = 0x1f; als[1] = 65; als[2] = 76; als[3] = 1
assertEquals(24, RayNeoIoProtocol.parseAlsReport(als)!!.size)
assertEquals(65, RayNeoIoProtocol.parseAlsReport(als)!![0].toInt())
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf(24)))
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf().also { it[3] = 2 }))
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf().also { it[0] = 0x15 }))
assertEquals(1, RayNeoIoProtocol.parsePageState(hex("130100")))
val g = RayNeoIoProtocol.parseGesture(hex("0703010a000000"))!!
assertEquals(3, g.eventType)
assertEquals(1, g.source)
assertEquals(10L, g.tick)
}
@Test
fun recordsShareTheG2Encoder() {
// the G2 envelope is unchanged by the record/packet split
val g2 = CfwTransport.frame("123456789abcdef".encodeToByteArray(), 255, 3, 23)
assertContentEquals(hex("aa21ff0c0101f000830b0f0078c331323334862b"), g2[0])
// an iO record carries the same flags/length/CRC header
val t = CfwTransport(testPlatform())
val message = ByteArray(64) { (it % 7).toByte() }
val rec = t.encodeRecord(message, CfwTransport.BOTH)
assertEquals(CfwTransport.BOTH or CfwTransport.COMPRESSED or CfwTransport.RESET_CONTEXT, rec[0].toInt())
assertEquals(CfwTransport.crc(message), (rec[3].toInt() and 255) or ((rec[4].toInt() and 255) shl 8))
assertContentEquals(message, inflateRecords(listOf(rec))[0])
// the next record continues the same compression context
val second = t.encodeRecord(message, CfwTransport.BOTH)
assertEquals(CfwTransport.BOTH or CfwTransport.COMPRESSED, second[0].toInt())
t.close()
}
@Test
fun advertisement() {
assertEquals("00:6A:5E:5F:33:C2", RayNeoIoBle.macFromManufacturerData(hex("07006a5e5f33c2130000000000000001")))
assertNull(RayNeoIoBle.macFromManufacturerData(hex("0800")))
assertTrue(RayNeoIoBle.matchesName("RayNeo iO-2229"))
assertFalse(RayNeoIoBle.matchesName("Even G2_32_L_693CCB"))
}
private companion object {
const val GENERAL_STATUS = "080110011aa6037b2267656e6572616c537461747573223a7b226175746f6d617469634272696768746e657373223a66616c73652c2262617474657279223a39382c22626174745f74656d70223a33342c22626c7565746f6f746841646472657373223a2230303a36413a35453a35463a33333a4332222c226272696768746e657373223a312c226465766963654e616d65223a225261794e656f20694f2d32323239222c2269734368617267696e67223a747275652c2263686172676554797065223a302c2273637265656e537461747573223a312c2268616c6c537461747573223a302c226d6963537461747573223a302c22666f6375734d6f6465223a7b22656e61626c65223a302c22656e61626c65476c617373436c6f7365223a312c22706f6c696379223a7b226175746f223a312c22626567696e223a2230393a3030222c22656e64223a2231383a3030222c227765656b646179223a5b302c312c322c332c342c352c365d7d7d2c22707265736372697074696f6e223a7b22656e61626c65223a312c22646567726565223a222d332c302c2d322e37352c30222c227064223a223633227d7d7d"
}
}
@@ -0,0 +1,608 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private const val IO = "00:6A:5E:5F:33:C2"
private const val RING = "FF:AA:F1:F6:7E:28"
private val PHONE_ID = byteArrayOf(1, 2, 3, 4, 5, 6)
private class IoClock(private val base: ProtocolPlatform) : ProtocolPlatform by base {
@Volatile var offsetMs = 0L
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
}
private fun awaitTrue(timeoutMs: Long, condition: () -> Boolean): Boolean {
val platform = testPlatform()
val deadline = platform.elapsedRealtimeMs() + timeoutMs
while (platform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(10)
}
return condition()
}
/**
* A RayNeo iO running faceclaw-rayneo-cfw, as the phone sees it over GATT: answers the
* handshake, guest auth, launcher status, OS version, QUERY and page controls, reassembles
* and inflates CFW records, and ACKs each lens of every record whose CRC checks out.
*/
private class FakeIoGlasses(platform: ProtocolPlatform) : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = platform.createLock()
val glassesId = byteArrayOf(0x00, 0x6a, 0x5e, 0x5f, 0x33, 0xc2.toByte())
/** The phone id the glasses accept; null = pairing mode (they bind to the next one). */
@Volatile var boundTo: ByteArray? = null
@Volatile var faceclaw = true
/** Firmware with message 30 and the light sensor (IDENT's features string). */
@Volatile var brightnessFirmware = false
@Volatile var pageOpen = false
@Volatile var hangUps = 0
private val controlsList = ArrayList<Int>()
private val messagesList = ArrayList<ByteArray>()
private val launcherList = ArrayList<String>()
val launcher: List<String> get() = lock.withLock { launcherList.toList() }
/** Voice-channel (business 13) messages from the phone: type to JSON. */
private val voiceList = ArrayList<Pair<Int, String>>()
val voice: List<Pair<Int, String>> get() = lock.withLock { voiceList.toList() }
/** A voice-channel message from the glasses. */
fun voiceNotify(type: Int, json: String = "{}", binary: ByteArray? = null) =
notify(13, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(type, json, binary)))
private val records = ArrayList<ByteArray>()
private var current = ByteArray(0)
private val inbound = RayNeoIoProtocol.FrameReassembler()
private var number = 1
val controls: List<Int> get() = lock.withLock { controlsList.toList() }
val messages: List<ByteArray> get() = lock.withLock { messagesList.toList() }
/** Writes to the R1 on [RING] (characteristic, bytes), and the CCCDs the session enabled on it. */
private val ringWritesList = ArrayList<Pair<String, ByteArray>>()
private val ringCccdsList = ArrayList<String>()
val ringWrites: List<Pair<String, ByteArray>> get() = lock.withLock { ringWritesList.toList() }
val ringCccds: List<String> get() = lock.withLock { ringCccdsList.toList() }
/** A notification from the R1, as its link delivers it. */
fun ringNotify(characteristicUuid: String, data: ByteArray) = core.onNotification(RING, characteristicUuid, data)
fun notify(business: Int, payload: ByteArray) {
val frame = lock.withLock { RayNeoIoProtocol.encodeFrame(number++, business, payload) }
core.onNotification(IO, RayNeoIoBle.NOTIFY_CHAR_UUID, frame)
}
fun page(state: Int, reason: Int) = notify(0xf0, byteArrayOf(0x13, state.toByte(), reason.toByte()))
override fun connect(address: String, timeoutMs: Int): Boolean = true
override fun isConnected(address: String): Boolean = true
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 185
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
if (address == RING) {
lock.withLock { ringCccdsList.add(characteristicUuid) }
return true
}
return characteristicUuid == RayNeoIoBle.NOTIFY_CHAR_UUID
}
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (address == RING) {
lock.withLock { for (frame in frames) ringWritesList.add(characteristicUuid to frame) }
return true
}
assertEquals(RayNeoIoBle.WRITE_CHAR_UUID, characteristicUuid)
assertTrue(frames.all { it.size <= 185 - 3 }, "writes must fit the MTU")
val decoded = lock.withLock { frames.flatMap { inbound.ingest(it) } }
for (frame in decoded) handle(frame)
return true
}
private fun handle(frame: RayNeoIoProtocol.Frame) {
val p = frame.payload
when (frame.business) {
0x10 -> {
val tlvs = RayNeoIoProtocol.decodeTlvs(p)!!
val version = tlvs.firstOrNull { it.tag == 0x11 }
val auth = tlvs.firstOrNull { it.tag == 0x18 }
if (version != null) {
val phone = RayNeoIoProtocol.decodeTlvs(version.value)!!.first { it.tag == 0x11 }.value
val bound = boundTo
if (bound != null && !bound.contentEquals(phone)) {
hangUps++
core.onConnectionStateChange(IO, false)
return
}
notify(0x10, RayNeoIoProtocol.tlv(0x11, RayNeoIoProtocol.tlv(0x10, byteArrayOf(2)) +
RayNeoIoProtocol.tlv(0x11, glassesId) + RayNeoIoProtocol.tlv(0x14, "006A5E5F33C2229".encodeToByteArray())))
} else if (auth != null) {
val fields = RayNeoIoProtocol.decodeTlvs(auth.value)!!
val phoneRandom = fields.first { it.tag == 0x10 }.value
val phone = PHONE_ID
assertTrue(RayNeoIoProtocol.authProof(phoneRandom, phone, glassesId).contentEquals(fields.first { it.tag == 0x11 }.value))
boundTo = phone
val random = byteArrayOf(9, 8, 7, 6)
notify(0x10, RayNeoIoProtocol.tlv(0x19, RayNeoIoProtocol.tlv(0x10, random) +
RayNeoIoProtocol.tlv(0x11, RayNeoIoProtocol.authProof(random, phone, glassesId))))
}
}
15 -> {
lock.withLock { launcherList.add(RayNeoIoProtocol.decodeEnvelope(p)!!.json) }
notify(15, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(1,
"""{"generalStatus":{"battery":77,"isCharging":false}}""", sequence = RayNeoIoProtocol.decodeEnvelope(p)!!.sequence, mode = 2)))
}
9 -> notify(9, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(1, """{"OsVersion":"Strix OS 1.0.4.12"}""")))
13 -> {
val envelope = RayNeoIoProtocol.decodeEnvelope(p)!!
lock.withLock { voiceList.add(envelope.type to envelope.json) }
}
0xf0 -> cfw(p)
}
}
private fun cfw(p: ByteArray) {
val opt = p[0].toInt() and 255
val stream = p[1].toInt() and 255
if (opt and RayNeoIoProtocol.OPT_CONTROL != 0) {
val ctrl = p[2].toInt() and 255
lock.withLock { controlsList.add(ctrl) }
when (ctrl) {
RayNeoIoProtocol.CTRL_QUERY -> if (faceclaw) notify(0xf0, ident())
RayNeoIoProtocol.CTRL_PAGE_OPEN, RayNeoIoProtocol.CTRL_KEEPALIVE -> { pageOpen = true; page(1, 0) }
RayNeoIoProtocol.CTRL_PAGE_CLOSE -> { pageOpen = false; page(0, 0) }
}
return
}
val complete = lock.withLock {
if (opt and RayNeoIoProtocol.OPT_RESET != 0) current = ByteArray(0)
current += p.copyOfRange(2, p.size)
val len = if (current.size >= 5) (current[1].toInt() and 255) or ((current[2].toInt() and 255) shl 8) else -1
if (len >= 0 && current.size == 5 + len) current.also { records.add(it); current = ByteArray(0) } else null
} ?: return
val message = lock.withLock { inflateRecords(records).last() }
val crc = (complete[3].toInt() and 255) or ((complete[4].toInt() and 255) shl 8)
val type = message[0].toInt() and 255
val ok = pageOpen && CfwTransport.crc(message) == crc &&
(ioSupportsCfwType(type) || (brightnessFirmware && (type == CFW_MSG_BRIGHTNESS || type == CFW_MSG_AMBIENT_LIGHT)))
if (ok) lock.withLock { messagesList.add(message) }
for (lens in 1..2) {
notify(0xf0, byteArrayOf(if (ok) 1 else 3, stream.toByte(), 0, 0, lens.toByte(),
message.size.toByte(), (message.size ushr 8).toByte(), crc.toByte(), (crc ushr 8).toByte()))
}
}
private fun ident(): ByteArray {
val name = "GLASSLYCFW-IO/13".encodeToByteArray()
return byteArrayOf(0x11, 13, 0x1c, 0x02, 0xdc.toByte(), 0x00, 0xf0.toByte(), 0x00, 0x00, 0x01, 0x0d, 0x00, 0xff.toByte()) +
name + byteArrayOf(0, 25) + "Faceclaw/38".encodeToByteArray() + byteArrayOf(0) +
(if (brightnessFirmware) "bright30 als16".encodeToByteArray() + byteArrayOf(0) else ByteArray(0))
}
/** RPL_ALS as the firmware sends it: a poll of [tenths] of a lux from a healthy sensor. */
fun alsPoll(tenths: Int) {
val report = ByteArray(25)
report[0] = 0x1f
report[1] = 65
report[2] = 76
report[3] = 1
report[4] = 2 // poll
report[5] = 0x0b // opened, passive, read ok
report[6] = 3
for (i in 0..3) report[7 + i] = (tenths ushr (8 * i)).toByte()
notify(0xf0, report)
}
override fun disconnect(address: String) {}
override fun close() {}
override fun isBonded(address: String): Boolean = false
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class IoListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
@Volatile var lastStatus = ""
val events = ArrayList<String>()
val batteries = ArrayList<String>()
val ringBatteries = ArrayList<String>()
val firmware = ArrayList<String>()
override fun onStateChange(phase: String?, status: String?) {
phases.add(phase ?: "")
lastStatus = status ?: ""
}
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {
events.add("$kind:$eventType:$eventSource")
}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
batteries.add("$headsetBattery/$headsetCharging")
if (ringBattery >= 0) ringBatteries.add("$ringBattery/$ringCharging")
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {
firmware.add("$leftVersion|$extension")
}
}
/** An iO session; with [ring], also the phone's own link to an R1 in the glasses role (Direct). */
private class IoSession(ring: String = "") {
val platform = IoClock(testPlatform())
val glasses = FakeIoGlasses(platform)
private val host = object : SessionHost {
private val lock = platform.createLock()
private val lines = ArrayList<String>()
private var done: Latch? = null
fun logs(): List<String> = lock.withLock { lines.toList() }
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {
val latch = Latch(1, platform)
done = latch
startThread("io-test-session", true) {
try {
body()
} finally {
latch.countDown()
}
}
}
override fun joinWorker(timeoutMs: Long) {
done?.await(timeoutMs)
}
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {
lock.withLock { lines.add("$level $tag: $message") }
}
}
val listener = IoListener()
val core = GlassesSessionCore(glasses, host, FrameTimingsCore(platform), platform, IO, IO, ring)
init {
glasses.core = core
core.setListener(listener)
core.setRequiredFirmwareRevision(38)
core.useRayNeoIo(PHONE_ID, "Pixel", "Google", "Pixel 11")
if (ring.isNotEmpty()) core.setDirectRingRole("glasses")
}
fun pageUp(): Boolean = core.monitor.withLock { core.sessionReady && core.fixedLayoutCreated }
fun displayedMatchesDesired(): Boolean = core.monitor.withLock {
core.desiredTilesLock.locked { core.desiredFingerprint.isNotEmpty() && core.desiredFingerprint == core.displayedFingerprint }
}
fun submitFrame(value: Byte, frameId: Int) {
val pixels = ByteArray(64 * 32) { if (it % 7 == 0) value else 0 }
core.submitSurfaceFrame(ArrayByteReader(pixels), "s", 0, 0, 64, 32, "content-$value", 0, frameId, null)
}
fun tail(): String = host.logs().takeLast(25).joinToString("\n")
}
class RayNeoIoSessionTest {
@Test
fun connectsAuthenticatesOpensThePageAndPresentsFrames() {
val s = IoSession()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(540, 220)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page never opened:\n" + s.tail())
assertTrue(s.core.isRayNeoIo())
assertTrue(s.listener.firmware.contains("Strix OS 1.0.4.12|Faceclaw/38"), s.listener.firmware.toString())
assertTrue(awaitTrue(2_000) { s.listener.batteries.contains("77/0") }, s.listener.batteries.toString())
assertEquals(listOf(RayNeoIoProtocol.CTRL_QUERY, RayNeoIoProtocol.CTRL_PAGE_OPEN), s.glasses.controls.take(2))
s.submitFrame(0x7f, 1)
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
val types = s.glasses.messages.map { it[0].toInt() and 255 }
assertTrue(types.contains(CFW_MSG_PRESENT), types.toString())
// nothing G2-only (brightness 30, ENTER_EVENHUB 31, debug flags 7, ...) reaches the iO
assertTrue(types.all { ioSupportsCfwType(it) }, types.toString())
// a visible frame wakes the screen through the launcher's brightness (70% -> level 6)
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { it.contains("brightness_change") && it.contains("\"value\":6") } },
s.glasses.launcher.toString())
// a second, different frame goes out as an update
val before = s.glasses.messages.size
s.submitFrame(0x30, 2)
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() && s.glasses.messages.size > before })
} finally {
s.core.close()
}
// disconnect closes the page so the glasses go back to their own UI at once
assertEquals(RayNeoIoProtocol.CTRL_PAGE_CLOSE, s.glasses.controls.last())
}
@Test
fun firmwareWithBrightnessControlGetsTheG2Messages() {
val s = IoSession()
s.glasses.brightnessFirmware = true
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(540, 220)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
val reportLock = s.platform.createLock()
val reports = ArrayList<ByteArray>()
s.core.addAmbientLightListener(object : FaceclawAmbientLightListener {
override fun onAmbientLight(body: ByteArray?) { reportLock.withLock { reports.add(body!!) } }
})
fun ofType(type: Int) = s.glasses.messages.filter { (it[0].toInt() and 255) == type }
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page never opened:\n" + s.tail())
s.submitFrame(0x7f, 1)
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
// visible at 70%, fading over the configured 280 ms, ahead of the frame it fades in
val wake = byteArrayOf(30, 1, 70, 1, 0x18, 0x01)
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).isNotEmpty() }, s.tail())
assertTrue(ofType(CFW_MSG_BRIGHTNESS).first().contentEquals(wake))
val order = s.glasses.messages.map { it[0].toInt() and 255 }
assertTrue(order.indexOf(CFW_MSG_BRIGHTNESS) < order.indexOf(CFW_MSG_PRESENT), order.toString())
// the launcher's command writes preferences and loses to stock auto: not used
assertTrue(s.glasses.launcher.none { "brightness_change" in it }, s.glasses.launcher.toString())
// the light sensor, at the manual rate; the iO needs telling only once
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).isNotEmpty() }, s.tail())
val poll = ofType(CFW_MSG_AMBIENT_LIGHT).first()
assertEquals(listOf(16, 1), poll.take(2).map { it.toInt() })
assertEquals(5000, (poll[3].toInt() and 255) or ((poll[4].toInt() and 255) shl 8))
// each 5 s the same command, as the screen keepalive
val sent = ofType(CFW_MSG_BRIGHTNESS).size
s.platform.offsetMs += IoTimings.SCREEN_REFRESH_MS + 1
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).size > sent }, s.tail())
assertTrue(ofType(CFW_MSG_BRIGHTNESS).last().let { it[2].toInt() == 70 && it[3].toInt() == 1 })
assertEquals(1, ofType(CFW_MSG_AMBIENT_LIGHT).size)
// Auto: reports reach the policy and listeners, the sample rate follows, a target goes out
s.core.configureBrightness(true, 70, 20, 100, "0:0,100:100", 280)
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size == 2 }, s.tail())
assertEquals(500, ofType(CFW_MSG_AMBIENT_LIGHT).last().let { (it[3].toInt() and 255) or ((it[4].toInt() and 255) shl 8) })
s.glasses.alsPoll(1000) // 100 lux, the curve's top
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).last()[2].toInt() == 100 }, s.tail())
assertTrue(awaitTrue(1_000) { reportLock.withLock { reports.isNotEmpty() } })
assertEquals(65, reportLock.withLock { reports.first()[0].toInt() })
// A request dropped with the queue before it was written goes out again
s.core.monitor.withLock { s.core.clearAllMessagesLocked("test") }
val queued = ofType(CFW_MSG_AMBIENT_LIGHT).size
s.glasses.alsPoll(1000)
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size > queued }, s.tail())
// A reopened page starts over: the firmware gave brightness back when it closed
val before = ofType(CFW_MSG_AMBIENT_LIGHT).size
s.glasses.pageOpen = false
s.glasses.page(0, 3)
assertTrue(awaitTrue(5_000) { s.glasses.pageOpen && s.pageUp() }, s.tail())
s.submitFrame(0x30, 2)
assertTrue(awaitTrue(5_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size > before }, s.tail())
} finally {
s.core.close()
}
}
@Test
fun refusalAsksForPairingModeAndConnectsOnceItIsOn() {
val s = IoSession()
s.glasses.boundTo = byteArrayOf(9, 9, 9, 9, 9, 9)
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.glasses.hangUps >= 1 && s.listener.lastStatus.contains("pairing mode") },
"no pairing-mode prompt:\n" + s.tail())
assertFalse(s.pageUp())
s.glasses.boundTo = null // the wearer held the button
s.platform.offsetMs += 5_000
s.core.interruptibleSleep.interrupt()
assertTrue(awaitTrue(5_000) { s.pageUp() }, "never connected after pairing mode:\n" + s.tail())
assertTrue(s.glasses.boundTo!!.contentEquals(PHONE_ID))
} finally {
s.core.close()
}
}
@Test
fun stockFirmwareIsIncompatible() {
val s = IoSession()
s.glasses.faceclaw = false
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(8_000) { s.listener.phases.contains("incompatible-firmware") }, "not halted:\n" + s.tail())
assertTrue(s.listener.firmware.contains("Strix OS 1.0.4.12|"))
assertFalse(s.glasses.controls.contains(RayNeoIoProtocol.CTRL_PAGE_OPEN))
} finally {
s.core.close()
}
}
@Test
fun gesturesPageLossAndKeepalive() {
val s = IoSession()
s.core.configureCompositorScreen(540, 220)
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
// taps/crown arrive as G2 sys-events from the right temple; head up wakes; head down is dropped
s.glasses.notify(0xf0, byteArrayOf(7, 3, 1, 0, 0, 0, 0))
s.glasses.notify(0xf0, byteArrayOf(7, 1, 0, 0, 0, 0, 0))
s.glasses.notify(0xf0, byteArrayOf(7, 12, 2, 0, 0, 0, 0))
s.glasses.notify(0xf0, byteArrayOf(7, 15, 2, 0, 0, 0, 0))
assertEquals(listOf("sys-event:3:1", "sys-event:1:1", "display-wake:12:1"), s.listener.events)
// the lease ran out on the glasses: the session reopens the page
s.glasses.pageOpen = false
s.glasses.page(0, 3)
assertFalse(s.pageUp())
s.platform.offsetMs += 4_000
s.core.interruptibleSleep.interrupt()
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page not reopened:\n" + s.tail())
// keepalives well inside the 120 s lease
val keepalives = s.glasses.controls.count { it == RayNeoIoProtocol.CTRL_KEEPALIVE }
s.platform.offsetMs += 31_000
s.core.interruptibleSleep.interrupt()
assertTrue(awaitTrue(5_000) { s.glasses.controls.count { it == RayNeoIoProtocol.CTRL_KEEPALIVE } > keepalives })
// the wearer closed it: stay closed until they touch the glasses again
s.glasses.pageOpen = false
s.glasses.page(0, 4)
s.platform.offsetMs += 4_000
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertFalse(s.pageUp())
s.glasses.notify(0xf0, byteArrayOf(7, 0, 1, 0, 0, 0, 0))
s.core.interruptibleSleep.interrupt()
assertTrue(awaitTrue(5_000) { s.pageUp() }, "touch did not reopen:\n" + s.tail())
} finally {
s.core.close()
}
}
@Test
fun anR1BesideTheIoIsTheSessionsOwnRingInput() {
val s = IoSession(RING)
s.core.configureCompositorScreen(540, 220)
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
// The phone takes the ring's glasses role itself: legacy CCCD, the glasses
// pair-auth, then the touch source on, all on the ring's link.
assertTrue(awaitTrue(5_000) { s.glasses.ringWrites.size >= 2 }, "ring setup not sent:\n" + s.tail())
assertTrue(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID in s.glasses.ringCccds)
val (authChar, auth) = s.glasses.ringWrites[0]
assertEquals(BleProtocol.R1_LEGACY_WRITE_CHAR_UUID, authChar)
assertTrue(auth.contentEquals(RingProtocol.LEGACY_GLASSES_PAIR_AUTH))
// Its battery and gestures reach the listener as they do beside a G2,
// not the iO's protocol parser.
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, byteArrayOf(0x00, 0x09, 0x8b.toByte(), 0x00, 64, 1))
assertTrue(awaitTrue(2_000) { "64/1" in s.listener.ringBatteries }, s.listener.ringBatteries.toString())
val swipe = byteArrayOf(0x00, 0x09, 0x61, 0x00, 0x04, 0x35, 0x00, 0x09, 0xcc.toByte(), 0x00, 0x00)
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, swipe)
assertTrue(awaitTrue(2_000) { s.listener.events.isNotEmpty() }, s.tail())
val expected = FaceclawRingEventDecoder.decode(swipe)!!.event
assertEquals("${expected.kind}:${expected.eventType}:${expected.eventSource}", s.listener.events.single())
// The wearer closed the page: a ring gesture takes it back, as a temple touch does.
s.glasses.pageOpen = false
s.glasses.page(0, 4)
s.platform.offsetMs += 4_000
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertFalse(s.pageUp())
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, byteArrayOf(0x00, 0x09, 0x61, 0x00, 0x01, 0x00, 0x00, 0x10, 0xcc.toByte(), 0x00, 0x00))
s.core.interruptibleSleep.interrupt()
assertTrue(awaitTrue(5_000) { s.pageUp() }, "ring input did not reopen:\n" + s.tail())
} finally {
s.core.close()
}
}
@Test
fun theWakeWordAndTheMicStream() {
val s = IoSession()
s.core.configureCompositorScreen(540, 220)
val lock = s.platform.createLock()
val packets = ArrayList<ByteArray>()
val listener = object : FaceclawAudioPacketListener {
override fun onAudioPacket(data: ByteArray?, arm: String?, arrivalMs: Long) {
lock.withLock { packets.add(data!!) }
}
}
val count = { lock.withLock { packets.size } }
fun sent(type: Int, json: String) = s.glasses.voice.count { it == type to json }
val start = """{"rc":1}"""
val stop = """{"rc":2}"""
try {
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
// "Hey RayNeo" goes to Faceclaw: the launcher's switch on, then each wake ends the
// stock session (declined, then aborted) and arrives as the G2's EVEN_AI_WAKE_UP.
s.core.setVoiceWakeEnabled(true)
// The firmware reads the switch from "mode", not "value".
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { "set_ai_voice_wakeup" in it && "\"mode\":1" in it } }, s.tail())
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE, """{"rc":2,"mode":2,"linkType":0}""")
assertTrue(awaitTrue(2_000) { "even-ai:${BleProtocol.EVEN_AI_STATUS_WAKE_UP}:0" in s.listener.events }, s.listener.events.toString())
// The same phrase's second-stage wake is not a second wake.
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE, """{"rc":2,"mode":3,"linkType":0}""")
sleepMs(200)
assertEquals(1, s.listener.events.count { it.startsWith("even-ai:") })
assertTrue(awaitTrue(2_000) {
sent(RayNeoIoProtocol.VOICE_RC, stop) >= 1 && sent(RayNeoIoProtocol.VOICE_ABORT, start) >= 1
}, s.glasses.voice.toString())
// The mic: capture opens the remote stream, its Opus packets go to the listener as
// they came, and stopping closes it.
assertTrue(s.core.startG2AudioCapture(listener))
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, start) == 1 }, s.tail())
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_STREAM_AUDIO, binary = byteArrayOf(0x78, 1, 2, 3))
assertTrue(awaitTrue(2_000) { count() == 1 })
assertTrue(lock.withLock { packets[0] }.contentEquals(byteArrayOf(0x78, 1, 2, 3)))
assertTrue(s.core.isAudioCaptureActive())
// A voice session that took the recorder ended: the stream is asked for again.
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_EXITED)
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, start) == 2 }, s.tail())
s.core.stopG2AudioCapture()
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, stop) == 1 }, s.tail())
assertFalse(s.core.isAudioCaptureActive())
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_STREAM_AUDIO, binary = byteArrayOf(9))
sleepMs(200)
assertEquals(1, count())
// With the wake action off: the switch follows, and a wake is ended but not reported.
s.core.setVoiceWakeEnabled(false)
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { "set_ai_voice_wakeup" in it && "\"mode\":0" in it } }, s.tail())
val events = s.listener.events.size
val aborts = sent(RayNeoIoProtocol.VOICE_ABORT, start)
s.platform.offsetMs += 5_000
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE)
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_ABORT, start) > aborts }, s.glasses.voice.toString())
assertEquals(events, s.listener.events.size)
} finally {
s.core.close()
}
}
}
+29
View File
@@ -0,0 +1,29 @@
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');
// lock-screen.ts on a screen of the given size; the text is not drawn.
function lockScreen(width, height) {
const font = { lineHeight: 20, measureText: (text) => text.length * 10, drawText() {} };
const load = loader({}, {
'../graphics/image': graphics,
'../graphics/screen-size': { screenWidth: () => width, screenHeight: () => height },
'../graphics/ui-fonts': { getDefaultMediumFont: () => font },
'../graphics/textwrap': { wrapText: (_font, text) => [text] },
});
return load('app/g2/lock-screen.ts').createLockScreenImage();
}
// The lock surface is the screen's size, so its frame must be too.
test('the lock screen fills the paired glasses\' screen, its box centred on it', () => {
for (const [width, height] of [[640, 480], [540, 220]]) {
const image = lockScreen(width, height);
assert.deepEqual([image.width, image.height], [width, height]);
const lit = [];
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) if (image.pixels[y * width + x]) lit.push([x, y]);
const xs = lit.map(([x]) => x), ys = lit.map(([, y]) => y);
const box = [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
assert.deepEqual(box, [(width - 480) / 2, (height - 150) / 2, (width + 480) / 2 - 1, (height + 150) / 2 - 1], `${width}x${height}`);
}
});
+35
View File
@@ -0,0 +1,35 @@
// EvenHub text-container wrapping (app/graphics/lvgl-wrap.ts), against what
// stock firmware 2.2.9.22 drew in the g2-firmware-emulator: spaces are kept
// everywhere, including ones that overflow onto a soft-wrapped line.
const test = require("node:test");
const assert = require("node:assert/strict");
const { wrapLvglText } = require("../.test-build/app/graphics/lvgl-wrap.js");
// The stock 20px font's advances for these: H 12px, E 11px, space 5px.
const ADVANCES = { H: 12, E: 11, " ": 5 };
const advance = (cp) => ADVANCES[String.fromCodePoint(cp)] ?? 10;
test("indentation after a newline and at the start is kept (Iris Pro's icon-clearing indent)", () => {
assert.deepEqual(wrapLvglText(" \n R E C O R D", 248, advance), [" ", " R E C O R D"]);
assert.deepEqual(wrapLvglText("AB\n CD", 248, advance), ["AB", " CD"]);
assert.deepEqual(wrapLvglText(" EF", 248, advance), [" EF"]);
});
test("spaces that overflow a line start the next one (emulator Q3)", () => {
const text = "HHHHHHHH EEEE";
assert.deepEqual(wrapLvglText(text, 100, advance), ["HHHHHHHH", " EEEE"]);
assert.deepEqual(wrapLvglText(text, 110, advance), ["HHHHHHHH ", " EEEE"]);
assert.deepEqual(wrapLvglText(text, 120, advance), ["HHHHHHHH ", "EEEE"]);
});
test("a word that overflows wraps after the last space or hyphen", () => {
assert.deepEqual(wrapLvglText("HH EEEEEEEE", 100, advance), ["HH ", "EEEEEEEE"]);
assert.deepEqual(wrapLvglText("HH-EEEEEEEE", 100, advance), ["HH-", "EEEEEEEE"]);
});
test("a run with no break opportunity breaks before the overflowing character", () => {
assert.deepEqual(wrapLvglText("HHHHHHHHHH", 50, advance), ["HHHH", "HHHH", "HH"]);
// A character wider than the line still gets one to itself.
assert.deepEqual(wrapLvglText("HH", 5, advance), ["H", "H"]);
});
+26 -4
View File
@@ -18,7 +18,7 @@ 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'),
});
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 },
'./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 },
'../graphics/image':graphics,'../graphics/textwrap':{wrapText:(_font,text)=>text.split('\n')},'../graphics/ui-fonts':{getDefaultSmallFont:()=>font},
'../util/numeric-util':{clamp:(n,a,b)=>Math.max(a,Math.min(b,n))},'./gestures':{},
'./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'),
@@ -50,7 +50,7 @@ test('later opaque planes add an occlusion to a replayed selection',()=>{
});
const {LayerStack,noopLayerActions}=load('app/ui/layers.ts',{
'../graphics/image':graphics,'../graphics/plane':planes,'../native/frame-timings':{spanCurrent:(_name,fn)=>fn()},'./gestures':{},
'../graphics/image':graphics,'../graphics/plane':planes,'../native/frame-timings':{spanCurrent:(_name,fn)=>fn()},'../graphics/screen-size':{screenWidth:()=>640,screenHeight:()=>480},'./gestures':{},
});
test('context menu surface and selected row both use +4 without changing the app screen',()=>{
const base=new graphics.GrayImage(100,90,96);
@@ -104,7 +104,7 @@ test('unselected sidebar icons retain -2 depth through shell cropping, including
'../../native/notification-icons':{},'../../native/notification-types':require('../.test-build/app/native/notification-types.js'),'../../native/phone-battery':{},'../../util/render-freshness':{},
'../../graphics/icons':{},'../dashboard-settings':{},'../clock-format':{},'../../graphics/bdffont':{},
'../layers':{LayerStack},'../menu':{scrollToKeepSelectionVisible:()=>0},'../metrics':{},
'./geometry':{MIN_WINDOW_HEIGHT:280,minWindowTop:()=>0,windowTop:()=>0,SHELL_OPAQUE_BLACK:1,SIDEBAR_WIDTH:64,TOP_BAR_HEIGHT:24,
'./geometry':{MIN_WINDOW_HEIGHT:280,minWindowHeight:()=>280,screenWidth:()=>640,screenHeight:()=>480,minWindowTop:()=>0,windowTop:()=>0,SHELL_OPAQUE_BLACK:1,SIDEBAR_WIDTH:64,TOP_BAR_HEIGHT:24,
SWITCHER_ROW_HEIGHT:36,switcherPosition:()=>'left',switcherRect:()=>({x:0,y:0,width:64,height:280})},
});
const state={selectedIndex:0,focus:'sidebar',windows:[0,1,2].map(n=>({attention:n===1,drawIcon:(image,x,y)=>image.fillRect(x,y,4,4,240)}))};
@@ -122,7 +122,7 @@ 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/plane':planes,'../native/frame-timings':{spanCurrent:(_name,fn)=>fn()},
'../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},
@@ -141,3 +141,25 @@ test('shell crop widens a fractional rect (TTF-measured status bar) to whole pix
assert.deepEqual([crop.x,crop.y,crop.image.width,crop.image.height],[400,250,176,15]);
assert.ok(crop.image.pixels.every(v=>v===7));
});
test('a stack without its own size follows the screen when the glasses type changes',()=>{
// The shell's stack is built once per process; re-pairing a G2 after a
// RayNeo iO must not leave its overlays painting on a 540x220 canvas.
const screen={width:540,height:220};
const {LayerStack}=load('app/ui/layers.ts',{
'../graphics/image':graphics,'../graphics/plane':planes,'../native/frame-timings':{spanCurrent:(_name,fn)=>fn()},
'../graphics/screen-size':{screenWidth:()=>screen.width,screenHeight:()=>screen.height},'./gestures':{},
});
const stack=new LayerStack({paint:()=>new graphics.GrayImage(screen.width,screen.height,0)},noopLayerActions);
stack.push({paint:(_ctx,below)=>below(),handleInput:async()=>{}});
// JSON: the stack's arrays and objects come from the vm's realm.
const sizes=()=>JSON.parse(JSON.stringify(stack.paint().map(p=>[p.image.width,p.image.height])));
assert.deepEqual(sizes(),[[540,220],[540,220]]);
screen.width=640;screen.height=480;
assert.deepEqual({...stack.getBaseSize()},{width:640,height:480});
assert.deepEqual(sizes(),[[640,480],[640,480]]);
// An explicit size (a window's viewport, the modal's interior) stays put.
const sized=new LayerStack({paint:()=>new graphics.GrayImage(100,90,0)},noopLayerActions,{width:100,height:90});
screen.width=540;screen.height=220;
assert.deepEqual({...sized.getBaseSize()},{width:100,height:90});
});
+1 -1
View File
@@ -161,7 +161,7 @@ test('Music settings keeps toggles and selection when a new app arrives and supp
'../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'),
'./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 },
'./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 },
};
deps['./menu-core'] = load('app/ui/menu-core.ts', (name) => deps[name]);
const menu = load('app/ui/menu.ts', (name) => deps[name]);
+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")
+19 -3
View File
@@ -125,14 +125,14 @@ test('overflow warning backgrounds cover graph pixels and deferred graph labels'
assert.equal(baked.getPixel(200, 8), 56, 'uncovered graph remains visible');
});
function fixture(always = false) {
function fixture(always = false, GrayImage = Image, uiFont = font) {
let time = now, icon, tick, changed, notify, renders = 0;
const state = { ...healthy, available: true, latest: { sgv: 100, timestampMs: now }, history: [], units: 'mg/dL', delta: 0, direction: '', iob: 1, cob: 0, pumpStatus: '0m ago', configurationMissing: false };
const bridge = { snapshot: () => state, onStateChange(fn) { notify = fn; fn(state); } };
const settings = { loadNightscoutThresholds: () => limits, nightscoutAlwaysShowInTopBarSetting: { get: () => always }, onAnySettingChanged(fn) { changed = fn; }, isNightscoutSettingsConfigured: () => true };
const deps = {
'../../graphics/image': { GrayImage: Image },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultLargeFont: () => font },
'../../graphics/image': { GrayImage },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => uiFont, getDefaultLargeFont: () => uiFont },
'../../native/nightscout-bridge': { nightscoutBridge: bridge },
'../../ui/dashboard-settings': settings,
'./nightscout-alerts': alerts,
@@ -181,6 +181,22 @@ test('tray is hidden by default and clears recovered measurement warnings immedi
second.close(); assert.equal(f.icon(), null);
});
test('tray keeps every pixel row when a TTF font measures the reading fractionally', () => {
const { GrayImage } = require('../.test-build/app/graphics/image.js');
// 8.875 is Roboto-Light 16's digit advance under iOS Core Text.
const f = fixture(true, GrayImage, { ...font, measureText: text => text.length * 8.875, drawText() {} });
f.state.latest = { sgv: 142, timestampMs: now };
// Spans the graph's full 60..200 range, so its line crosses every row.
f.state.history = [{ timestampMs: now - 10 * 60_000, sgv: 200 }, { timestampMs: now, sgv: 60 }];
f.app.startNightscoutTrayIcon();
const icon = f.icon();
assert.ok(Number.isInteger(icon.width), `width ${icon.width}`);
for (let y = 0; y < icon.height; y++) {
const row = Array.from({ length: icon.width }, (_, x) => icon.getPixel(x, y));
assert.ok(row.some(value => value !== 0), `row ${y} of the graph is drawn`);
}
});
test('main page highlights only the breached field and removes highlights on recovery', () => {
const f = fixture();
const page = load('app/apps/nightscout/nightscout.ts', {
+53 -3
View File
@@ -23,6 +23,42 @@ function store(settings = new Map()) {
}
const mail = { packageName: 'com.mail', appName: 'Mail' };
/** dashboard-settings.ts over the same in-memory store, with `prefs` as its notification-sources. */
function dashboardSettings(settings, prefs) {
return evaluate(source('app/ui/dashboard-settings.ts'), (id) => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => settings.set(key, value),
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback, setBooleanSetting: (key, value) => settings.set(key, value),
};
if (id.includes('notification-sources')) return prefs;
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
if (id.includes('animation-speed')) return require('../.test-build/app/ui/animation-speed.js');
if (id.includes('transcription-language')) return load('app/native/transcription-language.ts');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
}, { global: { isIOS: false } });
}
test('"Display new notifications" defaults to 15s; Off stops every popup, the filter still mutes single apps', () => {
const settings = new Map();
const prefs = store(settings);
const api = dashboardSettings(settings, prefs);
assert.equal(api.newNotificationDisplaySetting.get(), '15s');
// Array.from: the module's arrays come from its own VM realm.
const values = Array.from(api.newNotificationDisplaySetting.values);
assert.deepEqual(values.map((value) => api.newNotificationDisplaySetting.displayValue(value)),
['Off', 'Until dismissed', '5s', '15s', '1min']);
assert.deepEqual(values.map(api.newNotificationDisplayTimeoutMs), [null, null, 5_000, 15_000, 60_000]);
assert.equal(api.shouldPopUpNewNotification(mail.packageName), true);
prefs.setNotificationSourceEnabled(mail, false);
assert.equal(api.shouldPopUpNewNotification(mail.packageName), false);
assert.equal(api.shouldPopUpNewNotification('com.other'), true);
api.newNotificationDisplaySetting.set('off');
assert.equal(api.shouldPopUpNewNotification('com.other'), false);
api.newNotificationDisplaySetting.set('until-dismissed');
assert.equal(api.shouldPopUpNewNotification('com.other'), true);
});
test('sources default on and retain per-package choices and names across restart and rediscovery', () => {
const settings = new Map();
let prefs = store(settings);
@@ -88,7 +124,7 @@ function ui(fontSize = 12) {
'../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'),
'./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 },
'./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': {},
};
const requireModule = (name) => {
@@ -258,14 +294,16 @@ test('controller filters before waking or opening a popup, and still refreshes t
const members = ['handleAndroidNotificationPosted', 'handleAndroidNotificationRemoved', 'popUpAndroidNotification']
.map((name) => controller.members.find((node) => node.name?.getText(file) === name).getText(file));
const { NotificationPopupDelay, notificationPopupDelayMs } = require('../.test-build/app/ui/shell/notification-popup-delay.js');
const prefs = store();
const settings = new Map();
const prefs = store(settings);
const { newNotificationDisplaySetting, shouldPopUpNewNotification } = dashboardSettings(settings, prefs);
let active = [{ ...mail, key: 'key' }];
let wakes = 0, popups = 0, renders = 0;
const removed = [];
const { Harness } = evaluate(`export class Harness { ${members.join('\n')} }`, null, {
ALL_NOTIFICATIONS: 0x7fffffff,
readActiveNotifications: () => active,
shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
shouldPopUpNewNotification,
notificationPopupDelayMs,
shell: {
isScreenOn: () => false,
@@ -317,6 +355,18 @@ test('controller filters before waking or opening a popup, and still refreshes t
prefs.setNotificationSourceEnabled(mail, false);
elapse();
assert.equal(popups, 1);
// "Display new notifications: Off" holds back every app's popup, also once the delay is over.
prefs.setNotificationSourceEnabled(mail, true);
newNotificationDisplaySetting.set('off');
instance.handleAndroidNotificationPosted('key');
elapse();
newNotificationDisplaySetting.set('15s');
instance.handleAndroidNotificationPosted('key');
newNotificationDisplaySetting.set('off');
elapse();
assert.equal(wakes, 1);
assert.equal(popups, 1);
});
test('Android display filters before limits and reapplies preferences to cached tray icons', () => {
+94
View File
@@ -0,0 +1,94 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { NotificationPopupTimeout } = require("../.test-build/app/ui/shell/notification-popup-timeout.js");
/** A manual clock: schedule() queues timers that advance() fires when due. */
function makeClock() {
const clock = {
nowMs: 0,
timers: [],
schedule(run, delayMs) {
const timer = { dueAtMs: clock.nowMs + delayMs, run, cancelled: false };
clock.timers.push(timer);
return () => { timer.cancelled = true; };
},
advance(ms) {
const until = clock.nowMs + ms;
for (;;) {
const due = clock.timers.filter((timer) => !timer.cancelled && timer.dueAtMs <= until)
.sort((a, b) => a.dueAtMs - b.dueAtMs)[0];
if (!due) break;
clock.nowMs = due.dueAtMs;
due.cancelled = true;
due.run();
}
clock.nowMs = until;
},
};
return clock;
}
function makeTimeout(timeoutMs) {
const clock = makeClock();
let expiries = 0;
const timeout = new NotificationPopupTimeout(timeoutMs, () => { expiries++; }, clock.schedule);
return { clock, timeout, expiries: () => expiries };
}
test("an untouched popup expires once its timeout passes", () => {
const { clock, timeout, expiries } = makeTimeout(15_000);
timeout.restart();
clock.advance(14_999);
assert.equal(expiries(), 0);
clock.advance(1);
assert.equal(expiries(), 1);
assert.equal(timeout.isRunning(), false);
clock.advance(60_000);
assert.equal(expiries(), 1);
});
test("each interaction starts the countdown over", () => {
const { clock, timeout, expiries } = makeTimeout(5_000);
timeout.restart();
clock.advance(4_000);
timeout.restart(); // e.g. scrolling the action menu
clock.advance(4_000);
assert.equal(expiries(), 0);
clock.advance(1_000);
assert.equal(expiries(), 1);
});
test("a popup that goes away first never expires", () => {
const { clock, timeout, expiries } = makeTimeout(5_000);
timeout.restart();
clock.advance(2_000);
timeout.stop();
clock.advance(10_000);
assert.equal(expiries(), 0);
});
test("until-dismissed (no timeout) never schedules anything", () => {
const { clock, timeout, expiries } = makeTimeout(null);
timeout.restart();
assert.equal(timeout.isRunning(), false);
assert.equal(clock.timers.length, 0);
clock.advance(1_000_000);
assert.equal(expiries(), 0);
});
test("the expiry callback can restart the countdown (something was over the popup)", () => {
const clock = makeClock();
let expiries = 0;
const timeout = new NotificationPopupTimeout(5_000, () => {
expiries++;
if (expiries === 1) timeout.restart();
}, clock.schedule);
timeout.restart();
clock.advance(5_000);
assert.equal(expiries, 1);
assert.equal(timeout.isRunning(), true);
clock.advance(5_000);
assert.equal(expiries, 2);
assert.equal(timeout.isRunning(), false);
});
+235
View File
@@ -0,0 +1,235 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
function load(file, modules, globals) {
const context = { exports: {}, require: name => {
if (!(name in modules)) throw new Error(`Missing mock: ${name} in ${file}`);
return modules[name];
}, setInterval, clearInterval, Date, ...globals };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
function fixture({ glasses = 'g2', ios = false, completed = false, ring = false, watch = false, previewOnly = false } = {}) {
const state = { glasses, ring, watch, navigations: [], backs: 0, previewOnly, completed };
const frame = { navigate: entry => state.navigations.push(entry), goBack: () => { state.backs++; }, canGoBack: () => true, backStack: [] };
class Observable { notifyPropertyChange() {} }
const core = {
Observable, Frame: { topmost: () => frame }, Screen: { mainScreen: { heightDIPs: 800, widthDIPs: 400 } },
Application: { on() {}, off() {}, suspendEvent: 'suspend', resumeEvent: 'resume' },
};
const onboardingState = {
hasCompletedOnboarding: () => state.completed,
setOnboardingCompleted: value => { state.completed = value; },
isPreviewOnlyMode: () => state.previewOnly, setPreviewOnlyMode: value => { state.previewOnly = value; },
ownsRing: () => state.ring, setOwnsRing: value => { state.ring = value; },
ownsWatch: () => state.watch, setOwnsWatch: value => { state.watch = value; },
};
const settings = { glassesTypeSetting: { get: () => state.glasses, set: value => { state.glasses = value; } } };
const globals = { global: { isIOS: ios, isAndroid: !ios } };
const modules = {
'@nativescript/core': core, './onboarding-state': onboardingState, '../ui/dashboard-settings': settings,
'./onboarding-navigation': { finishOnboardingNavigation: () => state.navigations.push('finish') },
'../g1/even-firmware': { EVEN_G1_RESTORE: { version: '1.6.6' } },
'../native/even-app-conflict': { openEvenAppSettings() {} },
'../native/ble-permissions': { ensureBlePermissions: async () => {} },
'../g2/device-addresses': {
loadDeviceAddresses: () => ({ right: '', left: '', ring: '' }), loadPairedGlassesIdentity: () => null,
saveDeviceAddresses() {}, savePairedGlassesIdentity() {},
},
'../util/format-error': { formatErrorMessage: String },
'../g2/pairing-candidates': {
DiscoveryAggregator: class { prune() {} pairs() { return []; } rings() { return []; } rayneos() { return []; } clear() {} },
DEFAULT_STALE_AFTER_MS: 1, nearestCandidateId: () => null,
},
'../native/device-discovery': { DeviceDiscoveryBridge: class {} },
};
// Permission checks: everything granted.
const granted = new Proxy({}, { get: () => () => true });
for (const name of ['../native/ios-bluetooth', '../g2/android-permissions', '../native/calendar-permissions', '../native/battery-optimization',
'../native/file-access', '../native/notification-access']) modules[name] = granted;
modules['../native/media-controller'] = { mediaControllerBridge: { hasAccess: () => true } };
const loadPage = file => load(`app/phone-ui/${file}.ts`, modules, globals);
return { state, loadPage };
}
const rowFor = (model, choice) => model.glassesOptions.find(option => option.choice === choice);
const selected = model => model.glassesOptions.filter(option => option.checkVisibility === 'visible').map(option => option.choice).join();
const tap = (model, type) => model.onGlassesRowTap({ object: { bindingContext: rowFor(model, type) } });
test('the devices page sits between the splash and the disclaimer', () => {
const { state, loadPage } = fixture();
const { OnboardingViewModel } = loadPage('onboarding-view-model');
new OnboardingViewModel().onPrimaryTap();
assert.equal(state.navigations.pop().moduleName, 'phone-ui/onboarding-devices-page');
const { OnboardingDevicesViewModel } = loadPage('onboarding-devices-view-model');
const devices = new OnboardingDevicesViewModel();
tap(devices, 'g2');
devices.onNextTap();
const next = state.navigations.pop();
assert.equal(next.moduleName, 'phone-ui/onboarding-page');
assert.equal(next.context.step, 2);
const disclaimer = new OnboardingViewModel(next.context.step);
assert.equal(disclaimer.headline, 'Before You Continue');
// Backing out of the disclaimer lands on the devices page, not the splash.
disclaimer.onSecondaryTap();
assert.equal(state.backs, 1);
assert.equal(state.navigations.length, 0);
});
test('iOS registers the devices page, which it cannot resolve otherwise', () => {
const source = fs.readFileSync('app/phone-ui/onboarding-register.ios.ts', 'utf8');
assert.match(source, /registerModule\('phone-ui\/onboarding-devices-page', /);
assert.match(source, /registerModule\('phone-ui\/onboarding-devices-page\.xml', /);
});
test('choosing glasses selects exactly one, and the accessories are stored', () => {
const { state, loadPage } = fixture();
const { OnboardingDevicesViewModel } = loadPage('onboarding-devices-view-model');
const model = new OnboardingDevicesViewModel();
assert.equal(model.glassesOptions.map(option => option.choice).join(), 'preview,g1,g2');
// Nothing is chosen until you choose, even with a stored glasses type, and Next waits for it.
assert.equal(selected(model), '');
assert.equal(model.nextEnabled, false);
model.onNextTap();
assert.equal(state.navigations.length, 0);
tap(model, 'g1');
assert.equal(state.glasses, 'g1');
assert.equal(selected(model), 'g1');
assert.equal(model.nextEnabled, true);
assert.equal(model.hasRing, false);
model.hasRing = true;
model.hasWatch = true;
assert.equal(state.ring, true);
assert.equal(state.watch, true);
assert.equal(new OnboardingDevicesViewModel().hasRing, true);
});
test('the watch follows the platform, and unreleased RayNeo iO is hidden on both platforms', () => {
const android = fixture();
const onAndroid = new (android.loadPage('onboarding-devices-view-model').OnboardingDevicesViewModel)();
assert.equal(onAndroid.watchLabel, 'Wear OS watch');
assert.equal(rowFor(onAndroid, 'rayneo-io'), undefined);
const ios = fixture({ ios: true });
const onIos = new (ios.loadPage('onboarding-devices-view-model').OnboardingDevicesViewModel)();
assert.equal(onIos.watchLabel, 'Apple Watch');
assert.equal(rowFor(onIos, 'rayneo-io'), undefined);
assert.equal(ios.state.glasses, 'g2');
assert.equal(selected(onIos), '');
assert.equal(onIos.nextEnabled, false);
});
test('the disclaimer and firmware steps name only the chosen glasses', () => {
const copy = glasses => {
const { OnboardingViewModel } = fixture({ glasses }).loadPage('onboarding-view-model');
return { disclaimer: new OnboardingViewModel(2), firmware: new OnboardingViewModel(3) };
};
const g2 = copy('g2'), g1 = copy('g1'), io = copy('rayneo-io');
assert.match(g2.disclaimer.body, /for the Even Realities G2 smart glasses/);
assert.doesNotMatch(g2.disclaimer.body, /G1|RayNeo/);
assert.match(g1.disclaimer.body, /for the Even Realities G1 smart glasses/);
assert.match(io.disclaimer.body, /for the RayNeo iO smart glasses\. It is not created or supported by RayNeo\./);
assert.doesNotMatch(io.disclaimer.body, /Even/);
assert.match(g2.firmware.body, /reconnecting the official Even Realities app/);
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');
// The app has no flasher for an iO.
assert.equal(io.firmware.primaryLabel, 'Pair Glasses');
assert.doesNotMatch(io.firmware.body, /Flash Firmware|Even/);
// Preview Only moved to Your Devices: the firmware step only goes forward or back.
for (const { firmware } of [g2, g1, io]) {
assert.equal(firmware.secondaryLabel, 'Back');
assert.doesNotMatch(firmware.body, /two choices/);
assert.match(firmware.body, /Go back to Your Devices and choose Preview Only/);
}
});
test('Preview Only is a glasses choice that skips the firmware step', () => {
const { state, loadPage } = fixture({ glasses: 'rayneo-io' });
const { OnboardingDevicesViewModel } = loadPage('onboarding-devices-view-model');
const devices = new OnboardingDevicesViewModel();
assert.equal(rowFor(devices, 'preview').noteVisibility, 'visible');
tap(devices, 'preview');
assert.equal(state.previewOnly, true);
assert.equal(state.glasses, 'rayneo-io');
assert.equal(selected(devices), 'preview');
assert.equal(devices.nextEnabled, true);
// A later visit (say, after restarting mid-setup) asks again.
assert.equal(selected(new OnboardingDevicesViewModel()), '');
// The disclaimer can't name glasses nobody chose.
const { OnboardingViewModel } = loadPage('onboarding-view-model');
assert.match(new OnboardingViewModel(2).body, /for the Even Realities G1 and G2 and RayNeo iO smart glasses\. It is not created or supported by Even Realities or RayNeo\./);
// Permissions is the last page: onboarding completes there, in preview mode.
const { PermissionsViewModel } = loadPage('permissions-view-model');
return new PermissionsViewModel({ onboarding: true }).onPrimaryTap().then(async () => {
assert.equal(state.completed, true);
assert.deepEqual(state.navigations, ['finish']);
// Choosing glasses again turns preview off, and Permissions leads to the firmware step.
state.completed = false;
state.navigations.length = 0;
tap(devices, 'g1');
assert.equal(state.previewOnly, false);
assert.equal(state.glasses, 'g1');
await new PermissionsViewModel({ onboarding: true }).onPrimaryTap();
assert.equal(state.completed, false);
assert.equal(state.navigations[0].moduleName, 'phone-ui/onboarding-page');
assert.equal(state.navigations[0].context.step, 3);
// And that step's Back returns to Permissions.
new OnboardingViewModel(3).onSecondaryTap();
assert.equal(state.backs, 1);
});
});
test('the disconnect page drops the Even app instructions only when setting up an iO', () => {
const page = options => new (fixture(options).loadPage('onboarding-unpair-view-model').OnboardingUnpairViewModel)();
const setup = page({ glasses: 'rayneo-io' });
assert.equal(setup.evenAppVisibility, 'collapse');
assert.equal(setup.settingsButtonVisibility, 'collapse');
assert.doesNotMatch(setup.otherAppsInstructions, /Even/);
for (const options of [{ glasses: 'g2' }, { glasses: 'rayneo-io', completed: true }]) {
const model = page(options);
assert.equal(model.evenAppVisibility, 'visible');
assert.equal(model.settingsButtonVisibility, 'visible');
assert.match(model.otherAppsInstructions, /Even Realities/);
}
});
test('pairing during setup follows the choices; from the menu it offers everything', () => {
const page = (options, onboarding = true) => new (fixture(options).loadPage('pairing-view-model').PairingViewModel)({ onboarding });
const g1 = page({ glasses: 'g1' });
assert.match(g1.instructions, /^Select your G1 glasses below\. Put the glasses in their case with the lid open/);
assert.equal(g1.ringSectionVisibility, 'collapse');
const io = page({ glasses: 'rayneo-io', ring: true });
assert.match(io.instructions, /^Select your RayNeo iO and your R1 ring below\. Wear the glasses/);
assert.equal(io.ringSectionVisibility, 'visible');
// Past setup, "Pair glasses" re-enters with onboarding set, including for an
// install from before the devices page existed (nothing stored: no ring).
for (const model of [page({ glasses: 'g2', completed: true }), page({ glasses: 'g2' }, false)]) {
assert.match(model.instructions, /G2 or G1 glasses or RayNeo iO, and your R1 ring if you have one/);
assert.equal(model.ringSectionVisibility, 'visible');
}
});
+54 -6
View File
@@ -11,19 +11,22 @@ function setting(value, values) {
writes: [], displayValue: (v) => v[0].toUpperCase() + v.slice(1) };
}
function harness() {
// The onboarding pages over G2 glasses (640x480), or a RayNeo iO's 540x220 screen.
function harness(glasses = 'g2') {
const screen = glasses === 'rayneo-io' ? { width: 540, height: 220 } : { width: 640, height: 480 };
const settings = {
glassesTypeSetting: setting(glasses, ['g2', 'rayneo-io']),
appSwitcherPositionSetting: setting('bottom', ['left', 'right', 'bottom', 'popup']),
statusBarPositionSetting: setting('bottom', ['top', 'bottom']),
uiDepthSetting: setting('48', ['-62', '-48', '-32', '-16', '0', '16', '32', '48', '62']),
};
const load = loader({}, {
'./onboarding-fonts': { onboardingFont: font },
'../../graphics/image': { G2_LENS_WIDTH: 640 },
'../../ui/dashboard-settings': settings,
'../../ui/shell/geometry': { MIN_WINDOW_HEIGHT: 288, SIDEBAR_WIDTH: 64, SWITCHER_ROW_HEIGHT: 36, TOP_BAR_HEIGHT: 28 },
'../../ui/shell/geometry': { MIN_WINDOW_HEIGHT: 288, SIDEBAR_WIDTH: 64, SWITCHER_ROW_HEIGHT: 36, TOP_BAR_HEIGHT: 28,
screenWidth: () => screen.width, screenHeight: () => screen.height },
});
return { settings, load };
return { settings, screen, load };
}
/** An image that records what is drawn, checking it all lands on the image. */
@@ -111,7 +114,7 @@ test('the text size page offers 12 to 18px, starts on the recommended 16px, and
'./onboarding-fonts': { onboardingFont: font },
'../../graphics/installed-fonts': { installedFontPath: (file) => `/fonts/${file}` },
'../../graphics/ttf-font': { TtfFont: { load: (path, size) => font(size === 12 ? 'title' : 'detail') } },
'../../graphics/ui-fonts': { fontSelectionLabel: () => 'Terminus', getDefaultSmallFont: () => font('detail'),
'../../graphics/ui-fonts': { defaultUiFontSize: () => 16, fontSelectionLabel: () => 'Terminus', getDefaultSmallFont: () => font('detail'),
getUiFontSelection: () => selection, setUiFontSelection: (value) => { selection = value; saved.push(value.size); },
uiFontSizeAllowed: (path, size) => size !== 13 },
'../../ui/font-picker': { FONT_SIZE_CHOICES: [8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 24] },
@@ -148,6 +151,51 @@ test('the text size page offers 12 to 18px, starts on the recommended 16px, and
assert.equal(menu.selectedItem, 15);
});
test('on a RayNeo iO the text size page recommends and starts on 14px, its default', () => {
const menu = { selected: null, items: [], setItems(items, index) { this.items = items; this.selected = index; },
get selectedItem() { return this.items[this.selected] ?? null; }, paint(image, box) { this.box = box; } };
let menuOptions;
const load = loader({}, {
'./onboarding-fonts': { onboardingFont: font },
'../../graphics/installed-fonts': { installedFontPath: (file) => `/fonts/${file}` },
'../../graphics/ttf-font': { TtfFont: { load: () => font('detail') } },
'../../graphics/ui-fonts': { defaultUiFontSize: () => 14, fontSelectionLabel: () => 'Terminus', getDefaultSmallFont: () => font('detail'),
getUiFontSelection: () => ({ kind: 'ttf', file: 'Roboto-Light.ttf', size: 14 }), setUiFontSelection: () => assert.fail('nothing to save'),
uiFontSizeAllowed: () => true },
'../../ui/font-picker': { FONT_SIZE_CHOICES: [8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 24] },
'../../ui/menu-core': { Menu: class { constructor(options) { menuOptions = options; return menu; } } },
'../../ui/metrics': { LIST_ROW_TEXT_INSET: 4, listRowHeight: (f) => f.lineHeight + 8 },
});
const { TextSizePage } = load('app/apps/onboarding/text-size-page.ts');
const page = new TextSizePage();
page.enter();
assert.equal(menu.selectedItem, 14);
const notes = menu.items.filter((size) => {
const row = recorder(200, 32);
menuOptions.draw({ image: row, item: size, x: 0, y: 0, width: 200, height: 32, selected: false });
return row.calls.some((call) => call.text === 'Recommended');
});
assert.deepEqual(notes, [14]);
// Taking the default leaves the size unset, so it keeps following the glasses.
page.handleInput({ type: 'click' }, { next: () => {} });
});
test('on a RayNeo iO the layout page recommends and starts on Left, and fits the 540x220 screen', () => {
const { load, settings } = harness('rayneo-io');
const { LayoutPage, recommendedLayout } = load('app/apps/onboarding/layout-page.ts');
assert.equal(recommendedLayout(), 'left');
const page = new LayoutPage();
const image = recorder(540, 220);
page.paint(image, true);
const captions = image.calls.filter((call) => call.kind === 'text').map((call) => call.text);
assert.ok(captions.includes('Left (Recommended)'));
assert.ok(captions.includes('Bottom'));
page.handleInput({ type: 'click' }, { next() {} });
assert.deepEqual(settings.appSwitcherPositionSetting.writes, ['left']);
// The G2 still recommends Bottom.
assert.equal(harness().load('app/apps/onboarding/layout-page.ts').recommendedLayout(), 'bottom');
});
test('the depth page follows layouts that have depth, sits in the layout, and applies depth as it scrolls', () => {
const { load, settings } = harness();
const menu = { selected: 0, items: [], select(index) { this.selected = index; },
@@ -183,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');
+104 -1
View File
@@ -12,6 +12,7 @@ const {
isPreviouslyPaired,
glassesRow,
ringRow,
rayneoRow,
DEFAULT_STALE_AFTER_MS,
} = require("../.test-build/app/g2/pairing-candidates.js");
const { requiredArtworkFileNames, glassesImagePath, GENERIC_G2_IMAGE_PATH } = require("../.test-build/app/g2/glasses-artwork.js");
@@ -188,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);
@@ -289,3 +290,105 @@ test("every artwork file the resolver claims is bundled exists on disk", () => {
assert.ok(fs.existsSync(path.join(dir, name)), `missing app/images/glasses/${name}`);
}
});
test("a RayNeo iO is its own candidate, never half of a G2 pair", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest({
address: "00:6A:5E:5F:33:C2", name: "RayNeo iO-2229", manufacturerData: "1657" + "07006a5e5f33c2130000000000000001",
rssi: -50, txPower: null, connectable: true, bonded: false, source: "scan", seenAtMs: 1000,
});
assert.equal(aggregator.pairs().length, 0);
assert.equal(aggregator.rings().length, 0);
const found = aggregator.rayneos();
assert.equal(found.length, 1);
const row = rayneoRow(found[0], { pairedAddress: "00:6a:5e:5f:33:c2" });
assert.equal(row.kind, "rayneo-io");
assert.equal(row.canSelect, true);
assert.equal(row.isPreviouslyPaired, true);
});
// ---------------------------------------------------------------------------
// Even G1
// ---------------------------------------------------------------------------
const G1_SERIAL = "S110LABC030139";
const g1Arm = (name, address, manufacturerData) => ({
address, name, manufacturerData, rssi: -50, txPower: null, connectable: true, bonded: false, source: "scan", seenAtMs: 1000,
});
const g1v0Arm = (side, address) => g1Arm(`G1v0_${side}`, address, "ffff0104" + ascii(G1_SERIAL));
test("G1 arms on g1v0 join on the frame serial and can be selected", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1v0Arm("L", "F4:27:E9:CA:E8:3F"));
aggregator.ingest(g1v0Arm("R", "CD:EB:89:BF:E9:EC"));
const [pair, ...rest] = aggregator.pairs();
assert.equal(rest.length, 0);
assert.equal(pair.completeness, "complete");
assert.equal(pair.g1Firmware, "g1v0");
assert.equal(pair.identity, null);
const row = glassesRow(pair);
assert.equal(row.modelTitle, "Even Realities G1");
assert.equal(row.canSelect, true);
assert.match(row.armsSummary, /case/);
});
test("G1 arms on current firmware join on the serial, with the arm's own name", () => {
const record = (flags) => "ffff" + "02" + flags + "000542" + ascii(G1_SERIAL);
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("G1CFW_L_EF50E5", "C0:66:16:EF:50:E5", record("05")));
aggregator.ingest(g1Arm("G1CFW_R_CBE689", "E4:46:BA:CB:E6:89", record("04")));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "g1v0");
assert.equal(pair.completeness, "complete");
assert.equal(pair.left.g1Version, "0.5.66");
assert.equal(glassesRow(pair).canSelect, true);
});
test("a G1 pair halfway through an install is one pair, shown as needing it", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("G1CFW_L_EF50E5", "C0:66:16:EF:50:E5", "ffff" + "02" + "05" + "000542" + ascii(G1_SERIAL)));
aggregator.ingest(g1Arm("Even G1_70_R_CBE689", "E4:46:BA:CB:E6:89", "01" + ascii(G1_SERIAL)));
const pairs = aggregator.pairs();
assert.equal(pairs.length, 1);
assert.equal(pairs[0].g1Firmware, "stock");
assert.equal(glassesRow(pairs[0]).canSelect, true);
});
test("G1 arms on Even's firmware can be selected, to install on", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL)));
aggregator.ingest(g1Arm("Even G1_70_R_CBE689", "E4:46:BA:CB:E6:89", "01" + ascii(G1_SERIAL)));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "stock");
assert.equal(pair.completeness, "complete");
const row = glassesRow(pair);
assert.equal(row.canSelect, true);
assert.match(row.armsSummary, /install/);
});
test("a G1 pair with one arm in safe mode can be selected, to install again", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1v0Arm("L", "F4:27:E9:CA:E8:3F"));
aggregator.ingest(g1Arm("G1v0S_R", "CD:EB:89:BF:E9:EC", "ffff0104" + ascii(G1_SERIAL)));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "g1v0-safe");
assert.equal(glassesRow(pair).canSelect, true);
});
test("a G1 pair needs both arms heard, whatever it runs", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL)));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "stock");
assert.equal(pair.completeness, "left-only");
assert.equal(glassesRow(pair).canSelect, false);
});
test("G2 pairs carry no G1 firmware", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(arm("left", "S110LABC030139", "EC:D7:82:69:3C:CB", -50));
aggregator.ingest(arm("right", "S110LABC030139", "D0:7A:47:82:09:67", -50));
const pairs = aggregator.pairs();
assert.equal(pairs.length, 1);
assert.equal(pairs[0].g1Firmware, undefined);
});
+23 -1
View File
@@ -22,7 +22,7 @@ const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/te
const textwrap = load('app/graphics/textwrap.ts', {});
const fonts = { getDefaultSmallFont: () => font };
const menu = 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 },
'./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 },
'../graphics/image': graphics, '../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts,
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {},
'./metrics': metrics, './menu-core': menuCore,
@@ -111,3 +111,25 @@ test('the selected row stays clear of its description band', async () => {
assert.ok(row.y + row.source.height <= bandTop, `row ends at ${row.y + row.source.height}, band starts at ${bandTop}`);
assert.ok(row.y + row.source.height > bandTop - 30, 'the last item scrolled down to just above the band');
});
test('a section\'s detail gives its rows the pane while focus is in them, where the two don\'t fit (a RayNeo iO\'s window)', async () => {
const docs = ['README', 'License', 'Privacy policy', 'Acknowledgements'];
const detailDraws = [];
// About's blurb under its 72px logo: about 145px.
const about = { label: 'About', items: docs.map((label) => ({ label, onSelect() {} })),
renderDetail: ({ image, x, y }) => { detailDraws.push(image); image.fillRect(x, y, 72, 72, 90); return 145; } };
for (const [size, keeps] of [[{ width: 576, height: 260 }, true], [{ width: 476, height: 192 }, false], [{ width: 476, height: 155 }, false]]) {
const layer = new SettingsPanelLayer([about]);
const ctx = { stack: { getBaseSize: () => size, isFocused: () => true } };
const paint = () => { detailDraws.length = 0; const image = layer.paint(ctx); return { image, drawn: detailDraws.includes(image) }; };
// The preview (focus in the left column) always shows the detail.
assert.equal(paint().drawn, true, `preview at ${size.height}`);
await layer.handleInput({ type: 'click', timestampMs: 0 }, ctx);
const { image, drawn } = paint();
assert.equal(drawn, keeps, `focused at ${size.height}`);
const row = selections(image)[1];
if (keeps) assert.ok(row.y >= 8 + 145, 'the rows under the detail');
else assert.equal(row.y, 8, 'the first row at the top of the pane');
assert.ok(row.y + row.source.height <= size.height - 8);
}
});
+2 -2
View File
@@ -15,8 +15,8 @@ function worker() {
const messages = [];
const file = 'app/apps/terminal/terminal-app.worker.ts';
const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
const functions = new Set(['recencyKey', 'post', 'renderHubWindows', 'isSessionActive', 'isWindowSessionActive', 'hubAnimationShouldRun', 'syncWindowIconActivity', 'updateHubAnimation', 'noteSessionActivity', 'openWindow', 'closeWindow']);
const variables = new Set(['windows', 'pendingViews', 'activeViewId', 'sessionRecency', 'sessionActivity', 'ACTIVITY_ACTIVE_MS', 'HUB_ANIMATION_STEP_MS', 'hubAnimationPhase', 'hubAnimationTimer', 'windowIconActivity', 'screenOn']);
const functions = new Set(['recencyKey', 'post', 'stopViewConnection', 'renderHubWindows', 'isSessionActive', 'isWindowSessionActive', 'hubAnimationShouldRun', 'syncWindowIconActivity', 'updateHubAnimation', 'noteSessionActivity', 'openWindow', 'closeWindow']);
const variables = new Set(['windows', 'pendingViews', 'pendingHeightChanges', 'activeViewId', 'sessionRecency', 'sessionActivity', 'ACTIVITY_ACTIVE_MS', 'HUB_ANIMATION_STEP_MS', 'hubAnimationPhase', 'hubAnimationTimer', 'windowIconActivity', 'screenOn']);
const selected = source.statements.filter(s =>
ts.isFunctionDeclaration(s) && functions.has(s.name?.text) ||
ts.isVariableStatement(s) && s.declarationList.declarations.some(d => variables.has(d.name.getText(source))) ||
+483
View File
@@ -0,0 +1,483 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const HUB = 'terminal:hub';
const MIN = { width: 552, height: 260 };
const MAX = { width: 552, height: 452 };
const font = { lineHeight: 12, measureText: (text) => text.length * 6, getGlyph: () => null };
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
// A recording stand-in for the worker's images: enough to see what a frame shows.
function fakeImageModule() {
class GrayImage {
constructor(width, height) {
this.width = width;
this.height = height;
this.texts = [];
return new Proxy(this, { get: (target, key) => (key in target ? target[key] : () => {}) });
}
drawText(_font, _x, _y, text) { this.texts.push(text); }
drawMenuSelection(row) { this.texts.push(...row.texts.map((text) => `[${text}]`)); }
}
return { GrayImage };
}
// Runs the real worker against the shell's message protocol, stubbing only what
// sits behind it: the websocket client, the emulator, the display and the menu host.
function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } = {}) {
const replies = [], clients = [], frames = [], menus = [];
const global = { postMessage: (message) => replies.push(message) };
class FakeClient {
constructor(options) {
this.options = options;
this.stopped = false;
this.attached = null;
this.sent = [];
this.listeners = { state: [], bell: [], activity: [] };
this.statusText = 'Connected.';
clients.push(this);
}
state() { return { phase: this.stopped ? 'idle' : 'connected', status: this.statusText, serverName: 'host', sessions: sessions.map((title) => ({ socket: title, title, cwdHint: '' })) }; }
start() { this.stopped = false; this.listeners.state.forEach((listener) => listener(this.state())); }
stop() { this.stopped = true; }
setViewport(cols, rows) { this.viewport = [cols, rows]; }
connectSession(socket) { this.attached = socket; }
sendInput(text) { this.sent.push(text); }
submitInput(text) { this.sent.push(text); }
listSessions() {}
view() {}
requestHistory() {}
onStateChange(listener) { this.listeners.state.push(listener); return () => {}; }
onBell(listener) { this.listeners.bell.push(listener); return () => {}; }
onTitle() { return () => {}; }
onActivity(listener) { this.listeners.activity.push(listener); return () => {}; }
onSnapshot() { return () => {}; }
onHistoryLines() { return () => {}; }
onSessionAttached() { return () => {}; }
onTerminalData() { return () => {}; }
onSessionDetached() { return () => {}; }
}
class FakeEmulator {
dispose() { this.disposed = true; }
write() {}
reset() {}
bufferLength() { return 0; }
lineAt() { return ''; }
cursorRow() { return 0; }
cursorCol() { return 0; }
}
// Click runs the first item, the way the real menu does at its initial selection.
class FakeWindowMenu {
constructor(options) { this.options = options; this.opened = null; menus.push(this); }
isOpen() { return this.opened !== null; }
open(items = this.options.items()) { this.opened = items; }
close() { this.opened = null; }
resize(size) { this.options.size = size; }
paint() { this.options.items(); return [this.options.paintBase()]; }
async handleInput(event) {
if (event.type === 'click') {
await this.opened[0].onSelect({ stack: { pop: () => { this.opened = null; }, push() {} } });
}
}
}
const setting = (value) => ({ id: 'setting', get: () => value, set() {} });
const image = fakeImageModule();
const load = loader({ global, setTimeout, clearTimeout, setInterval, clearInterval }, {
'@nativescript/core/globals': {},
'./background': { hasTerminalBackgroundWork: () => false },
'../../ui/shell/worker-lifecycle': { finishWorkerShutdown() {} },
'../../graphics/image': image,
'../graphics/image': image,
'../../graphics/plane': {
planesFingerprint: (planes) => JSON.stringify([planes[0].width, planes[0].height, planes[0].texts]),
flattenPlanesWithDraws: (planes) => ({ image: { ...planes[0], width: planes[0].width, height: planes[0].height, texts: planes[0].texts, to8bppBuffer: () => ({ buffer: planes[0].texts }) }, draws: [] }),
},
'../../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../../graphics/ui-fonts': {
getDefaultSmallFont: () => font,
getTerminalFontConfig: () => ({ font, cellWidth: 6, cellHeight: 12 }),
},
'../../graphics/icons': { TERMINAL_ICON_GLYPHS: ['1', '2', '3'] },
'../../native/frame-timings': {
startFrame: () => 1, finishFrame() {}, logFrame() {},
span: (_frame, _name, run) => run(), runWithFrame: (_frame, run) => run(),
},
'../../native/active-display': {
getActiveDisplay: () => ({
submitSurfaceFrame: (texts, surfaceId, _x, _y, width, height) => frames.push({ surfaceId, width, height, texts }),
}),
},
'../../ui/gestures': { GESTURE_DOUBLE_CLICK: 'double-tap' },
'../../native/g2mirror-client': { G2MirrorClient: FakeClient },
'../../native/settings-store': { onSettingsStoreChanged() {} },
'../../ui/dashboard-settings': {
enumSettingMenuItem() {}, textSettingMenuItem() {}, toggleSettingMenuItem() {},
terminalAutoReconnectSetting: setting(false),
terminalDisplayLayoutSetting: setting('default'),
terminalLaunchPresetsSetting: setting(presets),
terminalNewConnectionSetting: setting(''),
terminalWakeOnBellSetting: setting(bellWake),
},
'../../ui/font-picker': { terminalFontPickerMenuItem() {} },
'./connections': {
TERMINAL_CONNECTIONS_KEY: 'terminal.connections',
connectionDisplayName: (config) => config.id,
loadConnections: () => [{ id: 'c1', url: 'ok', serverName: 'host', enabled: true }],
parseConnectionString: () => ({ host: 'host' }),
saveConnections() {}, updateConnection() {},
},
'./terminal-emulator': { TerminalEmulator: FakeEmulator },
'../../ui/menu': { drawSubmenuIndicator() {}, submenuItem: (label, onSelect) => ({ label, onSelect }) },
'../../ui/window-menu': { WindowMenu: FakeWindowMenu, WindowMenuLayer: class {} },
'../../ui/shell/geometry': { appViewportSize: () => MAX },
});
load('app/apps/terminal/terminal-app.worker.ts');
const send = (message) => global.onmessage({ data: message });
const input = (type, windowId = HUB) => send({ type: 'input', windowId, event: { type }, frameId: 0, focused: true });
const openWindow = (windowId, viewport) => {
send({ type: 'open-window', windowId, surfaceId: `window:${windowId}`, title: 'Terminal', viewport });
send({ type: 'foreground', windowId, foreground: true, focused: true });
};
const repliesOf = (type) => replies.filter((reply) => reply.type === type);
return {
clients, frames, replies, menus, send, input, openWindow, repliesOf,
lastFrame: () => frames[frames.length - 1],
clearReplies: () => { replies.length = 0; },
openMenu: (windowId = HUB) => input('short-then-long-press', windowId),
menuLabels: () => Array.from(menus.find((menu) => menu.isOpen()).opened, (item) => item.label),
closeMenu: () => menus.forEach((menu) => menu.close()),
// Past Manage Connections and Settings to the first session row.
selectFirstSession: () => { input('scroll-down'); input('scroll-down'); },
answerHeight: (viewport, windowId = HUB) => send({ type: 'resize-window', windowId, viewport }),
};
}
function hubShowingList() {
const t = terminal();
t.openWindow(HUB, MIN);
t.selectFirstSession();
return t;
}
function hubShowingSession() {
const t = hubShowingList();
t.input('click');
t.answerHeight(MAX);
t.clearReplies();
return t;
}
test('selecting a session shows it in the same window, at the height the shell answers with', () => {
const t = hubShowingList();
assert.equal(t.clients.length, 1, 'just the control connection so far');
assert.ok(t.lastFrame().texts.includes('[vim]') || t.lastFrame().texts.some((text) => text.includes('vim')));
t.input('click');
assert.deepEqual(t.repliesOf('open-window-request'), [], 'no new window');
assert.deepEqual(t.repliesOf('set-height-mode').map((reply) => reply.heightMode), ['max']);
assert.equal(t.clients.length, 1, 'no connection before the size is known');
t.answerHeight(MAX);
const view = t.clients[1];
assert.deepEqual([view.options.cols, view.options.rows], [92, 37], 'grid from the answered viewport');
assert.equal(view.attached, 'vim');
assert.deepEqual([t.lastFrame().surfaceId, t.lastFrame().width, t.lastFrame().height], [`window:${HUB}`, MAX.width, MAX.height]);
assert.ok(!t.lastFrame().texts.includes('Terminal'), 'the list is gone');
});
test('a repeated tap before the shell answers starts one view', () => {
const t = hubShowingList();
t.input('click');
t.input('click');
assert.equal(t.repliesOf('set-height-mode').length, 1);
t.answerHeight(MAX);
assert.equal(t.clients.length, 2);
});
test('text input reaches the session shown in place', () => {
const t = hubShowingSession();
t.send({ type: 'text-input', windowId: HUB, text: 'ls' });
assert.deepEqual(t.clients[1].sent, ['ls']);
});
test('double-tap in a session shown in place goes back to the list, not the sidebar', () => {
const t = hubShowingSession();
t.input('double-click');
assert.deepEqual(t.repliesOf('yield-focus'), []);
assert.deepEqual(t.repliesOf('set-height-mode').map((reply) => reply.heightMode), ['min']);
assert.equal(t.clients[1].stopped, false, 'the session stays up until the window has resized');
t.answerHeight(MIN);
assert.equal(t.clients[1].stopped, true);
assert.deepEqual([t.lastFrame().width, t.lastFrame().height], [MIN.width, MIN.height]);
assert.ok(t.lastFrame().texts.includes('Terminal'), 'the list is back');
assert.ok(t.lastFrame().texts.includes('[vim]'), 'with the session just viewed still selected');
t.input('double-click');
assert.deepEqual(t.repliesOf('yield-focus').map((reply) => reply.windowId), [HUB], 'then double-tap yields as usual');
});
test('coming back from a session keeps the list order despite its bumped recency, until the list next becomes visible', () => {
const t = hubShowingList();
const sessionRows = () => t.lastFrame().texts.filter((text) => /vim|top/.test(text));
t.input('scroll-down');
assert.deepEqual(sessionRows(), ['vim', '[top]']);
t.input('click');
t.answerHeight(MAX);
t.clients[0].listeners.activity.forEach((listener) => listener('top'));
t.input('double-click');
t.answerHeight(MIN);
assert.deepEqual(sessionRows(), ['vim', '[top]']);
t.send({ type: 'foreground', windowId: HUB, foreground: false, focused: false });
t.send({ type: 'foreground', windowId: HUB, foreground: true, focused: true });
assert.deepEqual(sessionRows().map((text) => text.replace(/[[\]]/g, '')), ['top', 'vim'], 're-sorted as usual');
});
test('the session just viewed stays selected when rows above it have shifted', () => {
const sessions = ['vim', 'top', 'htop'];
const t = terminal({ sessions });
t.openWindow(HUB, MIN);
t.selectFirstSession();
t.input('scroll-down');
t.input('click');
t.answerHeight(MAX);
// vim exits while top is on show, moving top's row up one (and htop into its place).
sessions.shift();
t.clients[0].listeners.state.forEach((listener) => listener(t.clients[0].state()));
t.input('double-click');
t.answerHeight(MIN);
assert.ok(t.lastFrame().texts.includes('[top]'));
});
test('the window menu leads with Open in new window only while a session is selected', () => {
const t = terminal();
t.openWindow(HUB, MIN);
t.openMenu();
assert.equal(t.menuLabels()[0], 'Settings', 'Manage Connections is selected');
t.closeMenu();
t.input('scroll-down');
t.openMenu();
assert.equal(t.menuLabels()[0], 'Settings', 'Settings is selected');
t.closeMenu();
t.input('scroll-down');
t.openMenu();
assert.deepEqual(t.menuLabels().slice(0, 2), ['Open in new window', 'Settings']);
});
test('Open in new window on a selected session opens a window and leaves the list up', async () => {
const t = hubShowingList();
t.openMenu();
t.input('click');
await tick();
assert.deepEqual(t.repliesOf('set-height-mode'), []);
const [request] = t.repliesOf('open-window-request');
assert.equal(request.title, 'vim');
assert.equal(request.heightMode, 'max');
assert.equal(request.focus, true);
assert.equal(t.repliesOf('open-window-request').length, 1);
});
test('selecting a session already in its own window focuses that window', async () => {
const t = hubShowingList();
t.openMenu();
t.input('click');
await tick();
const { windowId } = t.repliesOf('open-window-request')[0];
t.send({ type: 'foreground', windowId: HUB, foreground: false, focused: false });
t.openWindow(windowId, MAX);
t.send({ type: 'foreground', windowId: HUB, foreground: true, focused: true });
t.clearReplies();
t.input('click');
assert.deepEqual(t.repliesOf('focus-window').map((reply) => reply.windowId), [windowId]);
assert.deepEqual(t.repliesOf('set-height-mode'), []);
});
test('a session in place can move to a new window: the list comes back first, then the window opens', async () => {
const t = hubShowingSession();
t.openMenu();
assert.deepEqual(t.menuLabels().slice(0, 2), ['Open in new window', 'Settings']);
t.input('click');
await tick();
assert.deepEqual(t.repliesOf('set-height-mode').map((reply) => reply.heightMode), ['min']);
assert.deepEqual(t.repliesOf('open-window-request'), [], 'not while the old connection is up');
t.answerHeight(MIN);
assert.equal(t.clients[1].stopped, true);
const [request] = t.repliesOf('open-window-request');
assert.equal(request.title, 'vim');
assert.equal(request.iconGlyph, '1');
assert.ok(t.lastFrame().texts.includes('Terminal'));
});
test('a session in its own window keeps its plain menu and double-tap yields focus', async () => {
const t = hubShowingList();
t.openMenu();
t.input('click');
await tick();
const { windowId } = t.repliesOf('open-window-request')[0];
t.openWindow(windowId, MAX);
t.openMenu(windowId);
assert.equal(t.menuLabels()[0], 'Settings');
t.closeMenu();
t.input('double-click', windowId);
assert.deepEqual(t.repliesOf('yield-focus').map((reply) => reply.windowId), [windowId]);
});
test('a bell still finds the window while the hub is showing a session', () => {
const t = hubShowingSession();
// A session with no view of its own wakes to the hub's window.
t.clients[0].listeners.bell.forEach((listener) => listener('top', Date.now() + 1000));
assert.deepEqual(t.repliesOf('wake-window').map((reply) => reply.windowId), [HUB]);
t.clearReplies();
// The session on show: flagged only while the window is in the background.
t.send({ type: 'foreground', windowId: HUB, foreground: false, focused: false });
t.clients[0].listeners.bell.forEach((listener) => listener('vim', Date.now() + 2000));
assert.deepEqual(t.repliesOf('set-attention').map((reply) => reply.windowId), [HUB]);
});
test('a window backgrounded while waiting for the shell picks up the session without painting', () => {
const t = hubShowingList();
t.input('click');
t.send({ type: 'foreground', windowId: HUB, foreground: false, focused: false });
const painted = t.frames.length;
t.answerHeight(MAX);
assert.equal(t.frames.length, painted);
t.send({ type: 'foreground', windowId: HUB, foreground: true, focused: true });
assert.equal(t.lastFrame().height, MAX.height);
});
test('a list repaint scheduled before the swap does not paint over the session', async () => {
const sessions = ['vim', 'top'];
const t = terminal({ sessions });
t.openWindow(HUB, MIN);
t.selectFirstSession();
t.input('click');
// A new session makes the list's next paint differ, so it would be submitted.
sessions.push('htop');
t.clients[0].listeners.state.forEach((listener) => listener(t.clients[0].state()));
t.answerHeight(MAX);
await new Promise((resolve) => setTimeout(resolve, 80));
assert.equal(t.lastFrame().height, MAX.height);
assert.ok(!t.lastFrame().texts.includes('Terminal'));
});
test('a session repaint scheduled before the swap does not paint over the list', async () => {
const t = hubShowingSession();
t.input('double-click');
t.clients[1].statusText = 'Reconnecting...';
t.clients[1].listeners.state.forEach((listener) => listener(t.clients[1].state()));
t.answerHeight(MIN);
await new Promise((resolve) => setTimeout(resolve, 80));
assert.equal(t.lastFrame().height, MIN.height);
assert.ok(t.lastFrame().texts.includes('Terminal'));
});
test('closing the window while the shell has not answered drops the change', () => {
const t = hubShowingList();
t.input('click');
t.send({ type: 'close-window', windowId: HUB });
t.answerHeight(MAX);
assert.equal(t.clients.length, 1, 'no view connection started');
});
test('closing the window while it shows a session stops that session', () => {
const t = hubShowingSession();
t.send({ type: 'close-window', windowId: HUB });
assert.equal(t.clients[1].stopped, true);
});
test('a later resize of a session in place reconnects at the new grid, and the list then gets its own size', () => {
const t = hubShowingSession();
t.answerHeight({ width: 552, height: 400 });
assert.equal(t.clients[1].stopped, false);
assert.deepEqual(t.clients[1].viewport, [92, 33]);
t.input('double-click');
t.answerHeight({ width: 552, height: 240 });
assert.equal(t.lastFrame().height, 240);
});
test('the shell host resizes the surface before answering with the new viewport', async () => {
const worker = { posted: [], postMessage(message) { this.posted.push(message); } };
const surfaces = [];
const windows = [];
let renders = 0;
let foreground;
const load = loader({ global: { isIOS: false }, setTimeout, clearTimeout, Promise }, {
'../../graphics/image': {},
'./chrome-layer': { windowIcon() {} },
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
'./geometry': { appViewportSize: (mode) => (mode === 'max' ? MAX : MIN) },
'../../native/frame-timings': {},
'./worker-state': {},
'./shell': { shell: {
registerWindow: (window) => windows.push(window),
getWindows: () => windows,
foregroundWindow: () => foreground,
isWindowFocused: () => true,
} },
});
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts');
let finishConfigure = () => {};
const host = new WorkerAppHost({
appId: 'terminal', worker,
configureSurface: (surfaceId, visible, heightMode) => {
surfaces.push({ surfaceId, visible, heightMode });
return heightMode === 'min' ? Promise.resolve() : new Promise((resolve) => { finishConfigure = resolve; });
},
requestShellRender: () => { renders++; },
removeSurface() {},
});
worker.onmessage({ data: { type: 'worker-ready' } });
const window = host.openWindow({ windowId: HUB, title: 'Terminal', iconLetter: 'T' });
foreground = window;
await tick();
worker.posted.length = 0;
renders = 0;
worker.onmessage({ data: { type: 'set-height-mode', windowId: HUB, heightMode: 'max' } });
assert.equal(window.heightMode, 'max', 'the chrome reads the band from here');
const configured = surfaces[surfaces.length - 1];
assert.equal(configured.heightMode, 'max');
assert.equal(configured.visible(), true, 'asked late: the window may have lost the foreground');
foreground = undefined;
assert.equal(configured.visible(), false);
foreground = window;
await tick();
assert.deepEqual(worker.posted, [], 'no answer before the surface is ready');
finishConfigure();
await tick();
assert.deepEqual(worker.posted.map((message) => [message.type, message.viewport]), [['resize-window', MAX]]);
assert.equal(renders, 1);
// Any later relayout (a switcher height change) keeps the new band.
worker.posted.length = 0;
window.relayout();
assert.deepEqual(worker.posted.map((message) => message.viewport), [MAX]);
// Unchanged band: still answered, so the worker can always wait on it.
worker.posted.length = 0;
worker.onmessage({ data: { type: 'set-height-mode', windowId: HUB, heightMode: 'min' } });
await tick();
worker.onmessage({ data: { type: 'set-height-mode', windowId: HUB, heightMode: 'min' } });
await tick();
assert.deepEqual(worker.posted.map((message) => message.viewport), [MIN, MIN]);
// A closed window is not touched again.
window.close();
const count = surfaces.length;
worker.onmessage({ data: { type: 'set-height-mode', windowId: HUB, heightMode: 'max' } });
await tick();
assert.equal(surfaces.length, count);
});
+11
View File
@@ -21,6 +21,7 @@
"../app/g2/ios-peripheral-identity.ts",
"../app/graphics/image.ts",
"../app/graphics/textwrap.ts",
"../app/graphics/lvgl-wrap.ts",
"../app/graphics/battery.ts",
"../app/graphics/plane.ts",
"../app/graphics/shell-scene.ts",
@@ -39,9 +40,16 @@
"../app/g2/glance-state.ts",
"../app/ui/shell/notification-modal-queue.ts",
"../app/ui/shell/notification-popup-delay.ts",
"../app/ui/shell/notification-popup-timeout.ts",
"../app/apps/glanceboard/layout.ts",
"../app/apps/files/video-layout.ts",
"../app/g2/pairing-candidates.ts",
"../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",
"../app/apps/microphones/mic-protocol.ts",
"../app/apps/calculator/calculator-commands.ts",
@@ -51,6 +59,9 @@
"../app/apps/microphones/caption-clock.ts",
"../app/apps/microphones/name-guess.ts",
"../app/apps/evenhub/containers.ts",
"../app/apps/evenhub/layout-debug.ts",
"../app/apps/evenhub/image-pipeline.ts",
"../app/apps/evenhub/payload-validation.ts",
"../app/apps/evenhub/list-menu.ts",
"../app/apps/evenhub/device-status.ts",
"../app/apps/evenhub/font-spec.ts",
+45
View File
@@ -0,0 +1,45 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
// ui-fonts.ts and screen-size.ts over an in-memory settings store, with each
// TTF "loaded" as its path and size.
function fixture(entries = []) {
const store = new Map(entries);
const listeners = [];
const load = loader({}, {
'../native/settings-store': {
getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => { store.set(key, value); for (const listener of listeners) listener(key); },
onSettingsStoreChanged: (listener) => listeners.push(listener),
},
'./image': { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480, RAYNEO_IO_WIDTH: 540, RAYNEO_IO_HEIGHT: 220 },
'./bdffont': { getFont: (name) => ({ name }) },
'./ttf-font': { TtfFont: { load: (path, size) => ({ path, size, lineHeight: size + 4 }) } },
'./installed-fonts': { ensurePreinstalledFonts() {}, getInstalledFont: () => null, installedFontPath: (file) => `/fonts/${file}` },
});
return { fonts: load('app/graphics/ui-fonts.ts'), screen: load('app/graphics/screen-size.ts'), store, listeners };
}
test('the screen and the default UI font follow the paired glasses: 640x480 at 16px, or a RayNeo iO\'s 540x220 at 14px', () => {
const { fonts, screen, store, listeners } = fixture();
assert.deepEqual([screen.screenWidth(), screen.screenHeight(), screen.isRayNeoIoConfigured()], [640, 480, false]);
assert.equal(fonts.defaultUiFontSize(), 16);
assert.deepEqual({ ...fonts.getUiFontSelection() }, { kind: 'ttf', file: 'Roboto-Light.ttf', size: 16 });
assert.equal(fonts.getDefaultSmallFont().size, 16);
// Pairing a RayNeo iO: the cached fonts re-resolve at its size.
store.set(screen.GLASSES_TYPE_KEY, 'rayneo-io');
for (const listener of listeners) listener(screen.GLASSES_TYPE_KEY);
assert.deepEqual([screen.screenWidth(), screen.screenHeight(), screen.isRayNeoIoConfigured()], [540, 220, true]);
assert.equal(fonts.defaultUiFontSize(), 14);
assert.deepEqual({ ...fonts.getUiFontSelection() }, { kind: 'ttf', file: 'Roboto-Light.ttf', size: 14 });
assert.equal(fonts.getDefaultSmallFont().size, 14);
});
test('a chosen UI font keeps its size on either glasses', () => {
const { fonts, screen, store } = fixture([['deviceType', 'rayneo-io']]);
fonts.setUiFontSelection({ kind: 'ttf', file: 'Roboto-Light.ttf', size: 17 });
assert.equal(fonts.getUiFontSelection().size, 17);
store.set(screen.GLASSES_TYPE_KEY, 'g2');
assert.equal(fonts.getUiFontSelection().size, 17);
});
+71
View File
@@ -0,0 +1,71 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, dependencies) {
const context = { exports: {}, console, require: (name) => {
assert.ok(name in dependencies, name);
return dependencies[name];
} };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const installedApps = {
getInstalledEvenHubApps: () => [],
getInstalledEvenHubFingerprint: () => '',
installedEvenHubAppId: (packageId) => packageId,
renderInstalledEvenHubIcon: () => null,
};
test('the launcher grid leaves out an app the paired glasses cannot run', () => {
const { launcherEntries } = load('app/apps/launcher/index.ts', {
'../../ui/shell/shell': { shell: {} },
'./launcher-app': {},
'../evenhub/installed-apps': installedApps,
});
let supported = true;
const apps = [
{ appId: 'launcher', title: 'Apps', showInLauncher: false },
{ appId: 'timer', title: 'Timer' },
{ appId: 'compass', title: 'Compass', isSupported: () => supported },
];
const ids = () => Array.from(launcherEntries(apps), (entry) => entry.appId);
assert.deepEqual(ids(), ['timer', 'compass']);
supported = false;
assert.deepEqual(ids(), ['timer']);
});
test('apps.launch follows the paired glasses', async () => {
const listeners = [];
const { registerWindowTools } = load('app/assistant/window-tools.ts', {
'../ui/shell/shell': { shell: { wake() {} } },
'../apps/launcher/launcher-folders': {},
'../apps/evenhub/installed-apps': installedApps,
'../ui/dashboard-settings': { onAnySettingChanged: (listener) => listeners.push(listener) },
'./tool-registry': { toolRegistry: null },
});
const tools = new Map();
const registry = { registerSystemTool: (spec, handler) => tools.set(spec.name, { spec, handler }) };
const launched = [];
const timer = { appId: 'timer', title: 'Timer' };
const compass = { appId: 'compass', title: 'Compass' };
let apps = [timer, compass];
registerWindowTools({ apps: () => apps, launchApp: (appId) => launched.push(appId), requestShellRender() {} }, registry);
const launch = () => tools.get('apps.launch');
const launchIds = () => Array.from(launch().spec.inputSchema.properties.app_id.enum);
assert.deepEqual(launchIds(), ['compass', 'timer']);
apps = [timer];
listeners.forEach((listener) => listener());
assert.deepEqual(launchIds(), ['timer']);
await launch().handler({ app_id: 'compass' });
assert.deepEqual(launched, []);
await launch().handler({ app_id: 'timer' });
assert.deepEqual(launched, ['timer']);
});