Rebase firmware on 2.3.0, fixing issue with lost ring input events

This commit is contained in:
James Babcock committed 2026-09-19 17:19:21 -07:00
1 parent 8ceecb6393
commit b972cd7682
21 files changed
+790 -156

No files matched your search

+1
View File
@@ -250,6 +250,7 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
const { shell, rawInputEventToInputEvent } = load('app/ui/shell/shell.ts', {
'../../graphics/image': images, '../../graphics/plane': {}, '../../graphics/ui-fonts': {}, '../../g2/events': load('app/g2/events.ts', {}),
'../gestures': gestures, '../layers': layers, '../menu': { MenuLayer: Menu },
'../input-monitor': load('app/ui/input-monitor.ts', {}),
'./voice-input': { VoiceInputLayer: class {
constructor(options) { this.options = options; voiceDialogs.push(options); }
startCapture() {}
+3 -3
View File
@@ -62,9 +62,9 @@ test("stock firmware classifies by base version and warns on the main screen", (
assert.equal(compat.classifyOnboardingFirmware(info("", "", "")).kind, "unknown");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.9.22", "2.2.9.22")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.4.34", "")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.10.10", "2.2.10.10")).kind, "newer-stock-validated");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.1", "2.3.0.1")).kind, "newer-stock-validated");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.24")).kind, "newer-stock-validated");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.10.10", "2.2.10.10")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.1", "2.3.0.1")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.24")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.25")).kind, "newer-stock-unvalidated");
// Faceclaw firmware on a newer base is still judged by its revision, not the base.
assert.equal(compat.classifyOnboardingFirmware(info(`Faceclaw/${REQUIRED}`, "2.3.0.1", "2.3.0.1")).kind, "custom");
+188
View File
@@ -0,0 +1,188 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const root = path.join(__dirname, '..');
function load(file, modules = {}, globals = {}, extra = '') {
const context = { exports: {}, console, ...globals, require(name) {
assert.ok(name in modules, `Unexpected dependency ${name}`); return modules[name];
} };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(root, file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText + extra, context);
return context.exports;
}
const gestures = load('app/ui/gestures.ts');
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(root, `app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
const fonts = { terminus24: font(24), terminus32: font(32) }, small = font(18);
function worker(game) {
let now = 10000, id = 0, renders = 0;
const timers = new Map(), posts = [];
const schedule = (fn, delay, repeat) => { timers.set(++id, { fn, at: now + delay, repeat }); return id; };
const cancel = id => timers.delete(id);
const global = { postMessage: m => posts.push(m) };
class Menu {
constructor(options) { this.options = options; this.opened = false; }
isOpen() { return this.opened; }
open() { this.opened = true; }
async handleInput(e) {
if (e.type === 'click') this.options.items()[0].onSelect({ stack: { pop: () => { this.opened = false; } } });
if (e.type === 'double-click' || e.type === 'system-menu-opened') this.opened = false;
}
}
const modules = {
'@nativescript/core/globals': {}, '../../graphics/image': graphics,
'../../graphics/plane': {}, '../../graphics/glyph-wire': {},
'../../graphics/bdffont': { getFont: name => fonts[name] },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small },
'../../native/frame-timings': { finishFrame() {}, logFrame() {} },
'../../native/active-display': {}, '../../native/worker-buzzer': {},
'../../native/settings-store': { getStringSetting: () => '0', setStringSetting() {} },
'../../ui/sound-effects': {}, '../../ui/sound-setting': { loadSoundEnabled: () => false, saveSoundEnabled() {} },
'../../ui/window-menu': { WindowMenu: Menu }, '../../ui/gestures': gestures,
'../../util/numeric-util': { clamp: (v, a, b) => Math.max(a, Math.min(b, v)) },
'./flappy-sprites': load('app/apps/flappy/flappy-sprites.ts', { '../../graphics/image': graphics }),
};
const extra = game === 'blocks' ? 'tick, hardDrop, idleDelayMs, dropIntervalMs, spawnPiece, windowMenu' :
game === 'pinball' ? 'stepFlippers, flip, launchBall, windowMenu' : 'flap, windowMenu';
const api = load(`app/apps/${game}/${game}-app.worker.ts`, modules, {
global, Date: { now: () => now },
setTimeout: (f, d) => schedule(f, d, 0), clearTimeout: cancel,
setInterval: (f, d) => schedule(f, d, d), clearInterval: cancel,
recordRender: () => renders++,
}, `\nrenderAndSubmit = () => recordRender(); playSfx = () => {};
exports.api = { windows, resetGame, paintContent, ${extra} };`).api;
const message = data => global.onmessage({ data });
message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: game, viewport: { width: 576, height: 288 } });
message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
const w = api.windows.get('test');
if (game === 'blocks') { w.pieceIndex = 2; w.pieceRotation = 0; w.pieceY = 0; w.pieceX = 3; }
function advance(ms) {
const end = now + ms;
for (;;) {
const next = [...timers].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
const [key, t] = next; now = t.at;
if (t.repeat) t.at += t.repeat; else timers.delete(key);
t.fn();
}
now = end;
}
return { ...api, w, message, advance, posts, timers, now: () => now, renders: () => renders,
elapse: ms => { now += ms; }, input: (type, source = 'ring') => message({
type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type, source, timestampMs: now },
}) };
}
for (const [sequence, rotations, x] of [
[['ring-press','click'],1,3], [['ring-press',300],1,3],
[['ring-press',300,'click'],1,3], [['ring-press','ring-press','double-click'],2,3],
[['ring-press','ring-press','ring-press','double-click'],3,3],
[['ring-press','scroll-up'],0,2], [['ring-press','scroll-down'],0,4],
[['ring-press','ring-press','ring-press','scroll-up'],2,2],
[['ring-press','scroll-up','click'],0,2], [['click','double-click'],0,3],
]) test(`Blocks: ${sequence.join(', ')} gives ${rotations} rotations`, () => {
const h = worker('blocks');
for (const step of sequence) typeof step === 'number' ? h.advance(step) : h.input(step);
h.advance(350);
assert.equal(h.w.pieceRotation, rotations); assert.equal(h.w.pieceX, x);
assert.equal(h.w.phase, 'playing'); assert.equal(h.w.pendingRotationTimer, null);
});
test('Blocks replaces only the last buffered press and expires at 300 ms', () => {
const h = worker('blocks'); h.input('ring-press'); h.advance(200); h.input('ring-press');
assert.equal(h.w.pieceRotation, 1); h.advance(299); assert.equal(h.w.pieceRotation, 1);
h.advance(1); assert.equal(h.w.pieceRotation, 2); h.input('double-click'); assert.equal(h.w.pieceRotation, 2);
});
test('Blocks a click from another source commits the pending rotation without duplicating it', () => {
const h = worker('blocks'); h.input('ring-press'); h.input('click', 'left-arm');
h.advance(300); assert.equal(h.w.pieceRotation, 1);
h.input('click', 'watch'); assert.equal(h.w.pieceRotation, 2);
});
test('Blocks idle acceleration starts at the deadline, runs at 5x, and ends on input', () => {
const h = worker('blocks'); h.advance(1000);
assert.equal(h.w.pieceY, 0);
const before = h.w.gravityProgress; h.advance(300);
assert.ok(Math.abs((h.w.pieceY + h.w.gravityProgress) - before - 1) < 1e-9);
h.input('scroll-down'); const afterInput = h.w.pieceY + h.w.gravityProgress;
h.advance(300);
assert.ok(Math.abs((h.w.pieceY + h.w.gravityProgress) - afterInput - 0.2) < 1e-9);
for (const [lines, expected] of [[0,1000],[10,950],[50,750],[100,500],[200,500]]) {
h.w.lines = lines; assert.equal(h.idleDelayMs(h.w), expected);
}
});
test('Blocks continuous input cannot reset gravity progress; timeout rotation is not fresh input', () => {
const h = worker('blocks');
for (let i = 0; i < 20; i++) { h.input(i % 2 ? 'scroll-up' : 'scroll-down'); h.advance(100); }
assert.equal(h.w.pieceY, 1);
h.input('ring-press'); const when = h.w.lastInputAtMs; h.advance(300);
assert.equal(h.w.lastInputAtMs, when);
});
test('Blocks landing resets acceleration and prevents a pending rotation from reaching the next piece', () => {
const h = worker('blocks'); h.advance(1100); h.input('ring-press');
h.hardDrop(h.w);
assert.equal(h.w.gravityProgress, 0); assert.equal(h.w.lastInputAtMs, h.now());
h.advance(300); assert.equal(h.w.pieceRotation, 0);
assert.equal(h.w.gravityProgress.toFixed(3), '0.200');
// Let a naturally falling piece land while accelerated, then inspect its successor.
h.w.pieceY = 17; h.w.board.fill(0);
while (h.w.pieceY >= 17) h.advance(20);
assert.equal(h.w.gravityProgress, 0); assert.equal(h.w.lastInputAtMs, h.now());
});
test('Blocks hold pauses without dropping, opens a menu, and resumes with a fresh idle delay', async () => {
const h = worker('blocks'); h.input('ring-press'); h.advance(100); h.input('long-press');
assert.equal(h.w.phase, 'paused'); assert.equal(h.w.pieceY, 0);
assert.ok(h.w.menu.isOpen()); assert.equal(h.w.menu.options.claimsLongPress(), false);
h.advance(5000); assert.equal(h.w.pieceRotation, 0); assert.equal(h.w.pieceY, 0);
h.input('click'); await Promise.resolve();
assert.equal(h.w.phase, 'playing'); assert.equal(h.w.lastInputAtMs, h.now());
assert.equal(h.w.menu.options.claimsLongPress(), true);
h.advance(500); assert.equal(h.w.pieceY, 0);
});
for (const event of [
{ type: 'input-focus', windowId: 'test', focused: false },
{ type: 'foreground', windowId: 'test', foreground: false, focused: false },
{ type: 'screen', on: false }, { type: 'close-window', windowId: 'test' },
]) test(`Blocks cancels buffered input and timers on ${event.type}`, () => {
const h = worker('blocks'); h.input('ring-press'); h.message(event); h.advance(2000);
assert.equal(h.w.pieceRotation, 0); assert.equal(h.timers.size, 0);
});
test('Flappy acts on down and ignores subsequent ring click/scroll; watch still flaps', () => {
const h = worker('flappy'); h.input('ring-press');
assert.equal(h.w.phase, 'playing'); assert.ok(h.w.birdVy < 0);
h.w.birdVy = 20; h.input('click'); h.input('scroll-up'); assert.equal(h.w.birdVy, 20);
h.input('swipe-up', 'watch'); assert.ok(h.w.birdVy < 0);
h.w.birdVy = 20; h.input('click', 'watch'); assert.ok(h.w.birdVy < 0);
});
test('Pinball pulses both flippers for 300 ms, extends on another press, and ignores click in play', () => {
const h = worker('pinball'); h.w.ballState = 'live'; h.input('ring-press');
assert.ok(h.w.flippers.every(f => f.state === 'rising' && f.holdUntilMs === h.now() + 300));
h.stepFlippers(h.w, 0.2); assert.ok(h.w.flippers.every(f => f.state === 'hold'));
h.elapse(200); h.input('click'); assert.ok(h.w.flippers.every(f => f.holdUntilMs === h.now() + 100));
h.input('ring-press'); h.elapse(299); h.stepFlippers(h.w, 0);
assert.ok(h.w.flippers.every(f => f.state === 'hold'));
h.elapse(1); h.stepFlippers(h.w, 0); assert.ok(h.w.flippers.every(f => f.state === 'falling'));
});
test('Pinball swipes no longer flip; plunger power and click launch remain', () => {
const h = worker('pinball'); h.w.ballState = 'live';
for (const type of ['scroll-up','scroll-down','swipe-left','swipe-right']) h.input(type);
assert.ok(h.w.flippers.every(f => f.state === 'rest'));
h.w.ballState = 'ready'; h.w.launchPower = 2;
h.input('scroll-up'); assert.equal(h.w.launchPower, 3);
h.input('scroll-down'); assert.equal(h.w.launchPower, 2);
h.input('click'); assert.equal(h.w.ballState, 'live');
});
+126
View File
@@ -0,0 +1,126 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const js = (source) => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
function load(file, modules = {}) {
const context = { exports: {}, console, require(name) {
assert.ok(name in modules, name); return modules[name];
} };
vm.runInNewContext(js(read(file)), context);
return context.exports;
}
const monitor = load('app/ui/input-monitor.ts');
const event = (type, timestampMs = 1000) => ({ type, source: 'ring', timestampMs });
function shellDeclarations() {
const source = ts.createSourceFile('shell.ts', read('app/ui/shell/shell.ts'), ts.ScriptTarget.Latest, true);
const names = new Set(['rawInputEventToPayload', 'eventSourceToString', 'scrollEvent']);
const declarations = source.statements.filter((s) => ts.isFunctionDeclaration(s) && names.has(s.name?.text));
assert.equal(declarations.length, names.size);
const shell = source.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === 'Shell');
const methods = shell.members.filter((s) => ['receiveInput', 'routeInput'].includes(s.name?.getText(source)));
const context = { exports: {}, notifyInputListeners: monitor.notifyInputListeners,
...load('app/g2/events.ts') };
vm.createContext(context);
vm.runInContext(js(declarations.map((s) => s.getText(source)).join('\n') +
'\nexport class Shell {\n' + methods.map((s) => s.getText(source)).join('\n') + '\n}'), context);
return context;
}
test('new SysEvent decodes independently of click, double-tap, hold and release', () => {
const d = shellDeclarations();
for (const source of [0, 2]) {
const decoded = d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source });
assert.equal(decoded.type, 'ring-press'); assert.equal(decoded.source, 'ring');
}
for (const source of [1, 3, 99, undefined]) {
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source }).type, 'unknown');
}
for (const [id, type] of [[0,'click'],[3,'double-click'],[9,'long-press'],[10,'long-press-release'],[11,'short-then-long-press']]) {
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventType: id, eventSource: 2 }).type, type);
}
});
test('press is observed before routing and does not wake, operate shell menus or replace hold state', async () => {
const { exports: { Shell } } = shellDeclarations();
for (const screenOn of [true, false]) for (const focus of ['window', 'sidebar']) for (const atBase of [true, false]) {
const s = new Shell(), seen = [], delivered = [];
const unsubscribe = monitor.addInputListener((e) => seen.push(e));
Object.assign(s, { screenOn, focus, stack: { isAtBase: () => atBase },
foregroundWindow: () => ({ handleInput(e) { assert.equal(seen.length, 1); delivered.push(e); } }),
syncInputFocus() {}, lastInput: event('long-press'), lastInputAtMs: 123 });
try {
const result = await s.receiveInput(event('ring-press'));
assert.equal(result.shell, false);
assert.equal(delivered.length, Number(screenOn && focus === 'window' && atBase));
assert.equal(seen.length, 1);
assert.equal(s.lastInput.type, 'long-press'); assert.equal(s.lastInputAtMs, 123);
} finally { unsubscribe(); }
}
});
test('bounded history preserves equal-time events, snapshots and arrival gaps; pause and clear work', () => {
const log = new monitor.InputEventLog();
const first = event('ring-press'); log.add(first); first.type = 'unknown';
log.add(event('click')); log.add(event('double-click', 1250));
assert.equal(log.entries[2].event.type, 'ring-press');
assert.equal(log.entries[2].gapMs, null); assert.equal(log.entries[1].gapMs, 0);
assert.equal(log.entries[0].gapMs, 250);
log.paused = true; log.add(event('click')); assert.equal(log.count, 3);
log.paused = false;
for (let i = 0; i < 210; i++) log.add(event('click', 2000 + i));
assert.equal(log.entries.length, 200); assert.equal(log.count, 213);
log.clear(); log.add(event('ring-press')); assert.equal(log.count, 1); assert.equal(log.entries[0].gapMs, null);
assert.equal(monitor.inputTimestamp(new Date(2026, 0, 2, 3, 4, 5, 6).getTime()), '03:04:05.006');
});
test('Input events captures while visible, pauses for history, and unsubscribes on removal', () => {
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 = BdfFont.parse(read('app/fonts/terminus/ter-u18n.bdf'));
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);
}
}
const { InputEventsLayer } = load('app/apps/developer/input-events.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: RecordingImage }, '../../graphics/textwrap': textwrap,
'../../ui/input-monitor': monitor, '../../ui/menu': { drawListScrollbar() {} },
});
let visible = true, renders = 0, removed = 0, pops = 0;
const layer = new InputEventsLayer(() => renders++, () => visible, () => removed++);
const ctx = { stack: { getBaseSize: () => ({ width: 576, height: 260 }),
pop: () => pops++, popThrough: (page) => { assert.equal(page, layer); page.onRemoved(); } } };
try {
for (const type of ['ring-press','click','ring-press','ring-press','double-click','long-press','long-press-release','short-then-long-press']) {
const e = event(type, 1000 + renders * 75); monitor.notifyInputListeners(e); layer.handleInput(e);
}
assert.equal(renders, 8); assert.equal(layer.log.count, 8); assert.equal(pops, 0);
visible = false; monitor.notifyInputListeners(event('click')); assert.equal(renders, 8); visible = true;
const image = layer.paint(ctx);
for (const text of image.texts) {
assert.ok(text.x >= 0 && text.x + text.width <= image.width, text.text);
assert.ok(text.y >= 0 && text.y + text.height <= image.height, text.text);
}
if (process.env.INPUT_EVENTS_PREVIEW) fs.writeFileSync(process.env.INPUT_EVENTS_PREVIEW, Buffer.concat([
Buffer.from(`P5\n${image.width} ${image.height}\n255\n`), Buffer.from(image.withDrawsBaked().pixels),
]));
layer.menuItems()[0].onSelect(ctx); monitor.notifyInputListeners(event('click'));
assert.equal(layer.log.count, 8); assert.equal(layer.menuItems()[0].label, 'Resume capture');
layer.menuItems()[1].onSelect(ctx); assert.equal(layer.log.count, 0);
layer.menuItems()[0].onSelect(ctx); monitor.notifyInputListeners(event('ring-press'));
assert.equal(layer.log.count, 1);
layer.menuItems()[2].onSelect(ctx); monitor.notifyInputListeners(event('click'));
assert.equal(removed, 1); assert.equal(layer.log.count, 1);
} finally { layer.onRemoved(); }
});
+10 -3
View File
@@ -92,6 +92,12 @@ test('ring and arm input decoders preserve gesture and source', () => {
assert.equal(wake.kind, 'display-wake');
assert.equal(wake.eventType, 12);
assert.equal(wake.eventSource, 1);
// The stock G2 sender omits source for dedicated Faceclaw event 14.
const press = p.decodeGlassesInput({ sid: 224, flag: 1,
payload: p.bytes(13, p.bytes(3, p.integer(1, 14))) });
assert.equal(press.kind, 'sys-event');
assert.equal(press.eventType, 14);
assert.equal(press.eventSource, 0);
});
class FakeTransport {
@@ -605,7 +611,7 @@ test('wear notifications validate the event and peer and work during initial con
test('ANCS packets are scoped to the right link and cleared on disconnect and authorization revocation', async t => {
const transport = new FakeTransport(); transport.firmware = 16;
const transport = new FakeTransport(); transport.firmware = REQUIRED_FACECLAW_FIRMWARE_VERSION;
const h = harness(t, transport); await h.session.start(addresses);
await until(() => transport.ancs?.length);
const token = Array.from(transport.ancs[0].frame.subarray(4,8));
@@ -624,12 +630,13 @@ test('firmware 15 requires an upgrade before starting notification relay', async
const transport = new FakeTransport(); transport.firmware = 15;
const h = harness(t, transport); await h.session.start(addresses);
assert.equal(h.session.notifications.state, 'disconnected');
assert.match(h.session.notifications.statusMessage, /firmware 16 or newer/);
assert.equal(h.session.state.phase, 'error');
assert.match(h.session.state.status, new RegExp(`requires revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION}`));
assert.equal(transport.ancs?.length ?? 0, 0);
});
test('ANCS app-name lookup uses the right-link write limit, including after reauthorization', async t => {
const transport = new FakeTransport(); transport.firmware = 16;
const transport = new FakeTransport(); transport.firmware = REQUIRED_FACECLAW_FIRMWARE_VERSION;
const h = harness(t, transport); await h.session.start(addresses);
await until(() => transport.ancs?.length);
const id = 'net.superblock.Pushover';
+5 -1
View File
@@ -109,7 +109,11 @@ test('pinned stock firmware reproduces the custom image, extracts fonts, and pas
'@nativescript/core': { File: { exists: fs.existsSync, fromPath: file => ({ readTextSync: () => fs.readFileSync(file, 'utf8') }) },
knownFolders: { documents: () => ({ path: temp, getFile: name => ({ writeTextSync: text => fs.writeFileSync(path.join(temp, name), text) }) }) } },
'./firmware/cfw-patches': patches, './firmware-fonts': fonts,
'../util/http': { fetchWithUserAgent: async () => ({ ok: true, arrayBuffer: async () => Uint8Array.from(base).buffer }) },
'../util/http': { fetchWithUserAgent: async (url) => {
const md5 = crypto.createHash('md5').update(base).digest('hex');
assert.equal(url, `https://cdn.evenreal.co/firmware/${md5}.bin`);
return { ok: true, arrayBuffer: async () => Uint8Array.from(base).buffer };
} },
'../util/hex-util': require('../.test-build/app/util/hex-util.js'), '../graphics/evenhub-font': { EvenHubFont: { invalidate() {} } },
'../native/firmware-files': { firmwareSha256: hash, writeFirmwareFile: (file, buffer) => fs.writeFileSync(file, new Uint8Array(buffer)) },
});
+122
View File
@@ -0,0 +1,122 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { loader } = require('./helpers/load-typescript.cjs');
function fixture({ ios = false, connected = true } = {}) {
const messages = [], frames = [], sounds = [], errors = [], timers = new Set(), settings = new Map();
const global = { isIOS: ios, isAndroid: !ios, postMessage: message => messages.push(message) };
const timings = {
startFrame: () => 1, finishFrame() {}, logFrame() {},
span: (_id, _name, fn) => fn(), runWithFrame: (_id, fn) => fn(), spanCurrent: (_name, fn) => fn(),
};
const mocks = {
'@nativescript/core': {}, '@nativescript/core/globals': {},
'../../native/frame-timings': timings, '../native/frame-timings': timings,
'../../native/settings-store': {
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback,
setBooleanSetting: (key, value) => settings.set(key, value),
},
};
mocks['../native/settings-store'] = mocks['../../native/settings-store'];
const display = { submitSurfaceFrame: (...args) => frames.push(args) };
let active = connected;
const load = loader({
global, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn),
console: { log() {}, warn: error => errors.push(error), error: error => errors.push(error) },
com: { faceclaw: { app: {
FaceclawBleCommunicator: { getActive: () => active ? {
...display, playBuzzerSequence: payload => sounds.push(payload),
} : null },
FaceclawPreviewCompositor: { getActive: () => display },
} } },
NSData: { dataWithBytesLength: buffer => ({ base64EncodedStringWithOptions: () => Buffer.from(buffer).toString('base64') }) },
interop: { handleof: buffer => buffer },
}, mocks);
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), medium = font(24);
mocks['../../graphics/bdffont'] = { getFont: () => medium };
mocks['../../graphics/ui-fonts'] = mocks['../graphics/ui-fonts'] = { getDefaultSmallFont: () => small };
// Exercise the real iOS transport and Android preview selection. The atlas
// boundary is stubbed; text baking and plane composition remain production code.
mocks['../../graphics/glyph-wire'] = { prepareFrameDraws: () => null };
if (ios) mocks['../../native/active-display'] = load('app/native/active-display.ios.ts');
load('app/apps/paperclips/paperclips-app.worker.ts');
const send = data => global.onmessage({ data });
const input = type => send({ type: 'input', windowId: 'paperclips:main', focused: true, frameId: 1,
event: { type, source: 'ring', timestampMs: 1 } });
const open = () => {
send({ type: 'open-window', windowId: 'paperclips:main', surfaceId: 'window:paperclips:main',
title: 'Paperclips', viewport: { width: 576, height: 260 } });
send({ type: 'foreground', windowId: 'paperclips:main', foreground: true, focused: true });
};
const pixels = () => ios ? Buffer.from(messages.filter(m => m.type === 'surface-frame').at(-1).pixels, 'base64')
: Buffer.from(frames.at(-1)[0]);
return { messages, frames, sounds, errors, timers, settings, send, input, open, pixels,
disconnect: () => { active = false; } };
}
const flush = () => new Promise(resolve => setImmediate(resolve));
for (const ios of [false, true]) {
test(`Paperclips starts, renders text and plays sound through the ${ios ? 'iOS' : 'Android'} bridge`, () => {
const h = fixture({ ios });
assert.equal(h.messages[0].type, 'worker-ready');
h.open();
assert.equal(h.timers.size, 1);
assert.equal(h.pixels().length, 576 * 260);
assert.ok(h.pixels().some(value => value > 0));
const first = h.pixels();
h.input('click');
assert.notDeepEqual(h.pixels(), first);
h.input('long-press');
assert.equal(h.timers.size, 0);
assert.ok(ios ? h.messages.some(m => m.type === 'buzzer-sequence' && m.payload.length) : h.sounds.length);
const gestures = h.messages.filter(m => m.type === 'set-window-gestures');
assert.equal(gestures[0].claimsLongPress, true);
assert.equal(gestures.at(-1).claimsLongPress, false);
// The gap between the pause title and hints must occlude the deferred
// game labels below, rather than letting them draw over the modal.
const pixels = h.pixels();
for (let y = 124; y < 136; y++) {
assert.ok(pixels.subarray(y * 576 + 132, y * 576 + 444).every(value => value === 0));
}
h.input('click');
assert.equal(h.timers.size, 1);
h.send({ type: 'close-window', windowId: 'paperclips:main' });
assert.equal(h.timers.size, 0);
assert.deepEqual(h.errors, []);
});
}
test('Paperclips uses the disconnected preview and suppresses duplicate frames', () => {
const h = fixture({ connected: false });
h.open();
assert.equal(h.frames.length, 1);
h.send({ type: 'render', windowId: 'paperclips:main', focused: true });
assert.equal(h.frames.length, 1);
h.input('click');
assert.equal(h.frames.length, 2);
assert.deepEqual(h.errors, []);
});
test('Paperclips pauses for focus loss and its current context menu resumes and saves sound settings', async () => {
const h = fixture(); h.open();
h.send({ type: 'input-focus', windowId: 'paperclips:main', focused: false });
assert.equal(h.timers.size, 0);
h.input('short-then-long-press');
h.input('click'); await flush(); // Resume
assert.equal(h.timers.size, 1);
h.input('short-then-long-press');
assert.equal(h.timers.size, 0);
for (let i = 0; i < 3; i++) { h.input('scroll-down'); await flush(); }
h.input('click'); await flush(); // Sound: off
assert.equal(h.settings.get('paperclips.soundOn'), false);
const sounds = h.sounds.length;
h.input('click'); // Resume without sound
assert.equal(h.sounds.length, sounds);
h.send({ type: 'screen', on: false });
assert.equal(h.timers.size, 0);
assert.deepEqual(h.errors, []);
});
+2 -2
View File
@@ -96,7 +96,7 @@ test('pinball responds on contact, holds independently, and releases before tap'
assert.equal(h.w.flippers[1].state, 'falling');
});
test('pinball retains old firmware/ring controls and plunger click launch', () => {
test('pinball uses ring press for flippers and retains plunger click launch', () => {
const h = worker();
h.input('click');
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
@@ -106,7 +106,7 @@ test('pinball retains old firmware/ring controls and plunger click launch', () =
assert.equal(h.w.ballState, 'ready');
h.input('click');
assert.equal(h.w.ballState, 'live');
h.input('click', 'ring');
h.input('ring-press', 'ring');
assert.ok(h.w.flippers.every((f) => f.state === 'rising'));
});