First iteration of glanceboard

This commit is contained in:
James Babcock committed 2026-09-11 10:47:19 -07:00
1 parent a3660fac61
commit 8a340fc4ad
36 files changed
+2874 -357

No files matched your search

@@ -0,0 +1,100 @@
import { type GrayImage } from "../../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
import { hasLocationPermission } from "../../../g2/android-permissions";
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled } from "../../../native/compass";
import { isCompassCalibrated, normalizeHeading } from "../../compass/calibration";
import { cardinalDirection, createCompassBackground, drawCompassRose, layoutCompassRose, TICK_HEIGHT } from "../../compass/compass-rose";
import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "../../compass/declination";
import { getNorthReference, resolveHeading } from "../../compass/heading";
import { type GlanceWidget } from "../widget";
/** Owner token for the refcounted magnetometer, distinct from the Compass app's. */
const COMPASS_OWNER = "glanceboard";
const TOP_PAD = 4;
const BOTTOM_PAD = 4;
const EDGE_PAD = 8;
const MAX_ROSE_RADIUS = 60;
/**
* The Compass app's rose at card size: heading readout above, tilted rose
* below. Turns the magnetometer on for as long as the board shows it (the
* Compass app keeps its own hold, so the two never switch each other off).
* Never prompts for location: true north is used when a declination is
* already known, otherwise the readout says it is magnetic.
*/
export class CompassWidget implements GlanceWidget {
private rawHeading: number | null = null;
private unsubscribe: (() => void) | null = null;
private unsubscribeDeclination: (() => void) | null = null;
private enabled = false;
private background: { key: string; image: GrayImage } | null = null;
start(requestRender: () => void): void {
this.unsubscribe = addCompassListener((event) => {
if (event.command === COMPASS_CHANGED && event.headingDegrees >= 0) {
this.rawHeading = normalizeHeading(event.headingDegrees);
requestRender();
}
});
this.unsubscribeDeclination = onDeclinationChanged(requestRender);
if (!this.enabled) {
this.enabled = true;
setCompassEnabled(true, COMPASS_OWNER);
}
if (getNorthReference() === "true" && hasLocationPermission()) refreshDeclination();
}
stop(): void {
this.unsubscribe?.();
this.unsubscribe = null;
this.unsubscribeDeclination?.();
this.unsubscribeDeclination = null;
if (this.enabled) {
this.enabled = false;
setCompassEnabled(false, COMPASS_OWNER);
}
}
private statusText(): string | null {
if (this.rawHeading === null) return "Waiting for compass";
if (!isCompassCalibrated()) return "Uncalibrated";
if (getNorthReference() === "true" && getDeclinationAvailability() !== "available") return "Magnetic";
return null;
}
paint(image: GrayImage): void {
const medium = getDefaultMediumFont();
const small = getDefaultSmallFont();
const { width, height } = image;
const heading = this.rawHeading === null ? null : resolveHeading(this.rawHeading).displayDegrees;
const headingText = heading === null ? "--°" : `${Math.round(heading)}° ${cardinalDirection(heading)}`;
const status = this.statusText();
const textHeight = medium.lineHeight + (status ? small.lineHeight + 2 : 0);
const cx = width / 2;
const { cy, radius, ringTop } = layoutCompassRose({
width,
height,
cx,
topClearance: TOP_PAD + textHeight + 4,
bottomPad: BOTTOM_PAD,
edgePad: EDGE_PAD,
maxRadius: MAX_ROSE_RADIUS,
minRadius: 16,
});
const fade = heading === null ? 0.45 : 1;
const y = Math.max(TOP_PAD, Math.round((ringTop - TICK_HEIGHT - textHeight) / 2));
const clipY = y + textHeight + 4;
const key = [width, height, cx, cy, radius, clipY, fade].join(",");
if (this.background?.key !== key) {
this.background = { key, image: createCompassBackground(width, height, cx, cy, radius, clipY, fade) };
}
// composeInto keeps the background's cached interior texture as a
// deferred image draw, so the wire planner can restore it from cache.
this.background.image.composeInto(image, 0, 0);
drawCompassRose(image, cx, cy, radius, heading);
image.drawText(medium, Math.round(cx - medium.measureText(headingText) / 2), y, headingText, heading === null ? 150 : 255);
if (status) {
image.drawText(small, Math.round(cx - small.measureText(status) / 2), y + medium.lineHeight + 2, status, 125);
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import { type GlanceWidgetDefinition, type GlanceWidgetId } from "../widget";
import { CompassWidget } from "./compass-widget";
import { MusicWidget } from "./music-widget";
import { NightscoutWidget } from "./nightscout-widget";
import { SystemCardWidget } from "./system-card";
/** Every widget a board slot can hold. */
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
{ id: "system-card", label: "System card", create: () => new SystemCardWidget() },
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
{ id: "compass", label: "Compass", create: () => new CompassWidget() },
{ id: "music", label: "Music", create: () => new MusicWidget() },
];
export function findGlanceWidget(id: GlanceWidgetId | string): GlanceWidgetDefinition | null {
return GLANCE_WIDGETS.find((widget) => widget.id === id) ?? null;
}
@@ -0,0 +1,127 @@
import { type GrayImage } from "../../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
import { truncateText } from "../../../graphics/textwrap";
import { mediaControllerBridge, type MediaControllerState } from "../../../native/media-controller";
import { clamp } from "../../../util/numeric-util";
import { type GlanceWidget } from "../widget";
const PAD = 8;
const ART_SIZE = 96;
const ART_X = PAD;
const PROGRESS_BAR_HEIGHT = 5;
/**
* Now playing: album art, title/artist/album and a progress bar for the
* active Android media session, the Music app's header at card size. The
* media bridge runs for the whole session; the widget subscribes and ticks
* once a second only while something is playing.
*/
export class MusicWidget implements GlanceWidget {
private media: MediaControllerState = mediaControllerBridge.snapshot();
private unsubscribe: (() => void) | null = null;
private progressTimer: ReturnType<typeof setInterval> | null = null;
private art: GrayImage | null = null;
private artKey = "";
start(requestRender: () => void): void {
this.unsubscribe = mediaControllerBridge.onStateChange((state) => {
this.media = state;
if (state.playbackState === "playing" && state.durationMs > 0 && state.positionMs >= 0) {
this.progressTimer ??= setInterval(requestRender, 1_000);
} else {
this.stopProgressTimer();
}
requestRender();
});
}
stop(): void {
this.unsubscribe?.();
this.unsubscribe = null;
this.stopProgressTimer();
}
private stopProgressTimer(): void {
if (this.progressTimer !== null) clearInterval(this.progressTimer);
this.progressTimer = null;
}
paint(image: GrayImage): void {
const medium = getDefaultMediumFont();
const small = getDefaultSmallFont();
const media = mediaControllerBridge.snapshot();
this.media = media;
if (!media.available || (!media.title && !media.artist)) {
image.drawText(small, PAD, PAD, "Music", 150);
const text = media.accessEnabled ? "Nothing playing" : "Notification access needed";
image.drawText(small, PAD, PAD + small.lineHeight + 6, text, 140);
return;
}
const artY = Math.max(PAD, ((image.height - ART_SIZE) / 2) | 0);
this.drawArt(image, media, artY);
const textX = ART_X + ART_SIZE + 12;
const textWidth = image.width - textX - PAD;
let y = artY;
image.drawText(medium, textX, y, truncateText(medium, media.title || "Unknown title", textWidth), 230);
y += medium.lineHeight + 2;
if (media.artist) {
image.drawText(small, textX, y, truncateText(small, media.artist, textWidth), 170);
y += small.lineHeight + 2;
}
if (media.album) {
image.drawText(small, textX, y, truncateText(small, media.album, textWidth), 120);
}
// Progress pinned to the art's bottom edge; the state label sits beside it.
const barY = artY + ART_SIZE - PROGRESS_BAR_HEIGHT;
const timeY = barY - small.lineHeight - 3;
const stateLabel = media.playbackState === "playing" ? "" : media.playbackState === "paused" ? "Paused" : media.playbackState;
if (media.durationMs > 0 && media.positionMs >= 0) {
const elapsed = formatMediaTime(media.positionMs);
const duration = formatMediaTime(media.durationMs);
image.drawText(small, textX, timeY, elapsed, 140);
image.drawText(small, textX + textWidth - small.measureText(duration), timeY, duration, 140);
if (stateLabel) {
image.drawText(small, textX + (((textWidth - small.measureText(stateLabel)) / 2) | 0), timeY, stateLabel, 140);
}
image.drawRect(textX, barY, textWidth, PROGRESS_BAR_HEIGHT, 55);
const progress = clamp(media.positionMs / media.durationMs, 0, 1);
image.fillRect(textX + 1, barY + 1, Math.round((textWidth - 2) * progress), PROGRESS_BAR_HEIGHT - 2, 170);
} else if (stateLabel) {
image.drawText(small, textX, timeY, stateLabel, 140);
}
}
private drawArt(image: GrayImage, media: MediaControllerState, artY: number): void {
const key = `${media.packageName}|${media.title}|${media.album}`;
// Retry while null: players often publish metadata before the bitmap.
if (key !== this.artKey || this.art === null) {
this.artKey = key;
this.art = mediaControllerBridge.getAlbumArt(ART_SIZE);
}
if (this.art) {
const dx = ART_X + Math.max(0, ((ART_SIZE - this.art.width) / 2) | 0);
const dy = artY + Math.max(0, ((ART_SIZE - this.art.height) / 2) | 0);
image.bitBlt(this.art, dx, dy);
image.drawRect(dx - 1, dy - 1, this.art.width + 2, this.art.height + 2, 60);
} else {
image.drawRect(ART_X, artY, ART_SIZE, ART_SIZE, 60);
const font = getDefaultSmallFont();
image.drawText(font, ART_X + Math.round((ART_SIZE - font.measureText("no art")) / 2),
artY + Math.round((ART_SIZE - font.lineHeight) / 2), "no art", 90);
}
}
}
function formatMediaTime(milliseconds: number): string {
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1_000));
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
: `${minutes}:${String(seconds).padStart(2, "0")}`;
}
@@ -0,0 +1,95 @@
import { type GrayImage } from "../../../graphics/image";
import { getDefaultLargeFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
import { truncateText } from "../../../graphics/textwrap";
import { nightscoutBridge, type NightscoutState } from "../../../native/nightscout-bridge";
import { isNightscoutSettingsConfigured } from "../../../ui/dashboard-settings";
import { lineStep } from "../../../ui/metrics";
import { formatAgeShortFromTimestamp } from "~/util/date-util";
import {
drawDirectionIndicator,
drawNightscoutGraph,
drawNightscoutValueStrikeThrough,
formatDelta,
isNightscoutPointStale,
} from "../../nightscout/nightscout";
import { type GlanceWidget } from "../widget";
const PAD = 8;
/** Width of the readout column left of the graph. */
const READOUT_WIDTH = 96;
/**
* Current glucose with delta, trend and age beside the Nightscout app's
* 2-hour graph. The bridge polls on its own for the whole session, so the
* widget only subscribes; a minute tick keeps the age and staleness moving
* during a stalled fetch.
*/
export class NightscoutWidget implements GlanceWidget {
private state: NightscoutState = nightscoutBridge.snapshot();
private unsubscribe: (() => void) | null = null;
private tick: ReturnType<typeof setInterval> | null = null;
start(requestRender: () => void): void {
this.unsubscribe = nightscoutBridge.onStateChange((state) => {
this.state = state;
requestRender();
});
this.tick = setInterval(requestRender, 60_000);
}
stop(): void {
this.unsubscribe?.();
this.unsubscribe = null;
if (this.tick !== null) clearInterval(this.tick);
this.tick = null;
}
paint(image: GrayImage): void {
const small = getDefaultSmallFont();
const large = getDefaultLargeFont();
const state = this.state;
const nowMs = Date.now();
const step = lineStep(small);
image.drawText(small, PAD, PAD, "Nightscout", 150);
if (!isNightscoutSettingsConfigured() || state.configurationMissing) {
image.drawText(small, PAD, PAD + step + 4, "Not configured", 140);
image.drawText(small, PAD, PAD + 2 * step + 4, "Set the site URL in the Nightscout app", 100);
return;
}
const latest = state.latest;
if (!state.available || !latest) {
image.drawText(small, PAD, PAD + step + 4, "No data", 140);
image.drawText(small, PAD, PAD + 2 * step + 4, truncateText(small, state.status, image.width - 2 * PAD), 100);
return;
}
// Readout column: big value, units, then delta + trend and the age.
const glucoseText = `${latest.sgv}`;
const glucoseY = PAD + step;
const glucoseWidth = large.measureText(glucoseText);
image.drawText(large, PAD, glucoseY, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, PAD, glucoseY + (large.lineHeight >> 1), glucoseWidth);
}
const unitsX = PAD + glucoseWidth + 4;
if (unitsX + small.measureText(state.units) <= PAD + READOUT_WIDTH) {
image.drawText(small, unitsX, glucoseY + large.lineHeight - small.lineHeight, state.units, 140);
}
let y = glucoseY + large.lineHeight + 2;
const deltaText = `${formatDelta(state.delta)} `;
image.drawText(small, PAD, y, deltaText, 180);
drawDirectionIndicator(image, small, PAD + small.measureText(deltaText), y, state.direction, 180);
y += step;
image.drawText(small, PAD, y, `${formatAgeShortFromTimestamp(latest.timestampMs, nowMs)} ago`, 130);
const graphX = PAD + READOUT_WIDTH + PAD;
drawNightscoutGraph(
image,
{ x: graphX, y: PAD, width: image.width - graphX - PAD, height: image.height - 2 * PAD },
state,
nowMs,
small,
);
}
}
+173
View File
@@ -0,0 +1,173 @@
import { BATTERY_ICON_WIDTH, drawBattery } from "../../../graphics/battery";
import { type GrayImage, type UiFont } from "../../../graphics/image";
import { getDefaultLargeFont, getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
import { onAndroidNotificationPosted, readActiveNotificationIcons } from "../../../native/notification-icons";
import { readPhoneBatteryState } from "../../../native/phone-battery";
import { formatClockDate, formatClockTime } from "../../../ui/clock-format";
import {
batteryDisplayModeSetting,
batteryIndicatorVisible,
glassesBatteryVisibilitySetting,
onAnySettingChanged,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
type BatteryIndicatorVisibility,
} from "../../../ui/dashboard-settings";
import { shell } from "../../../ui/shell/shell";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../../util/render-freshness";
import { type GlanceWidget } from "../widget";
const PAD = 8;
const NOTIFICATION_ICON_SIZE = 24;
const NOTIFICATION_ICON_GAP = 4;
const BATTERY_ITEM_GAP = 12;
const BATTERY_LABEL_VALUE = 150;
type BatteryItem = { label: string; percent: number; charging: boolean };
/**
* Date and time, the phone's notification icons, and the phone/G2/R1
* battery indicators: the top bar's contents, laid out for a card. Battery
* style and per-device visibility follow Settings > Display > Battery
* indicators, so the card agrees with the bar.
*/
export class SystemCardWidget implements GlanceWidget {
private requestRender: (() => void) | null = null;
private minuteTimer: ReturnType<typeof setTimeout> | null = null;
private unsubscribeNotifications: (() => void) | null = null;
private unsubscribeSettings: (() => void) | null = null;
start(requestRender: () => void): void {
this.requestRender = requestRender;
this.scheduleMinuteTick();
this.unsubscribeNotifications = onAndroidNotificationPosted(() => this.requestRender?.());
this.unsubscribeSettings = onAnySettingChanged(() => this.requestRender?.());
}
stop(): void {
this.requestRender = null;
if (this.minuteTimer !== null) clearTimeout(this.minuteTimer);
this.minuteTimer = null;
this.unsubscribeNotifications?.();
this.unsubscribeNotifications = null;
this.unsubscribeSettings?.();
this.unsubscribeSettings = null;
}
/** Repaint on the minute boundary, so the clock never shows a stale minute. */
private scheduleMinuteTick(): void {
if (this.minuteTimer !== null) clearTimeout(this.minuteTimer);
const now = Date.now();
const untilNextMinute = 60_000 - (now % 60_000) + 50;
this.minuteTimer = setTimeout(() => {
this.minuteTimer = null;
if (!this.requestRender) return;
this.requestRender();
this.scheduleMinuteTick();
}, untilNextMinute);
}
paint(image: GrayImage): void {
const large = getDefaultLargeFont();
const medium = getDefaultMediumFont();
const small = getDefaultSmallFont();
const now = new Date();
// Clock and date down the left; batteries take the right edge.
const batteryLeft = drawBatteryBlock(image, small, image.width - PAD, PAD);
const textWidth = Math.max(0, batteryLeft - BATTERY_ITEM_GAP - PAD);
const timeText = formatClockTime(now);
const timeFont = large.measureText(timeText) <= textWidth ? large : medium;
let y = PAD;
image.drawText(timeFont, PAD, y, timeText, 230);
y += timeFont.lineHeight + 2;
image.drawText(medium, PAD, y, formatClockDate(now), 170);
// Notification icons along the bottom, as many as fit.
const iconY = image.height - PAD - NOTIFICATION_ICON_SIZE;
const maxIcons = Math.max(0, ((image.width - 2 * PAD + NOTIFICATION_ICON_GAP) / (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP)) | 0);
if (maxIcons > 0) {
const { icons, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
if (stale) noteStaleDataUsed();
for (let index = 0; index < icons.length; index++) {
image.drawImage(icons[index]!, PAD + index * (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP), iconY);
}
}
}
}
function collectBatteryItems(): BatteryItem[] {
const items: BatteryItem[] = [];
const push = (visibility: BatteryIndicatorVisibility, label: string, percent: number | null, charging: boolean | null) => {
if (percent === null || !Number.isFinite(percent)) return;
const clamped = Math.max(0, Math.min(100, Math.round(percent)));
if (!batteryIndicatorVisible(visibility, clamped)) return;
items.push({ label, percent: clamped, charging: Boolean(charging) });
};
const phone = readPhoneBatteryState();
push(phoneBatteryVisibilitySetting.get(), "Phone", phone.battery, phone.charging);
const levels = shell.getBatteryLevels();
push(glassesBatteryVisibilitySetting.get(), "G2", levels.headset, levels.headsetCharging);
if (levels.ring !== null && Number.isInteger(levels.ring) && levels.ring >= 0 && levels.ring <= 100) {
push(ringBatteryVisibilitySetting.get(), "R1", levels.ring, levels.ringCharging);
}
return items;
}
/**
* The battery indicators right-aligned at `right`, in the configured style.
* Side-by-side styles put the label beside the gauge (or percentage) on one
* line; stacked styles centre the label above it. Returns the block's left
* edge (or `right` when nothing is shown).
*/
function drawBatteryBlock(image: GrayImage, font: UiFont, right: number, top: number): number {
const items = collectBatteryItems();
if (!items.length) return right;
const mode = batteryDisplayModeSetting.get();
const percentage = mode === "percentage" || mode === "stacked-percentage";
const stacked = mode === "stacked" || mode === "stacked-percentage";
const gaugeHeight = drawBattery(0, false).height;
let x = right;
for (let index = items.length - 1; index >= 0; index--) {
const item = items[index]!;
const percentText = `${item.percent}%`;
const labelWidth = font.measureText(item.label);
const valueWidth = percentage ? font.measureText(percentText) : BATTERY_ICON_WIDTH;
if (stacked) {
const itemWidth = Math.max(labelWidth, valueWidth);
x -= itemWidth;
image.drawText(font, x + (((itemWidth - labelWidth) / 2) | 0), top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + (((itemWidth - valueWidth) / 2) | 0), top + font.lineHeight + 2, item, percentage, gaugeHeight);
} else {
x -= labelWidth + 5 + valueWidth;
image.drawText(font, x, top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + labelWidth + 5, top, item, percentage, gaugeHeight);
}
x -= BATTERY_ITEM_GAP;
}
return x + BATTERY_ITEM_GAP;
}
function drawBatteryValue(
image: GrayImage,
font: UiFont,
x: number,
lineTop: number,
item: BatteryItem,
percentage: boolean,
gaugeHeight: number,
): void {
if (percentage) {
const percentText = `${item.percent}%`;
if (item.charging) {
// Inverted text marks charging, as in the top bar.
image.fillRect(x - 2, lineTop - 1, font.measureText(percentText) + 4, font.lineHeight + 2, 255);
image.drawText(font, x, lineTop, percentText, 1);
} else {
image.drawText(font, x, lineTop, percentText, 200);
}
return;
}
const icon = drawBattery(item.percent, item.charging);
image.bitBlt(icon, x, lineTop + Math.max(0, ((font.lineHeight - gaugeHeight) / 2) | 0), { transparentZero: true });
}