Initial publishable release

This commit is contained in:
James Babcock committed 2026-04-26 23:07:54 -07:00
commit 6e442e7faa
120 files changed
+750769

No files matched your search

+664
View File
@@ -0,0 +1,664 @@
import takeRight from "lodash/takeRight";
import { BdfFont, loadEmbeddedTerminus24 } from "../graphics/bdffont";
import { GrayImage, imageFromAsciiArt } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { mediaControllerBridge, type MediaControllerState } from "../native/media-controller";
import { nightscoutBridge, type NightscoutState } from "../native/nightscout";
import { type DashboardPluginId } from "./dashboard-settings";
import { Layer, type DashboardInputEvent, type LayerContext } from "./layers";
export type DashboardPluginState = {
logLines: string[];
media: MediaControllerState;
nightscout: NightscoutState;
nightscoutConfigured: boolean;
};
export type DashboardPluginCardBounds = {
x: number;
y: number;
width: number;
height: number;
};
export type DashboardPluginCardRenderArgs = {
image: GrayImage;
bounds: DashboardPluginCardBounds;
selected: boolean;
font: BdfFont;
state: DashboardPluginState;
};
export interface DashboardPlugin {
readonly id: DashboardPluginId;
readonly label: string;
renderCard(args: DashboardPluginCardRenderArgs): void;
createFullscreenLayer?(getState: () => DashboardPluginState): Layer | null;
}
const DASHBOARD_PLUGINS: DashboardPlugin[] = [
{
id: "blank",
label: "Blank",
renderCard: () => {},
createFullscreenLayer: () => null,
},
{
id: "input-debug-log",
label: "Input debug log",
renderCard: ({ image, bounds, font, state }) => {
image.drawText(font, bounds.x + 10, bounds.y + 14, "Input log", 180);
const lineHeight = 14;
const visibleLineCount = Math.max(1, Math.floor((bounds.height - 28) / lineHeight));
const visibleLines = takeRight(state.logLines, visibleLineCount);
for (let i = 0; i < visibleLines.length; i++) {
image.drawText(font, bounds.x + 8, bounds.y + 26 + i * lineHeight, visibleLines[i]!, 190);
}
},
createFullscreenLayer: (getState) => new DebugLogLayer(getState),
},
{
id: "music-controller",
label: "Music controller",
renderCard: ({ image, bounds, font, state }) => {
const media = state.media;
image.drawText(font, bounds.x + 10, bounds.y + 14, "Now playing", 180);
if (!media.accessEnabled) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "Enable notification", 150);
image.drawText(font, bounds.x + 10, bounds.y + 44, "access for media", 150);
return;
}
if (!media.available) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "No active session", 150);
return;
}
const titleLines = wrapText(font, media.title || "Unknown title", bounds.width - 20).slice(0, 2);
const artistLine = media.artist || media.album || media.packageName || "Unknown source";
image.drawText(font, bounds.x + 10, bounds.y + 30, titleLines[0] ?? "", 210);
if (titleLines[1]) {
image.drawText(font, bounds.x + 10, bounds.y + 44, titleLines[1], 210);
}
image.drawText(font, bounds.x + 10, bounds.y + 62, artistLine, 160);
image.drawText(font, bounds.x + 10, bounds.y + bounds.height - 18, playbackLabel(media), 130);
},
createFullscreenLayer: (getState) => new MusicControllerLayer(getState),
},
{
id: "nightscout",
label: "Nightscout",
renderCard: ({ image, bounds, font, state }) => {
const nightscout = state.nightscout;
const nowMs = Date.now();
image.drawText(font, bounds.x + 10, bounds.y + 10, "Nightscout", 180);
if (!state.nightscoutConfigured || nightscout.configurationMissing) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "Needs setup", 170);
image.drawText(font, bounds.x + 10, bounds.y + 44, "Click to configure", 140);
return;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "No glucose data", 150);
image.drawText(font, bounds.x + 10, bounds.y + 44, truncateLine(nightscout.status, 26), 120);
return;
}
const latest = nightscout.latest;
const deltaLabel = formatDelta(nightscout.delta);
const glucoseText = `${latest.sgv}`;
const glucoseX = bounds.x + bounds.width - 92;
image.drawText(nightscoutLargeFont, glucoseX, bounds.y + 10, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, bounds.y + 22, nightscoutLargeFont.measureText(glucoseText));
}
drawNightscoutDelta(image, font, bounds.x + bounds.width - 92, bounds.y + 30, deltaLabel, nightscout.direction, 160);
image.drawText(
font,
bounds.x + 10,
bounds.y + 30,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(1)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)}`,
160,
);
image.drawText(
font,
bounds.x + 10,
bounds.y + 44,
`Loop ${nightscout.openapsStatusShort} CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)}`,
138,
);
drawNightscoutGraph(
image,
{
x: bounds.x + 10,
y: bounds.y + 60,
width: bounds.width - 20,
height: Math.max(16, bounds.height - 82),
},
nightscout,
nowMs,
font,
);
},
createFullscreenLayer: (getState) => new NightscoutLayer(getState),
},
];
const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
DASHBOARD_PLUGINS.map((plugin) => [plugin.id, plugin]),
);
const nightscoutLargeFont = loadEmbeddedTerminus24();
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
export function listDashboardPlugins(): DashboardPlugin[] {
return [...DASHBOARD_PLUGINS];
}
export function getDashboardPlugin(pluginId: DashboardPluginId): DashboardPlugin {
return PLUGIN_MAP.get(pluginId) ?? PLUGIN_MAP.get("blank")!;
}
export function isBlankDashboardPlugin(pluginId: DashboardPluginId): boolean {
return pluginId === "blank";
}
function playbackLabel(media: MediaControllerState): string {
switch (media.playbackState) {
case "playing":
return "Playing";
case "paused":
return "Paused";
case "buffering":
return "Buffering";
case "stopped":
return "Stopped";
case "notification-access-required":
return "Access required";
default:
return media.status || "Idle";
}
}
function formatDelta(delta: number | null): string {
if (delta === null) return "--";
return `${delta >= 0 ? "+" : ""}${Math.round(delta)}`;
}
function drawNightscoutDelta(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
deltaLabel: string,
direction: string,
shade: number,
): void {
const text = direction ? `${deltaLabel} ` : deltaLabel;
image.drawText(font, x, y, text, shade);
drawDirectionIndicator(image, font, x + font.measureText(text), y, direction, shade);
}
function drawDirectionIndicator(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
direction: string,
shade: number,
): void {
const label = directionGlyphLabel(font, direction);
if (label) {
image.drawText(font, x, y, label, shade);
return;
}
const art = directionAsciiArt(direction);
if (art) {
image.bitBlt(imageFromAsciiArt(art, shade), x, y + 1);
return;
}
if (direction) {
image.drawText(font, x, y, truncateLine(direction, 10), shade);
}
}
function directionGlyphLabel(font: BdfFont, direction: string): string {
switch (direction) {
case "DoubleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑↑" : "";
case "SingleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑" : "";
case "FortyFiveUp":
return font.hasGlyph("↗".codePointAt(0)!) ? "↗" : "";
case "Flat":
return font.hasGlyph("→".codePointAt(0)!) ? "→" : "";
case "FortyFiveDown":
return font.hasGlyph("↘".codePointAt(0)!) ? "↘" : "";
case "SingleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓" : "";
case "DoubleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓↓" : "";
default:
return "";
}
}
function directionAsciiArt(direction: string): readonly string[] | undefined {
switch (direction) {
case "FortyFiveUp":
return [" ##", " ###", " # ##", "# ##", " ##"];
case "FortyFiveDown":
return [" ##", "# ##", " # ##", " ###", " ##"];
default:
return undefined;
}
}
function truncateLine(text: string, maxChars: number): string {
if (text.length <= maxChars) return text;
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
function formatWholeNumber(value: number): string {
return `${Math.round(value)}`;
}
function formatBolusLabel(value: number): string {
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
}
function formatAgeShortFromTimestamp(timestampMs: number | null, nowMs: number): string {
if (!timestampMs) {
return "--";
}
const elapsedMinutes = Math.max(0, Math.round((nowMs - timestampMs) / 60_000));
if (elapsedMinutes < 60) {
return `${elapsedMinutes}m`;
}
const elapsedHours = Math.round(elapsedMinutes / 60);
if (elapsedHours < 48) {
return `${elapsedHours}h`;
}
return `${Math.round(elapsedHours / 24)}d`;
}
function drawNightscoutGraph(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
nightscout: NightscoutState,
nowMs: number,
font: BdfFont,
): void {
if (bounds.width <= 2 || bounds.height <= 2) {
return;
}
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleHistory = nightscout.history.filter((point) => point.timestampMs >= windowStartMs && point.timestampMs <= nowMs);
if (visibleHistory.length === 0) {
return;
}
const values = visibleHistory.map((point) => point.sgv);
const min = Math.min(...values, 60);
const max = Math.max(...values, 200);
const range = Math.max(20, max - min);
const paddedMin = min - range * 0.1;
const paddedMax = max + range * 0.1;
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
drawNightscoutBasalOverlay(image, bounds, nightscout.basal, nowMs);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 60, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
const plotted = visibleHistory.map((point) => ({
point,
x:
bounds.x +
Math.round(
((point.timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
),
y:
bounds.y +
bounds.height -
1 -
Math.round(((point.sgv - paddedMin) / Math.max(1, paddedMax - paddedMin)) * Math.max(1, bounds.height - 1)),
}));
for (let i = 0; i < plotted.length; i++) {
const current = plotted[i]!;
const previous = i > 0 ? plotted[i - 1]! : null;
const next = i + 1 < plotted.length ? plotted[i + 1]! : null;
const connectedToPrevious =
previous !== null && current.point.timestampMs - previous.point.timestampMs <= NIGHTSCOUT_STALE_MS;
const connectedToNext =
next !== null && next.point.timestampMs - current.point.timestampMs <= NIGHTSCOUT_STALE_MS;
if (connectedToPrevious && previous) {
image.drawLine(previous.x, previous.y, current.x, current.y, 220);
}
if (!connectedToPrevious && !connectedToNext) {
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
}
}
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, nowMs);
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, nowMs);
}
function drawNightscoutBasalOverlay(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
basalEvents: NightscoutState["basal"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleEvents = basalEvents.filter(
(event) => event.timestampMs + event.durationMinutes * 60_000 >= windowStartMs && event.timestampMs <= nowMs,
);
if (visibleEvents.length === 0) {
return;
}
const maxRate = Math.max(...visibleEvents.map((event) => event.rate), 0);
if (maxRate <= 0) {
return;
}
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
const bottomY = bounds.y + bounds.height - 2;
for (const event of visibleEvents) {
const startMs = Math.max(windowStartMs, event.timestampMs);
const endMs = Math.min(nowMs, event.timestampMs + event.durationMinutes * 60_000);
if (endMs <= startMs) {
continue;
}
const leftX = timeToGraphX(bounds, windowStartMs, startMs);
const rightX = timeToGraphX(bounds, windowStartMs, endMs);
const height = Math.max(1, Math.round((event.rate / maxRate) * overlayHeight));
image.fillRect(leftX, bottomY - height + 1, Math.max(1, rightX - leftX + 1), height, 18);
}
}
function drawNightscoutCarbMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
carbEvents: NightscoutState["carbs"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const baselineY = bounds.y + bounds.height - 2;
for (const event of carbEvents) {
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
image.drawLine(x, baselineY, x, baselineY - 6, 150);
drawTextCentered(image, font, x, Math.max(bounds.y + 2, baselineY - 18), `${Math.round(event.carbs)}`, 150, bounds);
}
}
function drawNightscoutBolusMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
bolusEvents: NightscoutState["boluses"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const topY = bounds.y + 1;
for (const event of bolusEvents) {
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
image.drawLine(x, topY, x, topY + 6, 144);
if (event.insulin >= 1) {
drawTextCentered(
image,
font,
x,
Math.min(bounds.y + bounds.height - font.lineHeight - 1, topY + 8),
formatBolusLabel(event.insulin),
144,
bounds,
);
}
}
}
function drawTextCentered(
image: GrayImage,
font: BdfFont,
centerX: number,
y: number,
text: string,
shade: number,
bounds: { x: number; y: number; width: number; height: number },
): void {
const textWidth = font.measureText(text);
const x = Math.max(bounds.x + 1, Math.min(bounds.x + bounds.width - textWidth - 1, centerX - Math.round(textWidth / 2)));
image.drawText(font, x, y, text, shade);
}
function timeToGraphX(
bounds: { x: number; y: number; width: number; height: number },
windowStartMs: number,
timestampMs: number,
): number {
return (
bounds.x +
Math.round(((timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1))
);
}
function drawNightscoutReferenceLine(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
minValue: number,
maxValue: number,
value: number,
shade: number,
): void {
const y =
bounds.y +
bounds.height -
1 -
Math.round(((value - minValue) / Math.max(1, maxValue - minValue)) * Math.max(1, bounds.height - 1));
image.drawLine(bounds.x + 1, y, bounds.x + bounds.width - 2, y, shade);
}
class DebugLogLayer implements Layer {
private scrollOffset = 0;
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Input debug log", 220);
const logs = this.getState().logLines;
const lineHeight = 14;
const visibleCount = Math.max(1, Math.floor((288 - 64) / lineHeight));
const maxOffset = Math.max(0, logs.length - visibleCount);
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxOffset));
const start = Math.max(0, maxOffset - this.scrollOffset);
const visible = logs.slice(start, start + visibleCount);
for (let index = 0; index < visible.length; index++) {
image.drawText(ctx.font, 22, 42 + index * lineHeight, visible[index]!, 180);
}
image.drawText(ctx.font, 22, 252, "Scroll: browse Double-click: back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
this.scrollOffset += 1;
return;
case "scroll-down":
this.scrollOffset = Math.max(0, this.scrollOffset - 1);
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
class MusicControllerLayer implements Layer {
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
const media = this.getState().media;
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Music controller", 220);
if (!media.accessEnabled) {
const lines = wrapText(
ctx.font,
"Notification access is required before Android will expose active media sessions to Faceclaw. Click to open settings.",
520,
);
for (let i = 0; i < lines.length; i++) {
image.drawText(ctx.font, 22, 44 + i * 14, lines[i]!, 180);
}
image.drawText(ctx.font, 22, 252, "Click: open settings Double-click: back", 110);
return image;
}
if (!media.available) {
image.drawText(ctx.font, 22, 44, "No active media session.", 180);
image.drawText(ctx.font, 22, 58, "Start playback in another app,", 180);
image.drawText(ctx.font, 22, 72, "then reopen this card.", 180);
image.drawText(ctx.font, 22, 252, "Double-click: back", 110);
return image;
}
image.drawText(ctx.font, 22, 44, media.title || "Unknown title", 220);
image.drawText(ctx.font, 22, 60, media.artist || media.album || "Unknown artist", 180);
image.drawText(ctx.font, 22, 76, media.packageName, 130);
image.drawText(ctx.font, 22, 104, `State: ${playbackLabel(media)}`, 180);
image.drawText(ctx.font, 22, 132, "Click: play/pause", 180);
image.drawText(ctx.font, 22, 146, "Scroll up: previous", 180);
image.drawText(ctx.font, 22, 160, "Scroll down: next", 180);
image.drawText(ctx.font, 22, 252, "Double-click: back", 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const media = this.getState().media;
switch (event.type) {
case "click":
if (!media.accessEnabled) {
mediaControllerBridge.openNotificationAccessSettings();
} else if (media.canPlayPause) {
await mediaControllerBridge.playPause();
}
return;
case "scroll-up":
if (media.canSkipPrevious) {
await mediaControllerBridge.skipPrevious();
}
return;
case "scroll-down":
if (media.canSkipNext) {
await mediaControllerBridge.skipNext();
}
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
class NightscoutLayer implements Layer {
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
const nightscout = this.getState().nightscout;
const nowMs = Date.now();
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Nightscout", 220);
if (!this.getState().nightscoutConfigured || nightscout.configurationMissing) {
image.drawText(ctx.font, 22, 44, "Nightscout needs configuration.", 180);
image.drawText(ctx.font, 22, 62, "Double-click and use Settings", 140);
image.drawText(ctx.font, 22, 78, "Integrations > Nightscout.", 140);
return image;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(ctx.font, 22, 44, "No Nightscout data available.", 180);
image.drawText(ctx.font, 22, 58, truncateLine(nightscout.status, 60), 140);
image.drawText(ctx.font, 22, 252, "Click: refresh Double-click: back", 110);
return image;
}
const latest = nightscout.latest;
const glucoseText = `${latest.sgv}`;
const glucoseX = 22;
const glucoseWidth = nightscoutLargeFont.measureText(glucoseText);
image.drawText(nightscoutLargeFont, glucoseX, 28, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, 40, glucoseWidth);
}
image.drawText(ctx.font, glucoseX + glucoseWidth + 8, 36, nightscout.units, 140);
const trendText = `Delta ${formatDelta(nightscout.delta)} Trend `;
image.drawText(ctx.font, 22, 62, trendText, 180);
drawDirectionIndicator(image, ctx.font, 22 + ctx.font.measureText(trendText), 62, nightscout.direction, 180);
image.drawText(
ctx.font,
22,
78,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
160,
);
image.drawText(
ctx.font,
22,
94,
`CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
160,
);
image.drawText(ctx.font, 22, 110, `Pump ${truncateLine(nightscout.pumpStatus || "--", 56)}`, 150);
drawNightscoutGraph(image, { x: 22, y: 128, width: 532, height: 96 }, nightscout, nowMs, ctx.font);
image.drawText(ctx.font, 22, 234, "2-hour glucose history with basal / carbs / boluses", 130);
image.drawText(ctx.font, 22, 252, "Click: refresh Double-click: back", 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "click":
await nightscoutBridge.refreshNow();
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
function formatTimestamp(timestampMs: number): string {
const date = new Date(timestampMs);
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}
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 {
image.drawLine(x, y, x + width, y, 180);
}
+154
View File
@@ -0,0 +1,154 @@
import { ApplicationSettings } from "@nativescript/core";
export type DashboardSlotId = "top-right" | "bottom-left" | "bottom-right";
export type DashboardPluginId = "blank" | "input-debug-log" | "music-controller" | "nightscout";
export type DashboardSlotConfig = Record<DashboardSlotId, DashboardPluginId>;
export type NightscoutSettings = {
siteUrl: string;
apiToken: string;
};
export type SystemCardSettings = {
showFaceclawLogo: boolean;
showBatteryIndicators: boolean;
showAndroidNotifications: boolean;
};
export type SystemCardSettingKey = keyof SystemCardSettings;
export const DEFAULT_SYSTEM_CARD_NAME = "Faceclaw";
const SYSTEM_CARD_NAME_KEY = "dashboard.systemCardName";
const SYSTEM_CARD_SETTING_KEYS: Record<SystemCardSettingKey, string> = {
showFaceclawLogo: "dashboard.systemCard.showFaceclawLogo",
showBatteryIndicators: "dashboard.systemCard.showBatteryIndicators",
showAndroidNotifications: "dashboard.systemCard.showAndroidNotifications",
};
const NIGHTSCOUT_SITE_URL_KEY = "integrations.nightscout.siteUrl";
const NIGHTSCOUT_API_TOKEN_KEY = "integrations.nightscout.apiToken";
const SLOT_KEYS: Record<DashboardSlotId, string> = {
"top-right": "dashboard.slot.topRight",
"bottom-left": "dashboard.slot.bottomLeft",
"bottom-right": "dashboard.slot.bottomRight",
};
const KNOWN_PLUGIN_IDS = new Set<DashboardPluginId>([
"blank",
"input-debug-log",
"music-controller",
"nightscout",
]);
const DEFAULT_SLOT_CONFIG: DashboardSlotConfig = {
"top-right": "input-debug-log",
"bottom-left": "blank",
"bottom-right": "blank",
};
const DEFAULT_SYSTEM_CARD_SETTINGS: SystemCardSettings = {
showFaceclawLogo: true,
showBatteryIndicators: true,
showAndroidNotifications: true,
};
export function getDashboardSlotIds(): DashboardSlotId[] {
return ["top-right", "bottom-left", "bottom-right"];
}
export function getDefaultDashboardSlotConfig(): DashboardSlotConfig {
return { ...DEFAULT_SLOT_CONFIG };
}
export function loadDashboardSlotConfig(): DashboardSlotConfig {
const config = getDefaultDashboardSlotConfig();
for (const slot of getDashboardSlotIds()) {
const stored = ApplicationSettings.getString(SLOT_KEYS[slot], config[slot]);
config[slot] = normalizePluginId(stored, config[slot]);
}
return config;
}
export function saveDashboardSlotPlugin(slot: DashboardSlotId, pluginId: DashboardPluginId): void {
ApplicationSettings.setString(SLOT_KEYS[slot], pluginId);
}
export function saveDashboardSlotConfig(config: DashboardSlotConfig): void {
for (const slot of getDashboardSlotIds()) {
saveDashboardSlotPlugin(slot, config[slot]);
}
}
export function loadSystemCardName(): string {
return normalizeSystemCardName(ApplicationSettings.getString(SYSTEM_CARD_NAME_KEY, DEFAULT_SYSTEM_CARD_NAME));
}
export function saveSystemCardName(name: string): string {
const normalized = normalizeSystemCardName(name);
ApplicationSettings.setString(SYSTEM_CARD_NAME_KEY, normalized);
return normalized;
}
export function loadSystemCardSettings(): SystemCardSettings {
return {
showFaceclawLogo: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showFaceclawLogo,
DEFAULT_SYSTEM_CARD_SETTINGS.showFaceclawLogo,
),
showBatteryIndicators: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showBatteryIndicators,
DEFAULT_SYSTEM_CARD_SETTINGS.showBatteryIndicators,
),
showAndroidNotifications: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showAndroidNotifications,
DEFAULT_SYSTEM_CARD_SETTINGS.showAndroidNotifications,
),
};
}
export function saveSystemCardSetting(key: SystemCardSettingKey, value: boolean): void {
ApplicationSettings.setBoolean(SYSTEM_CARD_SETTING_KEYS[key], value);
}
export function loadNightscoutSettings(): NightscoutSettings {
return {
siteUrl: normalizeNightscoutSiteUrl(ApplicationSettings.getString(NIGHTSCOUT_SITE_URL_KEY, "")),
apiToken: normalizeNightscoutApiToken(ApplicationSettings.getString(NIGHTSCOUT_API_TOKEN_KEY, "")),
};
}
export function saveNightscoutSiteUrl(siteUrl: string): string {
const normalized = normalizeNightscoutSiteUrl(siteUrl);
ApplicationSettings.setString(NIGHTSCOUT_SITE_URL_KEY, normalized);
return normalized;
}
export function saveNightscoutApiToken(apiToken: string): string {
const normalized = normalizeNightscoutApiToken(apiToken);
ApplicationSettings.setString(NIGHTSCOUT_API_TOKEN_KEY, normalized);
return normalized;
}
export function isNightscoutSettingsConfigured(settings = loadNightscoutSettings()): boolean {
return settings.siteUrl.length > 0 && settings.apiToken.length > 0;
}
export function normalizePluginId(
value: string | null | undefined,
fallback: DashboardPluginId = "blank",
): DashboardPluginId {
if (value && KNOWN_PLUGIN_IDS.has(value as DashboardPluginId)) {
return value as DashboardPluginId;
}
return fallback;
}
function normalizeSystemCardName(name: string | null | undefined): string {
const normalized = (name ?? "").replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
return normalized;
}
function normalizeNightscoutSiteUrl(siteUrl: string | null | undefined): string {
return (siteUrl ?? "").replace(/[\x00-\x1f]+/g, "").trim().replace(/\/+$/, "");
}
function normalizeNightscoutApiToken(apiToken: string | null | undefined): string {
return (apiToken ?? "").replace(/[\x00-\x1f]+/g, "").trim();
}
+823
View File
@@ -0,0 +1,823 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage, imageFromAsciiArt } from "../graphics/image";
import { loadEmbeddedTerminus12, loadEmbeddedTerminus16 } from "../graphics/bdffont";
import { loadPngAsGrayImage } from "../graphics/imagefile";
import { type RawInputEvent } from "../native/faceclaw-communicator";
import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout";
import { readActiveNotificationIcons } from "../native/notification-icons";
import { readPhoneBatteryState } from "../native/phone-battery";
import { OsEventTypeList, EventSourceType } from "g2-kit/lite";
import {
getDashboardPlugin,
isBlankDashboardPlugin,
listDashboardPlugins,
type DashboardPluginCardBounds,
type DashboardPluginState,
} from "./dashboard-plugins";
import {
DEFAULT_SYSTEM_CARD_NAME,
getDashboardSlotIds,
isNightscoutSettingsConfigured,
loadDashboardSlotConfig,
loadNightscoutSettings,
loadSystemCardSettings,
loadSystemCardName,
saveDashboardSlotPlugin,
saveNightscoutApiToken,
saveNightscoutSiteUrl,
saveSystemCardSetting,
saveSystemCardName,
type DashboardSlotId,
type NightscoutSettings,
type SystemCardSettingKey,
} from "./dashboard-settings";
import { Layer, LayerActions, LayerStack, type DashboardInputEvent, type LayerContext } from "./layers";
import { MenuLayer } from "./menu";
type DashboardCardId = "system" | DashboardSlotId;
export type DashboardBatteryLevels = {
headset: number | null;
headsetCharging: boolean | null;
ring: number | null;
};
let dashboardState = {
logLines: [] as string[],
screenOn: true,
selectedCard: "system" as DashboardCardId,
slotConfig: loadDashboardSlotConfig(),
systemCardName: loadSystemCardName(),
systemCardSettings: loadSystemCardSettings(),
nightscoutSettings: loadNightscoutSettings(),
battery: {
headset: null,
headsetCharging: null,
ring: null,
} as DashboardBatteryLevels,
};
let cachedDashboardLogo: GrayImage | null | undefined;
const dashboardActions: LayerActions = {
disconnect: () => {},
startSystemNameEdit: () => {},
endSystemNameEdit: () => {},
startNightscoutSiteUrlEdit: () => {},
startNightscoutApiTokenEdit: () => {},
endTextSettingEdit: () => {},
};
const dashboardFont = loadEmbeddedTerminus12();
const dashboardSystemFont = loadEmbeddedTerminus16();
const NOTIFICATION_ICON_SIZE = 24;
const SYSTEM_CARD_ITEM_HEIGHT = 38;
const SYSTEM_CARD_ITEM_GAP = 2;
const BATTERY_ITEM_Y_OFFSET = 4;
const EMPTY_BATTERY_ICON = imageFromAsciiArt(
[
" ################## ",
" #................# ",
" #................###",
" #................###",
" #................###",
" #................###",
" #................###",
" #................###",
" #................# ",
" ################## ",
],
120,
);
const BATTERY_BOLT_ICON = imageFromAsciiArt(
[
"....#..",
"...##..",
"..##...",
".######",
"...##..",
"..##...",
"..#....",
],
255,
);
const BATTERY_FILL_X = 3;
const BATTERY_FILL_Y = 2;
const BATTERY_FILL_WIDTH = 14;
const BATTERY_FILL_HEIGHT = 6;
function rawInputEventToInputEvent(event: RawInputEvent): DashboardInputEvent {
if (event.kind === "sys-event") {
if (event.eventType === OsEventTypeList.CLICK_EVENT) {
return {
type: "click",
source: eventSourceToString(event.eventSource),
};
} else if (event.eventType === OsEventTypeList.DOUBLE_CLICK_EVENT) {
return {
type: "double-click",
source: eventSourceToString(event.eventSource),
};
}
} else if (event.kind === "text-click") {
if (event.eventType === OsEventTypeList.SCROLL_BOTTOM_EVENT) {
return { type: "scroll-down" };
} else if (event.eventType === OsEventTypeList.SCROLL_TOP_EVENT) {
return { type: "scroll-up" };
}
}
return {
type: "unknown",
kind: event.kind,
eventSource: event.eventSource,
eventType: event.eventType,
};
}
function eventSourceToString(eventSource: number): "ring" | "left-arm" | "right-arm" {
if (eventSource === EventSourceType.TOUCH_EVENT_FROM_RING) {
return "ring";
} else if (eventSource === EventSourceType.TOUCH_EVENT_FROM_GLASSES_L) {
return "left-arm";
} else if (eventSource === EventSourceType.TOUCH_EVENT_FROM_GLASSES_R) {
return "right-arm";
}
return "ring";
}
export async function receiveInput(event: RawInputEvent): Promise<void> {
const inputEvent = rawInputEventToInputEvent(event);
dashboardState.logLines.push(eventToString(inputEvent));
await dashboardLayers.handleInput(inputEvent);
}
function eventToString(event: DashboardInputEvent): string {
switch (event.type) {
case "click":
return `Click from ${event.source}`;
case "double-click":
return `Double click from ${event.source}`;
case "scroll-up":
return `Scroll up`;
case "scroll-down":
return `Scroll down`;
default:
case "unknown":
return `Unknown event: ${event.kind} ${event.eventSource} ${event.eventType}`;
}
}
export function logToDashboard(message: string): void {
dashboardState.logLines.push(message);
}
export function setDashboardActions(actions: Partial<LayerActions>): void {
dashboardLayers.setActions(actions);
}
export function drawDashboard(): GrayImage {
return dashboardLayers.paint();
}
export function setDashboardSystemCardName(name: string): string {
const savedName = saveSystemCardName(name);
dashboardState.systemCardName = savedName;
return savedName;
}
export function getDashboardSystemCardName(): string {
return dashboardState.systemCardName;
}
export function setDashboardNightscoutSiteUrl(siteUrl: string): string {
const savedUrl = saveNightscoutSiteUrl(siteUrl);
dashboardState.nightscoutSettings = {
...dashboardState.nightscoutSettings,
siteUrl: savedUrl,
};
return savedUrl;
}
export function setDashboardNightscoutApiToken(apiToken: string): string {
const savedToken = saveNightscoutApiToken(apiToken);
dashboardState.nightscoutSettings = {
...dashboardState.nightscoutSettings,
apiToken: savedToken,
};
return savedToken;
}
export function getDashboardNightscoutSettings(): NightscoutSettings {
return { ...dashboardState.nightscoutSettings };
}
export function setDashboardSystemCardSetting(key: SystemCardSettingKey, value: boolean): void {
dashboardState.systemCardSettings = {
...dashboardState.systemCardSettings,
[key]: value,
};
saveSystemCardSetting(key, value);
}
export function setDashboardBatteryLevels(levels: Partial<DashboardBatteryLevels>): void {
dashboardState.battery = {
...dashboardState.battery,
...levels,
};
}
function getDisplayedSystemCardName(): string {
return dashboardState.systemCardName || DEFAULT_SYSTEM_CARD_NAME;
}
type SystemCardFlowItem =
| { type: "battery"; label: string; percentCharge: number; isCharging: boolean }
| { type: "notification"; icon: GrayImage };
function collectBatteryItems(): SystemCardFlowItem[] {
if (!dashboardState.systemCardSettings.showBatteryIndicators) return [];
const phone = readPhoneBatteryState();
const items: SystemCardFlowItem[] = [];
addBatteryItem(items, "Phone", phone.battery, phone.charging);
addBatteryItem(items, "G2", dashboardState.battery.headset, dashboardState.battery.headsetCharging);
addBatteryItem(items, "R1", dashboardState.battery.ring, null);
return items;
}
function addBatteryItem(
items: SystemCardFlowItem[],
label: string,
percentCharge: number | null,
isCharging: boolean | null,
): void {
if (percentCharge === null || !Number.isFinite(percentCharge)) return;
items.push({
type: "battery",
label,
percentCharge,
isCharging: Boolean(isCharging),
});
}
function drawBatteryFlowItem(image: GrayImage, x: number, y: number, item: Extract<SystemCardFlowItem, { type: "battery" }>): void {
const itemWidth = systemCardFlowItemWidth(item);
const labelX = x + Math.max(0, ((itemWidth - dashboardFont.measureText(item.label)) / 2) | 0);
image.drawText(dashboardFont, labelX, y + BATTERY_ITEM_Y_OFFSET, item.label, 150);
const battery = drawBattery(item.percentCharge, item.isCharging);
image.bitBlt(battery, x + ((itemWidth - battery.width) / 2) | 0, y + 16 + BATTERY_ITEM_Y_OFFSET);
}
function drawBattery(percentCharge: number, isCharging: boolean): GrayImage {
const icon = new GrayImage(EMPTY_BATTERY_ICON.width, EMPTY_BATTERY_ICON.height, 0);
icon.bitBlt(EMPTY_BATTERY_ICON, 0, 0);
const clamped = Math.max(0, Math.min(100, percentCharge));
const fillWidth = Math.round((BATTERY_FILL_WIDTH * clamped) / 100);
icon.fillRect(BATTERY_FILL_X, BATTERY_FILL_Y, fillWidth, BATTERY_FILL_HEIGHT, 190);
if (isCharging) {
overlayImage(icon, BATTERY_BOLT_ICON, 7, 1);
}
return icon;
}
function overlayImage(target: GrayImage, source: GrayImage, dx: number, dy: number): void {
for (let y = 0; y < source.height; y++) {
for (let x = 0; x < source.width; x++) {
const value = source.pixels[y * source.width + x] ?? 0;
if (value > 0) {
target.setPixel(dx + x, dy + y, value);
}
}
}
}
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function formatDashboardDate(now: Date): string {
return `${WEEKDAYS[now.getDay()]} ${MONTHS[now.getMonth()]} ${now.getDate()} ${pad2(now.getHours())}:${pad2(now.getMinutes())}`;
}
function pad2(value: number): string {
return String(value).padStart(2, "0");
}
function getDashboardLogo(): GrayImage | null {
if (cachedDashboardLogo !== undefined) {
return cachedDashboardLogo;
}
try {
cachedDashboardLogo = loadPngAsGrayImage("images/faceclaw-logo-dashboard.png");
} catch {
cachedDashboardLogo = null;
}
return cachedDashboardLogo;
}
function drawSystemCardFlowItems(image: GrayImage, bounds: DashboardPluginCardBounds): void {
const left = bounds.x + 10;
const top = bounds.y + 84;
const right = bounds.x + bounds.width - 10;
const bottom = bounds.y + bounds.height - 6;
const items = collectBatteryItems();
if (dashboardState.systemCardSettings.showAndroidNotifications) {
const maxNotificationIcons = Math.max(0, ((right - left) / Math.max(1, NOTIFICATION_ICON_SIZE + SYSTEM_CARD_ITEM_GAP)) | 0) * 2;
for (const icon of readActiveNotificationIcons(maxNotificationIcons)) {
items.push({ type: "notification", icon });
}
}
let itemX = left;
let itemY = top;
for (const item of items) {
const itemWidth = systemCardFlowItemWidth(item);
if (itemX > left && itemX + itemWidth > right) {
itemX = left;
itemY += SYSTEM_CARD_ITEM_HEIGHT + SYSTEM_CARD_ITEM_GAP;
}
if (itemY + SYSTEM_CARD_ITEM_HEIGHT > bottom) {
break;
}
if (item.type === "battery") {
drawBatteryFlowItem(image, itemX, itemY, item);
} else {
image.bitBlt(
item.icon,
itemX,
itemY + ((SYSTEM_CARD_ITEM_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0,
);
}
itemX += itemWidth + SYSTEM_CARD_ITEM_GAP;
}
}
function systemCardFlowItemWidth(item: SystemCardFlowItem): number {
if (item.type === "notification") {
return NOTIFICATION_ICON_SIZE;
}
return Math.max(EMPTY_BATTERY_ICON.width, dashboardFont.measureText(item.label));
}
class DashboardLayer implements Layer {
paint(): GrayImage {
if (!dashboardState.screenOn) {
return new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
}
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const now = new Date();
const logo = getDashboardLogo();
const pluginState = getPluginState();
const systemBounds = getCardBounds("system");
this.drawCardBorder(image, systemBounds, dashboardState.selectedCard === "system");
if (logo && dashboardState.systemCardSettings.showFaceclawLogo) {
image.bitBlt(logo, systemBounds.x + 10, systemBounds.y + 10);
}
const infoX = logo && dashboardState.systemCardSettings.showFaceclawLogo ? systemBounds.x + 92 : systemBounds.x + 10;
image.drawText(dashboardSystemFont, infoX, systemBounds.y + 10, getDisplayedSystemCardName(), 200);
image.drawText(dashboardSystemFont, infoX, systemBounds.y + 32, formatDashboardDate(now), 200);
drawSystemCardFlowItems(image, systemBounds);
for (const slot of getDashboardSlotIds()) {
const bounds = getCardBounds(slot);
const pluginId = dashboardState.slotConfig[slot];
if (!isBlankDashboardPlugin(pluginId)) {
this.drawCardBorder(image, bounds, dashboardState.selectedCard === slot);
}
getDashboardPlugin(pluginId).renderCard({
image,
bounds,
selected: dashboardState.selectedCard === slot,
font: dashboardFont,
state: pluginState,
});
}
return image;
}
handleInput(event: DashboardInputEvent, ctx: { stack: LayerStack }): void {
if (!dashboardState.screenOn) {
if (event.type === "double-click") {
dashboardState.selectedCard = "system";
dashboardState.screenOn = true;
}
return;
}
if (event.type === "scroll-up") {
cycleSelection(-1);
return;
}
if (event.type === "scroll-down") {
cycleSelection(1);
return;
}
if (event.type === "click") {
if (dashboardState.selectedCard === "system") {
ctx.stack.push(createRootMenuLayer());
} else {
const pluginId = dashboardState.slotConfig[dashboardState.selectedCard];
if (pluginId === "nightscout" && !isNightscoutSettingsConfigured(dashboardState.nightscoutSettings)) {
ctx.stack.push(createNightscoutSettingsMenuLayer());
return;
}
const layer = getDashboardPlugin(pluginId).createFullscreenLayer?.(
getPluginState,
);
if (layer) {
ctx.stack.push(layer);
}
}
return;
}
if (event.type === "double-click") {
dashboardState.selectedCard = "system";
dashboardState.screenOn = false;
}
}
private drawCardBorder(image: GrayImage, bounds: DashboardPluginCardBounds, selected: boolean): void {
if (selected) {
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 60);
}
}
}
function createRootMenuLayer(): MenuLayer {
return new MenuLayer(
"Menu",
[
{
label: "About",
onSelect: (ctx) => {
ctx.stack.push(new AboutLayer());
},
},
{
label: "Settings",
onSelect: (ctx) => {
ctx.stack.push(createSettingsMenuLayer());
},
},
{
label: "Quit / Disconnect",
onSelect: async (ctx) => {
ctx.stack.clearToBase();
await ctx.actions.disconnect();
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Settings",
[
{
label: "Dashboard",
onSelect: (ctx) => {
ctx.stack.push(createDashboardSettingsMenuLayer());
},
},
{
label: "Integrations",
onSelect: (ctx) => {
ctx.stack.push(createIntegrationsMenuLayer());
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createDashboardSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Dashboard",
[
{
label: "System Card",
onSelect: (ctx) => {
ctx.stack.push(createSystemCardSettingsMenuLayer());
},
},
...getDashboardSlotIds().map((slot) => ({
label: slotMenuLabel(slot),
onSelect: (ctx) => {
ctx.stack.push(createSlotPickerMenu(slot));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `${slotMenuLabel(slot)}: ${pluginLabelForSlot(slot)}`, 200);
},
})),
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createSystemCardSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"System Card",
[
{
label: "Name",
onSelect: (ctx) => {
void ctx.actions.startSystemNameEdit();
ctx.stack.push(new EditSystemNameLayer());
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `Name: ${getDisplayedSystemCardName()}`, 200);
},
},
createSystemCardToggleItem("Show Faceclaw Logo", "showFaceclawLogo"),
createSystemCardToggleItem("Show Battery Indicators", "showBatteryIndicators"),
createSystemCardToggleItem("Show Android Notifications", "showAndroidNotifications"),
],
{
x: 308,
y: 24,
width: 252,
height: 180,
},
true,
);
}
function createSystemCardToggleItem(label: string, key: SystemCardSettingKey) {
return {
label,
onSelect: () => {
setDashboardSystemCardSetting(key, !dashboardState.systemCardSettings[key]);
},
render: ({ image, x, y, width, selected }: { image: GrayImage; x: number; y: number; width: number; selected: boolean }) => {
drawToggleMenuItem(image, x, y, width, label, dashboardState.systemCardSettings[key], selected);
},
};
}
function drawToggleMenuItem(image: GrayImage, x: number, y: number, width: number, label: string, enabled: boolean, selected: boolean): void {
const switchWidth = 34;
const switchHeight = 16;
const switchX = x + width - switchWidth - 2;
const switchY = y + 2;
image.drawText(dashboardFont, x, y + 4, label, 200);
const offFill = selected ? 0 : 18;
image.fillRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 70 : offFill, 8);
image.drawRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 130 : 55, 8);
const knobSize = 12;
const knobX = enabled ? switchX + switchWidth - knobSize - 2 : switchX + 2;
image.fillRoundedRect(knobX, switchY + 2, knobSize, knobSize, enabled ? 230 : selected ? 170 : 90, 6);
}
function createIntegrationsMenuLayer(): MenuLayer {
return new MenuLayer(
"Integrations",
[
{
label: "Nightscout",
onSelect: (ctx) => {
ctx.stack.push(createNightscoutSettingsMenuLayer());
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createNightscoutSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Nightscout",
[
{
label: "Site URL",
onSelect: (ctx) => {
void ctx.actions.startNightscoutSiteUrlEdit();
ctx.stack.push(new EditTextSettingLayer("Edit Nightscout URL", () => dashboardState.nightscoutSettings.siteUrl || "(empty)"));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `URL: ${truncateSetting(dashboardState.nightscoutSettings.siteUrl)}`, 200);
},
},
{
label: "API token",
onSelect: (ctx) => {
void ctx.actions.startNightscoutApiTokenEdit();
ctx.stack.push(new EditTextSettingLayer("Edit API token", () => maskToken(dashboardState.nightscoutSettings.apiToken)));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `Token: ${maskToken(dashboardState.nightscoutSettings.apiToken)}`, 200);
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
class EditSystemNameLayer implements Layer {
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, "Edit dashboard name", 220);
image.drawText(dashboardFont, 22, 52, "Look at the phone app", 200);
image.drawText(dashboardFont, 22, 70, "to type a new name.", 200);
image.drawText(dashboardSystemFont, 22, 110, getDisplayedSystemCardName(), 220);
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
void ctx.actions.endSystemNameEdit();
void ctx.actions.endTextSettingEdit();
ctx.stack.pop();
}
}
}
class EditTextSettingLayer implements Layer {
constructor(
private readonly title: string,
private readonly value: () => string,
) {}
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, this.title, 220);
image.drawText(dashboardFont, 22, 52, "Look at the phone app", 200);
image.drawText(dashboardFont, 22, 70, "to type a value.", 200);
image.drawText(dashboardFont, 22, 110, truncateSetting(this.value(), 52), 220);
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
void ctx.actions.endTextSettingEdit();
ctx.stack.pop();
}
}
}
function createSlotPickerMenu(slot: DashboardSlotId): MenuLayer {
return new MenuLayer(
slotMenuLabel(slot),
listDashboardPlugins().map((plugin) => ({
label: plugin.label,
onSelect: (ctx) => {
dashboardState.slotConfig[slot] = plugin.id;
saveDashboardSlotPlugin(slot, plugin.id);
if (dashboardState.selectedCard === slot && isBlankDashboardPlugin(plugin.id)) {
dashboardState.selectedCard = "system";
}
ctx.stack.pop();
},
render: ({ image, x, y }) => {
const selected = dashboardState.slotConfig[slot] === plugin.id ? " *" : "";
image.drawText(dashboardFont, x, y + 4, `${plugin.label}${selected}`, 200);
},
})),
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
class AboutLayer implements Layer {
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const logo = getDashboardLogo();
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, "About Faceclaw", 220);
if (logo) {
image.bitBlt(logo, 22, 42);
}
image.drawText(dashboardFont, 108, 48, "Faceclaw", 220);
image.drawText(dashboardFont, 108, 64, "Dashboard prototype", 180);
const aboutLines = [
"A lobster on top of a smiley face.",
"Perching on the faces of giants.",
"",
"System card opens menus.",
"Swipe cycles dashboard cards.",
"Plugin cards open fullscreen views.",
];
for (let index = 0; index < aboutLines.length; index++) {
image.drawText(dashboardFont, 22, 128 + index * 14, aboutLines[index]!, 180);
}
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: { stack: LayerStack }): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
function getPluginState(): DashboardPluginState {
return {
logLines: dashboardState.logLines,
media: mediaControllerBridge.snapshot(),
nightscout: nightscoutBridge.snapshot(),
nightscoutConfigured: isNightscoutSettingsConfigured(dashboardState.nightscoutSettings),
};
}
function getCardBounds(card: DashboardCardId): DashboardPluginCardBounds {
switch (card) {
case "system":
return { x: 0, y: 0, width: G2_LENS_WIDTH / 2 - 2, height: G2_LENS_HEIGHT / 2 - 2 };
case "top-right":
return {
x: G2_LENS_WIDTH / 2 + 2,
y: 0,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
case "bottom-left":
return {
x: 0,
y: G2_LENS_HEIGHT / 2 + 2,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
case "bottom-right":
return {
x: G2_LENS_WIDTH / 2 + 2,
y: G2_LENS_HEIGHT / 2 + 2,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
}
}
function cycleSelection(direction: -1 | 1): void {
const order: DashboardCardId[] = [
"system",
...getDashboardSlotIds().filter((slot) => !isBlankDashboardPlugin(dashboardState.slotConfig[slot])),
];
const index = order.indexOf(dashboardState.selectedCard);
const currentIndex = index >= 0 ? index : 0;
dashboardState.selectedCard = order[(currentIndex + direction + order.length) % order.length]!;
}
function slotMenuLabel(slot: DashboardSlotId): string {
switch (slot) {
case "top-right":
return "Top-right slot";
case "bottom-left":
return "Bottom-left slot";
case "bottom-right":
return "Bottom-right slot";
}
}
function pluginLabelForSlot(slot: DashboardSlotId): string {
return getDashboardPlugin(dashboardState.slotConfig[slot]).label;
}
function truncateSetting(value: string, maxLength = 22): string {
const text = value || "(empty)";
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
function maskToken(token: string): string {
if (!token) return "(empty)";
return token.length <= 6 ? "******" : `${token.slice(0, 2)}...${token.slice(-4)}`;
}
const dashboardLayers = new LayerStack(new DashboardLayer(), dashboardFont, dashboardActions);
+90
View File
@@ -0,0 +1,90 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
import { BdfFont } from "../graphics/bdffont";
export type DashboardInputEvent =
| { type: "click"; source: "ring" | "left-arm" | "right-arm" }
| { type: "double-click"; source: "ring" | "left-arm" | "right-arm" }
| { type: "scroll-up" }
| { type: "scroll-down" }
| { type: "unknown"; kind: string; eventSource: number; eventType: number };
export type LayerActions = {
disconnect: () => Promise<void> | void;
startSystemNameEdit: () => Promise<void> | void;
endSystemNameEdit: () => Promise<void> | void;
startNightscoutSiteUrlEdit: () => Promise<void> | void;
startNightscoutApiTokenEdit: () => Promise<void> | void;
endTextSettingEdit: () => Promise<void> | void;
};
export type PaintBelow = () => GrayImage;
export interface LayerContext {
readonly stack: LayerStack;
readonly font: BdfFont;
readonly actions: LayerActions;
}
export interface Layer {
readonly paintOverBase?: boolean;
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage;
handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> | void;
}
export class LayerStack {
private readonly layers: Layer[];
private readonly ctx: LayerContext;
constructor(baseLayer: Layer, font: BdfFont, actions: LayerActions) {
this.layers = [baseLayer];
this.ctx = {
stack: this,
font,
actions,
};
}
push(layer: Layer): void {
this.layers.push(layer);
}
pop(): void {
if (this.layers.length > 1) {
this.layers.pop();
}
}
clearToBase(): void {
this.layers.splice(1);
}
setActions(actions: Partial<LayerActions>): void {
Object.assign(this.ctx.actions, actions);
}
paint(): GrayImage {
return this.paintLayer(this.layers.length - 1);
}
async handleInput(event: DashboardInputEvent): Promise<void> {
await this.layers[this.layers.length - 1]!.handleInput(event, this.ctx);
}
private paintLayer(index: number): GrayImage {
const layer = this.layers[index]!;
let cachedBelow: GrayImage | null = null;
return layer.paint(this.ctx, () => {
if (cachedBelow) {
return cachedBelow;
}
if (index <= 0) {
cachedBelow = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
} else if (layer.paintOverBase) {
cachedBelow = this.paintLayer(0);
} else {
cachedBelow = this.paintLayer(index - 1);
}
return cachedBelow;
});
}
}
+136
View File
@@ -0,0 +1,136 @@
import { GrayImage } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { DashboardInputEvent, Layer, LayerContext, PaintBelow } from "./layers";
const DEFAULT_MENU_X = 48;
const DEFAULT_MENU_Y = 24;
const DEFAULT_MENU_WIDTH = 480;
const DEFAULT_MENU_HEIGHT = 240;
const MENU_TITLE_HEIGHT = 24;
const MENU_ROW_HEIGHT = 28;
export type MenuLayout = {
x: number;
y: number;
width: number;
height: number;
};
export type MenuItemRenderArgs = {
image: GrayImage;
x: number;
y: number;
width: number;
height: number;
selected: boolean;
text: string;
ctx: LayerContext;
};
export type MenuItem = {
label: string;
onSelect: (ctx: LayerContext, menu: MenuLayer) => Promise<void> | void;
render?: (args: MenuItemRenderArgs) => void;
};
export class MenuLayer implements Layer {
private selectedIndex = 0;
constructor(
private readonly title: string,
private readonly items: MenuItem[],
private readonly layout: MenuLayout = {
x: DEFAULT_MENU_X,
y: DEFAULT_MENU_Y,
width: DEFAULT_MENU_WIDTH,
height: DEFAULT_MENU_HEIGHT,
},
public readonly paintOverBase = false,
) {}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const { x, y, width, height } = this.layout;
const image = paintBelow();
image.fillRoundedRect(x, y, width, height, 0);
image.drawRoundedRect(x, y, width, height, 72);
image.drawText(ctx.font, x + 18, y + 10, this.title, 220);
const bodyY = y + MENU_TITLE_HEIGHT + 12;
for (let index = 0; index < this.items.length; index++) {
const item = this.items[index]!;
const y = bodyY + index * MENU_ROW_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
image.fillRoundedRect(x + 12, y - 2, width - 24, MENU_ROW_HEIGHT - 4, 18);
image.drawRoundedRect(x + 12, y - 2, width - 24, MENU_ROW_HEIGHT - 4, 45);
}
if (item.render) {
item.render({
image,
x: x + 22,
y,
width: width - 44,
height: MENU_ROW_HEIGHT - 4,
selected,
text: item.label,
ctx,
});
} else {
image.drawText(ctx.font, x + 22, y + 4, item.label, selected ? 255 : 200);
}
}
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (!this.items.length) {
if (event.type === "double-click") {
ctx.stack.pop();
}
return;
}
switch (event.type) {
case "scroll-up":
this.selectedIndex = (this.selectedIndex + this.items.length - 1) % this.items.length;
return;
case "scroll-down":
this.selectedIndex = (this.selectedIndex + 1) % this.items.length;
return;
case "double-click":
ctx.stack.pop();
return;
case "click":
await this.items[this.selectedIndex]!.onSelect(ctx, this);
return;
default:
return;
}
}
}
export class TextPageLayer implements Layer {
constructor(
private readonly title: string,
private readonly body: string,
) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
image.drawText(ctx.font, 18, 14, this.title, 220);
image.drawRect(12, 12, 552, 264, 52);
const wrapped = wrapText(ctx.font, this.body, 520);
for (let index = 0; index < wrapped.length; index++) {
image.drawText(ctx.font, 24, 42 + index * 14, wrapped[index]!, 190);
}
image.drawText(ctx.font, 24, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}