Refactor settings

This commit is contained in:
James Babcock committed 2026-06-01 15:35:35 -07:00
1 parent d67afcbfdb
commit 5da3b48c7d
13 files changed
+538 -721

No files matched your search

+30 -108
View File
@@ -16,10 +16,6 @@ import {
applyDashboardScreenTimeout, applyDashboardScreenTimeout,
consumeDashboardTiledWakePaint, consumeDashboardTiledWakePaint,
drawDashboard, drawDashboard,
getDashboardNightscoutSettings,
getDashboardSystemCardName,
isDashboardCompressionRatioEstimationEnabled,
isDashboardVoiceControlEnabled,
noteDashboardPhoneTextInput, noteDashboardPhoneTextInput,
openAndroidNotificationFromSleep, openAndroidNotificationFromSleep,
openTelepromptDocument, openTelepromptDocument,
@@ -27,23 +23,24 @@ import {
resetDashboardSleepTimerAndWake, resetDashboardSleepTimerAndWake,
setDashboardBatteryLevels, setDashboardBatteryLevels,
setDashboardActions, setDashboardActions,
setDashboardNightscoutApiToken,
setDashboardNightscoutSiteUrl,
setDashboardSystemCardName,
setDashboardVoiceControlEnabled,
} from "../ui/dashboard"; } from "../ui/dashboard";
import {
estimateCompressionRatiosSetting,
nightscoutApiTokenSetting,
nightscoutSiteUrlSetting,
systemCardNameSetting,
voiceControlEnabledSetting,
type ConfigSettingString,
} from "../ui/dashboard-settings";
type ConnectionPhase = "disconnected" | "connecting" | "connected" | "disconnecting"; type ConnectionPhase = "disconnected" | "connecting" | "connected" | "disconnecting";
export type TextSettingEditorKind = "dashboard-name" | "nightscout-site-url" | "nightscout-api-token";
export type DashboardSnapshot = { export type DashboardSnapshot = {
phase: ConnectionPhase; phase: ConnectionPhase;
status: string; status: string;
log: string; log: string;
displayPreview: ImageSource | null; displayPreview: ImageSource | null;
systemCardName: string; activeTextSettingId: string | null;
editingSystemCardName: boolean;
activeTextSettingEditorKind: TextSettingEditorKind | null;
activeTextSettingTitle: string; activeTextSettingTitle: string;
activeTextSettingValue: string; activeTextSettingValue: string;
evenAppConflictMessage: string; evenAppConflictMessage: string;
@@ -119,8 +116,7 @@ class DashboardController {
private phase: ConnectionPhase = "disconnected"; private phase: ConnectionPhase = "disconnected";
private status = "Disconnected."; private status = "Disconnected.";
private log = ""; private log = "";
private editingSystemCardName = false; private activeTextSetting: ConfigSettingString | null = null;
private activeTextSettingEditorKind: TextSettingEditorKind | null = null;
private evenNotificationActive = false; private evenNotificationActive = false;
private evenAppConflictMessage = ""; private evenAppConflictMessage = "";
private displayPreview: ImageSource | null = createInitialDisplayPreview(); private displayPreview: ImageSource | null = createInitialDisplayPreview();
@@ -154,10 +150,7 @@ class DashboardController {
constructor() { constructor() {
setDashboardActions({ setDashboardActions({
disconnect: () => this.disconnect(), disconnect: () => this.disconnect(),
startSystemNameEdit: () => this.startSystemNameEdit(), startTextSettingEdit: (setting) => this.startTextSettingEdit(setting),
endSystemNameEdit: () => this.endSystemNameEdit(),
startNightscoutSiteUrlEdit: () => this.startNightscoutSiteUrlEdit(),
startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(),
endTextSettingEdit: () => this.endTextSettingEdit(), endTextSettingEdit: () => this.endTextSettingEdit(),
setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled), setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled),
setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active), setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active),
@@ -186,11 +179,9 @@ class DashboardController {
status: this.status, status: this.status,
log: this.log, log: this.log,
displayPreview: this.displayPreview, displayPreview: this.displayPreview,
systemCardName: getDashboardSystemCardName(), activeTextSettingId: this.activeTextSetting?.id ?? null,
editingSystemCardName: this.editingSystemCardName, activeTextSettingTitle: this.activeTextSetting?.editorTitle ?? "",
activeTextSettingEditorKind: this.activeTextSettingEditorKind, activeTextSettingValue: this.activeTextSetting?.get() ?? "",
activeTextSettingTitle: this.getActiveTextSettingTitle(),
activeTextSettingValue: this.getActiveTextSettingValue(),
evenAppConflictMessage: this.evenAppConflictMessage, evenAppConflictMessage: this.evenAppConflictMessage,
evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0, evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0,
}; };
@@ -218,49 +209,13 @@ class DashboardController {
} }
setSystemCardName(name: string): void { setSystemCardName(name: string): void {
const savedName = setDashboardSystemCardName(name); this.updateTextSetting(systemCardNameSetting, name);
this.emit();
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
this.appendLog(`dashboard name update failed: ${this.formatError(error)}`);
});
} else {
const image = drawDashboard();
this.updateDisplayPreviewFromImage(image);
}
if (savedName !== name) {
this.emit();
}
} }
setActiveTextSettingValue(value: string): void { setActiveTextSettingValue(value: string): void {
noteDashboardPhoneTextInput(); noteDashboardPhoneTextInput();
switch (this.activeTextSettingEditorKind) { if (!this.activeTextSetting) return;
case "dashboard-name": this.updateTextSetting(this.activeTextSetting, value);
this.setSystemCardName(value);
return;
case "nightscout-site-url":
setDashboardNightscoutSiteUrl(value);
this.emit();
this.previewOrRenderAfterTextSettingChange("nightscout site URL");
return;
case "nightscout-api-token":
setDashboardNightscoutApiToken(value);
this.emit();
this.previewOrRenderAfterTextSettingChange("nightscout API token");
return;
default:
return;
}
}
endSystemNameEdit(): void {
if (!this.editingSystemCardName) return;
this.editingSystemCardName = false;
if (this.activeTextSettingEditorKind === "dashboard-name") {
this.activeTextSettingEditorKind = null;
}
this.emit();
} }
async connect(): Promise<void> { async connect(): Promise<void> {
@@ -505,21 +460,8 @@ class DashboardController {
this.updateDisplayPreviewFromImage(image); this.updateDisplayPreviewFromImage(image);
} }
private startSystemNameEdit(): void { private startTextSettingEdit(setting: ConfigSettingString): void {
this.editingSystemCardName = true; this.activeTextSetting = setting;
this.activeTextSettingEditorKind = "dashboard-name";
this.emit();
}
private startNightscoutSiteUrlEdit(): void {
this.editingSystemCardName = false;
this.activeTextSettingEditorKind = "nightscout-site-url";
this.emit();
}
private startNightscoutApiTokenEdit(): void {
this.editingSystemCardName = false;
this.activeTextSettingEditorKind = "nightscout-api-token";
this.emit(); this.emit();
} }
@@ -535,7 +477,7 @@ class DashboardController {
} }
} }
setDashboardVoiceControlEnabled(enabled); voiceControlEnabledSetting.set(enabled);
this.appendLog(`Voice control ${enabled ? "enabled" : "disabled"}.`); this.appendLog(`Voice control ${enabled ? "enabled" : "disabled"}.`);
if (enabled) { if (enabled) {
this.startVoiceControlIfEnabled(); this.startVoiceControlIfEnabled();
@@ -550,39 +492,19 @@ class DashboardController {
} }
private endTextSettingEdit(): void { private endTextSettingEdit(): void {
const finishedKind = this.activeTextSettingEditorKind; const finishedSetting = this.activeTextSetting;
this.editingSystemCardName = false; this.activeTextSetting = null;
this.activeTextSettingEditorKind = null;
this.emit(); this.emit();
if (finishedKind === "nightscout-site-url" || finishedKind === "nightscout-api-token") { if (finishedSetting === nightscoutSiteUrlSetting || finishedSetting === nightscoutApiTokenSetting) {
void this.refreshNightscoutAfterSettingsChange(); void this.refreshNightscoutAfterSettingsChange();
} }
} }
private getActiveTextSettingTitle(): string { private updateTextSetting(setting: ConfigSettingString, value: string): void {
switch (this.activeTextSettingEditorKind) { if (setting.get() !== value) {
case "dashboard-name": setting.set(value);
return "Dashboard name"; this.emit();
case "nightscout-site-url": this.previewOrRenderAfterTextSettingChange(setting.label);
return "Nightscout site URL";
case "nightscout-api-token":
return "Nightscout API token";
default:
return "";
}
}
private getActiveTextSettingValue(): string {
const nightscoutSettings = getDashboardNightscoutSettings();
switch (this.activeTextSettingEditorKind) {
case "dashboard-name":
return getDashboardSystemCardName();
case "nightscout-site-url":
return nightscoutSettings.siteUrl;
case "nightscout-api-token":
return nightscoutSettings.apiToken;
default:
return "";
} }
} }
@@ -639,7 +561,7 @@ class DashboardController {
const forceTiledCommit = consumeDashboardTiledWakePaint(); const forceTiledCommit = consumeDashboardTiledWakePaint();
const fingerprint = image.fingerprint(); const fingerprint = image.fingerprint();
const imageTiles = image.toEvenHubTiles(); const imageTiles = image.toEvenHubTiles();
if (isDashboardCompressionRatioEstimationEnabled()) { if (estimateCompressionRatiosSetting.get()) {
this.logCompressionEstimate(imageTiles); this.logCompressionEstimate(imageTiles);
} }
const tiles = imageTiles.map((tile) => tile.bmp); const tiles = imageTiles.map((tile) => tile.bmp);
@@ -735,7 +657,7 @@ class DashboardController {
private startVoiceControlIfEnabled(): void { private startVoiceControlIfEnabled(): void {
if (!this.communicator) return; if (!this.communicator) return;
if (!isDashboardVoiceControlEnabled()) return; if (!voiceControlEnabledSetting.get()) return;
this.updateConnectedForegroundNotification(); this.updateConnectedForegroundNotification();
voiceControlBridge.start(this.communicator.getNativeCommunicator(), "wakeword"); voiceControlBridge.start(this.communicator.getNativeCommunicator(), "wakeword");
} }
+10 -9
View File
@@ -1,4 +1,4 @@
import { loadNightscoutSettings } from "../ui/dashboard-settings"; import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
export type NightscoutPoint = { export type NightscoutPoint = {
timestampMs: number; timestampMs: number;
@@ -181,8 +181,9 @@ export class NightscoutBridge {
private async refresh(): Promise<void> { private async refresh(): Promise<void> {
try { try {
const nowMs = Date.now(); const nowMs = Date.now();
const settings = loadNightscoutSettings(); const siteUrl = nightscoutSiteUrlSetting.get();
if (!settings.siteUrl || !settings.apiToken) { const apiToken = nightscoutApiTokenSetting.get();
if (!siteUrl || !apiToken) {
this.state = { this.state = {
...DEFAULT_NIGHTSCOUT_STATE, ...DEFAULT_NIGHTSCOUT_STATE,
status: "Configure Nightscout site URL and API token.", status: "Configure Nightscout site URL and API token.",
@@ -192,22 +193,22 @@ export class NightscoutBridge {
return; return;
} }
const treatmentStartIso = new Date(nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS).toISOString(); const treatmentStartIso = new Date(nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS).toISOString();
const tokenQuery = `token=${encodeURIComponent(settings.apiToken)}`; const tokenQuery = `token=${encodeURIComponent(apiToken)}`;
const [entries, deviceStatus, status, treatments, siteChanges] = await Promise.all([ const [entries, deviceStatus, status, treatments, siteChanges] = await Promise.all([
fetchJson<NightscoutEntryResponse[]>( fetchJson<NightscoutEntryResponse[]>(
`${settings.siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`, `${siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`,
), ),
fetchJson<NightscoutDeviceStatusResponse[]>( fetchJson<NightscoutDeviceStatusResponse[]>(
`${settings.siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`, `${siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`,
), ),
fetchJson<NightscoutStatusResponse>( fetchJson<NightscoutStatusResponse>(
`${settings.siteUrl}/api/v1/status.json?${tokenQuery}`, `${siteUrl}/api/v1/status.json?${tokenQuery}`,
), ),
fetchJson<NightscoutTreatmentResponse[]>( fetchJson<NightscoutTreatmentResponse[]>(
`${settings.siteUrl}/api/v1/treatments.json?find%5Bcreated_at%5D%5B%24gte%5D=${encodeURIComponent(treatmentStartIso)}&${tokenQuery}`, `${siteUrl}/api/v1/treatments.json?find%5Bcreated_at%5D%5B%24gte%5D=${encodeURIComponent(treatmentStartIso)}&${tokenQuery}`,
), ),
fetchJson<NightscoutTreatmentResponse[]>( fetchJson<NightscoutTreatmentResponse[]>(
`${settings.siteUrl}/api/v1/treatments.json?find%5BeventType%5D=Site%20Change&count=1&${tokenQuery}`, `${siteUrl}/api/v1/treatments.json?find%5BeventType%5D=Site%20Change&count=1&${tokenQuery}`,
), ),
]); ]);
+1 -1
View File
@@ -128,7 +128,7 @@ export function loaded(args: EventData) {
} }
return return
} }
if (propertyArgs.propertyName === 'activeTextSettingEditorKind') { if (propertyArgs.propertyName === 'activeTextSettingId') {
if (model.isTextSettingEditorActive) { if (model.isTextSettingEditorActive) {
focusSystemNameField(page) focusSystemNameField(page)
} }
+10 -41
View File
@@ -1,5 +1,5 @@
import { Application, Frame, ImageSource, Observable, Screen } from "@nativescript/core"; import { Application, Frame, ImageSource, Observable, Screen } from "@nativescript/core";
import { dashboardController, type TextSettingEditorKind } from "../g2/dashboard-controller"; import { dashboardController } from "../g2/dashboard-controller";
type LayoutOrientation = "portrait" | "landscape"; type LayoutOrientation = "portrait" | "landscape";
@@ -8,9 +8,7 @@ export class MainViewModel extends Observable {
private _log = ""; private _log = "";
private _displayPreview: ImageSource | null = null; private _displayPreview: ImageSource | null = null;
private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation(); private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation();
private _systemCardName = "Faceclaw"; private _activeTextSettingId: string | null = null;
private _editingSystemCardName = false;
private _activeTextSettingEditorKind: TextSettingEditorKind | null = null;
private _activeTextSettingTitle = ""; private _activeTextSettingTitle = "";
private _activeTextSettingValue = ""; private _activeTextSettingValue = "";
private _evenAppConflictMessage = ""; private _evenAppConflictMessage = "";
@@ -25,9 +23,7 @@ export class MainViewModel extends Observable {
this.log = snapshot.log; this.log = snapshot.log;
this.displayPreview = snapshot.displayPreview; this.displayPreview = snapshot.displayPreview;
this.phase = snapshot.phase; this.phase = snapshot.phase;
this.systemCardName = snapshot.systemCardName; this.activeTextSettingId = snapshot.activeTextSettingId;
this.editingSystemCardName = snapshot.editingSystemCardName;
this.activeTextSettingEditorKind = snapshot.activeTextSettingEditorKind;
this.activeTextSettingTitle = snapshot.activeTextSettingTitle; this.activeTextSettingTitle = snapshot.activeTextSettingTitle;
this.activeTextSettingValue = snapshot.activeTextSettingValue; this.activeTextSettingValue = snapshot.activeTextSettingValue;
this.evenAppConflictMessage = snapshot.evenAppConflictMessage; this.evenAppConflictMessage = snapshot.evenAppConflictMessage;
@@ -133,41 +129,14 @@ export class MainViewModel extends Observable {
return this._showLog ? "Hide Log" : "Show Log"; return this._showLog ? "Hide Log" : "Show Log";
} }
get systemCardName(): string { get activeTextSettingId(): string | null {
return this._systemCardName; return this._activeTextSettingId;
} }
set systemCardName(value: string) { set activeTextSettingId(value: string | null) {
if (this._systemCardName !== value) { if (this._activeTextSettingId !== value) {
this._systemCardName = value; this._activeTextSettingId = value;
this.notifyPropertyChange("systemCardName", value); this.notifyPropertyChange("activeTextSettingId", value);
}
}
get editingSystemCardName(): boolean {
return this._editingSystemCardName;
}
set editingSystemCardName(value: boolean) {
if (this._editingSystemCardName !== value) {
this._editingSystemCardName = value;
this.notifyPropertyChange("editingSystemCardName", value);
this.notifyPropertyChange("systemCardNameEditorVisibility", this.systemCardNameEditorVisibility);
}
}
get systemCardNameEditorVisibility(): "visible" | "collapse" {
return this._editingSystemCardName ? "visible" : "collapse";
}
get activeTextSettingEditorKind(): TextSettingEditorKind | null {
return this._activeTextSettingEditorKind;
}
set activeTextSettingEditorKind(value: TextSettingEditorKind | null) {
if (this._activeTextSettingEditorKind !== value) {
this._activeTextSettingEditorKind = value;
this.notifyPropertyChange("activeTextSettingEditorKind", value);
this.notifyPropertyChange("textSettingEditorVisibility", this.textSettingEditorVisibility); this.notifyPropertyChange("textSettingEditorVisibility", this.textSettingEditorVisibility);
this.notifyPropertyChange("isTextSettingEditorActive", this.isTextSettingEditorActive); this.notifyPropertyChange("isTextSettingEditorActive", this.isTextSettingEditorActive);
} }
@@ -196,7 +165,7 @@ export class MainViewModel extends Observable {
} }
get isTextSettingEditorActive(): boolean { get isTextSettingEditorActive(): boolean {
return this._activeTextSettingEditorKind !== null; return this._activeTextSettingId !== null;
} }
get textSettingEditorVisibility(): "visible" | "collapse" { get textSettingEditorVisibility(): "visible" | "collapse" {
+1 -1
View File
@@ -1,6 +1,6 @@
import takeRight from "lodash/takeRight"; import takeRight from "lodash/takeRight";
import { getDefaultSmallFont } from "~/graphics/bdffont"; import { getDefaultSmallFont } from "~/graphics/bdffont";
import { DashboardPlugin, DashboardPluginCardRenderArgs, DashboardPluginState } from "../dashboard-plugins"; import { DashboardPlugin, type DashboardPluginCardRenderArgs, type DashboardPluginState } from "../dashboard-plugin";
import { Layer, LayerContext, type DashboardInputEvent } from "../layers"; import { Layer, LayerContext, type DashboardInputEvent } from "../layers";
import { GrayImage } from "~/graphics/image"; import { GrayImage } from "~/graphics/image";
+1 -1
View File
@@ -1,4 +1,4 @@
import { DashboardPlugin, DashboardPluginCardRenderArgs, DashboardPluginState } from "../dashboard-plugins"; import { DashboardPlugin, type DashboardPluginCardRenderArgs, type DashboardPluginState } from "../dashboard-plugin";
import { getDefaultSmallFont } from "../../graphics/bdffont"; import { getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage } from "../../graphics/image"; import { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap"; import { wrapText } from "../../graphics/textwrap";
+1 -1
View File
@@ -1,6 +1,6 @@
import { BdfFont, getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/bdffont"; import { BdfFont, getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/bdffont";
import { GrayImage, imageFromAsciiArt } from "../../graphics/image"; import { GrayImage, imageFromAsciiArt } from "../../graphics/image";
import { DashboardPlugin, DashboardPluginCardRenderArgs, DashboardPluginState } from "../dashboard-plugins"; import { DashboardPlugin, type DashboardPluginCardRenderArgs, type DashboardPluginState } from "../dashboard-plugin";
import { DashboardInputEvent, Layer, LayerContext } from "../layers"; import { DashboardInputEvent, Layer, LayerContext } from "../layers";
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge"; import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
import { formatAgeShortFromTimestamp, formatTimestamp } from "~/util/date-util"; import { formatAgeShortFromTimestamp, formatTimestamp } from "~/util/date-util";
+45
View File
@@ -0,0 +1,45 @@
import { type GrayImage } from "../graphics/image";
import { type MediaControllerState } from "../native/media-controller";
import { type NightscoutState } from "../native/nightscout-bridge";
import { type DashboardPluginId } from "./dashboard-settings";
import { type Layer } 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;
state: DashboardPluginState;
};
export abstract class DashboardPlugin {
readonly id: DashboardPluginId;
readonly label: string;
constructor(config: {
id: DashboardPluginId;
label: string;
}) {
this.id = config.id;
this.label = config.label;
}
abstract renderCard(args: DashboardPluginCardRenderArgs): void;
createFullscreenLayer(getState: () => DashboardPluginState): Layer | null {
return null;
}
}
+23 -57
View File
@@ -1,72 +1,38 @@
import { GrayImage } from "../graphics/image";
import { type MediaControllerState } from "../native/media-controller";
import { type DashboardPluginId } from "./dashboard-settings"; import { type DashboardPluginId } from "./dashboard-settings";
import { Layer } from "./layers"; import { DashboardPlugin } from "./dashboard-plugin";
import { NightscoutDashboardPlugin } from "./apps/nightscout"; import { NightscoutDashboardPlugin } from "./apps/nightscout";
import { NightscoutState } from "~/native/nightscout-bridge";
import { MusicControllerDashboardPlugin } from "./apps/music-controller"; import { MusicControllerDashboardPlugin } from "./apps/music-controller";
import { DebugLogDashboardPlugin } from "./apps/debug-log"; import { DebugLogDashboardPlugin } from "./apps/debug-log";
export type DashboardPluginState = { export { DashboardPlugin } from "./dashboard-plugin";
logLines: string[]; export type { DashboardPluginCardBounds, DashboardPluginCardRenderArgs, DashboardPluginState } from "./dashboard-plugin";
media: MediaControllerState;
nightscout: NightscoutState;
nightscoutConfigured: boolean;
};
export type DashboardPluginCardBounds = { let dashboardPlugins: DashboardPlugin[] | null = null;
x: number; function getDashboardPlugins(): DashboardPlugin[] {
y: number; if (!dashboardPlugins) {
width: number; dashboardPlugins = [
height: number; {
}; id: "blank",
label: "Blank",
export type DashboardPluginCardRenderArgs = { renderCard: () => {},
image: GrayImage; createFullscreenLayer: () => null,
bounds: DashboardPluginCardBounds; },
selected: boolean; new DebugLogDashboardPlugin(),
state: DashboardPluginState; new MusicControllerDashboardPlugin(),
}; new NightscoutDashboardPlugin(),
];
export abstract class DashboardPlugin {
readonly id: DashboardPluginId;
readonly label: string;
constructor(config: {
id: DashboardPluginId;
label: string;
}) {
this.id = config.id;
this.label = config.label;
} }
return dashboardPlugins;
};
abstract renderCard(args: DashboardPluginCardRenderArgs): void;
createFullscreenLayer(getState: () => DashboardPluginState): Layer | null {
return null;
}
}
const DASHBOARD_PLUGINS: DashboardPlugin[] = [
{
id: "blank",
label: "Blank",
renderCard: () => {},
createFullscreenLayer: () => null,
},
new DebugLogDashboardPlugin(),
new MusicControllerDashboardPlugin(),
new NightscoutDashboardPlugin(),
];
const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
DASHBOARD_PLUGINS.map((plugin) => [plugin.id, plugin]),
);
export function listDashboardPlugins(): DashboardPlugin[] { export function listDashboardPlugins(): DashboardPlugin[] {
return [...DASHBOARD_PLUGINS]; return [...getDashboardPlugins()];
} }
export function getDashboardPlugin(pluginId: DashboardPluginId): DashboardPlugin { export function getDashboardPlugin(pluginId: DashboardPluginId): DashboardPlugin {
const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
getDashboardPlugins().map((plugin) => [plugin.id, plugin]),
);
return PLUGIN_MAP.get(pluginId) ?? PLUGIN_MAP.get("blank")!; return PLUGIN_MAP.get(pluginId) ?? PLUGIN_MAP.get("blank")!;
} }
+335 -177
View File
@@ -1,6 +1,12 @@
import { ApplicationSettings } from "@nativescript/core"; import { ApplicationSettings } from "@nativescript/core";
import { getDefaultSmallFont } from "~/graphics/bdffont";
import { drawRightValueMenuItem, drawToggleMenuItem, MenuItem, MenuLayer } from "./menu";
import { DashboardInputEvent, Layer, type LayerContext } from "./layers";
import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "~/graphics/image";
import { GrayImage } from "~/graphics/image";
export type DashboardSlotId = "bottom-left" | "bottom-right"; export type DashboardSlotId = "bottom-left" | "bottom-right";
export const dashboardSlotIds: DashboardSlotId[] = ["bottom-left", "bottom-right"];
export type DashboardPluginId = "blank" | "input-debug-log" | "music-controller" | "nightscout"; export type DashboardPluginId = "blank" | "input-debug-log" | "music-controller" | "nightscout";
export type DashboardSlotConfig = Record<DashboardSlotId, DashboardPluginId>; export type DashboardSlotConfig = Record<DashboardSlotId, DashboardPluginId>;
@@ -18,29 +24,126 @@ export type SystemCardSettingKey = keyof SystemCardSettings;
export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "never"; export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "never";
export type WakeModeSetting = "tiled" | "synchronized"; export type WakeModeSetting = "tiled" | "synchronized";
export const DEFAULT_SYSTEM_CARD_NAME = "Faceclaw"; type ConfigSettingOptions<TValue, TId extends string> = {
export const DEFAULT_SCREEN_TIMEOUT: ScreenTimeoutSetting = "30s"; id: TId;
export const DEFAULT_WAKE_MODE: WakeModeSetting = "tiled"; label: string;
export const DEFAULT_VOICE_CONTROL_ENABLED = false; storageKey: string;
export const DEFAULT_ESTIMATE_COMPRESSION_RATIOS_ENABLED = false; defaultValue: TValue;
const SYSTEM_CARD_NAME_KEY = "dashboard.systemCardName"; formatValue?: (value: TValue) => string;
const SCREEN_TIMEOUT_KEY = "display.screenTimeout";
const WAKE_MODE_KEY = "display.wakeMode";
const VOICE_CONTROL_ENABLED_KEY = "voice.enabled";
const ESTIMATE_COMPRESSION_RATIOS_ENABLED_KEY = "debug.estimateCompressionRatios";
const SYSTEM_CARD_SETTING_KEYS: Record<SystemCardSettingKey, string> = {
showFaceclawLogo: "dashboard.systemCard.showFaceclawLogo",
showBatteryIndicators: "dashboard.systemCard.showBatteryIndicators",
showAndroidNotifications: "dashboard.systemCard.showAndroidNotifications",
showSignalStrength: "dashboard.systemCard.showSignalStrength",
}; };
const NIGHTSCOUT_SITE_URL_KEY = "integrations.nightscout.siteUrl";
const NIGHTSCOUT_API_TOKEN_KEY = "integrations.nightscout.apiToken"; export abstract class ConfigSetting<TValue, TId extends string = string> {
const SLOT_KEYS: Record<DashboardSlotId, string> = { readonly id: TId;
"bottom-left": "dashboard.slot.bottomLeft", readonly label: string;
"bottom-right": "dashboard.slot.bottomRight", protected readonly storageKey: string;
protected readonly defaultValue: TValue;
private readonly valueFormatter: (value: TValue) => string;
protected constructor(options: ConfigSettingOptions<TValue, TId>) {
this.id = options.id;
this.label = options.label;
this.storageKey = options.storageKey;
this.defaultValue = options.defaultValue;
this.valueFormatter = options.formatValue ?? ((value) => String(value));
}
abstract get(): TValue;
abstract set(value: TValue): TValue;
displayValue(value?: TValue): string {
const displayValue = arguments.length > 0 ? value as TValue : this.get();
return this.valueFormatter(displayValue);
}
}
export class ConfigSettingBoolean<TId extends string = string> extends ConfigSetting<boolean, TId> {
constructor(options: ConfigSettingOptions<boolean, TId>) {
super(options);
}
get(): boolean {
return ApplicationSettings.getBoolean(this.storageKey, this.defaultValue);
}
set(value: boolean): boolean {
ApplicationSettings.setBoolean(this.storageKey, value);
return value;
}
toggle(value = this.get()): boolean {
return this.set(!value);
}
}
type ConfigSettingEnumOptions<TValue extends string, TId extends string> = ConfigSettingOptions<TValue, TId> & {
values: readonly TValue[];
normalize?: (value: string | null | undefined) => TValue;
}; };
export class ConfigSettingEnum<TValue extends string, TId extends string = string> extends ConfigSetting<TValue, TId> {
readonly values: readonly TValue[];
private readonly normalizer: (value: string | null | undefined) => TValue;
constructor(options: ConfigSettingEnumOptions<TValue, TId>) {
super(options);
this.values = options.values;
if (options.normalize) {
this.normalizer = (value: string | null | undefined) => {
const normalized = options.normalize(value) as TValue|undefined;
if (normalized === undefined) return this.defaultValue;
return normalized;
}
} else {
this.normalizer = (value) => this.values.includes(value as TValue) ? value as TValue : this.defaultValue;
}
}
get(): TValue {
return this.normalizer(ApplicationSettings.getString(this.storageKey, this.defaultValue));
}
set(value: TValue): TValue {
const normalized = this.normalizer(value);
ApplicationSettings.setString(this.storageKey, normalized);
return normalized;
}
next(value = this.get()): TValue {
const index = this.values.indexOf(value);
return this.values[(index + 1) % this.values.length] ?? this.defaultValue;
}
}
type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<string, TId> & {
editorTitle?: string;
glassesEditTitle?: string;
normalize?: (value: string | null | undefined) => string;
};
export class ConfigSettingString<TId extends string = string> extends ConfigSetting<string, TId> {
readonly editorTitle: string;
readonly glassesEditTitle: string;
private readonly normalizer: (value: string | null | undefined) => string;
constructor(options: ConfigSettingStringOptions<TId>) {
super(options);
this.editorTitle = options.editorTitle ?? options.label;
this.glassesEditTitle = options.glassesEditTitle ?? `Edit ${options.label}`;
this.normalizer = options.normalize ?? ((value) => value ?? "");
}
get(): string {
return this.normalizer(ApplicationSettings.getString(this.storageKey, this.defaultValue));
}
set(value: string): string {
const normalized = this.normalizer(value);
ApplicationSettings.setString(this.storageKey, normalized);
return normalized;
}
}
const KNOWN_PLUGIN_IDS = new Set<DashboardPluginId>([ const KNOWN_PLUGIN_IDS = new Set<DashboardPluginId>([
"blank", "blank",
"input-debug-log", "input-debug-log",
@@ -48,136 +151,123 @@ const KNOWN_PLUGIN_IDS = new Set<DashboardPluginId>([
"nightscout", "nightscout",
]); ]);
const DEFAULT_SLOT_CONFIG: DashboardSlotConfig = {
"bottom-left": "input-debug-log", export const bottomLeftSlotSetting = new ConfigSettingEnum<DashboardPluginId>({
"bottom-right": "blank", id: "bottom-left-slot",
label: "Bottom left slot",
storageKey: "dashboard.slot.bottomLeft",
defaultValue: "blank",
values: Array.from(KNOWN_PLUGIN_IDS),
});
export const bottomRightSlotSetting = new ConfigSettingEnum<DashboardPluginId>({
id: "bottom-right-slot",
label: "Bottom right slot",
storageKey: "dashboard.slot.bottomRight",
defaultValue: "blank",
values: Array.from(KNOWN_PLUGIN_IDS),
});
export const dashboardSlotSettings: Record<DashboardSlotId, ConfigSettingEnum<DashboardPluginId>> = {
"bottom-left": bottomLeftSlotSetting,
"bottom-right": bottomRightSlotSetting,
}; };
const DEFAULT_SYSTEM_CARD_SETTINGS: SystemCardSettings = { export const systemCardNameSetting = new ConfigSettingString({
showFaceclawLogo: true, id: "dashboard-name",
showBatteryIndicators: true, label: "Dashboard name",
showAndroidNotifications: true, storageKey: "dashboard.systemCardName",
showSignalStrength: true, defaultValue: "Faceclaw",
}; editorTitle: "Dashboard name",
glassesEditTitle: "Edit dashboard name",
normalize: normalizeSystemCardName,
formatValue: (value) => value || "Faceclaw",
});
export function getDashboardSlotIds(): DashboardSlotId[] { export const showFaceclawLogoSetting = new ConfigSettingBoolean({
return ["bottom-left", "bottom-right"]; id: "showFaceclawLogo",
} label: "Show Faceclaw Logo",
storageKey: "dashboard.systemCard.showFaceclawLogo",
defaultValue: true,
});
export function getDefaultDashboardSlotConfig(): DashboardSlotConfig { export const showBatteryIndicatorsSetting = new ConfigSettingBoolean({
return { ...DEFAULT_SLOT_CONFIG }; id: "showBatteryIndicators",
} label: "Show Battery Indicators",
storageKey: "dashboard.systemCard.showBatteryIndicators",
defaultValue: true,
});
export function loadDashboardSlotConfig(): DashboardSlotConfig { export const showAndroidNotificationsSetting = new ConfigSettingBoolean({
const config = getDefaultDashboardSlotConfig(); id: "showAndroidNotifications",
for (const slot of getDashboardSlotIds()) { label: "Show Android Notifications",
const stored = ApplicationSettings.getString(SLOT_KEYS[slot], config[slot]); storageKey: "dashboard.systemCard.showAndroidNotifications",
config[slot] = normalizePluginId(stored, config[slot]); defaultValue: true,
} });
return config;
}
export function saveDashboardSlotPlugin(slot: DashboardSlotId, pluginId: DashboardPluginId): void { export const showSignalStrengthSetting = new ConfigSettingBoolean({
ApplicationSettings.setString(SLOT_KEYS[slot], pluginId); id: "showSignalStrength",
} label: "Show Signal Strength",
storageKey: "dashboard.systemCard.showSignalStrength",
defaultValue: true,
});
export function saveDashboardSlotConfig(config: DashboardSlotConfig): void { export const screenTimeoutSetting = new ConfigSettingEnum<ScreenTimeoutSetting>({
for (const slot of getDashboardSlotIds()) { id: "screen-timeout",
saveDashboardSlotPlugin(slot, config[slot]); label: "Screen timeout",
} storageKey: "display.screenTimeout",
} defaultValue: "30s",
values: ["15s", "30s", "1m", "never"],
formatValue: screenTimeoutLabel,
});
export function loadSystemCardName(): string { export const wakeModeSetting = new ConfigSettingEnum<WakeModeSetting>({
return normalizeSystemCardName(ApplicationSettings.getString(SYSTEM_CARD_NAME_KEY, DEFAULT_SYSTEM_CARD_NAME)); id: "wake-mode",
} label: "Wake mode",
storageKey: "display.wakeMode",
defaultValue: "tiled",
values: ["tiled", "synchronized"],
formatValue: (value) => value === "tiled" ? "Tiled" : "Synchronized",
});
export function saveSystemCardName(name: string): string { export const voiceControlEnabledSetting = new ConfigSettingBoolean({
const normalized = normalizeSystemCardName(name); id: "voice-control-enabled",
ApplicationSettings.setString(SYSTEM_CARD_NAME_KEY, normalized); label: "Enable",
return normalized; storageKey: "voice.enabled",
} defaultValue: false,
});
export function loadSystemCardSettings(): SystemCardSettings { export const estimateCompressionRatiosSetting = new ConfigSettingBoolean({
return { id: "estimate-compression-ratios",
showFaceclawLogo: ApplicationSettings.getBoolean( label: "Estimate compression ratios",
SYSTEM_CARD_SETTING_KEYS.showFaceclawLogo, storageKey: "debug.estimateCompressionRatios",
DEFAULT_SYSTEM_CARD_SETTINGS.showFaceclawLogo, defaultValue: false,
), });
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,
),
showSignalStrength: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showSignalStrength,
DEFAULT_SYSTEM_CARD_SETTINGS.showSignalStrength,
),
};
}
export function saveSystemCardSetting(key: SystemCardSettingKey, value: boolean): void { export const nightscoutSiteUrlSetting = new ConfigSettingString({
ApplicationSettings.setBoolean(SYSTEM_CARD_SETTING_KEYS[key], value); id: "nightscout-site-url",
} label: "Nightscout site URL",
storageKey: "integrations.nightscout.siteUrl",
defaultValue: "",
editorTitle: "Nightscout site URL",
glassesEditTitle: "Edit Nightscout URL",
normalize: normalizeNightscoutSiteUrl,
formatValue: emptySettingDisplay,
});
export function loadScreenTimeoutSetting(): ScreenTimeoutSetting { export const nightscoutApiTokenSetting = new ConfigSettingString({
return normalizeScreenTimeoutSetting(ApplicationSettings.getString(SCREEN_TIMEOUT_KEY, DEFAULT_SCREEN_TIMEOUT)); id: "nightscout-api-token",
} label: "Nightscout API token",
storageKey: "integrations.nightscout.apiToken",
defaultValue: "",
editorTitle: "Nightscout API token",
glassesEditTitle: "Edit API token",
normalize: normalizeNightscoutApiToken,
formatValue: maskToken,
});
export function saveScreenTimeoutSetting(value: ScreenTimeoutSetting): ScreenTimeoutSetting {
const normalized = normalizeScreenTimeoutSetting(value);
ApplicationSettings.setString(SCREEN_TIMEOUT_KEY, normalized);
return normalized;
}
export function loadWakeModeSetting(): WakeModeSetting { export function screenTimeoutSettingToMs(value: ScreenTimeoutSetting): number | null {
return normalizeWakeModeSetting(ApplicationSettings.getString(WAKE_MODE_KEY, DEFAULT_WAKE_MODE));
}
export function saveWakeModeSetting(value: WakeModeSetting): WakeModeSetting {
const normalized = normalizeWakeModeSetting(value);
ApplicationSettings.setString(WAKE_MODE_KEY, normalized);
return normalized;
}
export function loadVoiceControlEnabled(): boolean {
return ApplicationSettings.getBoolean(VOICE_CONTROL_ENABLED_KEY, DEFAULT_VOICE_CONTROL_ENABLED);
}
export function saveVoiceControlEnabled(value: boolean): boolean {
ApplicationSettings.setBoolean(VOICE_CONTROL_ENABLED_KEY, value);
return value;
}
export function loadEstimateCompressionRatiosEnabled(): boolean {
return ApplicationSettings.getBoolean(
ESTIMATE_COMPRESSION_RATIOS_ENABLED_KEY,
DEFAULT_ESTIMATE_COMPRESSION_RATIOS_ENABLED,
);
}
export function saveEstimateCompressionRatiosEnabled(value: boolean): boolean {
ApplicationSettings.setBoolean(ESTIMATE_COMPRESSION_RATIOS_ENABLED_KEY, value);
return value;
}
export function nextScreenTimeoutSetting(value: ScreenTimeoutSetting): ScreenTimeoutSetting {
switch (value) {
case "15s":
return "30s";
case "30s":
return "1m";
case "1m":
return "never";
case "never":
default:
return "15s";
}
}
export function screenTimeoutMs(value: ScreenTimeoutSetting): number | null {
switch (value) { switch (value) {
case "15s": case "15s":
return 15_000; return 15_000;
@@ -194,35 +284,15 @@ export function screenTimeoutLabel(value: ScreenTimeoutSetting): string {
return value === "never" ? "Never" : value; return value === "never" ? "Never" : value;
} }
export function nextWakeModeSetting(value: WakeModeSetting): WakeModeSetting {
return value === "tiled" ? "synchronized" : "tiled";
}
export function wakeModeLabel(value: WakeModeSetting): string {
return value === "tiled" ? "Tiled" : "Synchronized";
}
export function loadNightscoutSettings(): NightscoutSettings { export function loadNightscoutSettings(): NightscoutSettings {
return { return {
siteUrl: normalizeNightscoutSiteUrl(ApplicationSettings.getString(NIGHTSCOUT_SITE_URL_KEY, "")), siteUrl: nightscoutSiteUrlSetting.get(),
apiToken: normalizeNightscoutApiToken(ApplicationSettings.getString(NIGHTSCOUT_API_TOKEN_KEY, "")), apiToken: nightscoutApiTokenSetting.get(),
}; };
} }
export function saveNightscoutSiteUrl(siteUrl: string): string { export function isNightscoutSettingsConfigured(): boolean {
const normalized = normalizeNightscoutSiteUrl(siteUrl); return nightscoutSiteUrlSetting.get().length > 0 && nightscoutApiTokenSetting.get().length > 0;
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( export function normalizePluginId(
@@ -248,24 +318,112 @@ function normalizeNightscoutApiToken(apiToken: string | null | undefined): strin
return (apiToken ?? "").replace(/[\x00-\x1f]+/g, "").trim(); return (apiToken ?? "").replace(/[\x00-\x1f]+/g, "").trim();
} }
function normalizeScreenTimeoutSetting(value: string | null | undefined): ScreenTimeoutSetting { function emptySettingDisplay(value: string): string {
switch (value) { return value || "(empty)";
case "15s":
case "30s":
case "1m":
case "never":
return value;
default:
return DEFAULT_SCREEN_TIMEOUT;
}
} }
function normalizeWakeModeSetting(value: string | null | undefined): WakeModeSetting { function maskToken(token: string): string {
switch (value) { if (!token) return "(empty)";
case "tiled": return token.length <= 6 ? "******" : `${token.slice(0, 2)}...${token.slice(-4)}`;
case "synchronized": }
return value;
default:
return DEFAULT_WAKE_MODE; type SettingsMenuOptions<T> = {
style?: "cycle"|"submenu"
onChange?: (newValue: T, oldValue: T) => void
}
export function enumSettingMenuItem<TValue extends string, TId extends string = string>(
setting: ConfigSettingEnum<TValue, TId>,
opts?: SettingsMenuOptions<TValue>
): MenuItem {
const style = opts?.style ?? "cycle";
return {
label: setting.label,
onSelect: (ctx) => {
if (style === "cycle") {
const oldValue = setting.get();
const newValue = setting.next(oldValue);
setting.set(newValue);
opts?.onChange?.(newValue, oldValue);
} else {
const submenu = new MenuLayer(setting.label, setting.values.map((value) => ({
label: value,
onSelect: () => {
setting.set(value);
opts?.onChange?.(value, setting.get());
ctx.stack.pop();
},
render: ({ image, x, y }) => {
const selected = setting.get() === value ? " *" : "";
image.drawText(getDefaultSmallFont(), x, y + 3, `${value}${selected}`, 200);
}
})));
ctx.stack.push(submenu);
}
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, setting.label, setting.displayValue(setting.get()));
},
};
}
export function toggleSettingMenuItem<TId extends string = string>(
setting: ConfigSettingBoolean<TId>,
opts?: SettingsMenuOptions<boolean>
): MenuItem {
return {
label: setting.label,
onSelect: () => {
setting.set(!setting.get());
opts?.onChange?.(setting.get(), !setting.get());
},
render: ({ image, x, y, width, selected }) => {
drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width, setting.label, setting.get(), selected);
},
};
}
export function textSettingMenuItem<TId extends string = string>(
setting: ConfigSettingString<TId>,
opts?: SettingsMenuOptions<string>
): MenuItem {
return {
label: setting.label,
onSelect: (ctx: LayerContext) => {
void ctx.actions.startTextSettingEdit(setting);
ctx.stack.push(new EditTextSettingLayer(setting));
},
render: ({ image, x, y, width, selected }) => {
image.drawText(getDefaultSmallFont(), x, y + 3, `${setting.label}: ${truncateSetting(setting.get())}`, 200);
}
};
}
function truncateSetting(value: string, maxLength = 22): string {
const text = value || "(empty)";
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
class EditTextSettingLayer implements Layer {
constructor(private readonly setting: ConfigSettingString) {}
paint(): GrayImage {
const font = getDefaultSmallFont();
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(font, 22, 16, this.setting.glassesEditTitle, 220);
image.drawText(font, 22, 52, "Look at the phone app", 200);
image.drawText(font, 22, 70, "to type a value.", 200);
image.drawText(font, 22, 110, truncateSetting(this.setting.get(), 52), 220);
image.drawText(font, 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();
}
} }
} }
+72 -309
View File
@@ -1,57 +1,43 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../graphics/bdffont"; import { getDefaultSmallFont } from "../graphics/bdffont";
import { loadPngAsGrayImage } from "../graphics/imagefile";
import { type RawInputEvent } from "../native/faceclaw-communicator"; import { type RawInputEvent } from "../native/faceclaw-communicator";
import { mediaControllerBridge } from "../native/media-controller"; import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout-bridge"; import { nightscoutBridge } from "../native/nightscout-bridge";
import { EventSourceType, OsEventTypeList } from "../g2/events"; import { EventSourceType, OsEventTypeList } from "../g2/events";
import { getDashboardPlugin, isBlankDashboardPlugin, type DashboardPluginCardBounds, type DashboardPluginState } from "./dashboard-plugins";
import { import {
getDashboardPlugin, estimateCompressionRatiosSetting,
isBlankDashboardPlugin,
listDashboardPlugins,
type DashboardPluginCardBounds,
type DashboardPluginState,
} from "./dashboard-plugins";
import {
getDashboardSlotIds,
isNightscoutSettingsConfigured, isNightscoutSettingsConfigured,
loadDashboardSlotConfig, nightscoutApiTokenSetting,
loadEstimateCompressionRatiosEnabled, nightscoutSiteUrlSetting,
loadNightscoutSettings, screenTimeoutSettingToMs,
loadScreenTimeoutSetting, screenTimeoutSetting,
loadSystemCardSettings, systemCardNameSetting,
loadSystemCardName, voiceControlEnabledSetting,
loadVoiceControlEnabled, wakeModeSetting,
loadWakeModeSetting,
nextScreenTimeoutSetting,
nextWakeModeSetting,
saveDashboardSlotPlugin,
saveEstimateCompressionRatiosEnabled,
saveNightscoutApiToken,
saveNightscoutSiteUrl,
saveScreenTimeoutSetting,
saveWakeModeSetting,
screenTimeoutLabel,
screenTimeoutMs,
saveSystemCardSetting,
saveSystemCardName,
saveVoiceControlEnabled,
wakeModeLabel,
type DashboardSlotId, type DashboardSlotId,
type NightscoutSettings, DashboardPluginId,
type ScreenTimeoutSetting, bottomRightSlotSetting,
type SystemCardSettingKey, bottomLeftSlotSetting,
type WakeModeSetting, dashboardSlotSettings,
dashboardSlotIds,
enumSettingMenuItem,
toggleSettingMenuItem,
showFaceclawLogoSetting,
showBatteryIndicatorsSetting,
showAndroidNotificationsSetting,
showSignalStrengthSetting,
textSettingMenuItem,
} from "./dashboard-settings"; } from "./dashboard-settings";
import { Layer, LayerActions, LayerStack, type DashboardInputEvent, type LayerContext } from "./layers"; import { Layer, LayerActions, LayerStack, type DashboardInputEvent, type LayerContext } from "./layers";
import { drawRightValueMenuItem, drawToggleMenuItem, MenuLayer } from "./menu"; import { MenuLayer } from "./menu";
import { StopwatchLayer } from "./apps/stopwatch"; import { StopwatchLayer } from "./apps/stopwatch";
import { NotificationsListLayer, SingleNotificationLayer } from "./notifications"; import { NotificationsListLayer, SingleNotificationLayer } from "./notifications";
import { TranscribeLayer } from "./apps/transcribe"; import { TranscribeLayer } from "./apps/transcribe";
import { TelepromptLayer } from "./apps/teleprompt"; import { TelepromptLayer } from "./apps/teleprompt";
import { ScreenTestLayer } from "./apps/screen-test"; import { ScreenTestLayer } from "./apps/screen-test";
import { getDashboardLogo } from "~/graphics/logo"; import { getDashboardLogo } from "~/graphics/logo";
import { drawSystemCard, getDisplayedSystemCardName } from "./dashboard/system-card"; import { drawSystemCard } from "./dashboard/system-card";
type DashboardCardId = "system" | DashboardSlotId; type DashboardCardId = "system" | DashboardSlotId;
export type DashboardBatteryLevels = { export type DashboardBatteryLevels = {
@@ -60,20 +46,21 @@ export type DashboardBatteryLevels = {
ring: number | null; ring: number | null;
}; };
export let dashboardState = { type DashboardState = {
logLines: string[];
screenOn: boolean;
lastInputAtMs: number;
tiledWakePaintPending: boolean;
telepromptDocumentText: string | null;
battery: DashboardBatteryLevels;
};
export let dashboardState: DashboardState = {
logLines: [] as string[], logLines: [] as string[],
screenOn: true, screenOn: true,
lastInputAtMs: Date.now(), lastInputAtMs: Date.now(),
slotConfig: loadDashboardSlotConfig(),
systemCardName: loadSystemCardName(),
systemCardSettings: loadSystemCardSettings(),
screenTimeout: loadScreenTimeoutSetting(),
wakeMode: loadWakeModeSetting(),
voiceControlEnabled: loadVoiceControlEnabled(),
estimateCompressionRatiosEnabled: loadEstimateCompressionRatiosEnabled(),
tiledWakePaintPending: false, tiledWakePaintPending: false,
telepromptDocumentText: null as string | null, telepromptDocumentText: null as string | null,
nightscoutSettings: loadNightscoutSettings(),
battery: { battery: {
headset: null, headset: null,
headsetCharging: null, headsetCharging: null,
@@ -83,10 +70,7 @@ export let dashboardState = {
const dashboardActions: LayerActions = { const dashboardActions: LayerActions = {
disconnect: () => {}, disconnect: () => {},
startSystemNameEdit: () => {}, startTextSettingEdit: () => {},
endSystemNameEdit: () => {},
startNightscoutSiteUrlEdit: () => {},
startNightscoutApiTokenEdit: () => {},
endTextSettingEdit: () => {}, endTextSettingEdit: () => {},
setVoiceControlEnabled: () => {}, setVoiceControlEnabled: () => {},
setStopwatchRenderActive: () => {}, setStopwatchRenderActive: () => {},
@@ -143,7 +127,7 @@ export async function receiveInput(event: RawInputEvent): Promise<void> {
if (!dashboardState.screenOn) { if (!dashboardState.screenOn) {
if (inputEvent.type === "double-click") { if (inputEvent.type === "double-click") {
dashboardState.screenOn = true; dashboardState.screenOn = true;
dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled";
if (dashboardLayers.isAtBase()) { if (dashboardLayers.isAtBase()) {
dashboardLayers.push(createRootMenuLayer()); dashboardLayers.push(createRootMenuLayer());
} }
@@ -190,60 +174,8 @@ export function consumeDashboardTiledWakePaint(): boolean {
return value; return value;
} }
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 isDashboardVoiceControlEnabled(): boolean {
return dashboardState.voiceControlEnabled;
}
export function setDashboardVoiceControlEnabled(value: boolean): void {
dashboardState.voiceControlEnabled = saveVoiceControlEnabled(value);
}
export function isDashboardCompressionRatioEstimationEnabled(): boolean {
return dashboardState.estimateCompressionRatiosEnabled;
}
export function applyDashboardScreenTimeout(nowMs = Date.now()): boolean { export function applyDashboardScreenTimeout(nowMs = Date.now()): boolean {
const timeoutMs = screenTimeoutMs(dashboardState.screenTimeout); const timeoutMs = screenTimeoutSettingToMs(screenTimeoutSetting.get());
if (timeoutMs === null || !dashboardState.screenOn) return false; if (timeoutMs === null || !dashboardState.screenOn) return false;
if (nowMs - dashboardState.lastInputAtMs < timeoutMs) return false; if (nowMs - dashboardState.lastInputAtMs < timeoutMs) return false;
dashboardState.screenOn = false; dashboardState.screenOn = false;
@@ -270,7 +202,7 @@ export function openAndroidNotificationFromSleep(notificationKey: string, nowMs
dashboardState.lastInputAtMs = nowMs; dashboardState.lastInputAtMs = nowMs;
dashboardState.screenOn = true; dashboardState.screenOn = true;
dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled";
dashboardLayers.clearToBase(); dashboardLayers.clearToBase();
dashboardLayers.push(createRootMenuLayer()); dashboardLayers.push(createRootMenuLayer());
dashboardLayers.push(new SingleNotificationLayer(notificationKey)); dashboardLayers.push(new SingleNotificationLayer(notificationKey));
@@ -282,7 +214,7 @@ export function resetDashboardSleepTimerAndWake(nowMs = Date.now()): boolean {
if (dashboardState.screenOn) return false; if (dashboardState.screenOn) return false;
dashboardState.screenOn = true; dashboardState.screenOn = true;
dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled";
dashboardLayers.clearToBase(); dashboardLayers.clearToBase();
dashboardLayers.push(createRootMenuLayer()); dashboardLayers.push(createRootMenuLayer());
return true; return true;
@@ -295,6 +227,15 @@ export function setDashboardBatteryLevels(levels: Partial<DashboardBatteryLevels
}; };
} }
function getPluginIdForSlot(slot: DashboardSlotId): DashboardPluginId {
switch (slot) {
case "bottom-left":
return bottomLeftSlotSetting.get();
case "bottom-right":
return bottomRightSlotSetting.get();
}
}
class DashboardLayer implements Layer { class DashboardLayer implements Layer {
paint(): GrayImage { paint(): GrayImage {
@@ -306,9 +247,9 @@ class DashboardLayer implements Layer {
const pluginState = getPluginState(); const pluginState = getPluginState();
drawSystemCard(image, getCardBounds("system")); drawSystemCard(image, getCardBounds("system"));
for (const slot of getDashboardSlotIds()) { for (const slot of dashboardSlotIds) {
const bounds = getCardBounds(slot); const bounds = getCardBounds(slot);
const pluginId = dashboardState.slotConfig[slot]; const pluginId = getPluginIdForSlot(slot);
getDashboardPlugin(pluginId).renderCard({ getDashboardPlugin(pluginId).renderCard({
image, image,
bounds, bounds,
@@ -371,8 +312,8 @@ function createRootMenuLayer(): MenuLayer {
ctx.stack.push(createSettingsMenuLayer()); ctx.stack.push(createSettingsMenuLayer());
}, },
}, },
...getDashboardSlotIds() ...dashboardSlotIds
.filter((slot) => !isBlankDashboardPlugin(dashboardState.slotConfig[slot])) .filter((slot) => !isBlankDashboardPlugin(getPluginIdForSlot(slot)))
.map((slot) => ({ .map((slot) => ({
label: pluginLabelForSlot(slot), label: pluginLabelForSlot(slot),
onSelect: (ctx: LayerContext) => { onSelect: (ctx: LayerContext) => {
@@ -452,11 +393,11 @@ function createSystemMenuLayer(): MenuLayer {
} }
function openDashboardSlot(slot: DashboardSlotId, ctx: LayerContext): void { function openDashboardSlot(slot: DashboardSlotId, ctx: LayerContext): void {
const pluginId = dashboardState.slotConfig[slot]; const pluginId = getPluginIdForSlot(slot);
if (isBlankDashboardPlugin(pluginId)) { if (isBlankDashboardPlugin(pluginId)) {
return; return;
} }
if (pluginId === "nightscout" && !isNightscoutSettingsConfigured(dashboardState.nightscoutSettings)) { if (pluginId === "nightscout" && !isNightscoutSettingsConfigured()) {
ctx.stack.push(createNightscoutSettingsMenuLayer()); ctx.stack.push(createNightscoutSettingsMenuLayer());
return; return;
} }
@@ -503,73 +444,23 @@ function createDisplaySettingsMenuLayer(): MenuLayer {
return new MenuLayer( return new MenuLayer(
"Settings > Display", "Settings > Display",
[ [
{ enumSettingMenuItem(screenTimeoutSetting, {
label: "Screen timeout", onChange: (newValue, oldValue) => {
onSelect: () => { dashboardState.lastInputAtMs = Date.now();
setScreenTimeout(nextScreenTimeoutSetting(dashboardState.screenTimeout));
}, },
render: ({ image, x, y, width }) => { }),
drawRightValueMenuItem(image, dashboardFont, x, y, width, "Screen timeout", screenTimeoutLabel(dashboardState.screenTimeout)); enumSettingMenuItem(wakeModeSetting),
}, toggleSettingMenuItem(estimateCompressionRatiosSetting),
},
{
label: "Wake mode",
onSelect: () => {
setWakeMode(nextWakeModeSetting(dashboardState.wakeMode));
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, dashboardFont, x, y, width, "Wake mode", wakeModeLabel(dashboardState.wakeMode));
},
},
{
label: "Estimate compression ratios",
onSelect: () => {
setEstimateCompressionRatiosEnabled(!dashboardState.estimateCompressionRatiosEnabled);
},
render: ({ image, x, y, width, selected }) => {
drawToggleMenuItem(
image,
dashboardFont,
x,
y,
width,
"Estimate compression ratios",
dashboardState.estimateCompressionRatiosEnabled,
selected,
);
},
},
], ],
TOP_LEFT_MENU_LAYOUT, TOP_LEFT_MENU_LAYOUT,
); );
} }
function setScreenTimeout(value: ScreenTimeoutSetting): void {
dashboardState.screenTimeout = saveScreenTimeoutSetting(value);
dashboardState.lastInputAtMs = Date.now();
}
function setWakeMode(value: WakeModeSetting): void {
dashboardState.wakeMode = saveWakeModeSetting(value);
}
function setEstimateCompressionRatiosEnabled(value: boolean): void {
dashboardState.estimateCompressionRatiosEnabled = saveEstimateCompressionRatiosEnabled(value);
}
function createVoiceSettingsMenuLayer(): MenuLayer { function createVoiceSettingsMenuLayer(): MenuLayer {
return new MenuLayer( return new MenuLayer(
"Settings > Voice", "Settings > Voice",
[ [
{ toggleSettingMenuItem(voiceControlEnabledSetting),
label: "Enable",
onSelect: async (ctx) => {
await ctx.actions.setVoiceControlEnabled(!dashboardState.voiceControlEnabled);
},
render: ({ image, x, y, width, selected }) => {
drawToggleMenuItem(image, dashboardFont, x, y, width, "Enable", dashboardState.voiceControlEnabled, selected);
},
},
], ],
TOP_LEFT_MENU_LAYOUT, TOP_LEFT_MENU_LAYOUT,
); );
@@ -585,14 +476,8 @@ function createDashboardSettingsMenuLayer(): MenuLayer {
ctx.stack.push(createSystemCardSettingsMenuLayer()); ctx.stack.push(createSystemCardSettingsMenuLayer());
}, },
}, },
...getDashboardSlotIds().map((slot) => ({ ...dashboardSlotIds.map((slot) => enumSettingMenuItem(dashboardSlotSettings[slot], {
label: slotMenuLabel(slot), style: "submenu",
onSelect: (ctx) => {
ctx.stack.push(createSlotPickerMenu(slot));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 3, `${slotMenuLabel(slot)}: ${pluginLabelForSlot(slot)}`, 200);
},
})), })),
], ],
TOP_LEFT_MENU_LAYOUT, TOP_LEFT_MENU_LAYOUT,
@@ -603,37 +488,16 @@ function createSystemCardSettingsMenuLayer(): MenuLayer {
return new MenuLayer( return new MenuLayer(
"Settings > Dashboard > System Card", "Settings > Dashboard > System Card",
[ [
{ textSettingMenuItem(systemCardNameSetting),
label: "Name", toggleSettingMenuItem(showFaceclawLogoSetting),
onSelect: (ctx) => { toggleSettingMenuItem(showBatteryIndicatorsSetting),
void ctx.actions.startSystemNameEdit(); toggleSettingMenuItem(showAndroidNotificationsSetting),
ctx.stack.push(new EditSystemNameLayer()); toggleSettingMenuItem(showSignalStrengthSetting),
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 3, `Name: ${getDisplayedSystemCardName()}`, 200);
},
},
createSystemCardToggleItem("Show Faceclaw Logo", "showFaceclawLogo"),
createSystemCardToggleItem("Show Battery Indicators", "showBatteryIndicators"),
createSystemCardToggleItem("Show Android Notifications", "showAndroidNotifications"),
createSystemCardToggleItem("Show Signal Strength", "showSignalStrength"),
], ],
TOP_LEFT_MENU_LAYOUT, TOP_LEFT_MENU_LAYOUT,
); );
} }
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, dashboardFont, x, y, width, label, dashboardState.systemCardSettings[key], selected);
},
};
}
function createIntegrationsMenuLayer(): MenuLayer { function createIntegrationsMenuLayer(): MenuLayer {
return new MenuLayer( return new MenuLayer(
"Settings > Integrations", "Settings > Integrations",
@@ -653,95 +517,13 @@ function createNightscoutSettingsMenuLayer(): MenuLayer {
return new MenuLayer( return new MenuLayer(
"Settings > Integrations > Nightscout", "Settings > Integrations > Nightscout",
[ [
{ textSettingMenuItem(nightscoutSiteUrlSetting),
label: "Site URL", textSettingMenuItem(nightscoutApiTokenSetting),
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 + 3, `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 + 3, `Token: ${maskToken(dashboardState.nightscoutSettings.apiToken)}`, 200);
},
},
], ],
TOP_LEFT_MENU_LAYOUT, TOP_LEFT_MENU_LAYOUT,
); );
} }
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(getDefaultMediumFont(), 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(
`Settings > Dashboard > ${slotMenuLabel(slot)}`,
listDashboardPlugins().map((plugin) => ({
label: plugin.label,
onSelect: (ctx) => {
dashboardState.slotConfig[slot] = plugin.id;
saveDashboardSlotPlugin(slot, plugin.id);
ctx.stack.pop();
},
render: ({ image, x, y }) => {
const selected = dashboardState.slotConfig[slot] === plugin.id ? " *" : "";
image.drawText(dashboardFont, x, y + 3, `${plugin.label}${selected}`, 200);
},
})),
TOP_LEFT_MENU_LAYOUT,
);
}
class AboutLayer implements Layer { class AboutLayer implements Layer {
paint(): GrayImage { paint(): GrayImage {
@@ -776,7 +558,7 @@ function getPluginState(): DashboardPluginState {
logLines: dashboardState.logLines, logLines: dashboardState.logLines,
media: mediaControllerBridge.snapshot(), media: mediaControllerBridge.snapshot(),
nightscout: nightscoutBridge.snapshot(), nightscout: nightscoutBridge.snapshot(),
nightscoutConfigured: isNightscoutSettingsConfigured(dashboardState.nightscoutSettings), nightscoutConfigured: isNightscoutSettingsConfigured(),
}; };
} }
@@ -806,27 +588,8 @@ function getCardBounds(card: DashboardCardId): DashboardPluginCardBounds {
} }
} }
function slotMenuLabel(slot: DashboardSlotId): string {
switch (slot) {
case "bottom-left":
return "Bottom-left";
case "bottom-right":
return "Bottom-right";
}
}
function pluginLabelForSlot(slot: DashboardSlotId): string { function pluginLabelForSlot(slot: DashboardSlotId): string {
return getDashboardPlugin(dashboardState.slotConfig[slot]).label; return getDashboardPlugin(getPluginIdForSlot(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(), dashboardActions); const dashboardLayers = new LayerStack(new DashboardLayer(), dashboardActions);
+7 -12
View File
@@ -7,7 +7,7 @@ import { type DashboardPluginCardBounds } from "../dashboard-plugins";
import { dashboardState } from "../dashboard"; import { dashboardState } from "../dashboard";
import { getDefaultMediumFont, getDefaultSmallFont } from "~/graphics/bdffont"; import { getDefaultMediumFont, getDefaultSmallFont } from "~/graphics/bdffont";
import { getDashboardLogo } from "~/graphics/logo"; import { getDashboardLogo } from "~/graphics/logo";
import { DEFAULT_SYSTEM_CARD_NAME } from "../dashboard-settings"; import { showAndroidNotificationsSetting, showBatteryIndicatorsSetting, showFaceclawLogoSetting, showSignalStrengthSetting, systemCardNameSetting } from "../dashboard-settings";
const NOTIFICATION_ICON_SIZE = 24; const NOTIFICATION_ICON_SIZE = 24;
const SYSTEM_CARD_ITEM_HEIGHT = 38; const SYSTEM_CARD_ITEM_HEIGHT = 38;
@@ -29,14 +29,14 @@ function drawSystemCardFlowItems(image: GrayImage, bounds: DashboardPluginCardBo
const right = bounds.x + bounds.width - 10; const right = bounds.x + bounds.width - 10;
const bottom = bounds.y + bounds.height - 6; const bottom = bounds.y + bounds.height - 6;
const items: SystemCardFlowItem[] = []; const items: SystemCardFlowItem[] = [];
if (dashboardState.systemCardSettings.showAndroidNotifications) { if (showAndroidNotificationsSetting.get()) {
const maxNotificationIcons = Math.max(0, ((right - left) / Math.max(1, NOTIFICATION_ICON_SIZE + SYSTEM_CARD_ITEM_GAP)) | 0) * 2; 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)) { for (const icon of readActiveNotificationIcons(maxNotificationIcons)) {
items.push({ type: "notification", icon }); items.push({ type: "notification", icon });
} }
} }
items.push(...collectBatteryItems()); items.push(...collectBatteryItems());
if (dashboardState.systemCardSettings.showSignalStrength) { if (showSignalStrengthSetting.get()) {
for (const icon of readSystemStatusIcons()) { for (const icon of readSystemStatusIcons()) {
items.push({ type: "notification", icon }); items.push({ type: "notification", icon });
} }
@@ -74,7 +74,7 @@ function systemCardFlowItemWidth(item: SystemCardFlowItem): number {
} }
function collectBatteryItems(): SystemCardFlowItem[] { function collectBatteryItems(): SystemCardFlowItem[] {
if (!dashboardState.systemCardSettings.showBatteryIndicators) return []; if (!showBatteryIndicatorsSetting.get()) return [];
const phone = readPhoneBatteryState(); const phone = readPhoneBatteryState();
const items: SystemCardFlowItem[] = []; const items: SystemCardFlowItem[] = [];
addBatteryItem(items, "Phone", phone.battery, phone.charging); addBatteryItem(items, "Phone", phone.battery, phone.charging);
@@ -114,20 +114,15 @@ function pad2(value: number): string {
return String(value).padStart(2, "0"); return String(value).padStart(2, "0");
} }
export function getDisplayedSystemCardName(): string {
return dashboardState.systemCardName || DEFAULT_SYSTEM_CARD_NAME;
}
export function drawSystemCard(image: GrayImage, bounds: DashboardPluginCardBounds): void { export function drawSystemCard(image: GrayImage, bounds: DashboardPluginCardBounds): void {
const now = new Date(); const now = new Date();
const logo = getDashboardLogo(); const logo = getDashboardLogo();
if (logo && dashboardState.systemCardSettings.showFaceclawLogo) { if (logo && showFaceclawLogoSetting.get()) {
image.bitBlt(logo, bounds.x + 10, bounds.y + 10); image.bitBlt(logo, bounds.x + 10, bounds.y + 10);
} }
const infoX = logo && dashboardState.systemCardSettings.showFaceclawLogo ? bounds.x + 92 : bounds.x + 10; const infoX = logo && showFaceclawLogoSetting.get() ? bounds.x + 92 : bounds.x + 10;
image.drawText(mediumFont, infoX, bounds.y + 10, getDisplayedSystemCardName(), 200); image.drawText(mediumFont, infoX, bounds.y + 10, systemCardNameSetting.get(), 200);
image.drawText(mediumFont, infoX, bounds.y + 32, formatDashboardDate(now), 200); image.drawText(mediumFont, infoX, bounds.y + 32, formatDashboardDate(now), 200);
drawSystemCardFlowItems(image, bounds); drawSystemCardFlowItems(image, bounds);
} }
+2 -4
View File
@@ -1,5 +1,6 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
import { BdfFont } from "../graphics/bdffont"; import { BdfFont } from "../graphics/bdffont";
import { type ConfigSettingString } from "./dashboard-settings";
export type DashboardInputEvent = export type DashboardInputEvent =
| { type: "click"; source: "ring" | "left-arm" | "right-arm" } | { type: "click"; source: "ring" | "left-arm" | "right-arm" }
@@ -10,10 +11,7 @@ export type DashboardInputEvent =
export type LayerActions = { export type LayerActions = {
disconnect: () => Promise<void> | void; disconnect: () => Promise<void> | void;
startSystemNameEdit: () => Promise<void> | void; startTextSettingEdit: (setting: ConfigSettingString) => Promise<void> | void;
endSystemNameEdit: () => Promise<void> | void;
startNightscoutSiteUrlEdit: () => Promise<void> | void;
startNightscoutApiTokenEdit: () => Promise<void> | void;
endTextSettingEdit: () => Promise<void> | void; endTextSettingEdit: () => Promise<void> | void;
setVoiceControlEnabled: (enabled: boolean) => Promise<void> | void; setVoiceControlEnabled: (enabled: boolean) => Promise<void> | void;
setStopwatchRenderActive: (active: boolean) => Promise<void> | void; setStopwatchRenderActive: (active: boolean) => Promise<void> | void;