forked from Blendman974/faceclaw
Merge branch 'main' into ios-port
This commit is contained in:
commit
a31ddae4d2
49 files changed
+2068
-212
No files matched your search
@@ -14,3 +14,11 @@ That compiles the pure modules with the project's TypeScript into
|
||||
`.test-build/` (git-ignored) and runs `node --test tests/`. No extra
|
||||
dependencies are needed — the tests are plain `.test.cjs` files that use
|
||||
`node:test` and `node:assert`.
|
||||
|
||||
Compass diagnostics have focused UI and wire-format checks:
|
||||
|
||||
node --test tests/compass-debug.test.cjs tests/compass-protocol.test.cjs
|
||||
|
||||
The protocol check also compiles the production Java parser, so it needs a
|
||||
JDK (`JAVA_HOME`, or `javac` and `java` on `PATH`). Its golden packet is shared
|
||||
with the firmware encoder test in `g2flash/tests/compass_diagnostics_test.c`.
|
||||
@@ -0,0 +1,114 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const context = { exports: {}, require: (name) => {
|
||||
assert.ok(name in modules, `Unexpected dependency: ${name}`);
|
||||
return modules[name];
|
||||
}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context, { filename: file });
|
||||
return context.exports;
|
||||
}
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
|
||||
const font = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const small = font(18), large = font(32);
|
||||
const diagnostics = { magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 0x8c, sampleTimeMs: 1234 };
|
||||
|
||||
function compass(width = 576, height = 260) {
|
||||
const settings = new Map();
|
||||
const debug = load('app/apps/compass/debug.ts', { '../../native/settings-store': {
|
||||
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setBooleanSetting: (key, value) => settings.set(key, value),
|
||||
} });
|
||||
let listener, window, renders = 0, pops = 0;
|
||||
class RecordingImage extends graphics.GrayImage {
|
||||
texts = [];
|
||||
drawText(font, x, y, text, value) {
|
||||
this.texts.push({ x, y, text, width: font.measureText(text), height: font.lineHeight });
|
||||
super.drawText(font, x, y, text, value);
|
||||
}
|
||||
}
|
||||
// GrayImage.clone returns the base class; retain text recording for main-screen paints.
|
||||
const baseClone = RecordingImage.prototype.clone;
|
||||
RecordingImage.prototype.clone = function () {
|
||||
const image = baseClone.call(this); Object.setPrototypeOf(image, RecordingImage.prototype); image.texts = []; return image;
|
||||
};
|
||||
const app = load('app/apps/compass/compass-app.ts', {
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
|
||||
'../../graphics/image': { GrayImage: RecordingImage }, '../../graphics/textwrap': textwrap,
|
||||
'../../native/compass': { COMPASS_CHANGED: 15, COMPASS_CALIBRATION_STARTED: 16, COMPASS_CALIBRATION_COMPLETE: 17,
|
||||
addCompassListener: (fn) => { listener = fn; return () => {}; }, setCompassEnabled() {} },
|
||||
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
|
||||
'../../ui/shell/geometry': { screenCenterInViewportX: () => width / 2 - 32 },
|
||||
'../../ui/shell/in-process-window': {
|
||||
YieldAtRootLayer: class { constructor(layer) { return layer; } },
|
||||
createInProcessWindow: (options) => { window = options; return { requestRender: () => ++renders }; },
|
||||
},
|
||||
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
|
||||
'../../g2/android-permissions': { hasLocationPermission: () => false },
|
||||
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (v) => v },
|
||||
'./calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
|
||||
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
|
||||
'./debug': debug,
|
||||
}, { setInterval: () => 1, clearInterval() {} });
|
||||
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => ++pops } };
|
||||
const open = () => app.createCompassAppWindow({ onClosed() {} }); open();
|
||||
return { open, debug, settings, menu: () => window.menuItems(),
|
||||
toggle: () => window.menuItems().find((item) => item.label.startsWith('Debug information:')).onSelect(ctx),
|
||||
paint: () => window.baseLayer.paint(ctx),
|
||||
heading: (info) => listener({ command: 15, headingDegrees: 359, diagnostics: info }),
|
||||
renders: () => renders, pops: () => pops };
|
||||
}
|
||||
|
||||
test('debug toggle defaults off, repaints, closes menu and survives reopening', () => {
|
||||
const app = compass(); app.heading(diagnostics);
|
||||
assert.equal(app.debug.isCompassDebugEnabled(), false);
|
||||
assert.ok(!app.paint().texts.some((t) => t.text.startsWith('Mag:')));
|
||||
const before = app.renders(); app.toggle();
|
||||
assert.equal(app.debug.isCompassDebugEnabled(), true);
|
||||
assert.ok(app.renders() > before && app.pops() === 1);
|
||||
app.open(); assert.equal(app.debug.isCompassDebugEnabled(), true);
|
||||
app.toggle(); assert.equal(app.debug.isCompassDebugEnabled(), false);
|
||||
});
|
||||
|
||||
test('diagnostics sit to the right of the heading without overlap or clipping', () => {
|
||||
for (const width of [240, 320, 576, 640]) {
|
||||
const app = compass(width); app.toggle(); app.heading(diagnostics);
|
||||
const image = app.paint();
|
||||
const heading = image.texts.find((t) => t.text === '359° N');
|
||||
for (const text of ['Mag: 3/3', 'Anom: 2', 'Src: RV']) {
|
||||
const label = image.texts.find((t) => t.text === text);
|
||||
assert.ok(label, text);
|
||||
assert.ok(label.x > heading.x + heading.width);
|
||||
assert.ok(label.x + label.width <= width && label.y + label.height <= image.height);
|
||||
}
|
||||
const status = image.texts.find((t) => t.text === 'Magnetic heading');
|
||||
assert.ok(image.texts.filter((t) => t.text.startsWith('Src:')).every((t) => t.y + t.height < status.y));
|
||||
if (process.env.COMPASS_PREVIEW && width === 576) {
|
||||
fs.writeFileSync(process.env.COMPASS_PREVIEW, Buffer.concat([
|
||||
Buffer.from(`P5\n${image.width} ${image.height}\n255\n`), Buffer.from(image.withDrawsBaked().pixels),
|
||||
]));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy and missing samples replace diagnostics instead of leaving stale values', () => {
|
||||
const app = compass(); app.toggle(); app.heading(diagnostics);
|
||||
assert.ok(app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
|
||||
app.heading(undefined);
|
||||
assert.ok(app.paint().texts.some((t) => t.text === 'unavailable'));
|
||||
assert.ok(!app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
|
||||
assert.deepEqual(Array.from(app.debug.compassDebugLines({ ...diagnostics, flags: 0 })), ['Sample data', 'unavailable']);
|
||||
for (const [source, name] of [[1, 'GRV'], [2, 'GMRV'], [3, 'RV']]) {
|
||||
assert.equal(app.debug.compassDebugLines({ ...diagnostics, orientationSource: source })[2], `Src: ${name}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const test = require('node:test');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('compass diagnostics decode with legacy and malformed-extension fallback', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-compass-java-'));
|
||||
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
|
||||
try {
|
||||
execFileSync(javaBin('javac'), ['-d', directory,
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
|
||||
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
|
||||
path.join(__dirname, 'fixtures/CompassProtocolTest.java')], { stdio: 'pipe' });
|
||||
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.CompassProtocolTest'], { stdio: 'pipe' });
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function load(file, requireModule, globals = {}) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const js = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
const context = { exports: {}, require: requireModule, ...globals };
|
||||
vm.runInNewContext(js, context, { filename: file });
|
||||
return context.exports;
|
||||
}
|
||||
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const graphics = load('app/graphics/image.ts', () => textwrap);
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
|
||||
const font = (size) => BdfFont.parse(fs.readFileSync(
|
||||
path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const small = font(12);
|
||||
const large = font(24);
|
||||
|
||||
function compass({ style, width = 576, height = 260 } = {}) {
|
||||
const settings = new Map(style === undefined ? [] : [['compass.style', style]]);
|
||||
let listener;
|
||||
let window;
|
||||
let renders = 0;
|
||||
let pops = 0;
|
||||
class RecordingImage extends graphics.GrayImage {
|
||||
lines = [];
|
||||
texts = [];
|
||||
drawLine(...args) { this.lines.push(args); super.drawLine(...args); }
|
||||
drawText(font, x, y, text, value) {
|
||||
this.texts.push({ x, y, text, value });
|
||||
super.drawText(font, x, y, text, value);
|
||||
}
|
||||
}
|
||||
const modules = {
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
|
||||
'../../graphics/image': { ...graphics, GrayImage: RecordingImage },
|
||||
'../../graphics/textwrap': textwrap,
|
||||
'../../native/settings-store': {
|
||||
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setStringSetting: (key, value) => settings.set(key, value),
|
||||
},
|
||||
'../../native/compass': {
|
||||
COMPASS_CHANGED: 1, COMPASS_CALIBRATION_STARTED: 2, COMPASS_CALIBRATION_COMPLETE: 3,
|
||||
addCompassListener: (fn) => { listener = fn; return () => {}; },
|
||||
setCompassEnabled() {},
|
||||
},
|
||||
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
|
||||
'../../ui/shell/geometry': { screenCenterInViewportX: () => width - 320 },
|
||||
'../../ui/shell/in-process-window': {
|
||||
YieldAtRootLayer: class { constructor(layer) { return layer; } },
|
||||
createInProcessWindow: (options) => { window = options; return { requestRender: () => renders++ }; },
|
||||
},
|
||||
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
|
||||
'../../g2/android-permissions': { hasLocationPermission: () => false },
|
||||
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
|
||||
'./calibration-layer': {},
|
||||
'./declination': { onDeclinationChanged: () => () => {} },
|
||||
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
|
||||
};
|
||||
const app = load('app/apps/compass/compass-app.ts', (name) => {
|
||||
assert.ok(name in modules, `Unexpected dependency: ${name}`);
|
||||
return modules[name];
|
||||
}, { setInterval: () => 1, clearInterval() {} });
|
||||
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => pops++ } };
|
||||
const open = () => app.createCompassAppWindow({ onClosed() {} });
|
||||
open();
|
||||
return {
|
||||
settings, open,
|
||||
menu: () => window.menuItems(),
|
||||
toggle: () => window.menuItems().find((item) => item.label.startsWith('Style:')).onSelect(ctx),
|
||||
paint: () => window.baseLayer.paint(ctx),
|
||||
heading: (degrees) => listener({ command: 1, headingDegrees: degrees }),
|
||||
renders: () => renders,
|
||||
pops: () => pops,
|
||||
};
|
||||
}
|
||||
|
||||
test('Circle is the default; the context menu switches, repaints and remembers the style', () => {
|
||||
const app = compass();
|
||||
assert.equal(app.menu()[0].label, 'Style: Circle');
|
||||
const before = app.renders();
|
||||
app.toggle();
|
||||
assert.equal(app.menu()[0].label, 'Style: Strip');
|
||||
assert.equal(app.settings.get('compass.style'), 'strip');
|
||||
assert.equal(app.renders(), before + 1);
|
||||
assert.equal(app.pops(), 1);
|
||||
app.open();
|
||||
assert.equal(app.menu()[0].label, 'Style: Strip');
|
||||
app.toggle();
|
||||
assert.equal(app.menu()[0].label, 'Style: Circle');
|
||||
assert.equal(compass({ style: 'unknown' }).menu()[0].label, 'Style: Circle');
|
||||
});
|
||||
|
||||
test('switching styles preserves the numeric readout and status at every display size', () => {
|
||||
for (const [width, height] of [[576, 260], [576, 452], [640, 452]]) {
|
||||
const app = compass({ width, height });
|
||||
app.heading(82);
|
||||
const circle = app.paint();
|
||||
app.toggle();
|
||||
const strip = app.paint();
|
||||
assert.deepEqual(strip.texts.slice(0, 2), circle.texts);
|
||||
assert.deepEqual(circle.texts.map((item) => item.text), ['82° E', 'Magnetic heading']);
|
||||
}
|
||||
});
|
||||
|
||||
test('strip ticks are 5 degrees apart on the full-display 23 degree scale', () => {
|
||||
for (const width of [576, 640]) {
|
||||
const app = compass({ style: 'strip', width });
|
||||
app.heading(90);
|
||||
const image = app.paint();
|
||||
const top = image.lines[0][1];
|
||||
const ticks = image.lines.filter(([x0, y0, x1]) => x0 === x1 && y0 === top);
|
||||
assert.deepEqual(ticks.map(([x]) => x), [80, 85, 90, 95, 100]
|
||||
.map((bearing) => Math.round(width - 320 + (bearing - 90) * 640 / 23))
|
||||
.filter((x) => x >= 0 && x < width));
|
||||
assert.equal(image.lines[0][0], 0);
|
||||
assert.equal(image.lines[0][2], width - 1);
|
||||
assert.equal(image.lines[1][1], image.height - 4);
|
||||
assert.ok(image.texts.some(({ text }) => text === 'E'));
|
||||
}
|
||||
});
|
||||
|
||||
test('bearings scroll continuously through north with wrapped labels', () => {
|
||||
const app = compass({ style: 'strip' });
|
||||
const northX = (heading) => {
|
||||
app.heading(heading);
|
||||
const image = app.paint();
|
||||
const north = image.texts.find(({ text }) => text === 'N');
|
||||
assert.ok(north);
|
||||
assert.ok(image.texts.some(({ text }) => text === '355°'));
|
||||
assert.ok(image.texts.some(({ text }) => text === '5°'));
|
||||
return north.x;
|
||||
};
|
||||
assert.ok(Math.abs(northX(359.9) - northX(0.1) - 0.2 * 640 / 23) <= 1);
|
||||
});
|
||||
|
||||
test('a strip waiting for sensor data shows the rails without invented bearings', () => {
|
||||
const app = compass({ style: 'strip' });
|
||||
const image = app.paint();
|
||||
assert.deepEqual(image.texts.map(({ text }) => text), ['--°', 'Waiting for compass data…']);
|
||||
assert.equal(image.lines.length, 2);
|
||||
assert.ok(image.lines[0][4] < 105);
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function load(file, modules = {}, extra = '', globals = {}) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8') + extra;
|
||||
const context = { exports: {}, require: (name) => {
|
||||
assert.ok(name in modules, `Unexpected dependency: ${name}`);
|
||||
return modules[name];
|
||||
}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context, { filename: file });
|
||||
return context.exports;
|
||||
}
|
||||
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
|
||||
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
|
||||
const { GrayImage } = graphics;
|
||||
const font = (size) => BdfFont.parse(fs.readFileSync(
|
||||
path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
|
||||
const small = font(12);
|
||||
const large = font(24);
|
||||
let viewportWidth = 576;
|
||||
const compass = load('app/apps/compass/compass-app.ts', {
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
|
||||
'../../graphics/image': graphics,
|
||||
'../../graphics/textwrap': textwrap,
|
||||
'../../native/compass': {},
|
||||
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
|
||||
'../../ui/shell/geometry': { screenCenterInViewportX: () => viewportWidth - 320 },
|
||||
'../../ui/shell/in-process-window': {},
|
||||
'../../ui/shell/shell': {},
|
||||
'../../g2/android-permissions': {},
|
||||
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
|
||||
'./calibration-layer': {},
|
||||
'./declination': {},
|
||||
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
|
||||
}, `
|
||||
export { CompassLayer, rotatingRoseBounds, createCompassBackground, drawCompassRose };
|
||||
export function referenceFrame(width, height, cx, cy, radius, clipY, heading) {
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const fade = heading === null ? 0.45 : 1;
|
||||
drawPlaneGrid(image, cx, cy, radius, clipY);
|
||||
drawDiscWall(image, cx, cy, radius, fade);
|
||||
drawTiltedRing(image, cx, cy, radius, 105 * fade);
|
||||
drawCompassRose(image, cx, cy, radius, heading);
|
||||
drawHeadingTick(image, cx, cy, radius, 255 * fade);
|
||||
return image;
|
||||
}
|
||||
`);
|
||||
|
||||
test('rotation bounds contain every painted point through a full turn', () => {
|
||||
for (const radius of [24, 60, 98]) {
|
||||
const cx = 120;
|
||||
const cy = 70.25;
|
||||
const bounds = compass.rotatingRoseBounds(cx, cy, radius);
|
||||
assert.ok(bounds.width <= 255 && bounds.height <= 255, 'fits a cache image');
|
||||
const image = new GrayImage(240, 160, 0);
|
||||
// Accumulate the entire sweep, including fractional-degree orientations.
|
||||
for (let heading = 0; heading < 360; heading += 0.5) {
|
||||
compass.drawCompassRose(image, cx, cy, radius, heading);
|
||||
}
|
||||
let count = 0;
|
||||
for (let y = 0; y < image.height; y++) {
|
||||
for (let x = 0; x < image.width; x++) {
|
||||
if (!image.getPixel(x, y)) continue;
|
||||
count++;
|
||||
assert.ok(x >= bounds.x && x < bounds.x + bounds.width
|
||||
&& y >= bounds.y && y < bounds.y + bounds.height, `point outside bounds at ${x},${y}`);
|
||||
}
|
||||
}
|
||||
assert.ok(count > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('cached background preserves the raster and tick layering at every heading', () => {
|
||||
for (const [width, height, radius] of [[576, 260, 98], [640, 452, 98], [240, 160, 24]]) {
|
||||
const cx = width / 2;
|
||||
const cy = height - 65.25;
|
||||
for (const heading of [null, ...Array.from({ length: 72 }, (_, i) => i * 5)]) {
|
||||
const background = compass.createCompassBackground(width, height, cx, cy, radius, 30, heading === null ? 0.45 : 1);
|
||||
const image = background.clone();
|
||||
compass.drawCompassRose(image, cx, cy, radius, heading);
|
||||
const expected = compass.referenceFrame(width, height, cx, cy, radius, 30, heading);
|
||||
assert.deepEqual(image.withDrawsBaked().pixels, expected.pixels, `heading ${heading}, radius ${radius}`);
|
||||
assert.equal(image.draws.length, 1);
|
||||
const draw = image.draws[0];
|
||||
assert.equal(draw.kind, 'image');
|
||||
assert.equal(draw.source.hasDeferredDraws(), false);
|
||||
const bounds = compass.rotatingRoseBounds(cx, cy, radius);
|
||||
assert.deepEqual({ x: draw.x, y: draw.y, width: draw.source.width, height: draw.source.height }, { ...bounds });
|
||||
// Every nonzero texture pixel must match the final composite, as the
|
||||
// wire planner requires before it can replay a cached image.
|
||||
for (let y = 0; y < draw.source.height; y++) {
|
||||
for (let x = 0; x < draw.source.width; x++) {
|
||||
const value = draw.source.getPixel(x, y);
|
||||
if (value) assert.equal(value, expected.getPixel(draw.x + x, draw.y + y));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('heading updates reuse the texture; brightness, layout and clipping changes rebuild it', () => {
|
||||
const layer = new compass.CompassLayer(() => {});
|
||||
layer.enabled = true;
|
||||
let height = 260;
|
||||
const ctx = { stack: { getBaseSize: () => ({ width: viewportWidth, height }) } };
|
||||
const texture = () => layer.paint(ctx).draws.find((draw) => draw.kind === 'image').source;
|
||||
const waiting = texture();
|
||||
layer.rawHeading = 0;
|
||||
const initial = texture();
|
||||
assert.notEqual(initial, waiting);
|
||||
const snapshot = initial.pixels.slice();
|
||||
for (const heading of [1, 45, 180, 359.9, 0]) {
|
||||
layer.rawHeading = heading;
|
||||
assert.equal(texture(), initial);
|
||||
}
|
||||
assert.deepEqual(initial.pixels, snapshot, 'shared texture remains immutable');
|
||||
height = 452;
|
||||
const tall = texture();
|
||||
assert.notEqual(tall, initial);
|
||||
viewportWidth = 640;
|
||||
const wide = texture();
|
||||
assert.notEqual(wide, tall);
|
||||
layer.firmwareStatus = 'Calibration status '.repeat(12);
|
||||
assert.notEqual(texture(), wide);
|
||||
viewportWidth = 576;
|
||||
});
|
||||
|
||||
test('the background registers once and uses a nine-byte image reference on later frames', () => {
|
||||
const registered = [];
|
||||
const { prepareFrameDraws } = load('app/graphics/glyph-wire.ts', {}, '', {
|
||||
global: { isAndroid: true },
|
||||
com: { faceclaw: { app: { ImageAtlas: { ensure: (...args) => {
|
||||
registered.push(args);
|
||||
return 1;
|
||||
} } } } },
|
||||
});
|
||||
const background = compass.createCompassBackground(576, 260, 256, 193.25, 98, 140, 1);
|
||||
for (const heading of [0, 1, 2, 45, 90]) {
|
||||
const image = background.clone();
|
||||
compass.drawCompassRose(image, 256, 193.25, 98, heading);
|
||||
const buffer = prepareFrameDraws(image.draws);
|
||||
assert.equal(buffer.byteLength, 9);
|
||||
assert.equal(new DataView(buffer).getUint8(0), 1);
|
||||
}
|
||||
assert.equal(registered.length, 1);
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CompassProtocolTest {
|
||||
private static byte[] hex(String value) {
|
||||
byte[] bytes = new byte[value.length() / 2];
|
||||
for (int i = 0; i < bytes.length; i++) bytes[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
|
||||
return bytes;
|
||||
}
|
||||
private static BleProtocol.CompassEvent parse(byte[] payload) {
|
||||
return parse(payload, BleProtocol.FLAG_NOTIFY);
|
||||
}
|
||||
private static BleProtocol.CompassEvent parse(byte[] payload, int flag) {
|
||||
byte[] frame = BleProtocol.framePb(payload, 8, flag, 15).get(0);
|
||||
return BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame));
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// Golden packet also checked against the real C encoder in g2flash's host test.
|
||||
byte[] packet = hex("080f1000520308e702a2060c434d010302038c0098badcfe");
|
||||
BleProtocol.CompassEvent event = parse(packet);
|
||||
assert event.headingDegrees == 359 && event.command == 15;
|
||||
assert event.magneticAccuracy == 3 && event.magneticAnomalies == 2;
|
||||
assert event.orientationSource == 3 && event.diagnosticFlags == 0x8c;
|
||||
assert event.sampleTimeMs == 0xfedcba98L; // unsigned 32-bit timestamp through Java long
|
||||
assert parse(packet, BleProtocol.FLAG_NOTIFY_ALT).headingDegrees == 359;
|
||||
assert parse(packet, BleProtocol.FLAG_REQUEST) == null;
|
||||
assert parse(packet, 0) == null;
|
||||
byte[] legacy = Arrays.copyOf(packet, 9);
|
||||
event = parse(legacy);
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
for (int n = 9; n < packet.length; ++n) {
|
||||
event = parse(Arrays.copyOf(packet, n));
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
}
|
||||
for (int offset : new int[] {12, 13, 14, 15, 16, 17, 19}) {
|
||||
byte[] invalid = packet.clone(); invalid[offset] = 99;
|
||||
event = parse(invalid);
|
||||
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
|
||||
}
|
||||
packet[15] = packet[16] = (byte)255; packet[17] = 0; packet[18] = 0;
|
||||
event = parse(packet);
|
||||
assert event.magneticAccuracy == -1 && event.magneticAnomalies == -1;
|
||||
assert event.orientationSource == 0 && event.diagnosticFlags == 0;
|
||||
event = parse(hex("08101000"));
|
||||
assert event.command == 16 && event.headingDegrees == -1 && event.diagnosticFlags == -1;
|
||||
event = parse(hex("08111000"));
|
||||
assert event.command == 17 && event.diagnosticFlags == -1;
|
||||
assert parse(hex("080f1000520308e802")) == null; // 360 isn't a heading
|
||||
assert BleProtocol.parseCompassEvent(null) == null;
|
||||
System.out.println("Compass protocol checks passed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
const alerts = require('../.test-build/app/apps/nightscout/nightscout-alerts.js');
|
||||
const now = 1_800_000_000_000;
|
||||
const limits = { maxCannulaAgeHours: 72, cartridgeLowUnits: 20, batteryLowVoltage: 1.2, maxLoopAgeMinutes: 15 };
|
||||
const healthy = { cageTimestampMs: now, reservoirUnits: 100, batteryVoltage: 1.5, loopTimestampMs: now };
|
||||
|
||||
function load(file, dependencies, globals = {}) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const context = { exports: {}, require(name) { assert.ok(name in dependencies, name); return dependencies[name]; }, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
|
||||
test('each threshold breaches independently, with strict boundaries and zero disabling it', () => {
|
||||
const cases = [
|
||||
['cageTimestampMs', 'maxCannulaAgeHours', 'cannula', now - 72 * 3_600_000, -1],
|
||||
['reservoirUnits', 'cartridgeLowUnits', 'cartridge', 20, -0.01],
|
||||
['batteryVoltage', 'batteryLowVoltage', 'battery', 1.2, -0.01],
|
||||
['loopTimestampMs', 'maxLoopAgeMinutes', 'loop', now - 15 * 60_000, -1],
|
||||
];
|
||||
for (const [field, threshold, warning, boundary, delta] of cases) {
|
||||
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary }, limits, now).any, false);
|
||||
const result = alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, limits, now);
|
||||
assert.equal(result[warning], true);
|
||||
assert.equal(result.any, true);
|
||||
assert.equal(Object.values(result).filter(Boolean).length, 2);
|
||||
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, { ...limits, [threshold]: 0 }, now).any, false);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing/invalid measurements do not alert; real empty reservoirs do', () => {
|
||||
for (const value of [null, NaN, -1, Infinity]) {
|
||||
const values = Object.fromEntries(Object.keys(healthy).map(key => [key, value]));
|
||||
assert.equal(alerts.evaluateNightscoutAlerts(values, limits, now).any, false);
|
||||
}
|
||||
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, reservoirUnits: 0 }, limits, now).cartridge, true);
|
||||
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, loopTimestampMs: now + 60_000 }, limits, now).loop, false);
|
||||
for (const value of ['', '-2', 'NaN', 'Infinity', '12abc', null]) assert.equal(alerts.normalizeNightscoutThreshold(value), '0');
|
||||
assert.equal(alerts.normalizeNightscoutThreshold(' 1.25 '), '1.25');
|
||||
assert.equal(alerts.normalizeNightscoutThreshold('.5'), '0.5');
|
||||
});
|
||||
|
||||
class Image {
|
||||
constructor(width, height) { this.width = width; this.height = height; this.draws = []; }
|
||||
drawText(font, ...args) { this.draws.push(['text', ...args]); }
|
||||
drawLine(...args) { this.draws.push(['line', ...args]); }
|
||||
fillRect(...args) { this.draws.push(['rect', ...args]); }
|
||||
}
|
||||
const font = { measureText: text => text.length * 6, lineHeight: 12, hasGlyph: () => true };
|
||||
function fixture(always = false) {
|
||||
let time = now, icon, tick, changed, notify, renders = 0;
|
||||
const state = { ...healthy, available: true, latest: { sgv: 100, timestampMs: now }, history: [], units: 'mg/dL', delta: 0, direction: '', iob: 1, cob: 0, pumpStatus: '0m ago', configurationMissing: false };
|
||||
const bridge = { snapshot: () => state, onStateChange(fn) { notify = fn; fn(state); } };
|
||||
const settings = { loadNightscoutThresholds: () => limits, nightscoutAlwaysShowInTopBarSetting: { get: () => always }, onAnySettingChanged(fn) { changed = fn; }, isNightscoutSettingsConfigured: () => true };
|
||||
const deps = {
|
||||
'../../graphics/image': { GrayImage: Image },
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultLargeFont: () => font },
|
||||
'../../native/nightscout-bridge': { nightscoutBridge: bridge },
|
||||
'../../ui/dashboard-settings': settings,
|
||||
'./nightscout-alerts': alerts,
|
||||
};
|
||||
const app = load('app/apps/nightscout/nightscout-app.ts', {
|
||||
...deps,
|
||||
'./nightscout': { NightscoutLayer: class {}, nightscoutMenuItems() {} },
|
||||
'../../ui/shell/shell': { shell: { setTrayIcon(id, value) { icon = value; } } },
|
||||
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: options => ({ close: options.onClosed, requestRender() { renders++; } }) },
|
||||
}, { Date: { now: () => time }, setInterval(fn) { tick = fn; return 1; }, clearInterval() { tick = null; } });
|
||||
return { app, deps, state, icon: () => icon, tick: () => tick?.(), advance(ms) { time += ms; }, notify: () => notify(), toggle(value) { always = value; changed(); }, renders: () => renders };
|
||||
}
|
||||
|
||||
test('tray boots without a window, persists on close, and responds to settings and elapsed time', () => {
|
||||
const f = fixture(true);
|
||||
f.app.startNightscoutTrayIcon();
|
||||
assert.ok(f.icon());
|
||||
const width = f.icon().width;
|
||||
f.advance(16 * 60_000); f.tick();
|
||||
assert.equal(f.icon().width, width + 24);
|
||||
const triangle = f.icon().draws.filter(d => d[0] === 'line' && d.at(-1) === 255);
|
||||
assert.equal(triangle.length, 3);
|
||||
assert.ok(triangle.every(d => d[1] > width && d[3] > width));
|
||||
f.toggle(false); assert.equal(f.icon(), null);
|
||||
const window = f.app.createNightscoutAppWindow({ onClosed() {} });
|
||||
assert.ok(f.icon());
|
||||
f.toggle(true); window.close(); assert.ok(f.icon());
|
||||
const renders = f.renders(); f.notify(); assert.equal(f.renders(), renders);
|
||||
f.toggle(false); assert.equal(f.icon(), null);
|
||||
const reopened = f.app.createNightscoutAppWindow({ onClosed() {} });
|
||||
reopened.close(); assert.equal(f.icon(), null);
|
||||
});
|
||||
|
||||
test('tray is hidden by default and clears recovered measurement warnings immediately', () => {
|
||||
const f = fixture();
|
||||
f.app.startNightscoutTrayIcon();
|
||||
assert.equal(f.icon(), null);
|
||||
const first = f.app.createNightscoutAppWindow({ onClosed() {} });
|
||||
const width = f.icon().width;
|
||||
f.state.batteryVoltage = 1;
|
||||
f.notify(); assert.equal(f.icon().width, width + 24);
|
||||
f.state.batteryVoltage = 1.5;
|
||||
f.notify(); assert.equal(f.icon().width, width);
|
||||
const second = f.app.createNightscoutAppWindow({ onClosed() {} });
|
||||
first.close(); assert.ok(f.icon());
|
||||
second.close(); assert.equal(f.icon(), null);
|
||||
});
|
||||
|
||||
test('main page highlights only the breached field and removes highlights on recovery', () => {
|
||||
const f = fixture();
|
||||
const page = load('app/apps/nightscout/nightscout.ts', {
|
||||
...f.deps,
|
||||
'../../graphics/textwrap': { truncateText: (font, text) => text },
|
||||
'../../ui/gestures': {}, '../../ui/layers': {}, '../../ui/menu': {},
|
||||
'../../ui/dashboard/settings-panel': {}, '../../ui/metrics': { lineStep: () => 16 },
|
||||
'~/util/date-util': { formatAgeShortFromTimestamp: () => '1m', formatTimestamp: () => '12:00' },
|
||||
}, { Date: { now: () => now } });
|
||||
const layer = new page.NightscoutLayer();
|
||||
const paint = () => layer.paint({ stack: { getBaseSize: () => ({ width: 576, height: 260 }) } });
|
||||
for (const [field, value, label] of [['reservoirUnits', 10, '10U'], ['batteryVoltage', 1, '1.00V'], ['cageTimestampMs', now - 73 * 3_600_000, 'CAGE 1m'], ['loopTimestampMs', now - 16 * 60_000, 'Loop 1m']]) {
|
||||
f.state[field] = value;
|
||||
const image = paint();
|
||||
const highlighted = image.draws.filter(d => d[0] === 'text' && d.at(-1) === 0);
|
||||
assert.equal(highlighted.length, 1);
|
||||
assert.equal(highlighted[0][3], label);
|
||||
f.state[field] = healthy[field];
|
||||
assert.equal(paint().draws.filter(d => d[0] === 'text' && d.at(-1) === 0).length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('bridge exposes numeric measurements and treats absent values as unknown', async () => {
|
||||
let pump = { reservoir: '10.5', battery: { voltage: '1.15' } };
|
||||
const module = load('app/native/nightscout-bridge.ts', {
|
||||
'../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
|
||||
'../util/http': { async fetchWithUserAgent(url) {
|
||||
const body = url.includes('/entries.') ? [{ date: now, sgv: 100 }] : url.includes('/devicestatus.') ? [{ pump, openaps: { suggested: { mills: now - 60_000 } } }] : url.includes('/status.') ? {} : [];
|
||||
return { ok: true, json: async () => body };
|
||||
} },
|
||||
}, { Date, console });
|
||||
const bridge = new module.NightscoutBridge();
|
||||
await bridge.refreshNow();
|
||||
assert.equal(bridge.snapshot().reservoirUnits, 10.5);
|
||||
assert.equal(bridge.snapshot().batteryVoltage, 1.15);
|
||||
assert.equal(bridge.snapshot().loopTimestampMs, now - 60_000);
|
||||
pump = { reservoir: null, battery: { voltage: '' } };
|
||||
await bridge.refreshNow();
|
||||
assert.equal(bridge.snapshot().reservoirUnits, null);
|
||||
assert.equal(bridge.snapshot().batteryVoltage, null);
|
||||
pump = { reservoir: 0, battery: { voltage: 0 } };
|
||||
await bridge.refreshNow();
|
||||
assert.equal(bridge.snapshot().reservoirUnits, 0);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function evaluate(source, requireModule, globals = {}) {
|
||||
const context = { exports: {}, require: requireModule, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
const source = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const load = (file, requireModule) => evaluate(source(file), requireModule);
|
||||
|
||||
function store(settings = new Map()) {
|
||||
return load('app/native/notification-sources.ts', () => ({
|
||||
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||
setStringSetting: (key, value) => settings.set(key, value),
|
||||
}));
|
||||
}
|
||||
const mail = { packageName: 'com.mail', appName: 'Mail' };
|
||||
|
||||
test('sources default on and retain per-package choices and names across restart and rediscovery', () => {
|
||||
const settings = new Map();
|
||||
let prefs = store(settings);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
prefs.rememberNotificationSources([mail, mail, { packageName: 'com.other', appName: 'Mail' }]);
|
||||
assert.equal(prefs.readNotificationSources().length, 2);
|
||||
prefs.setNotificationSourceEnabled({ ...mail, text: 'private notification content' }, false);
|
||||
assert.ok(!Array.from(settings.values()).join('').includes('private notification content'));
|
||||
prefs = store(settings);
|
||||
prefs.rememberNotificationSources([{ ...mail, appName: 'Renamed Mail' }, { packageName: 'com.new', appName: '' }]);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('com.other'), true);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('com.new'), true);
|
||||
assert.equal(prefs.readNotificationSources().find((s) => s.packageName === mail.packageName).appName, 'Renamed Mail');
|
||||
prefs.setNotificationSourceEnabled(mail, true);
|
||||
assert.equal(store(settings).shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
});
|
||||
|
||||
test('invalid saved source data falls back to enabled', () => {
|
||||
for (const raw of ['invalid', '{}', '[null, {}, {"packageName": 1}]']) {
|
||||
assert.equal(store(new Map([['notifications.sources', raw]])).shouldShowNotificationOnGlasses('com.mail'), true);
|
||||
}
|
||||
});
|
||||
|
||||
function ui(fontSize = 12) {
|
||||
const prefs = store();
|
||||
let active = [{ ...mail, key: 'key', title: 'Message', text: 'Hello', bigText: '', lines: [], actions: [], postTime: 0 }];
|
||||
let dismissals = 0;
|
||||
let closes = 0;
|
||||
const textwrap = load('app/graphics/textwrap.ts');
|
||||
const graphics = load('app/graphics/image.ts', () => textwrap);
|
||||
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
|
||||
const font = BdfFont.parse(source(`app/fonts/terminus/ter-u${fontSize}n.bdf`));
|
||||
class RecordingImage extends graphics.GrayImage {
|
||||
texts = [];
|
||||
drawText(font, x, y, text, value) {
|
||||
this.texts.push({ x, y, text });
|
||||
super.drawText(font, x, y, text, value);
|
||||
}
|
||||
}
|
||||
const native = {
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => { prefs.rememberNotificationSources(active); return active; },
|
||||
dismissNotification: () => { dismissals++; active = []; return true; },
|
||||
readNotificationIconByKey: () => ({ icon: null, stale: false }),
|
||||
};
|
||||
const dependencies = {
|
||||
'../graphics/image': { ...graphics, GrayImage: RecordingImage },
|
||||
'../graphics/textwrap': textwrap,
|
||||
'../graphics/ui-fonts': { getDefaultSmallFont: () => font },
|
||||
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
|
||||
'~/util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
|
||||
'~/util/date-util': { formatRelativeTime: () => '' },
|
||||
'../native/notification-icons': native,
|
||||
'../native/notification-sources': prefs,
|
||||
'../native/notification-access': { isNotificationListenerEnabled: () => true },
|
||||
'../util/render-freshness': { renderPassAllowsStaleData: () => false },
|
||||
'./metrics': load('app/ui/metrics.ts'),
|
||||
'./gestures': {},
|
||||
};
|
||||
const requireModule = (name) => {
|
||||
assert.ok(name in dependencies, `Unexpected dependency ${name}`);
|
||||
return dependencies[name];
|
||||
};
|
||||
dependencies['./menu'] = load('app/ui/menu.ts', requireModule);
|
||||
const { SingleNotificationLayer } = load('app/ui/notifications.ts', requireModule);
|
||||
const { NotificationFilterLayer } = load('app/ui/notification-filter.ts', requireModule);
|
||||
const ctx = { stack: { getBaseSize: () => ({ width: 540, height: 224 }), isFocused: () => true, pop: () => closes++ } };
|
||||
const popup = new SingleNotificationLayer('key', { origin: 'new-notification-modal', closeModal: () => closes++ });
|
||||
const filter = new NotificationFilterLayer();
|
||||
const paint = (layer) => layer.paint(ctx, () => new RecordingImage(540, 224));
|
||||
const input = (layer, type) => layer.handleInput({ type }, ctx);
|
||||
return { prefs, popup, filter, paint, input, active: (value) => { active = value; },
|
||||
dismissals: () => dismissals, closes: () => closes };
|
||||
}
|
||||
|
||||
test('popup dismisses before confirmation; confirming disables the source even after the notification disappears', async () => {
|
||||
const app = ui();
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'click');
|
||||
assert.equal(app.dismissals(), 1);
|
||||
assert.equal(app.closes(), 0);
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
assert.ok(app.paint(app.popup).texts.some(({ text }) => text.includes('Mail')));
|
||||
assert.equal(app.closes(), 0);
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
assert.equal(app.closes(), 1);
|
||||
});
|
||||
|
||||
test('cancel and back dismiss the popup without changing source preferences', async () => {
|
||||
for (const cancel of ['click', 'double-click']) {
|
||||
const app = ui();
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'click');
|
||||
await app.input(app.popup, cancel);
|
||||
assert.equal(app.dismissals(), 1);
|
||||
assert.equal(app.closes(), 1);
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('filter toggles persist after notifications disappear and discovers new sources while open', async () => {
|
||||
const app = ui();
|
||||
app.paint(app.filter);
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
app.active([{ packageName: 'com.alpha', appName: 'Alpha' }]);
|
||||
const image = app.paint(app.filter);
|
||||
assert.ok(image.texts.some(({ text }) => text === 'Alpha'));
|
||||
assert.ok(image.texts.some(({ text }) => text === 'Mail'));
|
||||
// A source inserted before the selection must not move the toggle to another app.
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses('com.alpha'), true);
|
||||
});
|
||||
|
||||
test('popup action wraps fully and stays visible with small and large fonts', async () => {
|
||||
for (const size of [12, 20]) {
|
||||
const app = ui(size);
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
await app.input(app.popup, 'scroll-down');
|
||||
const image = app.paint(app.popup);
|
||||
assert.ok(image.texts.map(({ text }) => text).join(' ').includes("Don't show on glasses again"));
|
||||
assert.ok(image.texts.every(({ y }) => y >= 0 && y < image.height));
|
||||
}
|
||||
});
|
||||
|
||||
test('controller filters before waking or opening a popup, and still refreshes the tray', async () => {
|
||||
const file = ts.createSourceFile('controller.ts', source('app/g2/dashboard-controller.ts'), ts.ScriptTarget.Latest, true);
|
||||
const controller = file.statements.find((node) => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
|
||||
const handler = controller.members.find((node) => node.name?.getText(file) === 'handleAndroidNotificationPosted');
|
||||
const prefs = store();
|
||||
let wakes = 0, popups = 0, renders = 0;
|
||||
const { Harness } = evaluate(`export class Harness { ${handler.getText(file)} }`, null, {
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => [{ ...mail, key: 'key' }],
|
||||
shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
|
||||
shell: { isScreenOn: () => false, wake: () => { wakes++; return true; }, openNotificationModal: () => popups++ },
|
||||
});
|
||||
const instance = new Harness();
|
||||
instance.requestShellRender = () => renders++;
|
||||
instance.appendLog = () => {};
|
||||
prefs.setNotificationSourceEnabled(mail, false);
|
||||
await instance.handleAndroidNotificationPosted('key');
|
||||
await instance.handleAndroidNotificationPosted('gone');
|
||||
assert.equal(wakes, 0);
|
||||
assert.equal(popups, 0);
|
||||
assert.equal(renders, 2);
|
||||
prefs.setNotificationSourceEnabled(mail, true);
|
||||
await instance.handleAndroidNotificationPosted('key');
|
||||
assert.equal(wakes, 1);
|
||||
assert.equal(popups, 1);
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
const read = file => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||
const js = source => ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText;
|
||||
|
||||
// Run the worker's actual activity and lifecycle code with platform work stubbed.
|
||||
function worker() {
|
||||
let now = 100_000, timer, renderCount = 0;
|
||||
const messages = [];
|
||||
const file = 'app/apps/terminal/terminal-app.worker.ts';
|
||||
const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
|
||||
const functions = new Set(['recencyKey', 'post', 'renderHubWindows', 'isSessionActive', 'isWindowSessionActive', 'hubAnimationShouldRun', 'syncWindowIconActivity', 'updateHubAnimation', 'noteSessionActivity', 'openWindow', 'closeWindow']);
|
||||
const variables = new Set(['windows', 'pendingViews', 'activeViewId', 'sessionRecency', 'sessionActivity', 'ACTIVITY_ACTIVE_MS', 'HUB_ANIMATION_STEP_MS', 'hubAnimationPhase', 'hubAnimationTimer', 'windowIconActivity', 'screenOn']);
|
||||
const selected = source.statements.filter(s =>
|
||||
ts.isFunctionDeclaration(s) && functions.has(s.name?.text) ||
|
||||
ts.isVariableStatement(s) && s.declarationList.declarations.some(d => variables.has(d.name.getText(source))) ||
|
||||
ts.isExpressionStatement(s) && ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage');
|
||||
const context = {
|
||||
exports: {}, Date: { now: () => now },
|
||||
setInterval(fn, ms) { assert.equal(ms, 800); assert.equal(timer, undefined); timer = fn; return 1; },
|
||||
clearInterval() { timer = undefined; },
|
||||
global: { postMessage: message => messages.push(message) },
|
||||
scheduleRender() { renderCount++; }, renderAndSubmit() {}, maybeReconnectView() {},
|
||||
controlsInitialized: true, controls: new Map(), TERMINAL_TOOLS: [],
|
||||
getTerminalFontConfig: () => ({ cellWidth: 6, cellHeight: 12 }),
|
||||
};
|
||||
vm.runInNewContext(js(selected.map(s => s.getText(source)).join('\n')) + '\nexports.windows = windows;', context);
|
||||
const message = data => context.global.onmessage({ data });
|
||||
return {
|
||||
messages, windows: context.exports.windows,
|
||||
activity: (connection = 'host1', socket = 'a') => context.noteSessionActivity(connection, socket),
|
||||
openHub() { context.openWindow('hub', 'surface:hub', 'Terminal', { width: 576, height: 260 }); },
|
||||
addView(id, connectionId = 'host1', socket = 'a') {
|
||||
context.exports.windows.set(id, { windowId: id, kind: 'view', connectionId, socket, foreground: false, unsubscribers: [], client: { stop() {} } });
|
||||
context.updateHubAnimation();
|
||||
},
|
||||
close: id => context.closeWindow(id),
|
||||
screen: on => message({ type: 'screen', on }),
|
||||
advance(ms) { now += ms; timer?.(); },
|
||||
running: () => !!timer,
|
||||
phase(id) { return messages.filter(m => m.type === 'set-icon-activity' && m.windowId === id).at(-1)?.activity ?? 'idle'; },
|
||||
};
|
||||
}
|
||||
|
||||
test('background hub aggregates activity; session icons match both host and socket', () => {
|
||||
const w = worker();
|
||||
w.openHub(); w.addView('a'); w.addView('b', 'host1', 'b'); w.addView('other-host', 'host2', 'a');
|
||||
assert.equal(w.running(), false);
|
||||
w.activity();
|
||||
assert.equal(w.phase('hub'), 'on'); assert.equal(w.phase('a'), 'on');
|
||||
assert.equal(w.phase('b'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
|
||||
w.advance(800);
|
||||
assert.equal(w.phase('hub'), 'off'); assert.equal(w.phase('a'), 'off');
|
||||
w.advance(800); assert.equal(w.phase('a'), 'on');
|
||||
w.activity('host2', 'a'); assert.equal(w.phase('other-host'), 'on');
|
||||
w.advance(3400);
|
||||
assert.equal(w.phase('a'), 'idle'); assert.notEqual(w.phase('hub'), 'idle');
|
||||
w.advance(1600);
|
||||
assert.equal(w.phase('hub'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
|
||||
assert.equal(w.running(), false);
|
||||
});
|
||||
|
||||
test('animation continues with hub closed and stops after the final window closes', () => {
|
||||
const w = worker();
|
||||
w.openHub(); w.addView('a'); w.activity(); w.close('hub');
|
||||
w.advance(800); assert.equal(w.phase('a'), 'off'); assert.equal(w.running(), true);
|
||||
w.close('a'); assert.equal(w.running(), false);
|
||||
w.activity(); assert.equal(w.running(), false);
|
||||
w.openHub(); assert.equal(w.phase('hub'), 'on'); assert.equal(w.running(), true);
|
||||
});
|
||||
|
||||
test('screen off pauses animation; wake recalculates fresh and expired activity', () => {
|
||||
const w = worker();
|
||||
w.addView('a'); w.activity(); w.screen(false);
|
||||
assert.equal(w.running(), false);
|
||||
w.advance(1000); w.screen(true);
|
||||
assert.equal(w.phase('a'), 'on'); assert.equal(w.running(), true);
|
||||
w.screen(false); w.advance(5000); w.screen(true);
|
||||
assert.equal(w.phase('a'), 'idle'); assert.equal(w.running(), false);
|
||||
});
|
||||
|
||||
test('unopened sessions activate the hub and repeated pushes extend activity without duplicate messages', () => {
|
||||
const w = worker();
|
||||
w.openHub(); w.activity('host2', 'unopened');
|
||||
assert.equal(w.phase('hub'), 'on');
|
||||
const count = w.messages.length; w.activity('host2', 'unopened'); assert.equal(w.messages.length, count);
|
||||
w.advance(4000); w.activity('host2', 'unopened'); w.advance(2000);
|
||||
assert.notEqual(w.phase('hub'), 'idle');
|
||||
w.advance(3000); assert.equal(w.phase('hub'), 'idle');
|
||||
});
|
||||
|
||||
function load(file, deps, globals = {}) {
|
||||
const context = { exports: {}, require(name) { assert.ok(name in deps, name); return deps[name]; }, ...globals };
|
||||
vm.runInNewContext(js(read(file)), context);
|
||||
return context.exports;
|
||||
}
|
||||
|
||||
class Image {
|
||||
constructor(width, height) { this.width = width; this.height = height; this.pixels = new Uint8Array(width * height); }
|
||||
}
|
||||
|
||||
test('cursor replaces only the prompt; marker and frame persist across cached blink phases', () => {
|
||||
const renders = [];
|
||||
const icons = load('app/graphics/icons.ts', { './image': { GrayImage: Image } }, {
|
||||
global: { isAndroid: true },
|
||||
com: { faceclaw: { app: { IconRenderer: { renderSvgGray(svg, size, stroke) {
|
||||
renders.push(svg); assert.equal(stroke, 2); return new Uint8Array(size * size).fill(255);
|
||||
} } } } },
|
||||
});
|
||||
for (const glyph of ['', '1', '3', 'A']) {
|
||||
const idle = icons.renderIconWithGlyph('terminal', glyph, 24, 'idle');
|
||||
const idleSvg = renders.at(-1);
|
||||
const on = icons.renderIconWithGlyph('terminal', glyph, 24, 'on');
|
||||
const onSvg = renders.at(-1);
|
||||
const off = icons.renderIconWithGlyph('terminal', glyph, 24, 'off');
|
||||
const offSvg = renders.at(-1);
|
||||
const prompt = '<path d="m7 11 2-2-2-2"/>';
|
||||
const cursor = '<rect x="7.5" y="8" width="1" height="6"/>';
|
||||
assert.ok(idleSvg.includes(prompt)); assert.ok(onSvg.includes(cursor));
|
||||
assert.equal(onSvg.includes(prompt), false); assert.equal(offSvg.includes(prompt), false);
|
||||
assert.equal(idleSvg.replace(prompt, ''), offSvg);
|
||||
assert.equal(onSvg.replace(cursor, ''), offSvg);
|
||||
assert.notEqual(on, off); assert.notEqual(idle, on);
|
||||
const count = renders.length;
|
||||
assert.equal(icons.renderIconWithGlyph('terminal', glyph, 24, 'on'), on);
|
||||
assert.equal(renders.length, count);
|
||||
}
|
||||
assert.equal(icons.renderIconWithGlyph('timer', '', 24, 'on'), icons.renderIcon('timer', 24));
|
||||
});
|
||||
|
||||
test('host applies activity only to its own open windows and cleans up on close', async () => {
|
||||
let paints = 0;
|
||||
const worker = { postMessage() {} };
|
||||
const shellWindows = new Map();
|
||||
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts', {
|
||||
'../../graphics/image': { GrayImage: Image },
|
||||
'./chrome-layer': { windowIcon: (icon, letter, glyph, phase) => phase },
|
||||
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
|
||||
'./geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
|
||||
'../../native/frame-timings': {},
|
||||
'./shell': { shell: { registerWindow: w => shellWindows.set(w.windowId, w) } },
|
||||
});
|
||||
const host = new WorkerAppHost({ appId: 'terminal', worker, configureSurface: async () => {}, requestShellRender() { paints++; }, removeSurface() {} });
|
||||
const spec = { windowId: 'a', title: 'A', icon: 'terminal', iconGlyph: '1' };
|
||||
const window = host.openWindow(spec);
|
||||
await Promise.resolve();
|
||||
const send = (windowId, activity) => worker.onmessage({ data: { type: 'set-icon-activity', windowId, activity } });
|
||||
assert.equal(window.drawIcon(), 'idle');
|
||||
let count = paints; send('unknown', 'on'); assert.equal(paints, count);
|
||||
send('a', 'on'); assert.equal(window.drawIcon(), 'on'); assert.equal(paints, count + 1);
|
||||
count = paints; send('a', 'on'); assert.equal(paints, count);
|
||||
send('a', 'off'); assert.equal(window.drawIcon(), 'off');
|
||||
send('a', 'idle'); assert.equal(window.drawIcon(), 'idle');
|
||||
send('a', 'on'); window.close(); count = paints;
|
||||
send('a', 'off'); assert.equal(paints, count);
|
||||
const reopened = host.openWindow(spec); assert.equal(reopened.drawIcon(), 'idle');
|
||||
});
|
||||
+2
-1
@@ -34,6 +34,7 @@
|
||||
"../app/apps/microphones/name-guess.ts",
|
||||
"../app/apps/evenhub/containers.ts",
|
||||
"../app/apps/timer/timer-model.ts",
|
||||
"../app/apps/teleprompter/script-tracker.ts"
|
||||
"../app/apps/teleprompter/script-tracker.ts",
|
||||
"../app/apps/nightscout/nightscout-alerts.ts"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user