forked from Blendman974/faceclaw
First iteration of glanceboard
This commit is contained in:
1 parent
a3660fac61
commit
8a340fc4ad
36 files changed
+2874
-357
No files matched your search
@@ -22,6 +22,7 @@ import freecellApp from "./freecell";
|
||||
import pinballApp from "./pinball";
|
||||
import developerApp from "./developer";
|
||||
import evenhubApp from "./evenhub";
|
||||
import glanceboardApp from "./glanceboard";
|
||||
import settingsApp from "./settings";
|
||||
|
||||
/**
|
||||
@@ -53,5 +54,6 @@ export const ALL_APPS: readonly AppDefinition[] = [
|
||||
pinballApp,
|
||||
developerApp,
|
||||
evenhubApp,
|
||||
glanceboardApp,
|
||||
settingsApp,
|
||||
];
|
||||
@@ -32,6 +32,31 @@ export type AppDefinition = {
|
||||
showInLauncher?: boolean;
|
||||
/** Present on the app that handles text shared via the Android share intent. */
|
||||
openSharedText?: (ctx: AppContext, title: string, text: string) => void;
|
||||
/**
|
||||
* Present on the app that supplies the Glanceboard: the sleep-time display
|
||||
* the controller shows on a tap or hold while the shell is asleep (see
|
||||
* app/g2/glance-host.ts). At most one app provides it.
|
||||
*/
|
||||
glanceboard?: GlanceboardProvider;
|
||||
};
|
||||
|
||||
/** A board the glance host can show while the shell sleeps. */
|
||||
export type GlanceboardProvider = {
|
||||
/** Board pixel size; the host centres it in the standard 576x288 band. */
|
||||
size: { width: number; height: number };
|
||||
/** Whether sleep-time gestures should show the board at all (user setting). */
|
||||
isEnabled: () => boolean;
|
||||
/** A fresh board; requestRender asks the host to repaint it. */
|
||||
createBoard: (requestRender: () => void) => GlanceBoardInstance;
|
||||
};
|
||||
|
||||
export type GlanceBoardInstance = {
|
||||
/** The board is about to show: start widgets (subscriptions, hardware). */
|
||||
start: () => void;
|
||||
/** The board was hidden: stop everything start began. */
|
||||
stop: () => void;
|
||||
/** Paint the board at its size. */
|
||||
paint: () => GrayImage;
|
||||
};
|
||||
|
||||
export type AppLaunchParams = {
|
||||
|
||||
+10
-322
@@ -23,6 +23,7 @@ import {
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
import { ensureLocationPermission, hasLocationPermission } from "../../g2/android-permissions";
|
||||
import { isCompassCalibrated, normalizeHeading } from "./calibration";
|
||||
import { cardinalDirection, createCompassBackground, drawCompassRose, layoutCompassRose, TICK_HEIGHT } from "./compass-rose";
|
||||
import { CompassCalibrationLayer } from "./calibration-layer";
|
||||
import { getDeclinationAvailability, onDeclinationChanged, refreshDeclination } from "./declination";
|
||||
import { getNorthReference, resolveHeading, setNorthReference, type NorthReference } from "./heading";
|
||||
@@ -41,59 +42,6 @@ const EDGE_PAD = 8;
|
||||
/** Cap on the rose's radius, so a tall window doesn't get a comical one. */
|
||||
const MAX_ROSE_RADIUS = 98;
|
||||
|
||||
/**
|
||||
* The rose is drawn as a flat disc lying in front of the wearer, tilted away
|
||||
* from vertical: `TILT_SQUASH` is how much that tilt shortens the depth axis,
|
||||
* and `TILT_PERSPECTIVE` how much nearer parts of the disc are magnified
|
||||
* relative to farther ones. Together they turn the ring into an egg-shaped
|
||||
* oval — wider and taller at the bottom — and give the rose's points their
|
||||
* foreshortening for free.
|
||||
*/
|
||||
const TILT_SQUASH = 0.42;
|
||||
const TILT_PERSPECTIVE = 0.22;
|
||||
/** Screen height of the projected ring, per unit of radius. */
|
||||
const RING_HEIGHT_PER_RADIUS =
|
||||
TILT_SQUASH * (1 / (1 + TILT_PERSPECTIVE) + 1 / (1 - TILT_PERSPECTIVE));
|
||||
/** Screen half-width of the projected ring, per unit of radius. */
|
||||
const RING_HALF_WIDTH_PER_RADIUS = 1 / Math.sqrt(1 - TILT_PERSPECTIVE * TILT_PERSPECTIVE);
|
||||
|
||||
/** Tip radii of the rose's long and short points, as a fraction of the ring. */
|
||||
const CARDINAL_TIP = 0.9;
|
||||
const INTERCARDINAL_TIP = 0.54;
|
||||
/** Radius the point bases sit on: how fat the rose is at its waist. */
|
||||
const POINT_BASE_RADIUS = 0.17;
|
||||
/** Half-angle of a point's base. 22.5° makes neighbouring bases just meet. */
|
||||
const POINT_BASE_HALF_ANGLE = 22.5;
|
||||
/**
|
||||
* A polar grid lying in the same plane as the disc, to give it somewhere to
|
||||
* sit and to fill the empty flanks either side of it. Rings are multiples of
|
||||
* the disc's radius; spokes are offset by half a step so none runs up the
|
||||
* middle into the heading tick.
|
||||
*/
|
||||
const PLANE_RINGS = [1.35, 1.8, 2.5, 3.6, 5.6];
|
||||
const PLANE_SPOKE_STEP = 30;
|
||||
/** Grid brightness at the disc's rim, and how fast it falls off with distance. */
|
||||
const PLANE_NEAR_VALUE = 78;
|
||||
const PLANE_FALLOFF = 0.55;
|
||||
/** Dimmer than this is left unpainted, so the grid ends by vanishing. */
|
||||
const PLANE_CUTOFF = 22;
|
||||
/** Height over which the grid fades out as it approaches the readout. */
|
||||
const PLANE_FADE_SPAN = 45;
|
||||
|
||||
/** Size of the fixed tick that marks the direction the wearer is facing. */
|
||||
const TICK_HEIGHT = 7;
|
||||
const TICK_HALF_WIDTH = 4;
|
||||
/** Depth of the disc's side wall, as a fraction of the ring's radius. */
|
||||
const DISC_DEPTH = 0.1;
|
||||
/**
|
||||
* Rim angle at which the silhouette turns vertical. Between this and its
|
||||
* mirror the wall faces the wearer; outside it the rim curves back away, so a
|
||||
* wall drawn there would hook inward instead of ending on the vertical edge.
|
||||
*/
|
||||
const WALL_START_ANGLE = (Math.acos(-TILT_PERSPECTIVE) * 180) / Math.PI;
|
||||
/** Side-wall shading, from the edges of the silhouette to the nearest point. */
|
||||
const WALL_DARK = 20;
|
||||
const WALL_LIT = 62;
|
||||
|
||||
class CompassLayer implements Layer {
|
||||
private rawHeading: number | null = null;
|
||||
@@ -233,21 +181,15 @@ 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 = readoutHeight + 4 + statusLines.length * smallStep;
|
||||
const radius = Math.max(
|
||||
24,
|
||||
Math.min(
|
||||
MAX_ROSE_RADIUS,
|
||||
Math.floor(
|
||||
(height - BOTTOM_PAD - TOP_PAD - textHeight - STACK_GAP - TICK_HEIGHT)
|
||||
/ (RING_HEIGHT_PER_RADIUS + DISC_DEPTH),
|
||||
),
|
||||
Math.floor((Math.min(cx, width - cx) - EDGE_PAD) / RING_HALF_WIDTH_PER_RADIUS),
|
||||
),
|
||||
);
|
||||
// The wall hangs below the rim, so the near rim sits a wall's depth up
|
||||
// from the bottom padding rather than on it.
|
||||
const cy = height - BOTTOM_PAD - discDepth(radius) - (radius * TILT_SQUASH) / (1 - TILT_PERSPECTIVE);
|
||||
const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE);
|
||||
const { cy, radius, ringTop } = layoutCompassRose({
|
||||
width,
|
||||
height,
|
||||
cx,
|
||||
topClearance: TOP_PAD + textHeight + STACK_GAP,
|
||||
bottomPad: BOTTOM_PAD,
|
||||
edgePad: EDGE_PAD,
|
||||
maxRadius: MAX_ROSE_RADIUS,
|
||||
});
|
||||
|
||||
let y = Math.max(TOP_PAD, Math.round((ringTop - TICK_HEIGHT - textHeight) / 2));
|
||||
const fade = heading === null ? 0.45 : 1;
|
||||
@@ -356,257 +298,3 @@ function frameStatusText(): string {
|
||||
return "Magnetic heading - waiting for location";
|
||||
}
|
||||
}
|
||||
|
||||
function cardinalDirection(heading: number): string {
|
||||
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
return names[Math.round(normalizeHeading(heading) / 45) % names.length]!;
|
||||
}
|
||||
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a point of the rose's plane onto the screen. `angle` is degrees
|
||||
* clockwise from the far side of the disc — the direction the wearer faces —
|
||||
* and `radius` is a fraction of the rose's outer ring.
|
||||
*/
|
||||
function projectRose(cx: number, cy: number, scale: number, radius: number, angle: number): Point {
|
||||
const radians = (angle * Math.PI) / 180;
|
||||
const across = radius * Math.sin(radians);
|
||||
const away = radius * Math.cos(radians);
|
||||
const depth = 1 + TILT_PERSPECTIVE * away;
|
||||
return {
|
||||
x: cx + (across * scale) / depth,
|
||||
y: cy - (away * scale * TILT_SQUASH) / depth,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
// 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.
|
||||
for (const degrees of [45, 135, 225, 315]) {
|
||||
drawRosePoint(image, cx, cy, radius, degrees - bearing, INTERCARDINAL_TIP, 85 * fade, 40 * fade);
|
||||
}
|
||||
for (const degrees of [90, 180, 270]) {
|
||||
drawRosePoint(image, cx, cy, radius, degrees - bearing, CARDINAL_TIP, 120 * fade, 55 * fade);
|
||||
}
|
||||
drawRosePoint(image, cx, cy, radius, -bearing, CARDINAL_TIP, 255 * fade, 140 * fade);
|
||||
}
|
||||
|
||||
/**
|
||||
* One point of the rose: a tapered spike split down its axis into a lit and a
|
||||
* shaded facet, which is what keeps the eight points readable once perspective
|
||||
* has squashed the ones lying across the wearer's line of sight.
|
||||
*/
|
||||
function drawRosePoint(
|
||||
image: GrayImage,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
angle: number,
|
||||
tipRadius: number,
|
||||
litValue: number,
|
||||
shadedValue: number,
|
||||
): void {
|
||||
const centre = { x: cx, y: cy };
|
||||
const tip = projectRose(cx, cy, radius, tipRadius, angle);
|
||||
const clockwise = projectRose(cx, cy, radius, POINT_BASE_RADIUS, angle + POINT_BASE_HALF_ANGLE);
|
||||
const anticlockwise = projectRose(cx, cy, radius, POINT_BASE_RADIUS, angle - POINT_BASE_HALF_ANGLE);
|
||||
fillTriangle(image, tip, centre, clockwise, litValue);
|
||||
fillTriangle(image, tip, centre, anticlockwise, shadedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* The side wall below the wearer-facing arc of the rim, which turns the tilted
|
||||
* disc into a shallow cylinder. The arc runs between the two points where the
|
||||
* silhouette turns vertical, so the wall ends flush with that vertical edge,
|
||||
* and it is shaded from dark there to lit where it faces the wearer head-on.
|
||||
*/
|
||||
function drawDiscWall(image: GrayImage, cx: number, cy: number, radius: number, fade: number): void {
|
||||
const depth = discDepth(radius);
|
||||
const segments = 48;
|
||||
const sweep = 360 - WALL_START_ANGLE * 2;
|
||||
const rimValue = 105 * fade;
|
||||
let previous = projectRose(cx, cy, radius, 1, WALL_START_ANGLE);
|
||||
image.drawLine(previous.x, previous.y, previous.x, previous.y + depth, rimValue);
|
||||
for (let i = 1; i <= segments; i++) {
|
||||
const angle = WALL_START_ANGLE + (i * sweep) / segments;
|
||||
const point = projectRose(cx, cy, radius, 1, angle);
|
||||
// Quads rather than per-column lines, so no gap opens up where the rim
|
||||
// runs nearly horizontal across the bottom of the oval.
|
||||
const value = (WALL_DARK + (WALL_LIT - WALL_DARK) * wallFacing(angle)) * fade;
|
||||
const top = { x: previous.x, y: previous.y };
|
||||
const next = { x: point.x, y: point.y };
|
||||
fillTriangle(image, top, next, { x: next.x, y: next.y + depth }, value);
|
||||
fillTriangle(image, top, { x: top.x, y: top.y + depth }, { x: next.x, y: next.y + depth }, value);
|
||||
image.drawLine(top.x, top.y + depth, next.x, next.y + depth, rimValue);
|
||||
previous = point;
|
||||
}
|
||||
image.drawLine(previous.x, previous.y, previous.x, previous.y + depth, rimValue);
|
||||
}
|
||||
|
||||
/** 1 where the wall faces the wearer head-on, 0 at the silhouette's edges. */
|
||||
function wallFacing(angle: number): number {
|
||||
const towardWearer = -Math.cos((angle * Math.PI) / 180);
|
||||
return (towardWearer - TILT_PERSPECTIVE) / (1 - TILT_PERSPECTIVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* The grid the disc sits on, drawn before the disc so the disc occludes it.
|
||||
* Brightness falls off with distance and fades to nothing as the plane climbs
|
||||
* towards `clipY`, so the grid dissolves into the black under the readout
|
||||
* rather than stopping at a hard edge.
|
||||
*/
|
||||
function drawPlaneGrid(image: GrayImage, cx: number, cy: number, radius: number, clipY: number): void {
|
||||
const shade = (point: Point, ringRadius: number): number => {
|
||||
if (point.y > image.height || Math.abs(point.x - cx) > image.width) return 0;
|
||||
const fade = Math.max(0, Math.min(1, (point.y - clipY) / PLANE_FADE_SPAN));
|
||||
const value = (PLANE_NEAR_VALUE / (1 + PLANE_FALLOFF * (ringRadius - 1))) * fade;
|
||||
return value >= PLANE_CUTOFF ? value : 0;
|
||||
};
|
||||
const trace = (
|
||||
steps: number,
|
||||
at: (step: number) => { point: Point; ringRadius: number },
|
||||
): void => {
|
||||
let previous: Point | null = null;
|
||||
let previousValue = 0;
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const { point, ringRadius } = at(i);
|
||||
const value = shade(point, ringRadius);
|
||||
if (previous !== null && previousValue > 0 && value > 0) {
|
||||
image.drawLine(previous.x, previous.y, point.x, point.y, (previousValue + value) / 2);
|
||||
}
|
||||
previous = point;
|
||||
previousValue = value;
|
||||
}
|
||||
};
|
||||
|
||||
for (const ringRadius of PLANE_RINGS) {
|
||||
trace(96, (step) => ({ point: projectRose(cx, cy, radius, ringRadius, (step * 360) / 96), ringRadius }));
|
||||
}
|
||||
// Spokes run from just outside the disc to the outermost ring, so the grid
|
||||
// closes on itself instead of trailing off into loose ends.
|
||||
const outer = PLANE_RINGS[PLANE_RINGS.length - 1]!;
|
||||
for (let angle = PLANE_SPOKE_STEP / 2; angle < 360; angle += PLANE_SPOKE_STEP) {
|
||||
trace(24, (step) => {
|
||||
const ringRadius = 1.05 + (step * (outer - 1.05)) / 24;
|
||||
return { point: projectRose(cx, cy, radius, ringRadius, angle), ringRadius };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Screen depth of the disc's side wall at the given ring radius. */
|
||||
function discDepth(radius: number): number {
|
||||
return Math.max(3, Math.round(radius * DISC_DEPTH));
|
||||
}
|
||||
|
||||
/** The ring bounding the rose: the tilted disc's rim, drawn as a polygon. */
|
||||
function drawTiltedRing(image: GrayImage, cx: number, cy: number, radius: number, value: number): void {
|
||||
const segments = 72;
|
||||
let previous = projectRose(cx, cy, radius, 1, 0);
|
||||
for (let i = 1; i <= segments; i++) {
|
||||
const point = projectRose(cx, cy, radius, 1, (i * 360) / segments);
|
||||
image.drawLine(previous.x, previous.y, point.x, point.y, value);
|
||||
previous = point;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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: tickTop + TICK_HEIGHT - 1 },
|
||||
{ x: cx - TICK_HALF_WIDTH, y: tickTop },
|
||||
{ x: cx + TICK_HALF_WIDTH, y: tickTop },
|
||||
value,
|
||||
);
|
||||
}
|
||||
|
||||
function fillTriangle(image: GrayImage, a: Point, b: Point, c: Point, value: number): void {
|
||||
const left = Math.max(0, Math.floor(Math.min(a.x, b.x, c.x)));
|
||||
const right = Math.min(image.width - 1, Math.ceil(Math.max(a.x, b.x, c.x)));
|
||||
const top = Math.max(0, Math.floor(Math.min(a.y, b.y, c.y)));
|
||||
const bottom = Math.min(image.height - 1, Math.ceil(Math.max(a.y, b.y, c.y)));
|
||||
const shade = Math.round(value);
|
||||
for (let y = top; y <= bottom; y++) {
|
||||
for (let x = left; x <= right; x++) {
|
||||
const point = { x: x + 0.5, y: y + 0.5 };
|
||||
const ab = edge(a, b, point);
|
||||
const bc = edge(b, c, point);
|
||||
const ca = edge(c, a, point);
|
||||
// Accept either winding, so callers don't have to order their vertices.
|
||||
if ((ab >= 0 && bc >= 0 && ca >= 0) || (ab <= 0 && bc <= 0 && ca <= 0)) {
|
||||
image.setPixel(x, y, shade);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Twice the signed area of the triangle a-b-p; its sign is p's side of a-b. */
|
||||
function edge(a: Point, b: Point, p: Point): number {
|
||||
return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
/**
|
||||
* The compass rose renderer: a tilted disc with eight rotating points, drawn
|
||||
* from a heading into any GrayImage. Pure drawing code shared by the Compass
|
||||
* app's full-window view and the Glanceboard's compass widget; the callers
|
||||
* own the magnetometer lifecycle and the readout text around it.
|
||||
*/
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { normalizeHeading } from "./calibration";
|
||||
|
||||
/**
|
||||
* The rose is drawn as a flat disc lying in front of the wearer, tilted away
|
||||
* from vertical: `TILT_SQUASH` is how much that tilt shortens the depth axis,
|
||||
* and `TILT_PERSPECTIVE` how much nearer parts of the disc are magnified
|
||||
* relative to farther ones. Together they turn the ring into an egg-shaped
|
||||
* oval — wider and taller at the bottom — and give the rose's points their
|
||||
* foreshortening for free.
|
||||
*/
|
||||
const TILT_SQUASH = 0.42;
|
||||
const TILT_PERSPECTIVE = 0.22;
|
||||
/** Screen height of the projected ring, per unit of radius. */
|
||||
const RING_HEIGHT_PER_RADIUS =
|
||||
TILT_SQUASH * (1 / (1 + TILT_PERSPECTIVE) + 1 / (1 - TILT_PERSPECTIVE));
|
||||
/** Screen half-width of the projected ring, per unit of radius. */
|
||||
const RING_HALF_WIDTH_PER_RADIUS = 1 / Math.sqrt(1 - TILT_PERSPECTIVE * TILT_PERSPECTIVE);
|
||||
|
||||
/** Tip radii of the rose's long and short points, as a fraction of the ring. */
|
||||
const CARDINAL_TIP = 0.9;
|
||||
const INTERCARDINAL_TIP = 0.54;
|
||||
/** Radius the point bases sit on: how fat the rose is at its waist. */
|
||||
const POINT_BASE_RADIUS = 0.17;
|
||||
/** Half-angle of a point's base. 22.5° makes neighbouring bases just meet. */
|
||||
const POINT_BASE_HALF_ANGLE = 22.5;
|
||||
/**
|
||||
* A polar grid lying in the same plane as the disc, to give it somewhere to
|
||||
* sit and to fill the empty flanks either side of it. Rings are multiples of
|
||||
* the disc's radius; spokes are offset by half a step so none runs up the
|
||||
* middle into the heading tick.
|
||||
*/
|
||||
const PLANE_RINGS = [1.35, 1.8, 2.5, 3.6, 5.6];
|
||||
const PLANE_SPOKE_STEP = 30;
|
||||
/** Grid brightness at the disc's rim, and how fast it falls off with distance. */
|
||||
const PLANE_NEAR_VALUE = 78;
|
||||
const PLANE_FALLOFF = 0.55;
|
||||
/** Dimmer than this is left unpainted, so the grid ends by vanishing. */
|
||||
const PLANE_CUTOFF = 22;
|
||||
/** Height over which the grid fades out as it approaches the readout. */
|
||||
const PLANE_FADE_SPAN = 45;
|
||||
|
||||
/** Size of the fixed tick that marks the direction the wearer is facing. */
|
||||
const TICK_HEIGHT = 7;
|
||||
const TICK_HALF_WIDTH = 4;
|
||||
/** Depth of the disc's side wall, as a fraction of the ring's radius. */
|
||||
const DISC_DEPTH = 0.1;
|
||||
/**
|
||||
* Rim angle at which the silhouette turns vertical. Between this and its
|
||||
* mirror the wall faces the wearer; outside it the rim curves back away, so a
|
||||
* wall drawn there would hook inward instead of ending on the vertical edge.
|
||||
*/
|
||||
const WALL_START_ANGLE = (Math.acos(-TILT_PERSPECTIVE) * 180) / Math.PI;
|
||||
/** Side-wall shading, from the edges of the silhouette to the nearest point. */
|
||||
const WALL_DARK = 20;
|
||||
const WALL_LIT = 62;
|
||||
|
||||
/** Size of the fixed tick that marks the direction the wearer is facing. */
|
||||
export { TICK_HEIGHT };
|
||||
|
||||
/**
|
||||
* Fit a rose into a box: the largest radius whose projected ring plus disc
|
||||
* wall fits between `topClearance` (the bottom of whatever text sits above)
|
||||
* and the box's bottom padding, and whose width clears the side padding
|
||||
* around `cx`. Returns the centre and radius to hand to drawCompassRose.
|
||||
*/
|
||||
export function layoutCompassRose(options: {
|
||||
width: number;
|
||||
height: number;
|
||||
cx: number;
|
||||
/** Lowest y already used above the rose (readout text, its gap). */
|
||||
topClearance: number;
|
||||
bottomPad: number;
|
||||
edgePad: number;
|
||||
maxRadius: number;
|
||||
minRadius?: number;
|
||||
}): { cx: number; cy: number; radius: number; ringTop: number } {
|
||||
const { width, height, cx } = options;
|
||||
const radius = Math.max(
|
||||
options.minRadius ?? 24,
|
||||
Math.min(
|
||||
options.maxRadius,
|
||||
Math.floor((height - options.bottomPad - options.topClearance - TICK_HEIGHT) / (RING_HEIGHT_PER_RADIUS + DISC_DEPTH)),
|
||||
Math.floor((Math.min(cx, width - cx) - options.edgePad) / RING_HALF_WIDTH_PER_RADIUS),
|
||||
),
|
||||
);
|
||||
// The wall hangs below the rim, so the near rim sits a wall's depth up
|
||||
// from the bottom padding rather than on it.
|
||||
const cy = height - options.bottomPad - discDepth(radius) - (radius * TILT_SQUASH) / (1 - TILT_PERSPECTIVE);
|
||||
const ringTop = cy - (radius * TILT_SQUASH) / (1 + TILT_PERSPECTIVE);
|
||||
return { cx, cy, radius, ringTop };
|
||||
}
|
||||
|
||||
export function cardinalDirection(heading: number): string {
|
||||
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
return names[Math.round(normalizeHeading(heading) / 45) % names.length]!;
|
||||
}
|
||||
|
||||
interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a point of the rose's plane onto the screen. `angle` is degrees
|
||||
* clockwise from the far side of the disc — the direction the wearer faces —
|
||||
* and `radius` is a fraction of the rose's outer ring.
|
||||
*/
|
||||
function projectRose(cx: number, cy: number, scale: number, radius: number, angle: number): Point {
|
||||
const radians = (angle * Math.PI) / 180;
|
||||
const across = radius * Math.sin(radians);
|
||||
const away = radius * Math.cos(radians);
|
||||
const depth = 1 + TILT_PERSPECTIVE * away;
|
||||
return {
|
||||
x: cx + (across * scale) / depth,
|
||||
y: cy - (away * scale * TILT_SQUASH) / depth,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export 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. */
|
||||
export 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;
|
||||
// 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.
|
||||
for (const degrees of [45, 135, 225, 315]) {
|
||||
drawRosePoint(image, cx, cy, radius, degrees - bearing, INTERCARDINAL_TIP, 85 * fade, 40 * fade);
|
||||
}
|
||||
for (const degrees of [90, 180, 270]) {
|
||||
drawRosePoint(image, cx, cy, radius, degrees - bearing, CARDINAL_TIP, 120 * fade, 55 * fade);
|
||||
}
|
||||
drawRosePoint(image, cx, cy, radius, -bearing, CARDINAL_TIP, 255 * fade, 140 * fade);
|
||||
}
|
||||
|
||||
/**
|
||||
* One point of the rose: a tapered spike split down its axis into a lit and a
|
||||
* shaded facet, which is what keeps the eight points readable once perspective
|
||||
* has squashed the ones lying across the wearer's line of sight.
|
||||
*/
|
||||
function drawRosePoint(
|
||||
image: GrayImage,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
angle: number,
|
||||
tipRadius: number,
|
||||
litValue: number,
|
||||
shadedValue: number,
|
||||
): void {
|
||||
const centre = { x: cx, y: cy };
|
||||
const tip = projectRose(cx, cy, radius, tipRadius, angle);
|
||||
const clockwise = projectRose(cx, cy, radius, POINT_BASE_RADIUS, angle + POINT_BASE_HALF_ANGLE);
|
||||
const anticlockwise = projectRose(cx, cy, radius, POINT_BASE_RADIUS, angle - POINT_BASE_HALF_ANGLE);
|
||||
fillTriangle(image, tip, centre, clockwise, litValue);
|
||||
fillTriangle(image, tip, centre, anticlockwise, shadedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* The side wall below the wearer-facing arc of the rim, which turns the tilted
|
||||
* disc into a shallow cylinder. The arc runs between the two points where the
|
||||
* silhouette turns vertical, so the wall ends flush with that vertical edge,
|
||||
* and it is shaded from dark there to lit where it faces the wearer head-on.
|
||||
*/
|
||||
function drawDiscWall(image: GrayImage, cx: number, cy: number, radius: number, fade: number): void {
|
||||
const depth = discDepth(radius);
|
||||
const segments = 48;
|
||||
const sweep = 360 - WALL_START_ANGLE * 2;
|
||||
const rimValue = 105 * fade;
|
||||
let previous = projectRose(cx, cy, radius, 1, WALL_START_ANGLE);
|
||||
image.drawLine(previous.x, previous.y, previous.x, previous.y + depth, rimValue);
|
||||
for (let i = 1; i <= segments; i++) {
|
||||
const angle = WALL_START_ANGLE + (i * sweep) / segments;
|
||||
const point = projectRose(cx, cy, radius, 1, angle);
|
||||
// Quads rather than per-column lines, so no gap opens up where the rim
|
||||
// runs nearly horizontal across the bottom of the oval.
|
||||
const value = (WALL_DARK + (WALL_LIT - WALL_DARK) * wallFacing(angle)) * fade;
|
||||
const top = { x: previous.x, y: previous.y };
|
||||
const next = { x: point.x, y: point.y };
|
||||
fillTriangle(image, top, next, { x: next.x, y: next.y + depth }, value);
|
||||
fillTriangle(image, top, { x: top.x, y: top.y + depth }, { x: next.x, y: next.y + depth }, value);
|
||||
image.drawLine(top.x, top.y + depth, next.x, next.y + depth, rimValue);
|
||||
previous = point;
|
||||
}
|
||||
image.drawLine(previous.x, previous.y, previous.x, previous.y + depth, rimValue);
|
||||
}
|
||||
|
||||
/** 1 where the wall faces the wearer head-on, 0 at the silhouette's edges. */
|
||||
function wallFacing(angle: number): number {
|
||||
const towardWearer = -Math.cos((angle * Math.PI) / 180);
|
||||
return (towardWearer - TILT_PERSPECTIVE) / (1 - TILT_PERSPECTIVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* The grid the disc sits on, drawn before the disc so the disc occludes it.
|
||||
* Brightness falls off with distance and fades to nothing as the plane climbs
|
||||
* towards `clipY`, so the grid dissolves into the black under the readout
|
||||
* rather than stopping at a hard edge.
|
||||
*/
|
||||
function drawPlaneGrid(image: GrayImage, cx: number, cy: number, radius: number, clipY: number): void {
|
||||
const shade = (point: Point, ringRadius: number): number => {
|
||||
if (point.y > image.height || Math.abs(point.x - cx) > image.width) return 0;
|
||||
const fade = Math.max(0, Math.min(1, (point.y - clipY) / PLANE_FADE_SPAN));
|
||||
const value = (PLANE_NEAR_VALUE / (1 + PLANE_FALLOFF * (ringRadius - 1))) * fade;
|
||||
return value >= PLANE_CUTOFF ? value : 0;
|
||||
};
|
||||
const trace = (
|
||||
steps: number,
|
||||
at: (step: number) => { point: Point; ringRadius: number },
|
||||
): void => {
|
||||
let previous: Point | null = null;
|
||||
let previousValue = 0;
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const { point, ringRadius } = at(i);
|
||||
const value = shade(point, ringRadius);
|
||||
if (previous !== null && previousValue > 0 && value > 0) {
|
||||
image.drawLine(previous.x, previous.y, point.x, point.y, (previousValue + value) / 2);
|
||||
}
|
||||
previous = point;
|
||||
previousValue = value;
|
||||
}
|
||||
};
|
||||
|
||||
for (const ringRadius of PLANE_RINGS) {
|
||||
trace(96, (step) => ({ point: projectRose(cx, cy, radius, ringRadius, (step * 360) / 96), ringRadius }));
|
||||
}
|
||||
// Spokes run from just outside the disc to the outermost ring, so the grid
|
||||
// closes on itself instead of trailing off into loose ends.
|
||||
const outer = PLANE_RINGS[PLANE_RINGS.length - 1]!;
|
||||
for (let angle = PLANE_SPOKE_STEP / 2; angle < 360; angle += PLANE_SPOKE_STEP) {
|
||||
trace(24, (step) => {
|
||||
const ringRadius = 1.05 + (step * (outer - 1.05)) / 24;
|
||||
return { point: projectRose(cx, cy, radius, ringRadius, angle), ringRadius };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Screen depth of the disc's side wall at the given ring radius. */
|
||||
function discDepth(radius: number): number {
|
||||
return Math.max(3, Math.round(radius * DISC_DEPTH));
|
||||
}
|
||||
|
||||
/** The ring bounding the rose: the tilted disc's rim, drawn as a polygon. */
|
||||
function drawTiltedRing(image: GrayImage, cx: number, cy: number, radius: number, value: number): void {
|
||||
const segments = 72;
|
||||
let previous = projectRose(cx, cy, radius, 1, 0);
|
||||
for (let i = 1; i <= segments; i++) {
|
||||
const point = projectRose(cx, cy, radius, 1, (i * 360) / segments);
|
||||
image.drawLine(previous.x, previous.y, point.x, point.y, value);
|
||||
previous = point;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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: tickTop + TICK_HEIGHT - 1 },
|
||||
{ x: cx - TICK_HALF_WIDTH, y: tickTop },
|
||||
{ x: cx + TICK_HALF_WIDTH, y: tickTop },
|
||||
value,
|
||||
);
|
||||
}
|
||||
|
||||
function fillTriangle(image: GrayImage, a: Point, b: Point, c: Point, value: number): void {
|
||||
const left = Math.max(0, Math.floor(Math.min(a.x, b.x, c.x)));
|
||||
const right = Math.min(image.width - 1, Math.ceil(Math.max(a.x, b.x, c.x)));
|
||||
const top = Math.max(0, Math.floor(Math.min(a.y, b.y, c.y)));
|
||||
const bottom = Math.min(image.height - 1, Math.ceil(Math.max(a.y, b.y, c.y)));
|
||||
const shade = Math.round(value);
|
||||
for (let y = top; y <= bottom; y++) {
|
||||
for (let x = left; x <= right; x++) {
|
||||
const point = { x: x + 0.5, y: y + 0.5 };
|
||||
const ab = edge(a, b, point);
|
||||
const bc = edge(b, c, point);
|
||||
const ca = edge(c, a, point);
|
||||
// Accept either winding, so callers don't have to order their vertices.
|
||||
if ((ab >= 0 && bc >= 0 && ca >= 0) || (ab <= 0 && bc <= 0 && ca <= 0)) {
|
||||
image.setPixel(x, y, shade);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Twice the signed area of the triangle a-b-p; its sign is p's side of a-b. */
|
||||
function edge(a: Point, b: Point, p: Point): number {
|
||||
return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { onAnySettingChanged } from "../../ui/dashboard-settings";
|
||||
import { glanceSlotSettings, type GlanceSlotChoice } from "./glanceboard-settings";
|
||||
import { QUADRANT_LAYOUT, type GlanceLayout } from "./layout";
|
||||
import { type GlanceWidget } from "./widget";
|
||||
import { findGlanceWidget } from "./widgets";
|
||||
|
||||
/** Brightness of the hairlines between slots. */
|
||||
const DIVIDER_VALUE = 40;
|
||||
|
||||
type Slot = { choice: GlanceSlotChoice; widget: GlanceWidget | null };
|
||||
|
||||
/**
|
||||
* A board: the layout's slots filled with the widgets the settings choose,
|
||||
* painted as one image. Widgets are created and started when the board
|
||||
* starts and stopped when it stops; a slot setting changed meanwhile swaps
|
||||
* just that slot's widget.
|
||||
*/
|
||||
export class GlanceBoard {
|
||||
private slots: Slot[] = [];
|
||||
private started = false;
|
||||
private unsubscribeSettings: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly requestRender: () => void,
|
||||
readonly layout: GlanceLayout = QUADRANT_LAYOUT,
|
||||
) {}
|
||||
|
||||
get width(): number {
|
||||
return this.layout.width;
|
||||
}
|
||||
|
||||
get height(): number {
|
||||
return this.layout.height;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.started) return;
|
||||
this.started = true;
|
||||
this.slots = glanceSlotSettings(this.layout).map((setting) => this.createSlot(setting.get()));
|
||||
this.unsubscribeSettings = onAnySettingChanged(() => this.applySlotSettings());
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (!this.started) return;
|
||||
this.started = false;
|
||||
this.unsubscribeSettings?.();
|
||||
this.unsubscribeSettings = null;
|
||||
for (const slot of this.slots) slot.widget?.stop();
|
||||
this.slots = [];
|
||||
}
|
||||
|
||||
private createSlot(choice: GlanceSlotChoice): Slot {
|
||||
const widget = choice === "none" ? null : (findGlanceWidget(choice)?.create() ?? null);
|
||||
widget?.start(this.requestRender);
|
||||
return { choice, widget };
|
||||
}
|
||||
|
||||
private applySlotSettings(): void {
|
||||
if (!this.started) return;
|
||||
let changed = false;
|
||||
glanceSlotSettings(this.layout).forEach((setting, index) => {
|
||||
const choice = setting.get();
|
||||
const slot = this.slots[index];
|
||||
if (!slot || slot.choice === choice) return;
|
||||
slot.widget?.stop();
|
||||
this.slots[index] = this.createSlot(choice);
|
||||
changed = true;
|
||||
});
|
||||
if (changed) this.requestRender();
|
||||
}
|
||||
|
||||
/** Paint the whole board (layout-sized). Widgets each get a fresh slot canvas. */
|
||||
paint(): GrayImage {
|
||||
const image = new GrayImage(this.layout.width, this.layout.height, 0);
|
||||
this.layout.slots.forEach((slot, index) => {
|
||||
const widget = this.slots[index]?.widget;
|
||||
if (!widget) return;
|
||||
const canvas = new GrayImage(slot.rect.width, slot.rect.height, 0);
|
||||
try {
|
||||
widget.paint(canvas);
|
||||
} catch (error) {
|
||||
console.warn(`glanceboard widget ${this.slots[index]?.choice} paint failed`, error);
|
||||
}
|
||||
canvas.composeInto(image, slot.rect.x, slot.rect.y);
|
||||
});
|
||||
drawDividers(image, this.layout);
|
||||
return image;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hairlines along every slot edge that is not the board's own edge. */
|
||||
function drawDividers(image: GrayImage, layout: GlanceLayout): void {
|
||||
for (const { rect } of layout.slots) {
|
||||
if (rect.x > 0) image.drawLine(rect.x, rect.y, rect.x, rect.y + rect.height - 1, DIVIDER_VALUE);
|
||||
if (rect.y > 0) image.drawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y, DIVIDER_VALUE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { enumSettingMenuItem, toggleSettingMenuItem } from "../../ui/dashboard-settings";
|
||||
import { type InputEvent } from "../../ui/gestures";
|
||||
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
|
||||
import { MenuLayer, type MenuItem } from "../../ui/menu";
|
||||
import { createInProcessWindow, YieldAtRootLayer, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
|
||||
import { GlanceBoard } from "./board";
|
||||
import { glanceboardEnabledSetting, glanceSlotSettings } from "./glanceboard-settings";
|
||||
import { QUADRANT_LAYOUT } from "./layout";
|
||||
|
||||
export const GLANCEBOARD_WINDOW_ID = "glanceboard";
|
||||
export const GLANCEBOARD_SURFACE_ID = "window:glanceboard";
|
||||
|
||||
/**
|
||||
* The Glanceboard app window: where the board is configured. A list of the
|
||||
* layout's slots (each a widget picker), the sleep-gesture toggle, and a
|
||||
* live preview of the board as it will look when glanced at.
|
||||
*/
|
||||
class GlanceboardConfigLayer implements Layer {
|
||||
private menu: MenuLayer | null = null;
|
||||
|
||||
private currentMenu(ctx: LayerContext): MenuLayer {
|
||||
if (!this.menu) {
|
||||
const { width } = ctx.stack.getBaseSize();
|
||||
const items: MenuItem[] = [
|
||||
{
|
||||
label: "Preview",
|
||||
description: "Show the board as it appears when the display is asleep and tapped.",
|
||||
onSelect: (menuCtx) => menuCtx.stack.push(new GlancePreviewLayer(() => menuCtx.actions.requestRender())),
|
||||
},
|
||||
...glanceSlotSettings(QUADRANT_LAYOUT).map((setting) => enumSettingMenuItem(setting)),
|
||||
toggleSettingMenuItem(glanceboardEnabledSetting),
|
||||
];
|
||||
this.menu = new MenuLayer("Glanceboard", items, {
|
||||
x: 8, y: 8, width: width - 16,
|
||||
opaque: true, showBorder: false,
|
||||
footer: "Asleep: tap shows, hold keeps, double-tap wakes",
|
||||
});
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/** The live board in the window; any click or double-click returns to the list. */
|
||||
class GlancePreviewLayer implements Layer {
|
||||
private readonly board: GlanceBoard;
|
||||
|
||||
constructor(requestRender: () => void) {
|
||||
this.board = new GlanceBoard(requestRender);
|
||||
this.board.start();
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const board = this.board.paint();
|
||||
if (board.width === width && board.height === height) return board;
|
||||
// A viewport of another size (a per-app display override) shows the board
|
||||
// top-left, cropped or padded, rather than scaled.
|
||||
const image = new GrayImage(width, height, 0);
|
||||
board.composeInto(image, 0, 0);
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: InputEvent, ctx: LayerContext): void {
|
||||
if (event.type === "click" || event.type === "double-click") ctx.stack.pop();
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.board.stop();
|
||||
}
|
||||
}
|
||||
|
||||
export function createGlanceboardAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
return createInProcessWindow({
|
||||
appId: "glanceboard",
|
||||
windowId: GLANCEBOARD_WINDOW_ID,
|
||||
title: "Glanceboard",
|
||||
iconLetter: "Gb",
|
||||
icon: "eye",
|
||||
closeable: true,
|
||||
// 576x288: the board's own size, so the preview is pixel-exact.
|
||||
heightMode: "medium",
|
||||
actions: options.actions,
|
||||
baseLayer: new YieldAtRootLayer(new GlanceboardConfigLayer()),
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
reconfigureSurface: options.reconfigureSurface,
|
||||
onClosed: options.onClosed,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
|
||||
import { QUADRANT_LAYOUT, type GlanceLayout } from "./layout";
|
||||
import { type GlanceWidgetId } from "./widget";
|
||||
|
||||
export type GlanceSlotChoice = GlanceWidgetId | "none";
|
||||
|
||||
const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "nightscout", "compass", "music"];
|
||||
|
||||
const SLOT_CHOICE_LABELS: Record<GlanceSlotChoice, string> = {
|
||||
none: "Empty",
|
||||
"system-card": "System card",
|
||||
nightscout: "Nightscout",
|
||||
compass: "Compass",
|
||||
music: "Music",
|
||||
};
|
||||
|
||||
export function glanceSlotChoiceLabel(choice: GlanceSlotChoice): string {
|
||||
return SLOT_CHOICE_LABELS[choice] ?? choice;
|
||||
}
|
||||
|
||||
const DEFAULT_QUADRANT_CHOICES: readonly GlanceSlotChoice[] = ["system-card", "music", "compass", "nightscout"];
|
||||
|
||||
/**
|
||||
* Whether sleep-time gestures show the board at all. Off restores the plain
|
||||
* behaviour: a tap or hold while asleep does nothing, double-tap wakes.
|
||||
*/
|
||||
export const glanceboardEnabledSetting = new ConfigSettingBoolean({
|
||||
id: "glanceboard-enabled",
|
||||
label: "Show on tap while asleep",
|
||||
storageKey: "glanceboard.enabled",
|
||||
defaultValue: true,
|
||||
description:
|
||||
"While the display is asleep, a single tap shows the Glanceboard for a few seconds and a long-press holds it up until released. Double-tap still wakes the regular UI.",
|
||||
});
|
||||
|
||||
/**
|
||||
* One picker per layout slot, keyed by layout id and slot index so a future
|
||||
* layout gets its own stored choices rather than inheriting the quadrants'.
|
||||
*/
|
||||
export function glanceSlotSettings(layout: GlanceLayout = QUADRANT_LAYOUT): ConfigSettingEnum<GlanceSlotChoice>[] {
|
||||
return layout.slots.map(
|
||||
(slot, index) =>
|
||||
new ConfigSettingEnum<GlanceSlotChoice>({
|
||||
id: `glanceboard-${layout.id}-slot-${index}`,
|
||||
label: slot.label,
|
||||
storageKey: `glanceboard.${layout.id}.slot.${index}`,
|
||||
defaultValue: (layout === QUADRANT_LAYOUT ? DEFAULT_QUADRANT_CHOICES[index] : undefined) ?? "none",
|
||||
values: SLOT_CHOICES,
|
||||
formatValue: glanceSlotChoiceLabel,
|
||||
description: `Which widget fills the ${slot.label.toLowerCase()} slot of the Glanceboard.`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { type AppDefinition } from "../app-definition";
|
||||
import { GlanceBoard } from "./board";
|
||||
import { createGlanceboardAppWindow, GLANCEBOARD_SURFACE_ID, GLANCEBOARD_WINDOW_ID } from "./glanceboard-app";
|
||||
import { glanceboardEnabledSetting } from "./glanceboard-settings";
|
||||
import { QUADRANT_LAYOUT } from "./layout";
|
||||
|
||||
const glanceboardApp: AppDefinition = {
|
||||
appId: "glanceboard",
|
||||
title: "Glanceboard",
|
||||
icon: "eye",
|
||||
launch: (ctx) => ctx.launchInProcessApp(GLANCEBOARD_WINDOW_ID, GLANCEBOARD_SURFACE_ID, createGlanceboardAppWindow),
|
||||
glanceboard: {
|
||||
size: { width: QUADRANT_LAYOUT.width, height: QUADRANT_LAYOUT.height },
|
||||
isEnabled: () => glanceboardEnabledSetting.get(),
|
||||
createBoard: (requestRender) => new GlanceBoard(requestRender, QUADRANT_LAYOUT),
|
||||
},
|
||||
};
|
||||
|
||||
export default glanceboardApp;
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Board geometry. A layout names its slots and places them on the board;
|
||||
* the Glanceboard app's slot pickers and the board renderer are both driven
|
||||
* by it, so a replacement layout (different slot count, sizes, positions) is
|
||||
* a matter of swapping this object out and reusing the same widgets.
|
||||
*/
|
||||
export const GLANCEBOARD_WIDTH = 576;
|
||||
export const GLANCEBOARD_HEIGHT = 288;
|
||||
|
||||
export type GlanceSlotRect = { x: number; y: number; width: number; height: number };
|
||||
|
||||
export type GlanceLayout = {
|
||||
id: string;
|
||||
width: number;
|
||||
height: number;
|
||||
slots: readonly { label: string; rect: GlanceSlotRect }[];
|
||||
};
|
||||
|
||||
/** The first layout: four equal quadrants, each 288x144. */
|
||||
export const QUADRANT_LAYOUT: GlanceLayout = {
|
||||
id: "quadrants",
|
||||
width: GLANCEBOARD_WIDTH,
|
||||
height: GLANCEBOARD_HEIGHT,
|
||||
slots: [
|
||||
{ label: "Top left", rect: { x: 0, y: 0, width: 288, height: 144 } },
|
||||
{ label: "Top right", rect: { x: 288, y: 0, width: 288, height: 144 } },
|
||||
{ label: "Bottom left", rect: { x: 0, y: 144, width: 288, height: 144 } },
|
||||
{ label: "Bottom right", rect: { x: 288, y: 144, width: 288, height: 144 } },
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { type GrayImage } from "../../graphics/image";
|
||||
|
||||
/**
|
||||
* A Glanceboard widget: a small self-contained view that paints into a slot
|
||||
* of the board. Widgets are sized by the layout (the first layout is four
|
||||
* 288x144 quadrants) and own their data subscriptions and any hardware they
|
||||
* need between start and stop, so a board that is not showing costs nothing.
|
||||
*
|
||||
* Layouts are expected to be swapped out and iterated on; widgets are the
|
||||
* stable part, so keep them independent of any particular board geometry
|
||||
* beyond the slot size they are handed.
|
||||
*/
|
||||
export interface GlanceWidget {
|
||||
/**
|
||||
* The board became visible (or this widget was added to a visible board):
|
||||
* subscribe to data, start timers, enable hardware. `requestRender` asks
|
||||
* the board to repaint when something changed.
|
||||
*/
|
||||
start(requestRender: () => void): void;
|
||||
/** Undo start. Called once for every start; must be safe to call twice. */
|
||||
stop(): void;
|
||||
/**
|
||||
* Paint the widget into `image`, a fresh 0-filled canvas of the slot's
|
||||
* size. Deferred draws (text, drawImage) are welcome and keep the cheap
|
||||
* texture-cache wire path.
|
||||
*/
|
||||
paint(image: GrayImage): void;
|
||||
}
|
||||
|
||||
export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music";
|
||||
|
||||
export type GlanceWidgetDefinition = {
|
||||
id: GlanceWidgetId;
|
||||
/** Picker label in the Glanceboard app. */
|
||||
label: string;
|
||||
create: () => GlanceWidget;
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -24,11 +24,11 @@ import { openSettingsSubMenu } from "../../ui/dashboard/settings-panel";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
|
||||
const nightscoutLargeFont = getDefaultLargeFont();
|
||||
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
|
||||
export const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
|
||||
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
||||
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
|
||||
|
||||
function drawDirectionIndicator(
|
||||
export function drawDirectionIndicator(
|
||||
image: GrayImage,
|
||||
font: UiFont,
|
||||
x: number,
|
||||
@@ -85,7 +85,7 @@ function truncateLine(text: string, maxChars: number): string {
|
||||
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
|
||||
}
|
||||
|
||||
function formatDelta(delta: number | null): string {
|
||||
export function formatDelta(delta: number | null): string {
|
||||
if (delta === null) return "--";
|
||||
return `${delta >= 0 ? "+" : ""}${Math.round(delta)}`;
|
||||
}
|
||||
@@ -98,7 +98,7 @@ function formatBolusLabel(value: number): string {
|
||||
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
|
||||
}
|
||||
|
||||
function drawNightscoutGraph(
|
||||
export function drawNightscoutGraph(
|
||||
image: GrayImage,
|
||||
bounds: { x: number; y: number; width: number; height: number },
|
||||
nightscout: NightscoutState,
|
||||
@@ -431,10 +431,10 @@ export function nightscoutMenuItems(): MenuItem[] {
|
||||
];
|
||||
}
|
||||
|
||||
function isNightscoutPointStale(point: NightscoutState["latest"], nowMs: number): boolean {
|
||||
export function isNightscoutPointStale(point: NightscoutState["latest"], nowMs: number): boolean {
|
||||
return point !== null && nowMs - point.timestampMs > NIGHTSCOUT_STALE_MS;
|
||||
}
|
||||
|
||||
function drawNightscoutValueStrikeThrough(image: GrayImage, x: number, y: number, width: number): void {
|
||||
export function drawNightscoutValueStrikeThrough(image: GrayImage, x: number, y: number, width: number): void {
|
||||
image.drawLine(x, y, x + width, y, 180);
|
||||
}
|
||||
Reference in new issue
Block a user