diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java index b7dd2b10..c13b0240 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java @@ -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_CONTROL_WAIT_MS = 1_500; private static final long CFW_CLEANUP_WAIT_MS = 4_000; - private static final int COMPASS_REPORT_INTERVAL_MS = 250; - private static final int COMPASS_MIN_CHANGE_DEGREES = 1; + private static final int COMPASS_REPORT_INTERVAL_MS = 100; + private static final int COMPASS_MIN_CHANGE_DEGREES = 0; private final Context appContext; private final PowerManager powerManager; @@ -1567,7 +1567,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { emitWearState(decodedWearState > 0); } if (compassEvent != null) { - emitCompassEvent(compassEvent.command, compassEvent.headingDegrees); + emitCompassEvent(compassEvent); } if (event != null) { if (event.hasImu) { @@ -3456,11 +3456,22 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { }); } - private void emitCompassEvent(int command, int headingDegrees) { + private void emitCompassEvent(BleProtocol.CompassEvent event) { + if (event.diagnosticFlags >= 0) { + String[] sources = { "unknown", "GRV", "GMRV", "RV" }; + Log.i("FaceclawCompass", "heading=" + event.headingDegrees + + " magneticAccuracy=" + event.magneticAccuracy + + " magneticAnomalies=" + event.magneticAnomalies + + " orientationSource=" + sources[event.orientationSource] + + " flags=0x" + Integer.toHexString(event.diagnosticFlags) + + " sampleTimeMs=" + event.sampleTimeMs); + } for (CompassSubscription subscription : compassSubscriptions) { subscription.handler.post(() -> { try { - subscription.listener.onCompassEvent(command, headingDegrees); + subscription.listener.onCompassEvent(event.command, event.headingDegrees, + event.magneticAccuracy, event.magneticAnomalies, event.orientationSource, + event.diagnosticFlags, event.sampleTimeMs); } catch (Throwable t) { Log.w(TAG, "listener onCompassEvent failed", t); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java index 9c77ce2c..1d6bb06e 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCompassListener.java @@ -2,5 +2,6 @@ package com.faceclaw.app; /** Receives stock compass heading and calibration notifications on the thread that subscribed. */ public interface FaceclawCompassListener { - void onCompassEvent(int command, int headingDegrees); + void onCompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies, + int orientationSource, int diagnosticFlags, long sampleTimeMs); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java index 3762aafb..eb97b21e 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java @@ -23,6 +23,8 @@ import org.json.JSONArray; import org.json.JSONObject; import java.util.List; +import java.util.HashSet; +import java.util.Set; public class FaceclawMediaController { private final Context appContext; @@ -71,6 +73,7 @@ public class FaceclawMediaController { private volatile FaceclawMediaControllerListener listener; private MediaController activeController; private boolean started; + private Set ignoredPackages = new HashSet<>(); public FaceclawMediaController(Context context) { 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 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() { synchronized (lock) { if (!started) { @@ -289,6 +309,7 @@ public class FaceclawMediaController { controllers = null; } } + emitSessionAppsLocked(controllers); setActiveControllerLocked(chooseController(controllers)); emitStateLocked(); } @@ -297,8 +318,10 @@ public class FaceclawMediaController { if (controllers == null || controllers.isEmpty()) { return null; } - MediaController first = controllers.get(0); + MediaController first = null; for (MediaController controller : controllers) { + if (ignoredPackages.contains(controller.getPackageName())) continue; + if (first == null) first = controller; PlaybackState playbackState = controller.getPlaybackState(); if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) { return controller; @@ -307,6 +330,27 @@ public class FaceclawMediaController { return first; } + private void emitSessionAppsLocked(List controllers) { + FaceclawMediaControllerListener currentListener = listener; + if (currentListener == null || controllers == null) return; + JSONArray apps = new JSONArray(); + Set 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) { if (sameController(activeController, controller)) { return; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java index 7953324b..75909f0e 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaControllerListener.java @@ -1,6 +1,9 @@ package com.faceclaw.app; public interface FaceclawMediaControllerListener { + /** All observed session owners, before filtering or choosing the active player. */ + void onSessionAppsChanged(String appsJson); + void onStateChange( String playbackState, String packageName, diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java index 0e062a67..8ca97f00 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java @@ -210,7 +210,7 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen public static String getActiveNotificationsJson(int maxNotifications) { FaceclawMediaNotificationListenerService service = activeService; - int limit = Math.max(0, Math.min(100, maxNotifications)); + int limit = Math.max(0, maxNotifications); if (service == null || limit == 0) { return "[]"; } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java index 7e89605f..686e0ae8 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java @@ -772,7 +772,23 @@ public class BleProtocol { byte[] compass = readFieldBytes(root, 10); if (compass == null) return null; int heading = readVarintFieldValue(compass, 1, -1); - return heading >= 0 ? new CompassEvent(command, heading) : null; + if (heading < 0 || heading >= 360) return null; + byte[] diagnostic = readFieldBytes(root, 100); + if (diagnostic != null && diagnostic.length == 12 + && diagnostic[0] == 'C' && diagnostic[1] == 'M' && diagnostic[2] == 1 + && diagnostic[7] == 0 + && ((diagnostic[3] & 0xff) <= 3 || diagnostic[3] == (byte) 255) + && ((diagnostic[4] & 0xff) <= 2 || diagnostic[4] == (byte) 255) + && (diagnostic[5] & 0xff) <= 3) { + long sampleTimeMs = 0; + for (int i = 0; i < 4; i++) sampleTimeMs |= (long) (diagnostic[8 + i] & 0xff) << (8 * i); + return new CompassEvent(command, heading, + diagnostic[3] == (byte) 255 ? -1 : diagnostic[3] & 0xff, + diagnostic[4] == (byte) 255 ? -1 : diagnostic[4] & 0xff, + diagnostic[5] & 0xff, diagnostic[6] & 0xff, sampleTimeMs); + } + // Stock/older CFW and unknown extensions still supply usable headings. + return new CompassEvent(command, heading); } if (command == NAV_CMD_COMPASS_CALIBRATION_STARTED || command == NAV_CMD_COMPASS_CALIBRATION_COMPLETE) { @@ -1014,10 +1030,23 @@ public class BleProtocol { public static final class CompassEvent { public final int command; public final int headingDegrees; + /** -1 means unavailable; source: 0 unknown, 1 GRV, 2 GMRV, 3 RV. */ + public final int magneticAccuracy, magneticAnomalies, orientationSource, diagnosticFlags; + public final long sampleTimeMs; CompassEvent(int command, int headingDegrees) { + this(command, headingDegrees, -1, -1, -1, -1, -1); + } + + CompassEvent(int command, int headingDegrees, int magneticAccuracy, int magneticAnomalies, + int orientationSource, int diagnosticFlags, long sampleTimeMs) { this.command = command; this.headingDegrees = headingDegrees; + this.magneticAccuracy = magneticAccuracy; + this.magneticAnomalies = magneticAnomalies; + this.orientationSource = orientationSource; + this.diagnosticFlags = diagnosticFlags; + this.sampleTimeMs = sampleTimeMs; } } diff --git a/CHANGELOG b/CHANGELOG index f0f292cc..8825e13a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,8 @@ ## 0.6.6 - Future * Navigate and terminal app: App-specific screen size/position setting * 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 * Changed context menu gestures: — for system, ●— for app context menu. diff --git a/app/app.css b/app/app.css index 1d96f325..faa23972 100644 --- a/app/app.css +++ b/app/app.css @@ -201,6 +201,27 @@ Button.-primary { height: 20; 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 { tint-color: #cccccc; } diff --git a/app/apps/compass/compass-app.ts b/app/apps/compass/compass-app.ts index 323e4daf..a0f75e18 100644 --- a/app/apps/compass/compass-app.ts +++ b/app/apps/compass/compass-app.ts @@ -7,6 +7,7 @@ import { addCompassListener, setCompassEnabled, type CompassEvent, + type CompassDiagnostics, } from "../../native/compass"; import { wrapText } from "../../graphics/textwrap"; import { type InputEvent } from "../../ui/gestures"; @@ -25,6 +26,7 @@ import { isCompassCalibrated, normalizeHeading } from "./calibration"; import { CompassCalibrationLayer } from "./calibration-layer"; import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination"; import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading"; +import { compassDebugLines, isCompassDebugEnabled, setCompassDebugEnabled } from "./debug"; export const COMPASS_WINDOW_ID = "compass"; export const COMPASS_SURFACE_ID = "window:compass"; @@ -95,6 +97,7 @@ const WALL_LIT = 62; class CompassLayer implements Layer { private rawHeading: number | null = null; + private diagnostics: CompassDiagnostics | null = null; /** A firmware calibration message, shown until the next heading arrives. */ private firmwareStatus: string | null = null; private enabled = false; @@ -103,6 +106,7 @@ class CompassLayer implements Layer { private unsubscribe: (() => void) | null = null; private unsubscribeDeclination: (() => void) | null = null; private requestingPermission = false; + private background: { key: string; image: GrayImage } | null = null; constructor(private readonly requestRender: () => void) {} @@ -140,6 +144,11 @@ class CompassLayer implements Layer { this.requestRender(); } + toggleDebugInfo(): void { + setCompassDebugEnabled(!isCompassDebugEnabled()); + this.requestRender(); + } + stop(): void { if (this.removed) return; this.removed = true; @@ -167,6 +176,7 @@ class CompassLayer implements Layer { const visible = shell.isWindowVisible(COMPASS_WINDOW_ID); if (visible === this.enabled) return; this.enabled = visible; + this.diagnostics = null; setCompassEnabled(visible); this.firmwareStatus = null; // The stored fix may have aged out while the compass was hidden. @@ -178,6 +188,7 @@ class CompassLayer implements Layer { if (this.removed) return; if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) { this.rawHeading = normalizeHeading(event.headingDegrees); + this.diagnostics = event.diagnostics ?? null; this.firmwareStatus = null; } else if (event.command === COMPASS_CALIBRATION_STARTED) { this.firmwareStatus = "Calibrating — move the glasses"; @@ -197,13 +208,23 @@ class CompassLayer implements Layer { paint(ctx: LayerContext): GrayImage { const { width, height } = ctx.stack.getBaseSize(); - const image = new GrayImage(width, height, 0); const small = getDefaultSmallFont(); const large = getDefaultLargeFont(); const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees; const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`; const statusLines = wrapText(small, this.statusText(), width - STACK_GAP * 2); const smallStep = lineStep(small); + const debugLines = isCompassDebugEnabled() ? compassDebugLines(this.diagnostics) : []; + const debugWidth = Math.max(0, ...debugLines.map((line) => small.measureText(line))); + const debugGap = debugLines.length ? 12 : 0; + // Keep diagnostics beside the heading even in narrow windows. The rose + // stays centred on the optical axis; the combined readout fits the viewport. + const headingFont = large.measureText(headingText) + debugGap + debugWidth <= width - EDGE_PAD * 2 + ? large : small; + const headingWidth = headingFont.measureText(headingText); + const readoutWidth = headingWidth + debugGap + debugWidth; + const debugHeight = debugLines.length ? (debugLines.length - 1) * smallStep + small.lineHeight : 0; + const readoutHeight = Math.max(headingFont.lineHeight, debugHeight); // One column centred on the display's true centre, so the rose sits where // the wearer is looking rather than 32px right of it. @@ -211,7 +232,7 @@ class CompassLayer implements Layer { // The rose is sized and placed first — it hangs off the bottom edge — and // the readout then floats in whatever room is left above it. - const textHeight = large.lineHeight + 4 + statusLines.length * smallStep; + const textHeight = readoutHeight + 4 + statusLines.length * smallStep; const radius = Math.max( 24, Math.min( @@ -229,15 +250,30 @@ class CompassLayer implements Layer { const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE); 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); - y += large.lineHeight + 4; + const fade = heading === null ? 0.45 : 1; + 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) { image.drawText(small, Math.round(cx - small.measureText(line) / 2), y, line, 125); y += smallStep; } - drawPlaneGrid(image, cx, cy, radius, y + 6); - drawCompassRose(image, cx, cy, radius, heading); return image; } @@ -277,6 +313,14 @@ export function createCompassAppWindow(options: InProcessAppOptions): InProcessW layer.toggleNorthReference(); }, }, + { + label: `Debug information: ${isCompassDebugEnabled() ? "On" : "Off"}`, + description: "Show magnetic accuracy (0–3), anomaly flags (0–2), and orientation source beside the heading.", + onSelect: (ctx) => { + ctx.stack.pop(); + layer.toggleDebugInfo(); + }, + }, ], baseLayer: new YieldAtRootLayer(layer), submitFrame: options.submitFrame, @@ -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 { // Without a reading there is nothing to aim, so show the rose in its resting // orientation, dimmed, rather than an empty ring. const fade = heading === null ? 0.45 : 1; 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 // 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. @@ -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 { const top = projectRose(cx, cy, radius, 1, 0); + const tickTop = top.y + 1; fillTriangle( image, - { x: cx, y: top.y - 1 }, - { x: cx - TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT }, - { x: cx + TICK_HALF_WIDTH, y: top.y - TICK_HEIGHT }, + { x: cx, y: tickTop + TICK_HEIGHT - 1 }, + { x: cx - TICK_HALF_WIDTH, y: tickTop }, + { x: cx + TICK_HALF_WIDTH, y: tickTop }, value, ); } diff --git a/app/apps/compass/debug.ts b/app/apps/compass/debug.ts new file mode 100644 index 00000000..72cdec70 --- /dev/null +++ b/app/apps/compass/debug.ts @@ -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}`]; +} diff --git a/app/apps/music/music-app.ts b/app/apps/music/music-app.ts index 13cb7b5e..c1895007 100644 --- a/app/apps/music/music-app.ts +++ b/app/apps/music/music-app.ts @@ -8,6 +8,7 @@ import { lineStep, tightRowHeight } from "../../ui/metrics"; import { mediaControllerBridge, type MediaControllerState, type MediaQueueItem } from "../../native/media-controller"; import { mediaBrowserBridge, type MediaBrowserApp } from "../../native/media-browser"; import { MediaBrowseLayer } from "./media-browse"; +import { MusicSettingsLayer } from "./music-settings"; import { Layer, type LayerContext, type PaintBelow } from "../../ui/layers"; 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", icon: "music", closeable: true, + menuItems: () => [{ + label: "Music settings", + onSelect: (ctx) => { + ctx.stack.pop(); + ctx.stack.push(new MusicSettingsLayer()); + }, + }], actions: options.actions, baseLayer: new MusicRootLayer(musicLayer), submitFrame: options.submitFrame, diff --git a/app/apps/music/music-settings.ts b/app/apps/music/music-settings.ts new file mode 100644 index 00000000..52dac95d --- /dev/null +++ b/app/apps/music/music-settings.ts @@ -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 { + await this.currentMenu(ctx).handleInput(event, ctx); + } +} diff --git a/app/apps/nightscout/index.ts b/app/apps/nightscout/index.ts index 078af81c..6f5f59ad 100644 --- a/app/apps/nightscout/index.ts +++ b/app/apps/nightscout/index.ts @@ -1,10 +1,11 @@ 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 = { appId: "nightscout", title: "Nightscout", icon: "nightscout", + boot: () => startNightscoutTrayIcon(), launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow), }; diff --git a/app/apps/nightscout/nightscout-alerts.ts b/app/apps/nightscout/nightscout-alerts.ts new file mode 100644 index 00000000..9c87accd --- /dev/null +++ b/app/apps/nightscout/nightscout-alerts.ts @@ -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"; +} diff --git a/app/apps/nightscout/nightscout-app.ts b/app/apps/nightscout/nightscout-app.ts index c2e479ba..b2fbdb00 100644 --- a/app/apps/nightscout/nightscout-app.ts +++ b/app/apps/nightscout/nightscout-app.ts @@ -8,6 +8,8 @@ import { type InProcessAppOptions, type InProcessWindow, } 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"; export const NIGHTSCOUT_WINDOW_ID = "nightscout"; @@ -19,14 +21,34 @@ const TRAY_GRAPH_WIDTH = 48; const TRAY_STALE_MS = 15 * 60 * 1000; const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000; -/** - * The Nightscout app: the full-screen glucose view (previously reached via - * the dashboard card) in its own in-process window. While the app is running - * it also publishes a top-bar tray icon: the latest blood-glucose value - * (struck through when stale) plus a minimal 48px history graph. - */ +const windowRenders = new Set<() => void>(); +let trayStarted = false; +let trayTick: ReturnType | null = null; + +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 { - let unsubscribe: (() => void) | null = null; + startNightscoutTrayIcon(); + const render = () => app.requestRender(); const app = createInProcessWindow({ appId: "nightscout", windowId: NIGHTSCOUT_WINDOW_ID, @@ -41,28 +63,25 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce setSurfaceVisible: options.setSurfaceVisible, removeSurface: options.removeSurface, onClosed: () => { - unsubscribe?.(); - unsubscribe = null; - shell.setTrayIcon(TRAY_ICON_ID, null); + windowRenders.delete(render); + syncNightscout(); options.onClosed(); }, }); - // onStateChange fires immediately with the current snapshot, so this also - // publishes the initial tray icon. - unsubscribe = nightscoutBridge.onStateChange((state) => { - shell.setTrayIcon(TRAY_ICON_ID, buildNightscoutTrayIcon(state)); - app.requestRender(); - }); + windowRenders.add(render); + syncNightscout(); 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 { const font = getDefaultSmallFont(); const nowMs = Date.now(); const label = state.latest ? `${state.latest.sgv}` : "--"; 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); image.drawText(font, 0, textY, label, 220); @@ -72,6 +91,14 @@ function buildNightscoutTrayIcon(state: NightscoutState): GrayImage { } 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; } diff --git a/app/apps/nightscout/nightscout.ts b/app/apps/nightscout/nightscout.ts index 82cab700..380f0595 100644 --- a/app/apps/nightscout/nightscout.ts +++ b/app/apps/nightscout/nightscout.ts @@ -1,3 +1,4 @@ +import { evaluateNightscoutAlerts } from "./nightscout-alerts"; import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; import { GrayImage, type UiFont } from "../../graphics/image"; import { truncateText } from "../../graphics/textwrap"; @@ -6,6 +7,13 @@ import { Layer, LayerContext } from "../../ui/layers"; import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge"; import { isNightscoutSettingsConfigured, + loadNightscoutThresholds, + nightscoutMaxCannulaAgeSetting, + nightscoutCartridgeLowSetting, + nightscoutBatteryLowSetting, + nightscoutMaxLoopAgeSetting, + nightscoutAlwaysShowInTopBarSetting, + toggleSettingMenuItem, nightscoutApiTokenSetting, nightscoutSiteUrlSetting, textSettingMenuItem, @@ -332,21 +340,43 @@ export class NightscoutLayer implements Layer { const statusX = 170; 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: `IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`, shade: 160, }, { - text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`, - shade: 160, + text: "", 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; 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); drawDirectionIndicator(image, font, statusX + font.measureText(line.text), statusY, line.direction, line.shade); } else { @@ -390,6 +420,11 @@ export function nightscoutMenuItems(): MenuItem[] { openSettingsSubMenu(ctx, "Nightscout settings", [ textSettingMenuItem(nightscoutSiteUrlSetting), textSettingMenuItem(nightscoutApiTokenSetting), + textSettingMenuItem(nightscoutMaxCannulaAgeSetting), + textSettingMenuItem(nightscoutCartridgeLowSetting), + textSettingMenuItem(nightscoutBatteryLowSetting), + textSettingMenuItem(nightscoutMaxLoopAgeSetting), + toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting), ]); }, }, diff --git a/app/apps/notifications/notifications-app.ts b/app/apps/notifications/notifications-app.ts index 168de962..a7f0bf75 100644 --- a/app/apps/notifications/notifications-app.ts +++ b/app/apps/notifications/notifications-app.ts @@ -1,4 +1,5 @@ import { NotificationsListLayer } from "../../ui/notifications"; +import { NotificationFilterLayer } from "../../ui/notification-filter"; import { onAndroidNotificationPosted } from "../../native/notification-icons"; import { createInProcessWindow, @@ -25,6 +26,13 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr iconLetter: "N", icon: "bell", closeable: true, + menuItems: () => [{ + label: "Notification filter", + onSelect: (ctx) => { + ctx.stack.pop(); + ctx.stack.push(new NotificationFilterLayer()); + }, + }], actions: options.actions, baseLayer: new YieldAtRootLayer(new NotificationsListLayer()), submitFrame: options.submitFrame, diff --git a/app/apps/terminal/terminal-app.worker.ts b/app/apps/terminal/terminal-app.worker.ts index 275505eb..8d60bdad 100644 --- a/app/apps/terminal/terminal-app.worker.ts +++ b/app/apps/terminal/terminal-app.worker.ts @@ -37,7 +37,7 @@ import { prepareFrameDraws } from "../../graphics/glyph-wire"; import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts"; import { layoutHubHeader } from "./hub-header"; 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 { getActiveDisplay } from "../../native/active-display"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures"; @@ -286,7 +286,7 @@ const sessionRecency = new Map(); // continues, so 5s of slack keeps the indicator lit through the gaps. const sessionActivity = new Map(); 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; function recencyKey(connectionId: string, socket: string): string { @@ -462,6 +462,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport if (pendingView) { pendingViews.delete(windowId); windows.set(windowId, createViewWindow(windowId, surfaceId, title, viewport, pendingView)); + updateHubAnimation(); renderHubWindows(); return; } @@ -491,6 +492,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport if (!controlsInitialized) { syncControlsFromSettings(); } + updateHubAnimation(); } function closeWindow(windowId: string): void { @@ -511,6 +513,8 @@ function closeWindow(windowId: string): void { endAddConnection(window); } windows.delete(windowId); + windowIconActivity.delete(windowId); + updateHubAnimation(); // Auto-reconnect only runs while at least one terminal window is open. if (windows.size === 0) { 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 -// session, a timer re-renders it so the per-row indicator alternates. The -// timer stops itself once every session's activity ages out (its final tick -// renders the rows indicator-free) or the hub leaves the foreground. +// One animation clock for foreground hub rows and every terminal sidebar icon. +// Keep ticking while the sidebar can show activity, even with the hub closed. let hubAnimationPhase = 0; let hubAnimationTimer: ReturnType | null = null; +const windowIconActivity = new Map(); function isSessionActive(connectionId: string, socket: string): boolean { const at = sessionActivity.get(recencyKey(connectionId, socket)); return at !== undefined && Date.now() - at < ACTIVITY_ACTIVE_MS; } -function hubAnimationShouldRun(): boolean { - if (!screenOn) return false; - let hubVisible = false; - for (const window of windows.values()) { - if (window.kind === "hub" && window.foreground) hubVisible = true; - } - if (!hubVisible) return false; +function isWindowSessionActive(window: TerminalWindow): boolean { + if (window.kind === "view") return isSessionActive(window.connectionId, window.socket); const now = Date.now(); - for (const at of sessionActivity.values()) { - if (now - at < ACTIVITY_ACTIVE_MS) return true; - } - return false; + return [...sessionActivity.values()].some((at) => now - at < ACTIVITY_ACTIVE_MS); } -/** 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 { - if (hubAnimationShouldRun()) { + const shouldRun = hubAnimationShouldRun(); + if (shouldRun && !hubAnimationTimer) hubAnimationPhase = 0; + syncWindowIconActivity(); + if (shouldRun) { if (hubAnimationTimer) return; hubAnimationTimer = setInterval(() => { hubAnimationPhase = (hubAnimationPhase + 1) % 2; - if (!hubAnimationShouldRun() && hubAnimationTimer) { - clearInterval(hubAnimationTimer); - hubAnimationTimer = null; - } + updateHubAnimation(); // Render even on the stopping tick, to clear expired indicators. renderHubWindows(); }, HUB_ANIMATION_STEP_MS); diff --git a/app/bootstrap.android.ts b/app/bootstrap.android.ts index c160dda1..0e42f85c 100644 --- a/app/bootstrap.android.ts +++ b/app/bootstrap.android.ts @@ -1,8 +1,10 @@ import { Application } from '@nativescript/core' import { registerShareIntentHandler } from './native/share-intents' import { installNativeUserAgent } from './util/http' +import { registerPhoneRotation } from './native/phone-rotation' installNativeUserAgent() registerShareIntentHandler() +registerPhoneRotation() Application.run({ moduleName: 'app-root' }) diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 8e05551c..adb0c7ca 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -12,7 +12,8 @@ import * as frameTimings from "../native/frame-timings"; import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service"; import { mediaControllerBridge } from "../native/media-controller"; 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 { grayImageToPreviewSource } from "../native/gray-image-preview"; import { firmwareIncompatibilityMessage } from "./firmware-compat"; @@ -374,6 +375,7 @@ class DashboardController { this.appendLog(`notification wake failed: ${this.formatError(error)}`); }); }); + readActiveNotifications(ALL_NOTIFICATIONS); // 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. onAnySettingChanged(() => { @@ -2464,7 +2466,8 @@ class DashboardController { } private async handleAndroidNotificationPosted(notificationKey: string): Promise { - if (!notificationKey) { + const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey); + if (!notification || !shouldShowNotificationOnGlasses(notification.packageName)) { this.requestShellRender(); return; } diff --git a/app/graphics/icons.ts b/app/graphics/icons.ts index fc6f23d1..0439cfb6 100644 --- a/app/graphics/icons.ts +++ b/app/graphics/icons.ts @@ -87,9 +87,11 @@ export const ICON_SVGS = { } as const; 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 -// renderIconWithGlyph. +// Prompt and session-marker elements replaced by renderIconWithGlyph. +const TERMINAL_PROMPT = ''; const TERMINAL_UNDERSCORE = ''; /** @@ -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 * 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 { - const shape = name === "terminal" ? TERMINAL_GLYPH_SHAPES[glyph] : undefined; - if (!shape) return renderIcon(name, size); - return renderSvgCached(`${name}[${glyph}]`, ICON_SVGS.terminal.replace(TERMINAL_UNDERSCORE, shape), size); +export function renderIconWithGlyph(name: IconName, glyph: string, size: number, activity: IconActivity = "idle"): GrayImage | null { + if (name !== "terminal") return renderIcon(name, size); + const shape = TERMINAL_GLYPH_SHAPES[glyph]; + 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" + ? '' + : ""); + } + return renderSvgCached(`${name}[${shape ? glyph : ""}]:${activity}`, svg, size); } function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null { diff --git a/app/native/compass.ts b/app/native/compass.ts index 5b4cbdfb..8a0d6491 100644 --- a/app/native/compass.ts +++ b/app/native/compass.ts @@ -5,10 +5,23 @@ export const COMPASS_CHANGED = 15; export const COMPASS_CALIBRATION_STARTED = 16; export const COMPASS_CALIBRATION_COMPLETE = 17; +export type CompassDiagnostics = { + /** 0 uncalibrated .. 3 well calibrated; -1 unavailable. */ + magneticAccuracy: number; + /** 0 none, 1 small/temperature, 2 large; -1 unavailable. */ + magneticAnomalies: number; + /** 0 unknown, 1 GRV (relative), 2 GMRV, 3 RV. */ + orientationSource: number; + flags: number; + sampleTimeMs: number; +}; + export type CompassEvent = { command: number; /** Magnetic heading in degrees, or -1 for calibration-only events. */ headingDegrees: number; + /** Absent with stock/older CFW or an unrecognized diagnostic extension. */ + diagnostics?: CompassDiagnostics; }; function activeCommunicator(): any { @@ -41,8 +54,16 @@ export function addCompassListener(listener: (event: CompassEvent) => void): () const active = activeCommunicator(); if (!active) return () => {}; const proxy = new com.faceclaw.app.FaceclawCompassListener({ - onCompassEvent: (command: number, headingDegrees: number) => { - listener({ command: Number(command), headingDegrees: Number(headingDegrees) }); + onCompassEvent: (command: number, headingDegrees: number, magneticAccuracy: number, + magneticAnomalies: number, orientationSource: number, diagnosticFlags: number, sampleTimeMs: number) => { + listener({ + command: Number(command), headingDegrees: Number(headingDegrees), + diagnostics: diagnosticFlags >= 0 ? { + magneticAccuracy: Number(magneticAccuracy), magneticAnomalies: Number(magneticAnomalies), + orientationSource: Number(orientationSource), flags: Number(diagnosticFlags), + sampleTimeMs: Number(sampleTimeMs), + } : undefined, + }); }, }); active.addCompassListener(proxy); diff --git a/app/native/media-apps.ts b/app/native/media-apps.ts new file mode 100644 index 00000000..20e1ec30 --- /dev/null +++ b/app/native/media-apps.ts @@ -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(); + 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()))); +} diff --git a/app/native/media-browser.ts b/app/native/media-browser.ts index cfb05f4b..80bd73b4 100644 --- a/app/native/media-browser.ts +++ b/app/native/media-browser.ts @@ -1,4 +1,6 @@ import { Utils } from "@nativescript/core"; +import { ignoredMediaPackages, isMediaAppEnabled, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps"; +import { onSettingsStoreChanged } from "./settings-store"; declare const com: any; @@ -34,11 +36,12 @@ export class FaceclawMediaBrowserBridge { private readonly pendingConnects = new Map>(); private readonly pendingBrowses = new Map>(); private appsCache: MediaBrowserApp[] | null = null; + private connectedPackage = ""; /** Installed apps exposing a media browser service; cached after the first call. */ listBrowsableApps(refresh = false): MediaBrowserApp[] { if (!global.isAndroid) return []; - if (this.appsCache && !refresh) return this.appsCache; + if (this.appsCache && !refresh) return this.enabledApps(); this.ensureBrowser(); if (!this.browser) return []; try { @@ -52,11 +55,17 @@ export class FaceclawMediaBrowserBridge { serviceClass: String(app.serviceClass ?? ""), appName: String(app.appName ?? ""), })); + rememberMediaApps(this.appsCache); } catch (error) { console.warn(`media browser app list parse failed: ${error}`); 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 { 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(); if (!this.browser) return Promise.reject(new Error("Media browser unavailable")); const requestId = this.nextRequestId++; + this.connectedPackage = app.packageName; return new Promise((resolve, reject) => { this.pendingConnects.set(requestId, { resolve, reject }); 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. */ browse(parentId: string): Promise { 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(); if (!this.browser) return Promise.reject(new Error("Media browser unavailable")); const requestId = this.nextRequestId++; @@ -89,6 +104,7 @@ export class FaceclawMediaBrowserBridge { /** Start playback of a browsed item through the connected player's session. */ playFromMediaId(mediaId: string): void { if (!global.isAndroid) return; + if (!this.connectedPackage || !isMediaAppEnabled(this.connectedPackage)) return; this.browser?.playFromMediaId(mediaId); } @@ -96,6 +112,7 @@ export class FaceclawMediaBrowserBridge { disconnect(): void { if (!global.isAndroid) return; this.rejectAllPending("Disconnected"); + this.connectedPackage = ""; this.browser?.disconnect(); } @@ -115,6 +132,11 @@ export class FaceclawMediaBrowserBridge { throw new Error("Android application context unavailable"); } 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({ onConnectResult: (requestId: number, connected: boolean, rootId: string, error: string) => { const pending = this.pendingConnects.get(Number(requestId)); diff --git a/app/native/media-controller.ts b/app/native/media-controller.ts index 600206c3..e685a123 100644 --- a/app/native/media-controller.ts +++ b/app/native/media-controller.ts @@ -1,6 +1,8 @@ import { Utils } from "@nativescript/core"; import { GrayImage } from "../graphics/image"; 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; @@ -173,7 +175,22 @@ export class FaceclawMediaControllerBridge { throw new Error("Android application context unavailable"); } 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({ + onSessionAppsChanged: (appsJson: string) => { + try { + const apps = JSON.parse(String(appsJson)); + rememberMediaApps(apps); + } catch (error) { + console.warn(`media session apps parse failed: ${error}`); + } + }, onStateChange: ( playbackState: string, packageName: string, diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts index 8ce2a38e..5da6237d 100644 --- a/app/native/nightscout-bridge.ts +++ b/app/native/nightscout-bridge.ts @@ -1,4 +1,4 @@ -import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings"; +import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings"; import { fetchWithUserAgent } from "../util/http"; export type NightscoutPoint = { @@ -33,6 +33,10 @@ export type NightscoutState = { iob: number | null; cob: 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; openapsStatusShort: string; carbs: NightscoutCarbEvent[]; @@ -121,6 +125,9 @@ const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = { iob: null, cob: null, cageTimestampMs: null, + reservoirUnits: null, + batteryVoltage: null, + loopTimestampMs: null, pumpStatus: "", openapsStatusShort: "--", carbs: [], @@ -259,6 +266,9 @@ export class NightscoutBridge { iob: Number.isFinite(iob) ? iob : null, cob, cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null, + reservoirUnits: firstFiniteNumber(latestDeviceStatus?.pump?.reservoir), + batteryVoltage: firstFiniteNumber(latestDeviceStatus?.pump?.battery?.voltage), + loopTimestampMs: loopTimestampMs > 0 ? loopTimestampMs : null, pumpStatus, openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--", carbs: parsedTreatments.carbs, @@ -359,6 +369,8 @@ function parseTimestampMs(value: unknown): number { function firstFiniteNumber(...values: unknown[]): number | null { for (const value of values) { + if (typeof value !== "number" && typeof value !== "string") continue; + if (typeof value === "string" && !value.trim()) continue; const numeric = Number(value); if (Number.isFinite(numeric)) { return numeric; @@ -371,8 +383,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no if (!status?.pump) { return "--"; } - const reservoir = firstFiniteNumber(status.pump.reservoir); - const voltage = firstFiniteNumber(status.pump.battery?.voltage); const commTimestampMs = Math.max( parseTimestampMs(status.pump.status?.timestamp), parseTimestampMs(status.pump.clock), @@ -380,12 +390,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no ); const stateLabel = summarizePumpState(status); const parts: string[] = []; - if (reservoir !== null) { - parts.push(`${Math.round(reservoir)}U`); - } - if (voltage !== null) { - parts.push(`${voltage.toFixed(2)}v`); - } if (commTimestampMs > 0) { parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`); } diff --git a/app/native/notification-icons.ts b/app/native/notification-icons.ts index aa06623a..d3f58d22 100644 --- a/app/native/notification-icons.ts +++ b/app/native/notification-icons.ts @@ -1,10 +1,13 @@ import { GrayImage } from "../graphics/image"; import { logCurrent, spanCurrent } from "./frame-timings"; import { toUint8Array } from "../util/array-util"; +import { rememberNotificationSources } from "./notification-sources"; declare const com: any; 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 // notification is posted or dismissed (see invalidateIconCaches callers), so // 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); 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 { return []; } diff --git a/app/native/notification-sources.ts b/app/native/notification-sources.ts new file mode 100644 index 00000000..cd00a5bb --- /dev/null +++ b/app/native/notification-sources.ts @@ -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()))); +} diff --git a/app/native/phone-rotation.ts b/app/native/phone-rotation.ts new file mode 100644 index 00000000..652a1fd2 --- /dev/null +++ b/app/native/phone-rotation.ts @@ -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(); +} diff --git a/app/phone-ui/main-page.ts b/app/phone-ui/main-page.ts index 01ed68fe..244b6d05 100644 --- a/app/phone-ui/main-page.ts +++ b/app/phone-ui/main-page.ts @@ -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 { 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 * 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.backgroundColor = SETTINGS_BACKGROUND_COLOR textField.placeholderColor = SETTINGS_PLACEHOLDER_COLOR @@ -53,7 +53,7 @@ function applySettingsTextFieldContrast(textField: TextField, selectAllOnFocus = return } - const nativeTextField = (textField as TextField & { nativeView?: android.widget.EditText }).nativeView + const nativeTextField = (textField as (TextField | TextView) & { nativeView?: android.widget.EditText }).nativeView if (!nativeTextField) { return } @@ -90,13 +90,13 @@ function focusTextEditor(page: Page): void { /** The keyboard dialog closed on the glasses (sent, discarded, or screen off). */ function dismissKeyboardInputKeyboard(page: Page): void { - page.getViewById('keyboardInputField')?.dismissSoftInput() + page.getViewById('keyboardInputField')?.dismissSoftInput() } /** The keyboard dialog opened: bring up the IME on its field right away. */ function focusKeyboardInput(page: Page): void { setTimeout(() => { - const textField = page.getViewById('keyboardInputField') + const textField = page.getViewById('keyboardInputField') if (textField) { applySettingsTextFieldContrast(textField, false) textField.focus() diff --git a/app/phone-ui/main-page.xml b/app/phone-ui/main-page.xml index 1127111c..c10ee6a5 100644 --- a/app/phone-ui/main-page.xml +++ b/app/phone-ui/main-page.xml @@ -38,30 +38,31 @@ - - - - + + + + + + - - - + + + +