Merge branch 'main' into ios-port

This commit is contained in:
James Babcock committed 2026-09-08 20:08:24 -07:00
commit a31ddae4d2
49 files changed
+2068 -212

No files matched your search

@@ -43,8 +43,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private static final long FACECLAW_WAKE_LEASE_RENEW_MS = 45_000; private static final long FACECLAW_WAKE_LEASE_RENEW_MS = 45_000;
private static final long FACECLAW_WAKE_CONTROL_WAIT_MS = 1_500; private static final long FACECLAW_WAKE_CONTROL_WAIT_MS = 1_500;
private static final long CFW_CLEANUP_WAIT_MS = 4_000; private static final long CFW_CLEANUP_WAIT_MS = 4_000;
private static final int COMPASS_REPORT_INTERVAL_MS = 250; private static final int COMPASS_REPORT_INTERVAL_MS = 100;
private static final int COMPASS_MIN_CHANGE_DEGREES = 1; private static final int COMPASS_MIN_CHANGE_DEGREES = 0;
private final Context appContext; private final Context appContext;
private final PowerManager powerManager; private final PowerManager powerManager;
@@ -1567,7 +1567,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
emitWearState(decodedWearState > 0); emitWearState(decodedWearState > 0);
} }
if (compassEvent != null) { if (compassEvent != null) {
emitCompassEvent(compassEvent.command, compassEvent.headingDegrees); emitCompassEvent(compassEvent);
} }
if (event != null) { if (event != null) {
if (event.hasImu) { 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) { for (CompassSubscription subscription : compassSubscriptions) {
subscription.handler.post(() -> { subscription.handler.post(() -> {
try { 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) { } catch (Throwable t) {
Log.w(TAG, "listener onCompassEvent failed", 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. */ /** Receives stock compass heading and calibration notifications on the thread that subscribed. */
public interface FaceclawCompassListener { 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);
} }
@@ -23,6 +23,8 @@ import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.List; import java.util.List;
import java.util.HashSet;
import java.util.Set;
public class FaceclawMediaController { public class FaceclawMediaController {
private final Context appContext; private final Context appContext;
@@ -71,6 +73,7 @@ public class FaceclawMediaController {
private volatile FaceclawMediaControllerListener listener; private volatile FaceclawMediaControllerListener listener;
private MediaController activeController; private MediaController activeController;
private boolean started; private boolean started;
private Set<String> ignoredPackages = new HashSet<>();
public FaceclawMediaController(Context context) { public FaceclawMediaController(Context context) {
this.appContext = context.getApplicationContext(); this.appContext = context.getApplicationContext();
@@ -113,6 +116,23 @@ public class FaceclawMediaController {
} }
} }
/** Apply the complete preference set and immediately choose an allowed session. */
public void setIgnoredPackagesJson(String packagesJson) {
Set<String> packages = new HashSet<>();
try {
JSONArray array = new JSONArray(packagesJson);
for (int i = 0; i < array.length(); i++) packages.add(array.getString(i));
} catch (Exception e) {
Log.w("FaceclawMedia", "invalid ignored packages", e);
return;
}
synchronized (lock) {
if (ignoredPackages.equals(packages)) return;
ignoredPackages = packages;
refreshActiveControllerLocked(null);
}
}
public void stop() { public void stop() {
synchronized (lock) { synchronized (lock) {
if (!started) { if (!started) {
@@ -289,6 +309,7 @@ public class FaceclawMediaController {
controllers = null; controllers = null;
} }
} }
emitSessionAppsLocked(controllers);
setActiveControllerLocked(chooseController(controllers)); setActiveControllerLocked(chooseController(controllers));
emitStateLocked(); emitStateLocked();
} }
@@ -297,8 +318,10 @@ public class FaceclawMediaController {
if (controllers == null || controllers.isEmpty()) { if (controllers == null || controllers.isEmpty()) {
return null; return null;
} }
MediaController first = controllers.get(0); MediaController first = null;
for (MediaController controller : controllers) { for (MediaController controller : controllers) {
if (ignoredPackages.contains(controller.getPackageName())) continue;
if (first == null) first = controller;
PlaybackState playbackState = controller.getPlaybackState(); PlaybackState playbackState = controller.getPlaybackState();
if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) { if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) {
return controller; return controller;
@@ -307,6 +330,27 @@ public class FaceclawMediaController {
return first; return first;
} }
private void emitSessionAppsLocked(List<MediaController> controllers) {
FaceclawMediaControllerListener currentListener = listener;
if (currentListener == null || controllers == null) return;
JSONArray apps = new JSONArray();
Set<String> seen = new HashSet<>();
for (MediaController controller : controllers) {
String packageName = safe(controller.getPackageName());
if (packageName.isEmpty() || !seen.add(packageName)) continue;
try {
JSONObject app = new JSONObject();
app.put("packageName", packageName);
app.put("appName", getApplicationLabel(packageName));
apps.put(app);
} catch (Exception e) {
Log.w("FaceclawMedia", "session app serialization failed", e);
}
}
String json = apps.toString();
mainHandler.post(() -> currentListener.onSessionAppsChanged(json));
}
private void setActiveControllerLocked(MediaController controller) { private void setActiveControllerLocked(MediaController controller) {
if (sameController(activeController, controller)) { if (sameController(activeController, controller)) {
return; return;
@@ -1,6 +1,9 @@
package com.faceclaw.app; package com.faceclaw.app;
public interface FaceclawMediaControllerListener { public interface FaceclawMediaControllerListener {
/** All observed session owners, before filtering or choosing the active player. */
void onSessionAppsChanged(String appsJson);
void onStateChange( void onStateChange(
String playbackState, String playbackState,
String packageName, String packageName,
@@ -210,7 +210,7 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen
public static String getActiveNotificationsJson(int maxNotifications) { public static String getActiveNotificationsJson(int maxNotifications) {
FaceclawMediaNotificationListenerService service = activeService; FaceclawMediaNotificationListenerService service = activeService;
int limit = Math.max(0, Math.min(100, maxNotifications)); int limit = Math.max(0, maxNotifications);
if (service == null || limit == 0) { if (service == null || limit == 0) {
return "[]"; return "[]";
} }
@@ -772,7 +772,23 @@ public class BleProtocol {
byte[] compass = readFieldBytes(root, 10); byte[] compass = readFieldBytes(root, 10);
if (compass == null) return null; if (compass == null) return null;
int heading = readVarintFieldValue(compass, 1, -1); 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 if (command == NAV_CMD_COMPASS_CALIBRATION_STARTED
|| command == NAV_CMD_COMPASS_CALIBRATION_COMPLETE) { || command == NAV_CMD_COMPASS_CALIBRATION_COMPLETE) {
@@ -1014,10 +1030,23 @@ public class BleProtocol {
public static final class CompassEvent { public static final class CompassEvent {
public final int command; public final int command;
public final int headingDegrees; 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) { 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.command = command;
this.headingDegrees = headingDegrees; this.headingDegrees = headingDegrees;
this.magneticAccuracy = magneticAccuracy;
this.magneticAnomalies = magneticAnomalies;
this.orientationSource = orientationSource;
this.diagnosticFlags = diagnosticFlags;
this.sampleTimeMs = sampleTimeMs;
} }
} }
+2
View File
@@ -3,6 +3,8 @@
## 0.6.6 - Future ## 0.6.6 - Future
* Navigate and terminal app: App-specific screen size/position setting * Navigate and terminal app: App-specific screen size/position setting
* Transcribe app: Scrolling; automatic reconnection; insert newlines * Transcribe app: Scrolling; automatic reconnection; insert newlines
* Notifications: Add notification filters
* Phone screen preview: Add rotation option; improve landscape layout
## 0.6.5 - 2026-09-04 ## 0.6.5 - 2026-09-04
* Changed context menu gestures: — for system, ●— for app context menu. * Changed context menu gestures: — for system, ●— for app context menu.
+21
View File
@@ -201,6 +201,27 @@ Button.-primary {
height: 20; height: 20;
tint-color: #333333; tint-color: #333333;
} }
/* Landscape uses the full page height and a shared left edge for tabs/pad. */
.landscape-layout .remote-controls {
margin: 0;
}
.landscape-layout .controls-tab-bar {
margin-bottom: 2;
}
.landscape-layout .tab-button {
margin-left: 1;
margin-right: 1;
min-width: 0;
}
.landscape-layout .tab-button[col="0"] {
margin-left: 0;
}
.landscape-layout .tab-icon-button {
width: 48;
}
.landscape-layout .tab-icon-button[col="4"] {
margin-right: 0;
}
.ns-dark .tab-icon { .ns-dark .tab-icon {
tint-color: #cccccc; tint-color: #cccccc;
} }
+110 -14
View File
@@ -7,6 +7,7 @@ import {
addCompassListener, addCompassListener,
setCompassEnabled, setCompassEnabled,
type CompassEvent, type CompassEvent,
type CompassDiagnostics,
} from "../../native/compass"; } from "../../native/compass";
import { wrapText } from "../../graphics/textwrap"; import { wrapText } from "../../graphics/textwrap";
import { type InputEvent } from "../../ui/gestures"; import { type InputEvent } from "../../ui/gestures";
@@ -25,6 +26,7 @@ import { isCompassCalibrated, normalizeHeading } from "./calibration";
import { CompassCalibrationLayer } from "./calibration-layer"; import { CompassCalibrationLayer } from "./calibration-layer";
import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination"; import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination";
import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading"; import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading";
import { compassDebugLines, isCompassDebugEnabled, setCompassDebugEnabled } from "./debug";
export const COMPASS_WINDOW_ID = "compass"; export const COMPASS_WINDOW_ID = "compass";
export const COMPASS_SURFACE_ID = "window:compass"; export const COMPASS_SURFACE_ID = "window:compass";
@@ -95,6 +97,7 @@ const WALL_LIT = 62;
class CompassLayer implements Layer { class CompassLayer implements Layer {
private rawHeading: number | null = null; private rawHeading: number | null = null;
private diagnostics: CompassDiagnostics | null = null;
/** A firmware calibration message, shown until the next heading arrives. */ /** A firmware calibration message, shown until the next heading arrives. */
private firmwareStatus: string | null = null; private firmwareStatus: string | null = null;
private enabled = false; private enabled = false;
@@ -103,6 +106,7 @@ class CompassLayer implements Layer {
private unsubscribe: (() => void) | null = null; private unsubscribe: (() => void) | null = null;
private unsubscribeDeclination: (() => void) | null = null; private unsubscribeDeclination: (() => void) | null = null;
private requestingPermission = false; private requestingPermission = false;
private background: { key: string; image: GrayImage } | null = null;
constructor(private readonly requestRender: () => void) {} constructor(private readonly requestRender: () => void) {}
@@ -140,6 +144,11 @@ class CompassLayer implements Layer {
this.requestRender(); this.requestRender();
} }
toggleDebugInfo(): void {
setCompassDebugEnabled(!isCompassDebugEnabled());
this.requestRender();
}
stop(): void { stop(): void {
if (this.removed) return; if (this.removed) return;
this.removed = true; this.removed = true;
@@ -167,6 +176,7 @@ class CompassLayer implements Layer {
const visible = shell.isWindowVisible(COMPASS_WINDOW_ID); const visible = shell.isWindowVisible(COMPASS_WINDOW_ID);
if (visible === this.enabled) return; if (visible === this.enabled) return;
this.enabled = visible; this.enabled = visible;
this.diagnostics = null;
setCompassEnabled(visible); setCompassEnabled(visible);
this.firmwareStatus = null; this.firmwareStatus = null;
// The stored fix may have aged out while the compass was hidden. // The stored fix may have aged out while the compass was hidden.
@@ -178,6 +188,7 @@ class CompassLayer implements Layer {
if (this.removed) return; if (this.removed) return;
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) { if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
this.rawHeading = normalizeHeading(event.headingDegrees); this.rawHeading = normalizeHeading(event.headingDegrees);
this.diagnostics = event.diagnostics ?? null;
this.firmwareStatus = null; this.firmwareStatus = null;
} else if (event.command === COMPASS_CALIBRATION_STARTED) { } else if (event.command === COMPASS_CALIBRATION_STARTED) {
this.firmwareStatus = "Calibrating — move the glasses"; this.firmwareStatus = "Calibrating — move the glasses";
@@ -197,13 +208,23 @@ class CompassLayer implements Layer {
paint(ctx: LayerContext): GrayImage { paint(ctx: LayerContext): GrayImage {
const { width, height } = ctx.stack.getBaseSize(); const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const small = getDefaultSmallFont(); const small = getDefaultSmallFont();
const large = getDefaultLargeFont(); const large = getDefaultLargeFont();
const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees; const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees;
const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`; const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`;
const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2); const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2);
const smallStep = lineStep(small); 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 // One column centred on the display's true centre, so the rose sits where
// the wearer is looking rather than 32px right of it. // 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 rose is sized and placed first — it hangs off the bottom edge — and
// the readout then floats in whatever room is left above it. // 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( const radius = Math.max(
24, 24,
Math.min( Math.min(
@@ -229,15 +250,30 @@ class CompassLayer implements Layer {
const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE); const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE);
let y = Math.max(TOP_PAD, Math.round((ringTop - TICK_HEIGHT - textHeight) / 2)); let y = Math.max(TOP_PAD, Math.round((ringTop - TICK_HEIGHT - textHeight) / 2));
image.drawText(large, Math.round(cx - large.measureText(headingText) / 2), y, headingText, heading === null ? 150 : 255); const fade = heading === null ? 0.45 : 1;
y += large.lineHeight + 4; const clipY = y + textHeight + 6;
const backgroundKey = [width, height, cx, cy, radius, clipY, fade].join(",");
if (this.background?.key !== backgroundKey) {
this.background = {
key: backgroundKey,
image: createCompassBackground(width, height, cx, cy, radius, clipY, fade),
};
}
const image = this.background.image.clone();
drawCompassRose(image, cx, cy, radius, heading);
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) { for (const line of statusLines) {
image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125); image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125);
y += smallStep; y += smallStep;
} }
drawPlaneGrid(image, cx, cy, radius, y + 6);
drawCompassRose(image, cx, cy, radius, heading);
return image; return image;
} }
@@ -277,6 +313,14 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW
layer.toggleNorthReference(); 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), baseLayer: new YieldAtRootLayer(layer),
submitFrame: options.submitFrame, submitFrame: options.submitFrame,
@@ -339,15 +383,66 @@ function projectRose(cx: number, cy: number, scale: number, radius: number, angl
}; };
} }
/** Draw the tilted rose, with its brightest point aimed at north. */ /**
* Bounds of every orientation of the rotating points. The longest tip sweeps
* a circle in the disc's plane; perspective projects it to an offset ellipse.
* Round outward so all rasterized triangle pixels fit inside the rectangle.
*/
function rotatingRoseBounds(cx: number, cy: number, radius: number): {
x: number; y: number; width: number; height: number;
} {
const perspective = TILT_PERSPECTIVE * CARDINAL_TIP;
const halfWidth = radius * CARDINAL_TIP / Math.sqrt(1 - perspective * perspective);
const depth = radius * CARDINAL_TIP * TILT_SQUASH;
const x = Math.floor(cx - halfWidth);
const y = Math.floor(cy - depth / (1 + perspective));
return {
x,
y,
width: Math.ceil(cx + halfWidth) - x,
height: Math.ceil(cy + depth / (1 - perspective)) - y,
};
}
/**
* Keep the fixed pixels inside the rotating rose's dirty rectangle as one
* immutable texture. The wire planner can omit them from each raster delta
* and restore them with a cached image draw. Outside that rectangle the
* background stays raster, since heading updates do not change it.
*
* The texture uses transparent zero for the empty disc interior, so it can
* overlay the rotating points. Its only ink over the points is the fixed
* heading tick, which belongs on top of them.
*/
function createCompassBackground(
width: number, height: number, cx: number, cy: number, radius: number, clipY: number, fade: number,
): GrayImage {
const image = new GrayImage(width, height, 0);
drawPlaneGrid(image, cx, cy, radius, clipY);
drawDiscWall(image, cx, cy, radius, fade);
drawTiltedRing(image, cx, cy, radius, 105 * fade);
drawHeadingTick(image, cx, cy, radius, 255 * fade);
const bounds = rotatingRoseBounds(cx, cy, radius);
const left = Math.max(0, bounds.x);
const top = Math.max(0, bounds.y);
const right = Math.min(width, bounds.x + bounds.width);
const bottom = Math.min(height, bounds.y + bounds.height);
if (right > left && bottom > top) {
const texture = new GrayImage(right - left, bottom - top, 0);
texture.bitBlt(image, 0, 0, { sx: left, sy: top, width: texture.width, height: texture.height });
image.fillRect(left, top, texture.width, texture.height, 0);
image.drawImage(texture, left, top);
}
return image;
}
/** Draw only the rotating points, with the brightest one aimed at north. */
function drawCompassRose(image: GrayImage, cx: number, cy: number, radius: number, heading: number | null): void { function drawCompassRose(image: GrayImage, cx: number, cy: number, radius: number, heading: number | null): void {
// Without a reading there is nothing to aim, so show the rose in its resting // Without a reading there is nothing to aim, so show the rose in its resting
// orientation, dimmed, rather than an empty ring. // orientation, dimmed, rather than an empty ring.
const fade = heading === null ? 0.45 : 1; const fade = heading === null ? 0.45 : 1;
const bearing = heading ?? 0; const bearing = heading ?? 0;
drawDiscWall(image, cx, cy, radius, fade);
drawTiltedRing(image, cx, cy, radius, 105 * fade);
drawHeadingTick(image, cx, cy, radius, 255 * fade);
// Short points first, so the long ones sit on top of them at the waist. Only // Short points first, so the long ones sit on top of them at the waist. Only
// north is drawn at full brightness: the other seven are there to make the // north is drawn at full brightness: the other seven are there to make the
// rose read as a rose, and competing with north would defeat the point. // rose read as a rose, and competing with north would defeat the point.
@@ -478,14 +573,15 @@ function drawTiltedRing(image: GrayImage, cx: number, cy: number, radius: number
} }
} }
/** A fixed mark at the top of the ring: the heading the wearer is facing. */ /** A fixed mark just inside the top rim: the heading the wearer is facing. */
function drawHeadingTick(image: GrayImage, cx: number, cy: number, radius: number, value: number): void { function drawHeadingTick(image: GrayImage, cx: number, cy: number, radius: number, value: number): void {
const top = projectRose(cx, cy, radius, 1, 0); const top = projectRose(cx, cy, radius, 1, 0);
const tickTop = top.y + 1;
fillTriangle( fillTriangle(
image, image,
{ x: cx, y: top.y - 1 }, { x: cx, y: tickTop + TICK_HEIGHT - 1 },
{ x: cx - TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT }, { x: cx - TICK_HALF_WIDTH, y: tickTop },
{ x: cx + TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT }, { x: cx + TICK_HALF_WIDTH, y: tickTop },
value, value,
); );
} }
+21
View File
@@ -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}`];
}
+8
View File
@@ -8,6 +8,7 @@ import { lineStep, tightRowHeight } from "../../ui/metrics";
import { mediaControllerBridge, type MediaControllerState, type MediaQueueItem } from "../../native/media-controller"; import { mediaControllerBridge, type MediaControllerState, type MediaQueueItem } from "../../native/media-controller";
import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser"; import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser";
import { MediaBrowseLayer } from "./media-browse"; import { MediaBrowseLayer } from "./media-browse";
import { MusicSettingsLayer } from "./music-settings";
import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers"; import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window"; import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
@@ -480,6 +481,13 @@ export function createMusicAppWindow(options: InProcessAppOptions): InProcessWin
iconLetter: "M", iconLetter: "M",
icon: "music", icon: "music",
closeable: true, closeable: true,
menuItems: () => [{
label: "Music settings",
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(new MusicSettingsLayer());
},
}],
actions: options.actions, actions: options.actions,
baseLayer: new MusicRootLayer(musicLayer), baseLayer: new MusicRootLayer(musicLayer),
submitFrame: options.submitFrame, submitFrame: options.submitFrame,
+57
View File
@@ -0,0 +1,57 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap";
import { mediaBrowserBridge } from "../../native/media-browser";
import { isMediaAppEnabled, readMediaApps, setMediaAppEnabled } from "../../native/media-apps";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { drawToggleMenuItem, MenuLayer, type MenuItem } from "../../ui/menu";
/** Discovered apps stay visible even when ignored or no longer publishing a session. */
export class MusicSettingsLayer implements Layer {
private menu: MenuLayer | null = null;
private signature = "";
private selectedPackage = "";
constructor() {
// Refresh installed browser services, remembering ignored services too.
mediaBrowserBridge.listBrowsableApps(true);
}
private currentMenu(ctx: LayerContext): MenuLayer {
const apps = readMediaApps().sort((a, b) =>
a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
const width = ctx.stack.getBaseSize().width;
const signature = JSON.stringify([width, apps.map((app) => [app.packageName, app.appName])]);
if (!this.menu || signature !== this.signature) {
this.signature = signature;
const items: MenuItem[] = apps.map((app) => ({
label: app.appName,
onSelect: () => setMediaAppEnabled(app, !isMediaAppEnabled(app.packageName)),
render: ({ image, x, y, width, selected }) => {
if (selected) this.selectedPackage = app.packageName;
const font = getDefaultSmallFont();
const duplicateName = apps.some((other) => other !== app && other.appName === app.appName);
const label = duplicateName ? `${app.appName} (${app.packageName})` : app.appName;
drawToggleMenuItem(image, font, x, y, width, truncateText(font, label, width - 48),
isMediaAppEnabled(app.packageName), selected);
},
}));
if (!items.length) items.push({ label: "No media apps discovered yet.", disabled: true, onSelect: () => {} });
this.menu = new MenuLayer("Music settings", items, {
x: 8, y: 8, width: width - 16,
opaque: true, showBorder: false,
footer: "On = enabled Off = ignored",
}).selectItem(Math.max(0, apps.findIndex((app) => app.packageName === this.selectedPackage)));
}
return this.menu;
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
return this.currentMenu(ctx).paint(ctx, paintBelow);
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
await this.currentMenu(ctx).handleInput(event, ctx);
}
}
+2 -1
View File
@@ -1,10 +1,11 @@
import { type AppDefinition } from "../app-definition"; import { type AppDefinition } from "../app-definition";
import { createNightscoutAppWindow, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app"; import { createNightscoutAppWindow, startNightscoutTrayIcon, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
const nightscoutApp: AppDefinition = { const nightscoutApp: AppDefinition = {
appId: "nightscout", appId: "nightscout",
title: "Nightscout", title: "Nightscout",
icon: "nightscout", icon: "nightscout",
boot: () => startNightscoutTrayIcon(),
launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow), launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
}; };
+33
View File
@@ -0,0 +1,33 @@
export type NightscoutAlertValues = {
cageTimestampMs: number | null;
reservoirUnits: number | null;
batteryVoltage: number | null;
loopTimestampMs: number | null;
};
export type NightscoutThresholds = {
maxCannulaAgeHours: number;
cartridgeLowUnits: number;
batteryLowVoltage: number;
maxLoopAgeMinutes: number;
};
/** Zero disables a threshold. Missing measurements do not imply a breach. */
export function evaluateNightscoutAlerts(values: NightscoutAlertValues, limits: NightscoutThresholds, nowMs: number) {
const known = (value: number | null): value is number => value !== null && Number.isFinite(value) && value >= 0;
const enabled = (value: number): boolean => Number.isFinite(value) && value > 0;
const tooOld = (timestamp: number | null, limit: number, unitMs: number): boolean =>
enabled(limit) && known(timestamp) && timestamp > 0 && nowMs - timestamp > limit * unitMs;
const tooLow = (value: number | null, limit: number): boolean => enabled(limit) && known(value) && value < limit;
const cannula = tooOld(values.cageTimestampMs, limits.maxCannulaAgeHours, 3_600_000);
const cartridge = tooLow(values.reservoirUnits, limits.cartridgeLowUnits);
const battery = tooLow(values.batteryVoltage, limits.batteryLowVoltage);
const loop = tooOld(values.loopTimestampMs, limits.maxLoopAgeMinutes, 60_000);
return { cannula, cartridge, battery, loop, any: cannula || cartridge || battery || loop };
}
export function normalizeNightscoutThreshold(value: string | null | undefined): string {
const text = (value ?? "").trim();
const number = Number(text);
return /^(\d+(\.\d*)?|\.\d+)$/.test(text) && Number.isFinite(number) && number >= 0 ? String(number) : "0";
}
+45 -18
View File
@@ -8,6 +8,8 @@ import {
type InProcessAppOptions, type InProcessAppOptions,
type InProcessWindow, type InProcessWindow,
} from "../../ui/shell/in-process-window"; } from "../../ui/shell/in-process-window";
import { evaluateNightscoutAlerts } from "./nightscout-alerts";
import { loadNightscoutThresholds, nightscoutAlwaysShowInTopBarSetting, onAnySettingChanged } from "../../ui/dashboard-settings";
import { shell } from "../../ui/shell/shell"; import { shell } from "../../ui/shell/shell";
export const NIGHTSCOUT_WINDOW_ID = "nightscout"; export const NIGHTSCOUT_WINDOW_ID = "nightscout";
@@ -19,14 +21,34 @@ const TRAY_GRAPH_WIDTH = 48;
const TRAY_STALE_MS = 15 * 60 * 1000; const TRAY_STALE_MS = 15 * 60 * 1000;
const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000; const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
/** const windowRenders = new Set<() => void>();
* The Nightscout app: the full-screen glucose view (previously reached via let trayStarted = false;
* the dashboard card) in its own in-process window. While the app is running let trayTick: ReturnType<typeof setInterval> | null = null;
* it also publishes a top-bar tray icon: the latest blood-glucose value
* (struck through when stale) plus a minimal 48px history graph. function syncNightscout(): void {
*/ const visible = windowRenders.size > 0 || nightscoutAlwaysShowInTopBarSetting.get();
shell.setTrayIcon(TRAY_ICON_ID, visible ? buildNightscoutTrayIcon(nightscoutBridge.snapshot()) : null);
for (const render of windowRenders) render();
// Age warnings and stale glucose must advance even during a stalled fetch.
if (visible && trayTick === null) trayTick = setInterval(syncNightscout, 60_000);
if (!visible && trayTick !== null) {
clearInterval(trayTick);
trayTick = null;
}
}
/** Shell-lifetime subscription so the tray can be enabled before any window opens. */
export function startNightscoutTrayIcon(): void {
if (trayStarted) return;
trayStarted = true;
nightscoutBridge.onStateChange(syncNightscout);
onAnySettingChanged(syncNightscout);
}
/** Full-screen glucose view with a shared, optionally persistent tray readout. */
export function createNightscoutAppWindow(options: InProcessAppOptions): InProcessWindow { export function createNightscoutAppWindow(options: InProcessAppOptions): InProcessWindow {
let unsubscribe: (() => void) | null = null; startNightscoutTrayIcon();
const render = () => app.requestRender();
const app = createInProcessWindow({ const app = createInProcessWindow({
appId: "nightscout", appId: "nightscout",
windowId: NIGHTSCOUT_WINDOW_ID, windowId: NIGHTSCOUT_WINDOW_ID,
@@ -41,28 +63,25 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce
setSurfaceVisible: options.setSurfaceVisible, setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface, removeSurface: options.removeSurface,
onClosed: () => { onClosed: () => {
unsubscribe?.(); windowRenders.delete(render);
unsubscribe = null; syncNightscout();
shell.setTrayIcon(TRAY_ICON_ID, null);
options.onClosed(); options.onClosed();
}, },
}); });
// onStateChange fires immediately with the current snapshot, so this also windowRenders.add(render);
// publishes the initial tray icon. syncNightscout();
unsubscribe = nightscoutBridge.onStateChange((state) => {
shell.setTrayIcon(TRAY_ICON_ID, buildNightscoutTrayIcon(state));
app.requestRender();
});
return app; return app;
} }
/** BG value (struck through when stale) + minimal 2-hour line graph. */ /** BG value, 2-hour graph, then a warning triangle when any threshold is breached. */
function buildNightscoutTrayIcon(state: NightscoutState): GrayImage { function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
const font = getDefaultSmallFont(); const font = getDefaultSmallFont();
const nowMs = Date.now(); const nowMs = Date.now();
const label = state.latest ? `${state.latest.sgv}` : "--"; const label = state.latest ? `${state.latest.sgv}` : "--";
const labelWidth = font.measureText(label); const labelWidth = font.measureText(label);
const image = new GrayImage(labelWidth + 4 + TRAY_GRAPH_WIDTH, TRAY_HEIGHT, 0); const warning = evaluateNightscoutAlerts(state, loadNightscoutThresholds(), nowMs).any;
const graphEnd = labelWidth + 4 + TRAY_GRAPH_WIDTH;
const image = new GrayImage(graphEnd + (warning ? 24 : 0), TRAY_HEIGHT, 0);
const textY = Math.max(0, ((TRAY_HEIGHT - font.lineHeight) / 2) | 0); const textY = Math.max(0, ((TRAY_HEIGHT - font.lineHeight) / 2) | 0);
image.drawText(font, 0, textY, label, 220); image.drawText(font, 0, textY, label, 220);
@@ -72,6 +91,14 @@ function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
} }
drawTrayGraph(image, labelWidth + 4, state, nowMs); drawTrayGraph(image, labelWidth + 4, state, nowMs);
if (warning) {
const x = graphEnd + 4;
image.drawLine(x + 9, 3, x, 20, 255);
image.drawLine(x, 20, x + 18, 20, 255);
image.drawLine(x + 18, 20, x + 9, 3, 255);
image.fillRect(x + 8, 9, 2, 6, 255);
image.fillRect(x + 8, 17, 2, 2, 255);
}
return image; return image;
} }
+40 -5
View File
@@ -1,3 +1,4 @@
import { evaluateNightscoutAlerts } from "./nightscout-alerts";
import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage, type UiFont } from "../../graphics/image"; import { GrayImage, type UiFont } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap"; import { truncateText } from "../../graphics/textwrap";
@@ -6,6 +7,13 @@ import { Layer, LayerContext } from "../../ui/layers";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge"; import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import { import {
isNightscoutSettingsConfigured, isNightscoutSettingsConfigured,
loadNightscoutThresholds,
nightscoutMaxCannulaAgeSetting,
nightscoutCartridgeLowSetting,
nightscoutBatteryLowSetting,
nightscoutMaxLoopAgeSetting,
nightscoutAlwaysShowInTopBarSetting,
toggleSettingMenuItem,
nightscoutApiTokenSetting, nightscoutApiTokenSetting,
nightscoutSiteUrlSetting, nightscoutSiteUrlSetting,
textSettingMenuItem, textSettingMenuItem,
@@ -332,21 +340,43 @@ export class NightscoutLayer implements Layer {
const statusX = 170; const statusX = 170;
const statusWidth = width - 22 - statusX; const statusWidth = width - 22 - statusX;
const statusLines: { text: string; shade: number; direction?: string }[] = [ const alerts = evaluateNightscoutAlerts(nightscout, loadNightscoutThresholds(), nowMs);
const statusLines: { text: string; shade: number; direction?: string; fields?: { text: string; warning?: boolean }[] }[] = [
{ text: `Delta ${formatDelta(nightscout.delta)} Trend `, shade: 180, direction: nightscout.direction }, { text: `Delta ${formatDelta(nightscout.delta)} Trend `, shade: 180, direction: nightscout.direction },
{ {
text: `IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`, text: `IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
shade: 160, shade: 160,
}, },
{ {
text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`, text: "", shade: 160,
shade: 160, fields: [
{ text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)}`, warning: alerts.cannula },
{ text: `Loop ${formatAgeShortFromTimestamp(nightscout.loopTimestampMs, nowMs)}`, warning: alerts.loop },
],
},
{
text: "", shade: 150,
fields: [
{ text: "Pump" },
{ text: nightscout.reservoirUnits === null ? "--U" : `${Math.round(nightscout.reservoirUnits)}U`, warning: alerts.cartridge },
{ text: nightscout.batteryVoltage === null ? "--V" : `${nightscout.batteryVoltage.toFixed(2)}V`, warning: alerts.battery },
{ text: nightscout.pumpStatus || "--" },
],
}, },
{ text: `Pump ${nightscout.pumpStatus || "--"}`, shade: 150 },
]; ];
let statusY = graphTop - 8 - statusLines.length * step; let statusY = graphTop - 8 - statusLines.length * step;
for (const line of statusLines) { for (const line of statusLines) {
if (line.direction !== undefined) { if (line.fields) {
let x = statusX;
for (const field of line.fields) {
const text = truncateText(font, field.text, Math.max(0, statusX + statusWidth - x));
const textWidth = font.measureText(text);
if (field.warning && textWidth > 0) image.fillRect(x - 2, statusY - 1, textWidth + 4, font.lineHeight + 2, 230);
image.drawText(font, x, statusY, text, field.warning ? 0 : line.shade);
x += textWidth + font.measureText(" ");
if (x >= statusX + statusWidth) break;
}
} else if (line.direction !== undefined) {
image.drawText(font, statusX, statusY, line.text, line.shade); image.drawText(font, statusX, statusY, line.text, line.shade);
drawDirectionIndicator(image, font, statusX + font.measureText(line.text), statusY, line.direction, line.shade); drawDirectionIndicator(image, font, statusX + font.measureText(line.text), statusY, line.direction, line.shade);
} else { } else {
@@ -390,6 +420,11 @@ export function nightscoutMenuItems(): MenuItem[] {
openSettingsSubMenu(ctx, "Nightscout settings", [ openSettingsSubMenu(ctx, "Nightscout settings", [
textSettingMenuItem(nightscoutSiteUrlSetting), textSettingMenuItem(nightscoutSiteUrlSetting),
textSettingMenuItem(nightscoutApiTokenSetting), textSettingMenuItem(nightscoutApiTokenSetting),
textSettingMenuItem(nightscoutMaxCannulaAgeSetting),
textSettingMenuItem(nightscoutCartridgeLowSetting),
textSettingMenuItem(nightscoutBatteryLowSetting),
textSettingMenuItem(nightscoutMaxLoopAgeSetting),
toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting),
]); ]);
}, },
}, },
@@ -1,4 +1,5 @@
import { NotificationsListLayer } from "../../ui/notifications"; import { NotificationsListLayer } from "../../ui/notifications";
import { NotificationFilterLayer } from "../../ui/notification-filter";
import { onAndroidNotificationPosted } from "../../native/notification-icons"; import { onAndroidNotificationPosted } from "../../native/notification-icons";
import { import {
createInProcessWindow, createInProcessWindow,
@@ -25,6 +26,13 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr
iconLetter: "N", iconLetter: "N",
icon: "bell", icon: "bell",
closeable: true, closeable: true,
menuItems: () => [{
label: "Notification filter",
onSelect: (ctx) => {
ctx.stack.pop();
ctx.stack.push(new NotificationFilterLayer());
},
}],
actions: options.actions, actions: options.actions,
baseLayer: new YieldAtRootLayer(new NotificationsListLayer()), baseLayer: new YieldAtRootLayer(new NotificationsListLayer()),
submitFrame: options.submitFrame, submitFrame: options.submitFrame,
+32 -23
View File
@@ -37,7 +37,7 @@ import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts"; import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts";
import { layoutHubHeader } from "./hub-header"; import { layoutHubHeader } from "./hub-header";
import { truncateText } from "../../graphics/textwrap"; import { truncateText } from "../../graphics/textwrap";
import { TERMINAL_ICON_GLYPHS } from "../../graphics/icons"; import { TERMINAL_ICON_GLYPHS, type IconActivity } from "../../graphics/icons";
import * as frameTimings from "../../native/frame-timings"; import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display"; import { getActiveDisplay } from "../../native/active-display";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
@@ -286,7 +286,7 @@ const sessionRecency = new Map<string, number>();
// continues, so 5s of slack keeps the indicator lit through the gaps. // continues, so 5s of slack keeps the indicator lit through the gaps.
const sessionActivity = new Map<string, number>(); const sessionActivity = new Map<string, number>();
const ACTIVITY_ACTIVE_MS = 5_000; const ACTIVITY_ACTIVE_MS = 5_000;
// Alternation period of the hub's activity indicator. // Alternation period shared by hub rows and sidebar cursors.
const HUB_ANIMATION_STEP_MS = 800; const HUB_ANIMATION_STEP_MS = 800;
function recencyKey(connectionId: string, socket: string): string { function recencyKey(connectionId: string, socket: string): string {
@@ -462,6 +462,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
if (pendingView) { if (pendingView) {
pendingViews.delete(windowId); pendingViews.delete(windowId);
windows.set(windowId, createViewWindow(windowId, surfaceId, title, viewport, pendingView)); windows.set(windowId, createViewWindow(windowId, surfaceId, title, viewport, pendingView));
updateHubAnimation();
renderHubWindows(); renderHubWindows();
return; return;
} }
@@ -491,6 +492,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
if (!controlsInitialized) { if (!controlsInitialized) {
syncControlsFromSettings(); syncControlsFromSettings();
} }
updateHubAnimation();
} }
function closeWindow(windowId: string): void { function closeWindow(windowId: string): void {
@@ -511,6 +513,8 @@ function closeWindow(windowId: string): void {
endAddConnection(window); endAddConnection(window);
} }
windows.delete(windowId); windows.delete(windowId);
windowIconActivity.delete(windowId);
updateHubAnimation();
// Auto-reconnect only runs while at least one terminal window is open. // Auto-reconnect only runs while at least one terminal window is open.
if (windows.size === 0) { if (windows.size === 0) {
for (const control of controls.values()) { for (const control of controls.values()) {
@@ -721,42 +725,47 @@ function renderHubWindows(): void {
} }
} }
// Hub activity animation: while a foregrounded hub lists at least one active // One animation clock for foreground hub rows and every terminal sidebar icon.
// session, a timer re-renders it so the per-row indicator alternates. The // Keep ticking while the sidebar can show activity, even with the hub closed.
// timer stops itself once every session's activity ages out (its final tick
// renders the rows indicator-free) or the hub leaves the foreground.
let hubAnimationPhase = 0; let hubAnimationPhase = 0;
let hubAnimationTimer: ReturnType<typeof setInterval> | null = null; let hubAnimationTimer: ReturnType<typeof setInterval> | null = null;
const windowIconActivity = new Map<string, IconActivity>();
function isSessionActive(connectionId: string, socket: string): boolean { function isSessionActive(connectionId: string, socket: string): boolean {
const at = sessionActivity.get(recencyKey(connectionId, socket)); const at = sessionActivity.get(recencyKey(connectionId, socket));
return at !== undefined && Date.now() - at < ACTIVITY_ACTIVE_MS; return at !== undefined && Date.now() - at < ACTIVITY_ACTIVE_MS;
} }
function hubAnimationShouldRun(): boolean { function isWindowSessionActive(window: TerminalWindow): boolean {
if (!screenOn) return false; if (window.kind === "view") return isSessionActive(window.connectionId, window.socket);
let hubVisible = false;
for (const window of windows.values()) {
if (window.kind === "hub" && window.foreground) hubVisible = true;
}
if (!hubVisible) return false;
const now = Date.now(); const now = Date.now();
for (const at of sessionActivity.values()) { return [...sessionActivity.values()].some((at) => now - at < ACTIVITY_ACTIVE_MS);
if (now - at < ACTIVITY_ACTIVE_MS) return true;
}
return false;
} }
/** Start or stop the animation timer to match the current state. */ function hubAnimationShouldRun(): boolean {
return screenOn && [...windows.values()].some(isWindowSessionActive);
}
function syncWindowIconActivity(): void {
for (const window of windows.values()) {
const activity: IconActivity = screenOn && isWindowSessionActive(window)
? (hubAnimationPhase === 0 ? "on" : "off") : "idle";
if ((windowIconActivity.get(window.windowId) ?? "idle") === activity) continue;
windowIconActivity.set(window.windowId, activity);
post({ type: "set-icon-activity", windowId: window.windowId, activity });
}
}
/** Start or stop animation and publish changed icons, including expiry/wake. */
function updateHubAnimation(): void { function updateHubAnimation(): void {
if (hubAnimationShouldRun()) { const shouldRun = hubAnimationShouldRun();
if (shouldRun && !hubAnimationTimer) hubAnimationPhase = 0;
syncWindowIconActivity();
if (shouldRun) {
if (hubAnimationTimer) return; if (hubAnimationTimer) return;
hubAnimationTimer = setInterval(() => { hubAnimationTimer = setInterval(() => {
hubAnimationPhase = (hubAnimationPhase + 1) % 2; hubAnimationPhase = (hubAnimationPhase + 1) % 2;
if (!hubAnimationShouldRun() && hubAnimationTimer) { updateHubAnimation();
clearInterval(hubAnimationTimer);
hubAnimationTimer = null;
}
// Render even on the stopping tick, to clear expired indicators. // Render even on the stopping tick, to clear expired indicators.
renderHubWindows(); renderHubWindows();
}, HUB_ANIMATION_STEP_MS); }, HUB_ANIMATION_STEP_MS);
+2
View File
@@ -1,8 +1,10 @@
import { Application } from '@nativescript/core' import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents' import { registerShareIntentHandler } from './native/share-intents'
import { installNativeUserAgent } from './util/http' import { installNativeUserAgent } from './util/http'
import { registerPhoneRotation } from './native/phone-rotation'
installNativeUserAgent() installNativeUserAgent()
registerShareIntentHandler() registerShareIntentHandler()
registerPhoneRotation()
Application.run({ moduleName: 'app-root' }) Application.run({ moduleName: 'app-root' })
+5 -2
View File
@@ -12,7 +12,8 @@ import * as frameTimings from "../native/frame-timings";
import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service"; import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service";
import { mediaControllerBridge } from "../native/media-controller"; import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout-bridge"; import { nightscoutBridge } from "../native/nightscout-bridge";
import { onAndroidNotificationPosted } from "../native/notification-icons"; import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, readActiveNotifications } from "../native/notification-icons";
import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict"; import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { grayImageToPreviewSource } from "../native/gray-image-preview"; import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage } from "./firmware-compat"; import { firmwareIncompatibilityMessage } from "./firmware-compat";
@@ -374,6 +375,7 @@ class DashboardController {
this.appendLog(`notification wake failed: ${this.formatError(error)}`); this.appendLog(`notification wake failed: ${this.formatError(error)}`);
}); });
}); });
readActiveNotifications(ALL_NOTIFICATIONS);
// Settings toggled from the glasses can change what the phone UI shows // Settings toggled from the glasses can change what the phone UI shows
// (e.g. the text-setting editor), so re-emit the snapshot on any change. // (e.g. the text-setting editor), so re-emit the snapshot on any change.
onAnySettingChanged(() => { onAnySettingChanged(() => {
@@ -2464,7 +2466,8 @@ class DashboardController {
} }
private async handleAndroidNotificationPosted(notificationKey: string): Promise<void> { private async handleAndroidNotificationPosted(notificationKey: string): Promise<void> {
if (!notificationKey) { const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
if (!notification || !shouldShowNotificationOnGlasses(notification.packageName)) {
this.requestShellRender(); this.requestShellRender();
return; return;
} }
+20 -7
View File
@@ -87,9 +87,11 @@ export const ICON_SVGS = {
} as const; } as const;
export type IconName = keyof typeof ICON_SVGS; export type IconName = keyof typeof ICON_SVGS;
/** Idle prompt, or the visible/hidden phases of an activity cursor. */
export type IconActivity = "idle" | "on" | "off";
// The "_" element of the terminal icon, swapped out for a session glyph in // Prompt and session-marker elements replaced by renderIconWithGlyph.
// renderIconWithGlyph. const TERMINAL_PROMPT = '<path d="m7 11 2-2-2-2"/>';
const TERMINAL_UNDERSCORE = '<path d="M11 13h4"/>'; const TERMINAL_UNDERSCORE = '<path d="M11 13h4"/>';
/** /**
@@ -155,12 +157,23 @@ export function renderSvgIcon(cacheName: string, svg: string, size: number): Gra
/** /**
* Render an icon with a glyph character substituted in — currently only the * Render an icon with a glyph character substituted in — currently only the
* terminal icon, whose "_" becomes the glyph (">3" instead of ">_"). Falls * terminal icon, whose "_" becomes the glyph (">3" instead of ">_"). Falls
* back to the plain icon for other names or unsupported characters. * back to the plain marker for unsupported characters. Active terminal icons
* replace the prompt with a blinking cursor, leaving the marker in place.
*/ */
export function renderIconWithGlyph(name: IconName, glyph: string, size: number): GrayImage | null { export function renderIconWithGlyph(name: IconName, glyph: string, size: number, activity: IconActivity = "idle"): GrayImage | null {
const shape = name === "terminal" ? TERMINAL_GLYPH_SHAPES[glyph] : undefined; if (name !== "terminal") return renderIcon(name, size);
if (!shape) return renderIcon(name, size); const shape = TERMINAL_GLYPH_SHAPES[glyph];
return renderSvgCached(`${name}[${glyph}]`, ICON_SVGS.terminal.replace(TERMINAL_UNDERSCORE, shape), size); if (!shape && activity === "idle") return renderIcon(name, size);
let svg: string = ICON_SVGS.terminal;
if (shape) svg = svg.replace(TERMINAL_UNDERSCORE, shape);
if (activity !== "idle") {
// IconRenderer strokes all elements at width 2; the narrow rectangle
// therefore becomes a solid cursor without needing per-element fills.
svg = svg.replace(TERMINAL_PROMPT, activity === "on"
? '<rect x="7.5" y="8" width="1" height="6"/>'
: "");
}
return renderSvgCached(`${name}[${shape ? glyph : ""}]:${activity}`, svg, size);
} }
function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null { function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null {
+23 -2
View File
@@ -5,10 +5,23 @@ export const COMPASS_CHANGED = 15;
export const COMPASS_CALIBRATION_STARTED = 16; export const COMPASS_CALIBRATION_STARTED = 16;
export const COMPASS_CALIBRATION_COMPLETE = 17; 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 = { export type CompassEvent = {
command: number; command: number;
/** Magnetic heading in degrees, or -1 for calibration-only events. */ /** Magnetic heading in degrees, or -1 for calibration-only events. */
headingDegrees: number; headingDegrees: number;
/** Absent with stock/older CFW or an unrecognized diagnostic extension. */
diagnostics?: CompassDiagnostics;
}; };
function activeCommunicator(): any { function activeCommunicator(): any {
@@ -41,8 +54,16 @@ export function addCompassListener(listener: (event: CompassEvent) => void): ()
const active = activeCommunicator(); const active = activeCommunicator();
if (!active) return () => {}; if (!active) return () => {};
const proxy = new com.faceclaw.app.FaceclawCompassListener({ const proxy = new com.faceclaw.app.FaceclawCompassListener({
onCompassEvent: (command: number, headingDegrees: number) => { onCompassEvent: (command: number, headingDegrees: number, magneticAccuracy: number,
listener({ command: Number(command), headingDegrees: Number(headingDegrees) }); 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); active.addCompassListener(proxy);
+83
View File
@@ -0,0 +1,83 @@
import { getStringSetting, setStringSetting } from "./settings-store";
export const MEDIA_APPS_KEY = "music.apps";
// Exact package IDs only: browsers, social feeds and messaging apps commonly
// publish sessions for embedded clips. Users can explicitly enable any of them.
export const DEFAULT_IGNORED_MEDIA_APPS: readonly string[] = [
"com.android.chrome",
"org.mozilla.firefox",
"com.microsoft.emmx",
"com.sec.android.app.sbrowser",
"com.facebook.katana",
"com.facebook.orca",
"com.instagram.android",
"com.whatsapp",
"org.telegram.messenger",
"com.snapchat.android",
"com.reddit.frontpage",
"com.twitter.android",
"com.discord",
];
export type MediaApp = {
packageName: string;
appName: string;
/** Absent until the user chooses; built-in defaults can evolve independently. */
enabled?: boolean;
};
/** Keep discovered apps after their sessions end, including ignored apps. */
export function readMediaApps(): MediaApp[] {
try {
const parsed = JSON.parse(getStringSetting(MEDIA_APPS_KEY, "[]"));
if (!Array.isArray(parsed)) return [];
const apps = new Map<string, MediaApp>();
for (const app of parsed) {
if (!app || typeof app.packageName !== "string" || !app.packageName) continue;
apps.set(app.packageName, {
packageName: app.packageName,
appName: typeof app.appName === "string" && app.appName ? app.appName : app.packageName,
...(typeof app.enabled === "boolean" ? { enabled: app.enabled } : {}),
});
}
return Array.from(apps.values());
} catch {
return [];
}
}
export function rememberMediaApps(discovered: { packageName: string; appName: string }[]): void {
const apps = new Map(readMediaApps().map((app) => [app.packageName, app]));
let changed = false;
for (const app of discovered) {
if (!app.packageName) continue;
const previous = apps.get(app.packageName);
const appName = app.appName || previous?.appName || app.packageName;
if (!previous || previous.appName !== appName) {
apps.set(app.packageName, { ...previous, packageName: app.packageName, appName });
changed = true;
}
}
if (changed) setStringSetting(MEDIA_APPS_KEY, JSON.stringify(Array.from(apps.values())));
}
export function ignoredMediaPackages(): string[] {
const ignored = new Set(DEFAULT_IGNORED_MEDIA_APPS);
for (const app of readMediaApps()) {
if (app.enabled === true) ignored.delete(app.packageName);
else if (app.enabled === false) ignored.add(app.packageName);
}
return Array.from(ignored).sort();
}
export function isMediaAppEnabled(packageName: string): boolean {
return !ignoredMediaPackages().includes(packageName);
}
export function setMediaAppEnabled(app: MediaApp, enabled: boolean): void {
if (!app.packageName) return;
const apps = new Map(readMediaApps().map((item) => [item.packageName, item]));
apps.set(app.packageName, { packageName: app.packageName, appName: app.appName || app.packageName, enabled });
setStringSetting(MEDIA_APPS_KEY, JSON.stringify(Array.from(apps.values())));
}
+24 -2
View File
@@ -1,4 +1,6 @@
import { Utils } from "@nativescript/core"; import { Utils } from "@nativescript/core";
import { ignoredMediaPackages, isMediaAppEnabled, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
import { onSettingsStoreChanged } from "./settings-store";
declare const com: any; declare const com: any;
@@ -34,11 +36,12 @@ export class FaceclawMediaBrowserBridge {
private readonly pendingConnects = new Map<number, PendingRequest<string>>(); private readonly pendingConnects = new Map<number, PendingRequest<string>>();
private readonly pendingBrowses = new Map<number, PendingRequest<MediaBrowseItem[]>>(); private readonly pendingBrowses = new Map<number, PendingRequest<MediaBrowseItem[]>>();
private appsCache: MediaBrowserApp[] | null = null; private appsCache: MediaBrowserApp[] | null = null;
private connectedPackage = "";
/** Installed apps exposing a media browser service; cached after the first call. */ /** Installed apps exposing a media browser service; cached after the first call. */
listBrowsableApps(refresh = false): MediaBrowserApp[] { listBrowsableApps(refresh = false): MediaBrowserApp[] {
if (!global.isAndroid) return []; if (!global.isAndroid) return [];
if (this.appsCache && !refresh) return this.appsCache; if (this.appsCache && !refresh) return this.enabledApps();
this.ensureBrowser(); this.ensureBrowser();
if (!this.browser) return []; if (!this.browser) return [];
try { try {
@@ -52,11 +55,17 @@ export class FaceclawMediaBrowserBridge {
serviceClass: String(app.serviceClass ?? ""), serviceClass: String(app.serviceClass ?? ""),
appName: String(app.appName ?? ""), appName: String(app.appName ?? ""),
})); }));
rememberMediaApps(this.appsCache);
} catch (error) { } catch (error) {
console.warn(`media browser app list parse failed: ${error}`); console.warn(`media browser app list parse failed: ${error}`);
this.appsCache = []; this.appsCache = [];
} }
return this.appsCache; return this.enabledApps();
}
private enabledApps(): MediaBrowserApp[] {
const ignored = new Set(ignoredMediaPackages());
return (this.appsCache ?? []).filter((app) => !ignored.has(app.packageName));
} }
/** /**
@@ -65,9 +74,11 @@ export class FaceclawMediaBrowserBridge {
*/ */
connect(app: MediaBrowserApp): Promise<string> { connect(app: MediaBrowserApp): Promise<string> {
if (!global.isAndroid) return Promise.reject(new Error("Android only")); if (!global.isAndroid) return Promise.reject(new Error("Android only"));
if (!isMediaAppEnabled(app.packageName)) return Promise.reject(new Error("App is ignored in Music settings"));
this.ensureBrowser(); this.ensureBrowser();
if (!this.browser) return Promise.reject(new Error("Media browser unavailable")); if (!this.browser) return Promise.reject(new Error("Media browser unavailable"));
const requestId = this.nextRequestId++; const requestId = this.nextRequestId++;
this.connectedPackage = app.packageName;
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
this.pendingConnects.set(requestId, { resolve, reject }); this.pendingConnects.set(requestId, { resolve, reject });
this.browser.connect(requestId, app.packageName, app.serviceClass); this.browser.connect(requestId, app.packageName, app.serviceClass);
@@ -77,6 +88,10 @@ export class FaceclawMediaBrowserBridge {
/** Fetch one level of the connected service's content tree. */ /** Fetch one level of the connected service's content tree. */
browse(parentId: string): Promise<MediaBrowseItem[]> { browse(parentId: string): Promise<MediaBrowseItem[]> {
if (!global.isAndroid) return Promise.reject(new Error("Android only")); if (!global.isAndroid) return Promise.reject(new Error("Android only"));
if (this.connectedPackage && !isMediaAppEnabled(this.connectedPackage)) {
this.disconnect();
return Promise.reject(new Error("App is ignored in Music settings"));
}
this.ensureBrowser(); this.ensureBrowser();
if (!this.browser) return Promise.reject(new Error("Media browser unavailable")); if (!this.browser) return Promise.reject(new Error("Media browser unavailable"));
const requestId = this.nextRequestId++; const requestId = this.nextRequestId++;
@@ -89,6 +104,7 @@ export class FaceclawMediaBrowserBridge {
/** Start playback of a browsed item through the connected player's session. */ /** Start playback of a browsed item through the connected player's session. */
playFromMediaId(mediaId: string): void { playFromMediaId(mediaId: string): void {
if (!global.isAndroid) return; if (!global.isAndroid) return;
if (!this.connectedPackage || !isMediaAppEnabled(this.connectedPackage)) return;
this.browser?.playFromMediaId(mediaId); this.browser?.playFromMediaId(mediaId);
} }
@@ -96,6 +112,7 @@ export class FaceclawMediaBrowserBridge {
disconnect(): void { disconnect(): void {
if (!global.isAndroid) return; if (!global.isAndroid) return;
this.rejectAllPending("Disconnected"); this.rejectAllPending("Disconnected");
this.connectedPackage = "";
this.browser?.disconnect(); this.browser?.disconnect();
} }
@@ -115,6 +132,11 @@ export class FaceclawMediaBrowserBridge {
throw new Error("Android application context unavailable"); throw new Error("Android application context unavailable");
} }
this.browser = new com.faceclaw.app.FaceclawMediaBrowser(context); this.browser = new com.faceclaw.app.FaceclawMediaBrowser(context);
onSettingsStoreChanged((key) => {
if (key === MEDIA_APPS_KEY && this.connectedPackage && !isMediaAppEnabled(this.connectedPackage)) {
this.disconnect();
}
});
this.listenerProxy = new com.faceclaw.app.FaceclawMediaBrowserListener({ this.listenerProxy = new com.faceclaw.app.FaceclawMediaBrowserListener({
onConnectResult: (requestId: number, connected: boolean, rootId: string, error: string) => { onConnectResult: (requestId: number, connected: boolean, rootId: string, error: string) => {
const pending = this.pendingConnects.get(Number(requestId)); const pending = this.pendingConnects.get(Number(requestId));
+17
View File
@@ -1,6 +1,8 @@
import { Utils } from "@nativescript/core"; import { Utils } from "@nativescript/core";
import { GrayImage } from "../graphics/image"; import { GrayImage } from "../graphics/image";
import { grayImageFromPacket, PHOTO_TONE } from "./image-files"; import { grayImageFromPacket, PHOTO_TONE } from "./image-files";
import { ignoredMediaPackages, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
import { onSettingsStoreChanged } from "./settings-store";
declare const com: any; declare const com: any;
@@ -173,7 +175,22 @@ export class FaceclawMediaControllerBridge {
throw new Error("Android application context unavailable"); throw new Error("Android application context unavailable");
} }
this.controller = new com.faceclaw.app.FaceclawMediaController(context); this.controller = new com.faceclaw.app.FaceclawMediaController(context);
// Install defaults and saved overrides before starting session discovery.
this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
onSettingsStoreChanged((key) => {
if (key === MEDIA_APPS_KEY) {
this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
}
});
this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({ this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({
onSessionAppsChanged: (appsJson: string) => {
try {
const apps = JSON.parse(String(appsJson));
rememberMediaApps(apps);
} catch (error) {
console.warn(`media session apps parse failed: ${error}`);
}
},
onStateChange: ( onStateChange: (
playbackState: string, playbackState: string,
packageName: string, packageName: string,
+13 -9
View File
@@ -1,4 +1,4 @@
import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings"; import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
import { fetchWithUserAgent } from "../util/http"; import { fetchWithUserAgent } from "../util/http";
export type NightscoutPoint = { export type NightscoutPoint = {
@@ -33,6 +33,10 @@ export type NightscoutState = {
iob: number | null; iob: number | null;
cob: number | null; cob: number | null;
cageTimestampMs: number | null; cageTimestampMs: number | null;
reservoirUnits: number | null;
batteryVoltage: number | null;
loopTimestampMs: number | null;
/** Pump communication age and operating state; measurements are separate. */
pumpStatus: string; pumpStatus: string;
openapsStatusShort: string; openapsStatusShort: string;
carbs: NightscoutCarbEvent[]; carbs: NightscoutCarbEvent[];
@@ -121,6 +125,9 @@ const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = {
iob: null, iob: null,
cob: null, cob: null,
cageTimestampMs: null, cageTimestampMs: null,
reservoirUnits: null,
batteryVoltage: null,
loopTimestampMs: null,
pumpStatus: "", pumpStatus: "",
openapsStatusShort: "--", openapsStatusShort: "--",
carbs: [], carbs: [],
@@ -259,6 +266,9 @@ export class NightscoutBridge {
iob: Number.isFinite(iob) ? iob : null, iob: Number.isFinite(iob) ? iob : null,
cob, cob,
cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null, cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null,
reservoirUnits: firstFiniteNumber(latestDeviceStatus?.pump?.reservoir),
batteryVoltage: firstFiniteNumber(latestDeviceStatus?.pump?.battery?.voltage),
loopTimestampMs: loopTimestampMs > 0 ? loopTimestampMs : null,
pumpStatus, pumpStatus,
openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--", openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--",
carbs: parsedTreatments.carbs, carbs: parsedTreatments.carbs,
@@ -359,6 +369,8 @@ function parseTimestampMs(value: unknown): number {
function firstFiniteNumber(...values: unknown[]): number | null { function firstFiniteNumber(...values: unknown[]): number | null {
for (const value of values) { for (const value of values) {
if (typeof value !== "number" && typeof value !== "string") continue;
if (typeof value === "string" && !value.trim()) continue;
const numeric = Number(value); const numeric = Number(value);
if (Number.isFinite(numeric)) { if (Number.isFinite(numeric)) {
return numeric; return numeric;
@@ -371,8 +383,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
if (!status?.pump) { if (!status?.pump) {
return "--"; return "--";
} }
const reservoir = firstFiniteNumber(status.pump.reservoir);
const voltage = firstFiniteNumber(status.pump.battery?.voltage);
const commTimestampMs = Math.max( const commTimestampMs = Math.max(
parseTimestampMs(status.pump.status?.timestamp), parseTimestampMs(status.pump.status?.timestamp),
parseTimestampMs(status.pump.clock), parseTimestampMs(status.pump.clock),
@@ -380,12 +390,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
); );
const stateLabel = summarizePumpState(status); const stateLabel = summarizePumpState(status);
const parts: string[] = []; const parts: string[] = [];
if (reservoir !== null) {
parts.push(`${Math.round(reservoir)}U`);
}
if (voltage !== null) {
parts.push(`${voltage.toFixed(2)}v`);
}
if (commTimestampMs > 0) { if (commTimestampMs > 0) {
parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`); parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`);
} }
+6 -1
View File
@@ -1,10 +1,13 @@
import { GrayImage } from "../graphics/image"; import { GrayImage } from "../graphics/image";
import { logCurrent, spanCurrent } from "./frame-timings"; import { logCurrent, spanCurrent } from "./frame-timings";
import { toUint8Array } from "../util/array-util"; import { toUint8Array } from "../util/array-util";
import { rememberNotificationSources } from "./notification-sources";
declare const com: any; declare const com: any;
const ICON_SIZE = 24; const ICON_SIZE = 24;
/** Ask the native listener for every active source, including those below the list's display limit. */
export const ALL_NOTIFICATIONS = 0x7fffffff;
// Backstop TTL only: the icon caches are invalidated eagerly whenever a // Backstop TTL only: the icon caches are invalidated eagerly whenever a
// notification is posted or dismissed (see invalidateIconCaches callers), so // notification is posted or dismissed (see invalidateIconCaches callers), so
// the tray is kept fresh by invalidation, not by expiry. A short TTL just // the tray is kept fresh by invalidation, not by expiry. A short TTL just
@@ -158,7 +161,9 @@ export function readActiveNotifications(maxNotifications = 50): AndroidNotificat
); );
const parsed = JSON.parse(json); const parsed = JSON.parse(json);
if (!Array.isArray(parsed)) return []; if (!Array.isArray(parsed)) return [];
return parsed.map(normalizeNotification).filter((item): item is AndroidNotification => Boolean(item)); const notifications = parsed.map(normalizeNotification).filter((item): item is AndroidNotification => Boolean(item));
rememberNotificationSources(notifications);
return notifications;
} catch { } catch {
return []; return [];
} }
+59
View File
@@ -0,0 +1,59 @@
import { getStringSetting, setStringSetting } from "./settings-store";
const SOURCES_KEY = "notifications.sources";
export type NotificationSource = {
packageName: string;
appName: string;
showOnGlasses: boolean;
};
/** Sources outlive their active notifications so a muted app can always be re-enabled. */
export function readNotificationSources(): NotificationSource[] {
try {
const parsed = JSON.parse(getStringSetting(SOURCES_KEY, "[]"));
if (!Array.isArray(parsed)) return [];
return parsed.filter((source) => source && typeof source.packageName === "string" && source.packageName)
.map((source) => ({
packageName: source.packageName,
appName: typeof source.appName === "string" && source.appName ? source.appName : source.packageName,
showOnGlasses: source.showOnGlasses !== false,
}));
} catch {
return [];
}
}
export function rememberNotificationSources(notifications: { packageName: string; appName: string }[]): void {
const sources = new Map(readNotificationSources().map((source) => [source.packageName, source]));
let changed = false;
for (const notification of notifications) {
if (!notification.packageName) continue;
const previous = sources.get(notification.packageName);
const appName = notification.appName || previous?.appName || notification.packageName;
if (!previous || previous.appName !== appName) {
sources.set(notification.packageName, {
packageName: notification.packageName,
appName,
showOnGlasses: previous?.showOnGlasses ?? true,
});
changed = true;
}
}
if (changed) setStringSetting(SOURCES_KEY, JSON.stringify(Array.from(sources.values())));
}
export function shouldShowNotificationOnGlasses(packageName: string): boolean {
return readNotificationSources().find((source) => source.packageName === packageName)?.showOnGlasses ?? true;
}
export function setNotificationSourceEnabled(source: { packageName: string; appName: string }, enabled: boolean): void {
if (!source.packageName) return;
const sources = new Map(readNotificationSources().map((item) => [item.packageName, item]));
sources.set(source.packageName, {
packageName: source.packageName,
appName: source.appName || source.packageName,
showOnGlasses: enabled,
});
setStringSetting(SOURCES_KEY, JSON.stringify(Array.from(sources.values())));
}
+30
View File
@@ -0,0 +1,30 @@
import { Application, isAndroid } from "@nativescript/core";
import { getStringSetting, onSettingsStoreChanged } from "./settings-store";
// Shared with phoneRotationSetting; keep startup independent of the glasses UI.
const ROTATION_KEY = "phone.rotation";
/** Installed once on the UI thread; also covers navigation and activity recreation. */
export function registerPhoneRotation(): void {
if (!isAndroid) return;
const apply = (activity = Application.android.foregroundActivity ?? Application.android.startActivity): void => {
if (!activity) return;
const orientations = android.content.pm.ActivityInfo;
const requested = {
auto: orientations.SCREEN_ORIENTATION_UNSPECIFIED,
portrait: orientations.SCREEN_ORIENTATION_PORTRAIT,
landscape: orientations.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
}[getStringSetting(ROTATION_KEY, "auto")] ?? orientations.SCREEN_ORIENTATION_UNSPECIFIED;
if (activity.getRequestedOrientation() !== requested) {
activity.setRequestedOrientation(requested);
}
};
Application.android.on(Application.android.activityCreatedEvent, (args) => apply(args.activity));
Application.android.on(Application.android.activityResumedEvent, (args) => apply(args.activity));
onSettingsStoreChanged((key) => {
if (key === ROTATION_KEY) apply();
});
apply();
}
+5 -5
View File
@@ -1,4 +1,4 @@
import { Application, Color, EventData, isAndroid, Observable, Page, TextField } from '@nativescript/core' import { Application, Color, EventData, isAndroid, Observable, Page, TextField, TextView } from '@nativescript/core'
import { MainViewModel } from './main-view-model' import { MainViewModel } from './main-view-model'
import { dashboardController } from '../g2/dashboard-controller' import { dashboardController } from '../g2/dashboard-controller'
@@ -44,7 +44,7 @@ function cleanupPage(page: Page): void {
* suits replacing an existing setting value; a message being composed keeps * suits replacing an existing setting value; a message being composed keeps
* its caret where the user taps. * its caret where the user taps.
*/ */
function applySettingsTextFieldContrast(textField: TextField, selectAllOnFocus = true): void { function applySettingsTextFieldContrast(textField: TextField | TextView, selectAllOnFocus = true): void {
textField.color = SETTINGS_TEXT_COLOR textField.color = SETTINGS_TEXT_COLOR
textField.backgroundColor = SETTINGS_BACKGROUND_COLOR textField.backgroundColor = SETTINGS_BACKGROUND_COLOR
textField.placeholderColor = SETTINGS_PLACEHOLDER_COLOR textField.placeholderColor = SETTINGS_PLACEHOLDER_COLOR
@@ -53,7 +53,7 @@ function applySettingsTextFieldContrast(textField: TextField, selectAllOnFocus =
return return
} }
const nativeTextField = (textField as TextField & { nativeView?: android.widget.EditText }).nativeView const nativeTextField = (textField as (TextField | TextView) & { nativeView?: android.widget.EditText }).nativeView
if (!nativeTextField) { if (!nativeTextField) {
return return
} }
@@ -90,13 +90,13 @@ function focusTextEditor(page: Page): void {
/** The keyboard dialog closed on the glasses (sent, discarded, or screen off). */ /** The keyboard dialog closed on the glasses (sent, discarded, or screen off). */
function dismissKeyboardInputKeyboard(page: Page): void { function dismissKeyboardInputKeyboard(page: Page): void {
page.getViewById<TextField>('keyboardInputField')?.dismissSoftInput() page.getViewById<TextView>('keyboardInputField')?.dismissSoftInput()
} }
/** The keyboard dialog opened: bring up the IME on its field right away. */ /** The keyboard dialog opened: bring up the IME on its field right away. */
function focusKeyboardInput(page: Page): void { function focusKeyboardInput(page: Page): void {
setTimeout(() => { setTimeout(() => {
const textField = page.getViewById<TextField>('keyboardInputField') const textField = page.getViewById<TextView>('keyboardInputField')
if (textField) { if (textField) {
applySettingsTextFieldContrast(textField, false) applySettingsTextFieldContrast(textField, false)
textField.focus() textField.focus()
+26 -27
View File
@@ -38,30 +38,31 @@
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
<GridLayout class="p-20" visibility="{{ landscapeLayoutVisibility }}"> <GridLayout class="landscape-layout" visibility="{{ landscapeLayoutVisibility }}">
<GridLayout rows="auto" columns="*,360"> <GridLayout rows="*" columns="*,345">
<StackLayout row="0" col="0" visibility="{{ displayPreviewVisibility }}" horizontalAlignment="left"> <GridLayout col="0" layoutChanged="{{ onLandscapePreviewLayoutChanged }}">
<Image <StackLayout visibility="{{ displayPreviewVisibility }}" horizontalAlignment="left" verticalAlignment="center">
src="{{ displayPreview }}" <Image
stretch="fill" src="{{ displayPreview }}"
stretch="fill"
width="{{ landscapeDisplayPreviewWidth }}"
height="{{ landscapeDisplayPreviewHeight }}"
tap="{{ onMirrorTap }}" doubleTap="{{ onMirrorDoubleTap }}" longPress="{{ onMirrorLongPress }}" swipe="{{ onMirrorSwipe }}" />
</StackLayout>
<GridLayout
class="display-preview-message"
horizontalAlignment="left"
verticalAlignment="center"
width="{{ landscapeDisplayPreviewWidth }}" width="{{ landscapeDisplayPreviewWidth }}"
height="{{ landscapeDisplayPreviewHeight }}" height="{{ landscapeDisplayPreviewHeight }}"
tap="{{ onMirrorTap }}" doubleTap="{{ onMirrorDoubleTap }}" longPress="{{ onMirrorLongPress }}" swipe="{{ onMirrorSwipe }}" /> visibility="{{ displayPreviewMessageVisibility }}">
</StackLayout> <Label text="{{ displayPreviewMessage }}" textWrap="true" horizontalAlignment="center" verticalAlignment="center" />
<GridLayout </GridLayout>
row="0" </GridLayout>
col="0" <GridLayout col="1" rows="*,auto">
class="display-preview-message" <rc:remote-controls row="0" visibility="{{ controlsVisibility }}" />
horizontalAlignment="left" <Button row="1" text="Stop recording" tap="{{ onStopRecordingTap }}" visibility="{{ stopRecordingButtonVisibility }}" />
width="{{ landscapeDisplayPreviewWidth }}"
height="{{ landscapeDisplayPreviewHeight }}"
visibility="{{ displayPreviewMessageVisibility }}">
<Label text="{{ displayPreviewMessage }}" textWrap="true" horizontalAlignment="center" verticalAlignment="center" />
</GridLayout> </GridLayout>
<StackLayout row="0" col="1" class="m-l-16">
<rc:remote-controls visibility="{{ controlsVisibility }}" />
<Button text="Stop recording" tap="{{ onStopRecordingTap }}" visibility="{{ stopRecordingButtonVisibility }}" />
</StackLayout>
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
<!-- Developer BLE-bandwidth indicator: overlays the bottom edge of the <!-- Developer BLE-bandwidth indicator: overlays the bottom edge of the
@@ -153,22 +154,20 @@
<!-- Keyboard-input panel (the keyboard button beside the mic button): <!-- Keyboard-input panel (the keyboard button beside the mic button):
the phone's end of the keyboard dialog on the glasses the phone's end of the keyboard dialog on the glasses
(ui/shell/keyboard-input.ts). Same placement and collapsing rules (ui/shell/keyboard-input.ts). Same placement and collapsing rules
as the setting editor above. The IME's send key goes to whichever as the setting editor above. Enter inserts a newline; the send
destination is highlighted on the glasses; the buttons pick one buttons pick a destination directly. -->
directly. -->
<StackLayout <StackLayout
class="system-name-modal" class="system-name-modal"
visibility="{{ keyboardInputVisibility }}" visibility="{{ keyboardInputVisibility }}"
horizontalAlignment="stretch" horizontalAlignment="stretch"
verticalAlignment="bottom"> verticalAlignment="bottom">
<Label text="Keyboard input" class="h2" /> <Label text="Keyboard input" class="h2" />
<TextField <TextView
id="keyboardInputField" id="keyboardInputField"
text="{{ keyboardInputText }}" text="{{ keyboardInputText }}"
hint="Type a message" hint="Type a message"
textChange="{{ onKeyboardInputTextChange }}" textChange="{{ onKeyboardInputTextChange }}"
returnPress="{{ onKeyboardInputReturnPress }}" height="120" />
returnKeyType="send" />
<!-- Wraps onto a second line when the labels don't fit side by side. --> <!-- Wraps onto a second line when the labels don't fit side by side. -->
<FlexboxLayout flexWrap="wrap" class="m-t-8"> <FlexboxLayout flexWrap="wrap" class="m-t-8">
<Button text="{{ keyboardInputPrimaryTargetLabel }}" tap="{{ onKeyboardInputPrimarySendTap }}" visibility="{{ keyboardInputPrimaryTargetVisibility }}" flexGrow="1" class="-primary" /> <Button text="{{ keyboardInputPrimaryTargetLabel }}" tap="{{ onKeyboardInputPrimarySendTap }}" visibility="{{ keyboardInputPrimaryTargetVisibility }}" flexGrow="1" class="-primary" />
+41 -24
View File
@@ -45,6 +45,9 @@ export class MainViewModel extends Observable {
private _displayPreview: ImageSource | null = null; private _displayPreview: ImageSource | null = null;
private _displayPreviewMessage = ""; private _displayPreviewMessage = "";
private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation(); private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation();
private _landscapePreviewWidth = 0;
private _landscapePreviewHeight = 0;
private _controlsContentHeight = 250;
private _activeTextSettingId: string | null = null; private _activeTextSettingId: string | null = null;
private _activeTextEditorTitle = ""; private _activeTextEditorTitle = "";
private _activeTextSettingTitle = ""; private _activeTextSettingTitle = "";
@@ -237,18 +240,25 @@ export class MainViewModel extends Observable {
} }
get landscapeDisplayPreviewWidth(): number { get landscapeDisplayPreviewWidth(): number {
return Math.floor(this.landscapeDisplayPreviewHeight * LENS_ASPECT_RATIO); return this._landscapePreviewWidth;
} }
get landscapeDisplayPreviewHeight(): number { get landscapeDisplayPreviewHeight(): number {
// Height keeps the vertical footprint the preview had at the old 2:1 return this._landscapePreviewHeight;
// aspect; the width is derived from it, so a wider lens aspect can't }
// grow the preview past the side panel.
const screenWidth = Screen.mainScreen.widthDIPs; onLandscapePreviewLayoutChanged(args: { object: View }): void {
// Must match the landscape grid's fixed side-panel column in main-page.xml. // Measure the actual content cell: excludes the action bar, system bars,
const sidePanelWidth = 360; // and controls, and updates for rotation, split-screen, and the keyboard.
const availableWidth = Math.max(240, Math.floor(screenWidth - sidePanelWidth - 56)); const { width, height } = args.object.getActualSize();
return Math.floor(availableWidth / 2); if (width <= 0 || height <= 0) return;
const previewHeight = Math.min(height, width / LENS_ASPECT_RATIO);
const previewWidth = previewHeight * LENS_ASPECT_RATIO;
if (previewWidth === this._landscapePreviewWidth && previewHeight === this._landscapePreviewHeight) return;
this._landscapePreviewWidth = previewWidth;
this._landscapePreviewHeight = previewHeight;
this.notifyPropertyChange("landscapeDisplayPreviewWidth", previewWidth);
this.notifyPropertyChange("landscapeDisplayPreviewHeight", previewHeight);
} }
/** Near-full-width on phones, capped on tablets (the 32 clears the 16 margins). */ /** Near-full-width on phones, capped on tablets (the 32 clears the 16 margins). */
@@ -265,13 +275,27 @@ export class MainViewModel extends Observable {
const faceHeight = 230; const faceHeight = 230;
const available = const available =
this._layoutOrientation === "landscape" this._layoutOrientation === "landscape"
? // The landscape side panel column (see main-page.xml) minus its ? 345 // Matches the unpadded landscape controls column in main-page.xml.
// m-l-16 margin and the controls' own 8+8 margins.
360 - 32
: Screen.mainScreen.widthDIPs - 56; // p-20 padding + controls margins : Screen.mainScreen.widthDIPs - 56; // p-20 padding + controls margins
return Math.min(available, Math.round(faceHeight * 1.5)); return Math.min(available, Math.round(faceHeight * 1.5));
} }
get watchFaceHeight(): number {
return Math.min(230, Math.max(0, this._controlsContentHeight - 2));
}
get ringTouchpadHeight(): number {
return Math.min(250, Math.max(0, this._controlsContentHeight - 2));
}
onControlsContentLayoutChanged(args: { object: View }): void {
const { height } = args.object.getActualSize();
if (height <= 0 || height === this._controlsContentHeight) return;
this._controlsContentHeight = height;
this.notifyPropertyChange("watchFaceHeight", this.watchFaceHeight);
this.notifyPropertyChange("ringTouchpadHeight", this.ringTouchpadHeight);
}
get portraitLayoutVisibility(): "visible" | "collapse" { get portraitLayoutVisibility(): "visible" | "collapse" {
return this._layoutOrientation === "portrait" ? "visible" : "collapse"; return this._layoutOrientation === "portrait" ? "visible" : "collapse";
} }
@@ -541,18 +565,11 @@ export class MainViewModel extends Observable {
} }
onKeyboardInputTextChange(args: { value?: string; object?: { text?: string } }): void { onKeyboardInputTextChange(args: { value?: string; object?: { text?: string } }): void {
dashboardController.setKeyboardInputText(args.object?.text ?? args.value ?? ""); const text = args.object?.text ?? args.value ?? "";
} // Track the draft so closing the dialog emits a clear even when the
// binding hasn't updated the model. Avoid echoing edits into the IME.
/** The IME's send key: the destination highlighted on the glasses. */ this._keyboardInputText = text;
onKeyboardInputReturnPress(args: { object?: { text?: string } }): void { dashboardController.setKeyboardInputText(text);
// Commit the field's actual text at send-time, in case the final
// keystroke's textChange hadn't landed yet.
const text = args?.object?.text;
if (typeof text === "string") {
dashboardController.setKeyboardInputText(text);
}
dashboardController.sendKeyboardInput();
} }
onKeyboardInputPrimarySendTap(): void { onKeyboardInputPrimarySendTap(): void {
+40 -41
View File
@@ -20,9 +20,9 @@
acts as star, and this component sits in a bounded (star-row) parent, acts as star, and this component sits in a bounded (star-row) parent,
where that would balloon the first grid to fill all remaining height. --> where that would balloon the first grid to fill all remaining height. -->
<GridLayout row="0" rows="auto" columns="*,*,*,auto,auto" class="controls-tab-bar"> <GridLayout row="0" rows="auto" columns="*,*,*,auto,auto" class="controls-tab-bar">
<Button col="0" text="Settings" tap="{{ onSettingsTabTap }}" class="{{ settingsTabClass }}" /> <Button col="0" text="Settings" textWrap="false" tap="{{ onSettingsTabTap }}" class="{{ settingsTabClass }}" />
<Button col="1" text="Watch" tap="{{ onWatchTabTap }}" class="{{ watchTabClass }}" /> <Button col="1" text="Watch" textWrap="false" tap="{{ onWatchTabTap }}" class="{{ watchTabClass }}" />
<Button col="2" text="Ring" tap="{{ onRingTabTap }}" class="{{ ringTabClass }}" /> <Button col="2" text="Ring" textWrap="false" tap="{{ onRingTabTap }}" class="{{ ringTabClass }}" />
<!-- A Button can't hold an image, so these are button-styled tiles. The <!-- A Button can't hold an image, so these are button-styled tiles. The
explicit star row makes the cell fill the tile's height so the icon's explicit star row makes the cell fill the tile's height so the icon's
center alignment has room to work in. --> center alignment has room to work in. -->
@@ -34,48 +34,47 @@
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
<!-- Settings tab --> <GridLayout row="1" layoutChanged="{{ onControlsContentLayoutChanged }}">
<StackLayout row="1" visibility="{{ settingsTabVisibility }}"> <!-- Settings tab -->
<GridLayout rows="auto" columns="auto,*" class="settings-row"> <StackLayout visibility="{{ settingsTabVisibility }}">
<Label col="0" text="Screen size" class="settings-row-label" verticalAlignment="center" /> <GridLayout rows="auto" columns="auto,*" class="settings-row">
<Button col="1" text="{{ displayModeLabel }}" tap="{{ onDisplayModeTap }}" class="mode-button" horizontalAlignment="left" /> <Label col="0" text="Screen size" class="settings-row-label" verticalAlignment="center" />
</GridLayout> <Button col="1" text="{{ displayModeLabel }}" tap="{{ onDisplayModeTap }}" class="mode-button" horizontalAlignment="left" />
<GridLayout rows="auto" columns="auto,*,auto" class="settings-row"> </GridLayout>
<Label col="0" text="☀" class="brightness-icon" verticalAlignment="center" /> <GridLayout rows="auto" columns="auto,*,auto" class="settings-row">
<Slider col="1" width="100%" minValue="0" maxValue="100" value="{{ brightnessPercent }}" valueChange="{{ onBrightnessChange }}" isEnabled="{{ brightnessSliderEnabled }}" /> <Label col="0" text="☀" class="brightness-icon" verticalAlignment="center" />
<StackLayout col="2" orientation="horizontal" verticalAlignment="center" class="auto-toggle"> <Slider col="1" width="100%" minValue="0" maxValue="100" value="{{ brightnessPercent }}" valueChange="{{ onBrightnessChange }}" isEnabled="{{ brightnessSliderEnabled }}" />
<Label text="Auto" verticalAlignment="center" /> <StackLayout col="2" orientation="horizontal" verticalAlignment="center" class="auto-toggle">
<Switch checked="{{ brightnessAuto }}" checkedChange="{{ onBrightnessAutoChange }}" /> <Label text="Auto" verticalAlignment="center" />
</StackLayout> <Switch checked="{{ brightnessAuto }}" checkedChange="{{ onBrightnessAutoChange }}" />
</GridLayout> </StackLayout>
</StackLayout> </GridLayout>
</StackLayout>
<!-- Watch tab: centered in the leftover height, capped at the 1.5:1 face <!-- Watch tab: centered in the leftover height, capped at the 1.5:1 face
aspect (watchFaceWidth = min(available, 1.5 x face height). --> aspect (watchFaceWidth = min(available, 1.5 x face height). -->
<StackLayout row="1" visibility="{{ watchTabVisibility }}" width="{{ watchFaceWidth }}" horizontalAlignment="center" verticalAlignment="center"> <GridLayout visibility="{{ watchTabVisibility }}" width="{{ watchFaceWidth }}" height="{{ watchFaceHeight }}" horizontalAlignment="center" verticalAlignment="center" class="touchpad" tap="{{ onPadTap }}" doubleTap="{{ onPadDoubleTap }}" longPress="{{ onPadLongPress }}" swipe="{{ onPadSwipe }}" touch="{{ onPadTouch }}">
<GridLayout class="touchpad" tap="{{ onPadTap }}" doubleTap="{{ onPadDoubleTap }}" longPress="{{ onPadLongPress }}" swipe="{{ onPadSwipe }}" touch="{{ onPadTouch }}">
<Label text="{{ padFocusLine }}" class="pad-focus" horizontalAlignment="center" verticalAlignment="center" /> <Label text="{{ padFocusLine }}" class="pad-focus" horizontalAlignment="center" verticalAlignment="center" />
<Label text="▲▼ swipe ● select ●● back ‒ menu" class="pad-legend" horizontalAlignment="center" verticalAlignment="bottom" /> <Label text="▲▼ swipe ● select ●● back ‒ menu" class="pad-legend" horizontalAlignment="center" verticalAlignment="bottom" />
</GridLayout> </GridLayout>
</StackLayout>
<!-- Ring tab: a touchpad on the ring's own scheme. Vertical swipes only <!-- Ring tab: a touchpad on the ring's own scheme. Vertical swipes only
(the ring has no horizontal axis) and no focus/status line; portrait (the ring has no horizontal axis) and no focus/status line; portrait
like the ring's pad itself. The auto rows hold the cosmetic markings the like the ring's pad itself. The auto rows hold the cosmetic markings the
physical ring has on its touch strip (they don't take touches); the star physical ring has on its touch strip (they don't take touches); the star
rows are the seven equal gaps around them, edges included. --> rows are the seven equal gaps around them, edges included. -->
<GridLayout row="1" visibility="{{ ringTabVisibility }}" class="touchpad ring-touchpad" <GridLayout visibility="{{ ringTabVisibility }}" height="{{ ringTouchpadHeight }}" class="touchpad ring-touchpad"
rows="*,auto,*,auto,*,auto,*,auto,*,auto,*,auto,*" rows="*,auto,*,auto,*,auto,*,auto,*,auto,*,auto,*"
horizontalAlignment="center" verticalAlignment="center" horizontalAlignment="center" verticalAlignment="center"
tap="{{ onRingPadTap }}" doubleTap="{{ onRingPadDoubleTap }}" tap="{{ onRingPadTap }}" doubleTap="{{ onRingPadDoubleTap }}"
longPress="{{ onRingPadLongPress }}" swipe="{{ onRingPadSwipe }}" longPress="{{ onRingPadLongPress }}" swipe="{{ onRingPadSwipe }}"
touch="{{ onRingPadTouch }}"> touch="{{ onRingPadTouch }}">
<Label row="1" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="1" class="ring-pad-marking" isUserInteractionEnabled="false" />
<Label row="3" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="3" class="ring-pad-marking" isUserInteractionEnabled="false" />
<Label row="5" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="5" class="ring-pad-marking" isUserInteractionEnabled="false" />
<Label row="7" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="7" class="ring-pad-marking" isUserInteractionEnabled="false" />
<Label row="9" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="9" class="ring-pad-marking" isUserInteractionEnabled="false" />
<Label row="11" class="ring-pad-marking" isUserInteractionEnabled="false" /> <Label row="11" class="ring-pad-marking" isUserInteractionEnabled="false" />
</GridLayout>
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
+54
View File
@@ -1,3 +1,4 @@
import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures"; import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import { import {
getBooleanSetting, getBooleanSetting,
@@ -290,6 +291,17 @@ export const lockScreenEnabledSetting = new ConfigSettingBoolean({
// Phone display: the phone app's mirror of the glasses screen and the // Phone display: the phone app's mirror of the glasses screen and the
// controls around it on the main page. // controls around it on the main page.
export type PreviewColor = "white" | "green"; export type PreviewColor = "white" | "green";
export type PhoneRotation = "auto" | "portrait" | "landscape";
export const phoneRotationSetting = new ConfigSettingEnum<PhoneRotation>({
id: "phone-rotation",
label: "Rotation",
storageKey: "phone.rotation",
defaultValue: "auto",
values: ["auto", "portrait", "landscape"],
formatValue: (value) => ({ auto: "Auto-Rotate", portrait: "Always Portrait", landscape: "Always Landscape" })[value],
description: "Automatically rotate with the phone, or keep the phone app in portrait or landscape. Auto-Rotate follows the phone's system rotation preference.",
});
export const previewColorSetting = new ConfigSettingEnum<PreviewColor>({ export const previewColorSetting = new ConfigSettingEnum<PreviewColor>({
id: "preview-color", id: "preview-color",
@@ -760,6 +772,48 @@ export const nightscoutApiTokenSetting = new ConfigSettingString({
description: "Access token for the Nightscout site's API.", description: "Access token for the Nightscout site's API.",
}); });
function nightscoutThresholdSetting(id: string, label: string, unit: string, description: string): ConfigSettingString {
return new ConfigSettingString({
id: `nightscout-${id}`,
label,
storageKey: `integrations.nightscout.${id}`,
defaultValue: "0",
editorTitle: `${label} (${unit}; 0 = off)`,
normalize: normalizeNightscoutThreshold,
formatValue: (value) => Number(value) > 0 ? `${value} ${unit}` : "Off",
description: `${description} Enter 0 to disable.`,
});
}
export const nightscoutMaxCannulaAgeSetting = nightscoutThresholdSetting(
"max-cannula-age-hours", "Max cannula age", "h", "Warn when time since the last site change exceeds this many hours.",
);
export const nightscoutCartridgeLowSetting = nightscoutThresholdSetting(
"cartridge-low-units", "Cartridge low threshold", "U", "Warn when the pump reservoir falls below this many units.",
);
export const nightscoutBatteryLowSetting = nightscoutThresholdSetting(
"battery-low-voltage", "Battery voltage threshold", "V", "Warn when pump battery voltage falls below this value.",
);
export const nightscoutMaxLoopAgeSetting = nightscoutThresholdSetting(
"max-loop-age-minutes", "Max time since last loop", "min", "Warn when time since the last loop exceeds this many minutes.",
);
export const nightscoutAlwaysShowInTopBarSetting = new ConfigSettingBoolean({
id: "nightscout-always-show-in-top-bar",
label: "Always show in top bar",
storageKey: "integrations.nightscout.alwaysShowInTopBar",
defaultValue: false,
description: "Keep the Nightscout glucose graph and warnings in the top bar even when all Nightscout windows are closed.",
});
export function loadNightscoutThresholds(): NightscoutThresholds {
return {
maxCannulaAgeHours: Number(nightscoutMaxCannulaAgeSetting.get()),
cartridgeLowUnits: Number(nightscoutCartridgeLowSetting.get()),
batteryLowVoltage: Number(nightscoutBatteryLowSetting.get()),
maxLoopAgeMinutes: Number(nightscoutMaxLoopAgeSetting.get()),
};
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Navigate app: saved and recent destinations. // Navigate app: saved and recent destinations.
+2
View File
@@ -48,6 +48,7 @@ import {
navigateWorkAddressSetting, navigateWorkAddressSetting,
openAiApiKeySetting, openAiApiKeySetting,
previewColorSetting, previewColorSetting,
phoneRotationSetting,
ringConnectionModeSetting, ringConnectionModeSetting,
sonioxApiKeySetting, sonioxApiKeySetting,
enumSettingMenuItem, enumSettingMenuItem,
@@ -177,6 +178,7 @@ function settingsSections(): SettingsSection[] {
// The phone app's mirror of the glasses screen and its controls // The phone app's mirror of the glasses screen and its controls
// (app/phone-ui/): all read live by the main page. // (app/phone-ui/): all read live by the main page.
items: [ items: [
enumSettingMenuItem(phoneRotationSetting),
enumSettingMenuItem(previewColorSetting), enumSettingMenuItem(previewColorSetting),
toggleSettingMenuItem(mirrorTouchSetting), toggleSettingMenuItem(mirrorTouchSetting),
], ],
+50
View File
@@ -0,0 +1,50 @@
import { getDefaultSmallFont } from "../graphics/ui-fonts";
import { GrayImage } from "../graphics/image";
import { truncateText } from "../graphics/textwrap";
import { ALL_NOTIFICATIONS, readActiveNotifications } from "../native/notification-icons";
import { readNotificationSources, setNotificationSourceEnabled, shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { type InputEvent } from "./gestures";
import { type Layer, type LayerContext, type PaintBelow } from "./layers";
import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu";
/** Rebuild rows when new sources arrive, keeping the current selection by package. */
export class NotificationFilterLayer implements Layer {
private menu: MenuLayer | null = null;
private packages = "";
private selectedPackage = "";
private currentMenu(ctx: LayerContext): MenuLayer {
readActiveNotifications(ALL_NOTIFICATIONS);
const sources = readNotificationSources().sort((a, b) =>
a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
const signature = JSON.stringify([ctx.stack.getBaseSize().width, sources.map((source) => [source.packageName, source.appName])]);
if (!this.menu || signature !== this.packages) {
this.packages = signature;
const items: MenuItem[] = sources.map((source) => ({
label: source.appName,
onSelect: () => setNotificationSourceEnabled(source, !shouldShowNotificationOnGlasses(source.packageName)),
render: ({ image, x, y, width, selected }) => {
if (selected) this.selectedPackage = source.packageName;
const font = getDefaultSmallFont();
drawToggleMenuItem(image, font, x, y, width, truncateText(font, source.appName, width - 48),
shouldShowNotificationOnGlasses(source.packageName), selected);
},
}));
if (!items.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} });
this.menu = new MenuLayer("Notification filter", items, {
x: 8, y: 8, width: ctx.stack.getBaseSize().width - 16,
opaque: true, showBorder: false,
footer: "On = show popups on glasses",
}).selectItem(Math.max(0, sources.findIndex((source) => source.packageName === this.selectedPackage)));
}
return this.menu;
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
return this.currentMenu(ctx).paint(ctx, paintBelow);
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
await this.currentMenu(ctx).handleInput(event, ctx);
}
}
+75 -14
View File
@@ -6,6 +6,7 @@ import { GrayImage, type UiFont } from "../graphics/image";
import { wrapText } from "../graphics/textwrap"; import { wrapText } from "../graphics/textwrap";
import { lineStep, listRowHeight } from "./metrics"; import { lineStep, listRowHeight } from "./metrics";
import { import {
ALL_NOTIFICATIONS,
dismissNotification, dismissNotification,
invokeNotificationAction, invokeNotificationAction,
readActiveNotifications, readActiveNotifications,
@@ -13,10 +14,12 @@ import {
type AndroidNotification, type AndroidNotification,
type AndroidNotificationAction, type AndroidNotificationAction,
} from "../native/notification-icons"; } from "../native/notification-icons";
import { setNotificationSourceEnabled } from "../native/notification-sources";
import { isNotificationListenerEnabled } from "../native/notification-access"; import { isNotificationListenerEnabled } from "../native/notification-access";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-freshness"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-freshness";
import { type InputEvent } from "./gestures"; import { type InputEvent } from "./gestures";
import { type Layer, type LayerContext, type PaintBelow } from "./layers"; import { type Layer, type LayerContext, type PaintBelow } from "./layers";
import { MenuLayer } from "./menu";
const PAGE_X = 12; const PAGE_X = 12;
const PAGE_Y = 12; const PAGE_Y = 12;
@@ -52,7 +55,8 @@ type CardLayout = {
type DetailMenuItem = type DetailMenuItem =
| { kind: "back"; label: string } | { kind: "back"; label: string }
| { kind: "action"; label: string; action: AndroidNotificationAction } | { kind: "action"; label: string; action: AndroidNotificationAction }
| { kind: "dismiss"; label: string }; | { kind: "dismiss"; label: string }
| { kind: "disable-source"; label: string };
export type SingleNotificationLayerOrigin = "notifications-list" | "new-notification-modal"; export type SingleNotificationLayerOrigin = "notifications-list" | "new-notification-modal";
@@ -167,6 +171,7 @@ export class NotificationsListLayer implements Layer {
*/ */
export class SingleNotificationLayer implements Layer { export class SingleNotificationLayer implements Layer {
private selectedMenuIndex = 0; private selectedMenuIndex = 0;
private confirmation: { source: AndroidNotification; menu: MenuLayer } | null = null;
constructor( constructor(
private readonly notificationKey: string, private readonly notificationKey: string,
@@ -174,29 +179,36 @@ export class SingleNotificationLayer implements Layer {
) {} ) {}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
if (this.confirmation) return this.paintConfirmation(ctx);
const font = getDefaultSmallFont(); const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize(); const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0); const image = new GrayImage(width, height, 0);
const notification = readActiveNotifications(MAX_NOTIFICATIONS).find((item) => item.key === this.notificationKey); const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
if (!notification) { if (!notification) {
return this.closeUnavailableNotification(ctx, paintBelow); return this.closeUnavailableNotification(ctx, paintBelow);
} }
const menu = buildDetailMenu(notification); const menu = buildDetailMenu(notification, this.options.origin);
this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, Math.max(0, menu.length - 1)); this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, Math.max(0, menu.length - 1));
drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height); drawDetailContent(image, font, notification, iconForNotification(notification.key), width, height);
drawDetailMenu(image, font, menu, this.selectedMenuIndex, width); drawDetailMenu(image, font, menu, this.selectedMenuIndex, width);
return image; return image;
} }
handleInput(event: InputEvent, ctx: LayerContext): void { async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
const notification = readActiveNotifications(MAX_NOTIFICATIONS).find((item) => item.key === this.notificationKey); if (this.confirmation) {
if (event.type === "double-click") this.close(ctx);
else await this.confirmation.menu.handleInput(event, ctx);
return;
}
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
if (!notification) { if (!notification) {
this.closeUnavailableNotification(ctx); this.closeUnavailableNotification(ctx);
return; return;
} }
const menu = buildDetailMenu(notification); const menu = buildDetailMenu(notification, this.options.origin);
this.selectedMenuIndex = clamp(this.selectedMenuIndex, 0, menu.length - 1);
if (event.type === "double-click") { if (event.type === "double-click") {
this.close(ctx); this.close(ctx);
@@ -217,15 +229,47 @@ export class SingleNotificationLayer implements Layer {
this.close(ctx); this.close(ctx);
} else if (item.kind === "action") { } else if (item.kind === "action") {
invokeNotificationAction(this.notificationKey, item.action.index); invokeNotificationAction(this.notificationKey, item.action.index);
if (!readActiveNotifications(MAX_NOTIFICATIONS).some((item) => item.key === this.notificationKey)) { if (!readActiveNotifications(ALL_NOTIFICATIONS).some((item) => item.key === this.notificationKey)) {
this.closeUnavailableNotification(ctx); this.closeUnavailableNotification(ctx);
} }
} else if (item.kind === "dismiss") { } else if (item.kind === "dismiss") {
dismissNotification(this.notificationKey); dismissNotification(this.notificationKey);
this.closeUnavailableNotification(ctx); this.closeUnavailableNotification(ctx);
} else if (item.kind === "disable-source") {
// Keep the modal alive for confirmation even after Android removes the notification.
this.confirmation = {
source: notification,
menu: new MenuLayer(null, [
{ label: "Cancel", onSelect: () => this.close(ctx) },
{ label: "Turn off popups", onSelect: () => {
setNotificationSourceEnabled(notification, false);
this.close(ctx);
} },
], { x: 12, y: 0, width: ctx.stack.getBaseSize().width - 24, minHeight: 0, showBorder: false }),
};
dismissNotification(this.notificationKey);
} }
} }
private paintConfirmation(ctx: LayerContext): GrayImage {
const { source, menu } = this.confirmation!;
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
// Put actions first so they remain reachable even with a large UI font.
menu.paint(ctx, () => image);
const top = 24 + 2 * listRowHeight(font);
const prompt = `Turn off notification popups from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`;
const lines = wrapText(font, prompt, width - 48);
const maxLines = Math.max(1, Math.floor((height - top - 12) / lineStep(font)));
for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
const text = index === maxLines - 1 && lines.length > maxLines
? truncateText(font, lines[index] + "...", width - 48) : lines[index]!;
image.drawText(font, 24, top + index * lineStep(font), text, 210);
}
return image;
}
/** Leave the detail view, whatever hosts it. */ /** Leave the detail view, whatever hosts it. */
private close(ctx: LayerContext): void { private close(ctx: LayerContext): void {
if (this.options.origin === "new-notification-modal") { if (this.options.origin === "new-notification-modal") {
@@ -365,20 +409,35 @@ function drawDetailContent(
function drawDetailMenu(image: GrayImage, font: UiFont, menu: DetailMenuItem[], selectedIndex: number, width: number): void { function drawDetailMenu(image: GrayImage, font: UiFont, menu: DetailMenuItem[], selectedIndex: number, width: number): void {
const menuX = width - DETAIL_MENU_WIDTH - 24; const menuX = width - DETAIL_MENU_WIDTH - 24;
const menuY = 24; const menuY = 24;
const rowH = listRowHeight(font); const rows = menu.map((item) => {
const lines = item.kind === "disable-source"
? wrapText(font, item.label, DETAIL_MENU_WIDTH - 16)
: [truncateText(font, item.label, DETAIL_MENU_WIDTH - 16)];
return { lines, height: lines.length * lineStep(font) + 8 };
});
const selectedBottom = rows.slice(0, selectedIndex + 1).reduce((sum, row) => sum + row.height, 0);
const scrollY = Math.max(0, selectedBottom - (image.height - menuY - 12));
let y = menuY - scrollY;
for (let index = 0; index < menu.length; index++) { for (let index = 0; index < menu.length; index++) {
const y = menuY + index * (rowH + 2); const row = rows[index]!;
if (y < menuY) {
y += row.height;
continue;
}
if (y + row.height > image.height - 12) break;
const selected = index === selectedIndex; const selected = index === selectedIndex;
if (selected) { if (selected) {
image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, rowH - 1, 18, 6); image.fillRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 18, 6);
image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, rowH - 1, 60, 6); image.drawRoundedRect(menuX - 8, y - 2, DETAIL_MENU_WIDTH, row.height - 3, 60, 6);
} }
const label = truncateText(font, menu[index]!.label, DETAIL_MENU_WIDTH - 12); for (let line = 0; line < row.lines.length; line++) {
image.drawText(font, menuX, y + 2, label, selected ? 255 : 185); image.drawText(font, menuX, y + 2 + line * lineStep(font), row.lines[line]!, selected ? 255 : 185);
}
y += row.height;
} }
} }
function buildDetailMenu(notification: AndroidNotification): DetailMenuItem[] { function buildDetailMenu(notification: AndroidNotification, origin: SingleNotificationLayerOrigin): DetailMenuItem[] {
return [ return [
{ kind: "back", label: "Back" }, { kind: "back", label: "Back" },
...notification.actions.map((action): DetailMenuItem => ({ ...notification.actions.map((action): DetailMenuItem => ({
@@ -387,6 +446,8 @@ function buildDetailMenu(notification: AndroidNotification): DetailMenuItem[] {
action, action,
})), })),
{ kind: "dismiss", label: "Dismiss" }, { kind: "dismiss", label: "Dismiss" },
...(origin === "new-notification-modal" && notification.packageName
? [{ kind: "disable-source" as const, label: "Don't show on glasses again" }] : []),
]; ];
} }
+5 -5
View File
@@ -6,7 +6,7 @@ import { BATTERY_ICON_WIDTH, drawBattery } from "../../graphics/battery";
import { readActiveNotificationIcons } from "../../native/notification-icons"; import { readActiveNotificationIcons } from "../../native/notification-icons";
import { readPhoneBatteryState } from "../../native/phone-battery"; import { readPhoneBatteryState } from "../../native/phone-battery";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness"; import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
import { renderIcon, renderIconWithGlyph, type IconName } from "../../graphics/icons"; import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons";
import { batteryDisplayModeSetting, timeFormatSetting } from "../dashboard-settings"; import { batteryDisplayModeSetting, timeFormatSetting } from "../dashboard-settings";
import { Layer } from "../layers"; import { Layer } from "../layers";
import { scrollToKeepSelectionVisible } from "../menu"; import { scrollToKeepSelectionVisible } from "../menu";
@@ -144,9 +144,9 @@ function invertedIcon(icon: GrayImage): GrayImage {
} }
/** Window icon rendered from an SVG (Lucide), rendered once per size and cached. */ /** Window icon rendered from an SVG (Lucide), rendered once per size and cached. */
export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWindow["drawIcon"] { export function makeSvgWindowIcon(name: IconName, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
return (image, x, y, size, inverted) => { return (image, x, y, size, inverted) => {
const icon = glyph ? renderIconWithGlyph(name, glyph, size) : renderIcon(name, size); const icon = glyph || activity ? renderIconWithGlyph(name, glyph ?? "", size, activity?.() ?? "idle") : renderIcon(name, size);
if (!icon) return; if (!icon) return;
const dx = x + Math.max(0, ((size - icon.width) / 2) | 0); const dx = x + Math.max(0, ((size - icon.width) / 2) | 0);
const dy = y + Math.max(0, ((size - icon.height) / 2) | 0); const dy = y + Math.max(0, ((size - icon.height) / 2) | 0);
@@ -155,8 +155,8 @@ export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWi
} }
/** SVG icon when a name is given, else the letter placeholder. */ /** SVG icon when a name is given, else the letter placeholder. */
export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string): ShellChromeWindow["drawIcon"] { export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
return icon ? makeSvgWindowIcon(icon, glyph) : makeLetterWindowIcon(letter); return icon ? makeSvgWindowIcon(icon, glyph, activity) : makeLetterWindowIcon(letter);
} }
/** Window icon backed by an arbitrary cached grayscale image renderer. */ /** Window icon backed by an arbitrary cached grayscale image renderer. */
+12 -2
View File
@@ -1,6 +1,6 @@
import { GrayImage } from "../../graphics/image"; import { GrayImage } from "../../graphics/image";
import { windowIcon } from "./chrome-layer"; import { windowIcon } from "./chrome-layer";
import { type IconName } from "../../graphics/icons"; import { type IconActivity, type IconName } from "../../graphics/icons";
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry"; import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
import { appViewportSize, type WindowHeightMode } from "./geometry"; import { appViewportSize, type WindowHeightMode } from "./geometry";
import * as frameTimings from "../../native/frame-timings"; import * as frameTimings from "../../native/frame-timings";
@@ -63,6 +63,8 @@ export type WorkerAppReply =
} }
| { type: "set-title"; windowId: string; title: string } | { type: "set-title"; windowId: string; title: string }
| { type: "set-attention"; windowId: string; attention: boolean } | { type: "set-attention"; windowId: string; attention: boolean }
/** App-driven animation phase for sidebar icons that support an activity cursor. */
| { type: "set-icon-activity"; windowId: string; activity: IconActivity }
| { | {
/** Open the shell's voice dialog aimed at this window (a menu pick). */ /** Open the shell's voice dialog aimed at this window (a menu pick). */
type: "start-voice-input"; type: "start-voice-input";
@@ -197,6 +199,7 @@ const TOOL_CALL_HOST_TIMEOUT_MS = 15_000;
export class WorkerAppHost { export class WorkerAppHost {
private readonly openWindows = new Set<string>(); private readonly openWindows = new Set<string>();
private readonly windowIconActivity = new Map<string, IconActivity>();
/** Per-window gesture bindings, as last reported (see set-window-gestures). */ /** Per-window gesture bindings, as last reported (see set-window-gestures). */
private readonly windowGestures = new Map<string, { hasAppMenu: boolean; claimsLongPress: boolean }>(); private readonly windowGestures = new Map<string, { hasAppMenu: boolean; claimsLongPress: boolean }>();
private readonly pendingToolCalls = new Map<string, PendingToolCall>(); private readonly pendingToolCalls = new Map<string, PendingToolCall>();
@@ -282,6 +285,12 @@ export class WorkerAppHost {
shell.openSystemMenu(message.windowId); shell.openSystemMenu(message.windowId);
} }
break; break;
case "set-icon-activity":
if (this.openWindows.has(message.windowId) && this.windowIconActivity.get(message.windowId) !== message.activity) {
this.windowIconActivity.set(message.windowId, message.activity);
this.options.requestShellRender();
}
break;
case "set-window-gestures": case "set-window-gestures":
this.windowGestures.set(message.windowId, { this.windowGestures.set(message.windowId, {
hasAppMenu: message.hasAppMenu, hasAppMenu: message.hasAppMenu,
@@ -370,13 +379,14 @@ export class WorkerAppHost {
close: () => { close: () => {
this.openWindows.delete(spec.windowId); this.openWindows.delete(spec.windowId);
this.windowGestures.delete(spec.windowId); this.windowGestures.delete(spec.windowId);
this.windowIconActivity.delete(spec.windowId);
// Withdraw this window's tools and fail any in-flight calls to it. // Withdraw this window's tools and fail any in-flight calls to it.
toolRegistry.removeAppTools(spec.windowId); toolRegistry.removeAppTools(spec.windowId);
this.failPendingToolCallsFor(spec.windowId); this.failPendingToolCallsFor(spec.windowId);
this.post({ type: "close-window", windowId: spec.windowId }); this.post({ type: "close-window", windowId: spec.windowId });
this.options.removeSurface(surfaceId); this.options.removeSurface(surfaceId);
}, },
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph), drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph, () => this.windowIconActivity.get(spec.windowId) ?? "idle"),
handleInput: (event, frameId) => { handleInput: (event, frameId) => {
frameTimings.logFrame(frameId, `input posted to the ${this.options.appId} worker`); frameTimings.logFrame(frameId, `input posted to the ${this.options.appId} worker`);
this.post({ this.post({
+8
View File
@@ -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 `.test-build/` (git-ignored) and runs `node --test tests/`. No extra
dependencies are needed — the tests are plain `.test.cjs` files that use dependencies are needed — the tests are plain `.test.cjs` files that use
`node:test` and `node:assert`. `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`.
+114
View File
@@ -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}`);
}
});
+19
View File
@@ -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 });
}
});
+150
View File
@@ -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);
});
+154
View File
@@ -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
View File
@@ -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");
}
}
+156
View File
@@ -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);
});
+182
View File
@@ -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);
});
+163
View File
@@ -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
View File
@@ -34,6 +34,7 @@
"../app/apps/microphones/name-guess.ts", "../app/apps/microphones/name-guess.ts",
"../app/apps/evenhub/containers.ts", "../app/apps/evenhub/containers.ts",
"../app/apps/timer/timer-model.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"
] ]
} }