Display compass diagnostic information
This commit is contained in:
1 parent
1154474754
commit
083628f37a
13 files changed
+807
-10
No files matched your search
@@ -1567,7 +1567,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
emitWearState(decodedWearState > 0);
|
||||
}
|
||||
if (compassEvent != null) {
|
||||
emitCompassEvent(compassEvent.command, compassEvent.headingDegrees);
|
||||
emitCompassEvent(compassEvent);
|
||||
}
|
||||
if (event != null) {
|
||||
if (event.hasImu) {
|
||||
@@ -3456,11 +3456,22 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
||||
});
|
||||
}
|
||||
|
||||
private void emitCompassEvent(int command, int headingDegrees) {
|
||||
private void emitCompassEvent(BleProtocol.CompassEvent event) {
|
||||
if (event.diagnosticFlags >= 0) {
|
||||
String[] sources = { "unknown", "GRV", "GMRV", "RV" };
|
||||
Log.i("FaceclawCompass", "heading=" + event.headingDegrees
|
||||
+ " magneticAccuracy=" + event.magneticAccuracy
|
||||
+ " magneticAnomalies=" + event.magneticAnomalies
|
||||
+ " orientationSource=" + sources[event.orientationSource]
|
||||
+ " flags=0x" + Integer.toHexString(event.diagnosticFlags)
|
||||
+ " sampleTimeMs=" + event.sampleTimeMs);
|
||||
}
|
||||
for (CompassSubscription subscription : compassSubscriptions) {
|
||||
subscription.handler.post(() -> {
|
||||
try {
|
||||
subscription.listener.onCompassEvent(command, headingDegrees);
|
||||
subscription.listener.onCompassEvent(event.command, event.headingDegrees,
|
||||
event.magneticAccuracy, event.magneticAnomalies, event.orientationSource,
|
||||
event.diagnosticFlags, event.sampleTimeMs);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "listener onCompassEvent failed", t);
|
||||
}
|
||||
|
||||
@@ -2,5 +2,6 @@ package com.faceclaw.app;
|
||||
|
||||
/** Receives stock compass heading and calibration notifications on the thread that subscribed. */
|
||||
public interface FaceclawCompassListener {
|
||||
void onCompassEvent(int command, int headingDegrees);
|
||||
void onCompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies,
|
||||
int orientationSource, int diagnosticFlags, long sampleTimeMs);
|
||||
}
|
||||
@@ -772,7 +772,23 @@ public class BleProtocol {
|
||||
byte[] compass = readFieldBytes(root, 10);
|
||||
if (compass == null) return null;
|
||||
int heading = readVarintFieldValue(compass, 1, -1);
|
||||
return heading >= 0 ? new CompassEvent(command, heading) : null;
|
||||
if (heading < 0 || heading >= 360) return null;
|
||||
byte[] diagnostic = readFieldBytes(root, 100);
|
||||
if (diagnostic != null && diagnostic.length == 12
|
||||
&& diagnostic[0] == 'C' && diagnostic[1] == 'M' && diagnostic[2] == 1
|
||||
&& diagnostic[7] == 0
|
||||
&& ((diagnostic[3] & 0xff) <= 3 || diagnostic[3] == (byte) 255)
|
||||
&& ((diagnostic[4] & 0xff) <= 2 || diagnostic[4] == (byte) 255)
|
||||
&& (diagnostic[5] & 0xff) <= 3) {
|
||||
long sampleTimeMs = 0;
|
||||
for (int i = 0; i < 4; i++) sampleTimeMs |= (long) (diagnostic[8 + i] & 0xff) << (8 * i);
|
||||
return new CompassEvent(command, heading,
|
||||
diagnostic[3] == (byte) 255 ? -1 : diagnostic[3] & 0xff,
|
||||
diagnostic[4] == (byte) 255 ? -1 : diagnostic[4] & 0xff,
|
||||
diagnostic[5] & 0xff, diagnostic[6] & 0xff, sampleTimeMs);
|
||||
}
|
||||
// Stock/older CFW and unknown extensions still supply usable headings.
|
||||
return new CompassEvent(command, heading);
|
||||
}
|
||||
if (command == NAV_CMD_COMPASS_CALIBRATION_STARTED
|
||||
|| command == NAV_CMD_COMPASS_CALIBRATION_COMPLETE) {
|
||||
@@ -1014,10 +1030,23 @@ public class BleProtocol {
|
||||
public static final class CompassEvent {
|
||||
public final int command;
|
||||
public final int headingDegrees;
|
||||
/** -1 means unavailable; source: 0 unknown, 1 GRV, 2 GMRV, 3 RV. */
|
||||
public final int magneticAccuracy, magneticAnomalies, orientationSource, diagnosticFlags;
|
||||
public final long sampleTimeMs;
|
||||
|
||||
CompassEvent(int command, int headingDegrees) {
|
||||
this(command, headingDegrees, -1, -1, -1, -1, -1);
|
||||
}
|
||||
|
||||
CompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies,
|
||||
int orientationSource, int diagnosticFlags, long sampleTimeMs) {
|
||||
this.command = command;
|
||||
this.headingDegrees = headingDegrees;
|
||||
this.magneticAccuracy = magneticAccuracy;
|
||||
this.magneticAnomalies = magneticAnomalies;
|
||||
this.orientationSource = orientationSource;
|
||||
this.diagnosticFlags = diagnosticFlags;
|
||||
this.sampleTimeMs = sampleTimeMs;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
addCompassListener,
|
||||
setCompassEnabled,
|
||||
type CompassEvent,
|
||||
type CompassDiagnostics,
|
||||
} from "../../native/compass";
|
||||
import { wrapText } from "../../graphics/textwrap";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
@@ -25,6 +26,7 @@ import { isCompassCalibrated, normalizeHeading } from "./calibration";
|
||||
import { CompassCalibrationLayer } from "./calibration-layer";
|
||||
import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination";
|
||||
import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading";
|
||||
import { compassDebugLines, isCompassDebugEnabled, setCompassDebugEnabled } from "./debug";
|
||||
|
||||
export const COMPASS_WINDOW_ID = "compass";
|
||||
export const COMPASS_SURFACE_ID = "window:compass";
|
||||
@@ -95,6 +97,7 @@ const WALL_LIT = 62;
|
||||
|
||||
class CompassLayer implements Layer {
|
||||
private rawHeading: number | null = null;
|
||||
private diagnostics: CompassDiagnostics | null = null;
|
||||
/** A firmware calibration message, shown until the next heading arrives. */
|
||||
private firmwareStatus: string | null = null;
|
||||
private enabled = false;
|
||||
@@ -141,6 +144,11 @@ class CompassLayer implements Layer {
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
toggleDebugInfo(): void {
|
||||
setCompassDebugEnabled(!isCompassDebugEnabled());
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.removed) return;
|
||||
this.removed = true;
|
||||
@@ -168,6 +176,7 @@ class CompassLayer implements Layer {
|
||||
const visible = shell.isWindowVisible(COMPASS_WINDOW_ID);
|
||||
if (visible === this.enabled) return;
|
||||
this.enabled = visible;
|
||||
this.diagnostics = null;
|
||||
setCompassEnabled(visible);
|
||||
this.firmwareStatus = null;
|
||||
// The stored fix may have aged out while the compass was hidden.
|
||||
@@ -179,6 +188,7 @@ class CompassLayer implements Layer {
|
||||
if (this.removed) return;
|
||||
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
|
||||
this.rawHeading = normalizeHeading(event.headingDegrees);
|
||||
this.diagnostics = event.diagnostics ?? null;
|
||||
this.firmwareStatus = null;
|
||||
} else if (event.command === COMPASS_CALIBRATION_STARTED) {
|
||||
this.firmwareStatus = "Calibrating — move the glasses";
|
||||
@@ -204,6 +214,17 @@ class CompassLayer implements Layer {
|
||||
const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`;
|
||||
const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2);
|
||||
const smallStep = lineStep(small);
|
||||
const debugLines = isCompassDebugEnabled() ? compassDebugLines(this.diagnostics) : [];
|
||||
const debugWidth = Math.max(0, ...debugLines.map((line) => small.measureText(line)));
|
||||
const debugGap = debugLines.length ? 12 : 0;
|
||||
// Keep diagnostics beside the heading even in narrow windows. The rose
|
||||
// stays centred on the optical axis; the combined readout fits the viewport.
|
||||
const headingFont = large.measureText(headingText) + debugGap + debugWidth <= width - EDGE_PAD * 2
|
||||
? large : small;
|
||||
const headingWidth = headingFont.measureText(headingText);
|
||||
const readoutWidth = headingWidth + debugGap + debugWidth;
|
||||
const debugHeight = debugLines.length ? (debugLines.length - 1) * smallStep + small.lineHeight : 0;
|
||||
const readoutHeight = Math.max(headingFont.lineHeight, debugHeight);
|
||||
|
||||
// One column centred on the display's true centre, so the rose sits where
|
||||
// the wearer is looking rather than 32px right of it.
|
||||
@@ -211,7 +232,7 @@ class CompassLayer implements Layer {
|
||||
|
||||
// The rose is sized and placed first — it hangs off the bottom edge — and
|
||||
// the readout then floats in whatever room is left above it.
|
||||
const textHeight = large.lineHeight + 4 + statusLines.length * smallStep;
|
||||
const textHeight = readoutHeight + 4 + statusLines.length * smallStep;
|
||||
const radius = Math.max(
|
||||
24,
|
||||
Math.min(
|
||||
@@ -240,8 +261,14 @@ class CompassLayer implements Layer {
|
||||
}
|
||||
const image = this.background.image.clone();
|
||||
drawCompassRose(image, cx, cy, radius, heading);
|
||||
image.drawText(large, Math.round(cx - large.measureText(headingText) / 2), y, headingText, heading === null ? 150 : 255);
|
||||
y += large.lineHeight + 4;
|
||||
const readoutX = Math.round(Math.max(EDGE_PAD, Math.min(width - EDGE_PAD - readoutWidth, cx - readoutWidth / 2)));
|
||||
image.drawText(headingFont, readoutX, y + Math.floor((readoutHeight - headingFont.lineHeight) / 2),
|
||||
headingText, heading === null ? 150 : 255);
|
||||
for (let i = 0; i < debugLines.length; i++) {
|
||||
image.drawText(small, readoutX + headingWidth + debugGap,
|
||||
y + Math.floor((readoutHeight - debugHeight) / 2) + i * smallStep, debugLines[i]!, 175);
|
||||
}
|
||||
y += readoutHeight + 4;
|
||||
for (const line of statusLines) {
|
||||
image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125);
|
||||
y += smallStep;
|
||||
@@ -286,6 +313,14 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
|
||||
layer.toggleNorthReference();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: `Debug information: ${isCompassDebugEnabled() ? "On" : "Off"}`,
|
||||
description: "Show magnetic accuracy (0–3), anomaly flags (0–2), and orientation source beside the heading.",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
layer.toggleDebugInfo();
|
||||
},
|
||||
},
|
||||
],
|
||||
baseLayer: new YieldAtRootLayer(layer),
|
||||
submitFrame: options.submitFrame,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { CompassDiagnostics } from "../../native/compass";
|
||||
import { getBooleanSetting, setBooleanSetting } from "../../native/settings-store";
|
||||
|
||||
const DEBUG_KEY = "compass.debugInfo";
|
||||
|
||||
export function isCompassDebugEnabled(): boolean {
|
||||
return getBooleanSetting(DEBUG_KEY, false);
|
||||
}
|
||||
|
||||
export function setCompassDebugEnabled(enabled: boolean): void {
|
||||
setBooleanSetting(DEBUG_KEY, enabled);
|
||||
}
|
||||
|
||||
export function compassDebugLines(diagnostics: CompassDiagnostics | null): string[] {
|
||||
if (!diagnostics) return ["Diagnostics", "unavailable"];
|
||||
if (!(diagnostics.flags & 0x80)) return ["Sample data", "unavailable"];
|
||||
const accuracy = diagnostics.magneticAccuracy < 0 ? "--" : `${diagnostics.magneticAccuracy}/3`;
|
||||
const anomalies = diagnostics.magneticAnomalies < 0 ? "--" : String(diagnostics.magneticAnomalies);
|
||||
const source = ["--", "GRV", "GMRV", "RV"][diagnostics.orientationSource] ?? "--";
|
||||
return [`Mag: ${accuracy}`, `Anom: ${anomalies}`, `Src: ${source}`];
|
||||
}
|
||||
+23
-2
@@ -5,10 +5,23 @@ export const COMPASS_CHANGED = 15;
|
||||
export const COMPASS_CALIBRATION_STARTED = 16;
|
||||
export const COMPASS_CALIBRATION_COMPLETE = 17;
|
||||
|
||||
export type CompassDiagnostics = {
|
||||
/** 0 uncalibrated .. 3 well calibrated; -1 unavailable. */
|
||||
magneticAccuracy: number;
|
||||
/** 0 none, 1 small/temperature, 2 large; -1 unavailable. */
|
||||
magneticAnomalies: number;
|
||||
/** 0 unknown, 1 GRV (relative), 2 GMRV, 3 RV. */
|
||||
orientationSource: number;
|
||||
flags: number;
|
||||
sampleTimeMs: number;
|
||||
};
|
||||
|
||||
export type CompassEvent = {
|
||||
command: number;
|
||||
/** Magnetic heading in degrees, or -1 for calibration-only events. */
|
||||
headingDegrees: number;
|
||||
/** Absent with stock/older CFW or an unrecognized diagnostic extension. */
|
||||
diagnostics?: CompassDiagnostics;
|
||||
};
|
||||
|
||||
function activeCommunicator(): any {
|
||||
@@ -41,8 +54,16 @@ export function addCompassListener(listener: (event: CompassEvent) => void): ()
|
||||
const active = activeCommunicator();
|
||||
if (!active) return () => {};
|
||||
const proxy = new com.faceclaw.app.FaceclawCompassListener({
|
||||
onCompassEvent: (command: number, headingDegrees: number) => {
|
||||
listener({ command: Number(command), headingDegrees: Number(headingDegrees) });
|
||||
onCompassEvent: (command: number, headingDegrees: number, magneticAccuracy: number,
|
||||
magneticAnomalies: number, orientationSource: number, diagnosticFlags: number, sampleTimeMs: number) => {
|
||||
listener({
|
||||
command: Number(command), headingDegrees: Number(headingDegrees),
|
||||
diagnostics: diagnosticFlags >= 0 ? {
|
||||
magneticAccuracy: Number(magneticAccuracy), magneticAnomalies: Number(magneticAnomalies),
|
||||
orientationSource: Number(orientationSource), flags: Number(diagnosticFlags),
|
||||
sampleTimeMs: Number(sampleTimeMs),
|
||||
} : undefined,
|
||||
});
|
||||
},
|
||||
});
|
||||
active.addCompassListener(proxy);
|
||||
|
||||
@@ -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,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);
|
||||
});
|
||||
Reference in new issue
Block a user