From 5da3b48c7dd39de3b65facfe78f371144b5ca965 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Mon, 1 Jun 2026 15:33:45 -0700 Subject: [PATCH] Refactor settings --- app/g2/dashboard-controller.ts | 138 ++------- app/native/nightscout-bridge.ts | 19 +- app/phone-ui/main-page.ts | 2 +- app/phone-ui/main-view-model.ts | 51 +--- app/ui/apps/debug-log.ts | 2 +- app/ui/apps/music-controller.ts | 2 +- app/ui/apps/nightscout.ts | 2 +- app/ui/dashboard-plugin.ts | 45 +++ app/ui/dashboard-plugins.ts | 80 ++--- app/ui/dashboard-settings.ts | 512 +++++++++++++++++++++----------- app/ui/dashboard.ts | 381 +++++------------------- app/ui/dashboard/system-card.ts | 19 +- app/ui/layers.ts | 6 +- 13 files changed, 538 insertions(+), 721 deletions(-) create mode 100644 app/ui/dashboard-plugin.ts diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 8d6addf1..b62ef994 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -16,10 +16,6 @@ import { applyDashboardScreenTimeout, consumeDashboardTiledWakePaint, drawDashboard, - getDashboardNightscoutSettings, - getDashboardSystemCardName, - isDashboardCompressionRatioEstimationEnabled, - isDashboardVoiceControlEnabled, noteDashboardPhoneTextInput, openAndroidNotificationFromSleep, openTelepromptDocument, @@ -27,23 +23,24 @@ import { resetDashboardSleepTimerAndWake, setDashboardBatteryLevels, setDashboardActions, - setDashboardNightscoutApiToken, - setDashboardNightscoutSiteUrl, - setDashboardSystemCardName, - setDashboardVoiceControlEnabled, } from "../ui/dashboard"; +import { + estimateCompressionRatiosSetting, + nightscoutApiTokenSetting, + nightscoutSiteUrlSetting, + systemCardNameSetting, + voiceControlEnabledSetting, + type ConfigSettingString, +} from "../ui/dashboard-settings"; type ConnectionPhase = "disconnected" | "connecting" | "connected" | "disconnecting"; -export type TextSettingEditorKind = "dashboard-name" | "nightscout-site-url" | "nightscout-api-token"; export type DashboardSnapshot = { phase: ConnectionPhase; status: string; log: string; displayPreview: ImageSource | null; - systemCardName: string; - editingSystemCardName: boolean; - activeTextSettingEditorKind: TextSettingEditorKind | null; + activeTextSettingId: string | null; activeTextSettingTitle: string; activeTextSettingValue: string; evenAppConflictMessage: string; @@ -119,8 +116,7 @@ class DashboardController { private phase: ConnectionPhase = "disconnected"; private status = "Disconnected."; private log = ""; - private editingSystemCardName = false; - private activeTextSettingEditorKind: TextSettingEditorKind | null = null; + private activeTextSetting: ConfigSettingString | null = null; private evenNotificationActive = false; private evenAppConflictMessage = ""; private displayPreview: ImageSource | null = createInitialDisplayPreview(); @@ -154,10 +150,7 @@ class DashboardController { constructor() { setDashboardActions({ disconnect: () => this.disconnect(), - startSystemNameEdit: () => this.startSystemNameEdit(), - endSystemNameEdit: () => this.endSystemNameEdit(), - startNightscoutSiteUrlEdit: () => this.startNightscoutSiteUrlEdit(), - startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(), + startTextSettingEdit: (setting) => this.startTextSettingEdit(setting), endTextSettingEdit: () => this.endTextSettingEdit(), setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled), setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active), @@ -186,11 +179,9 @@ class DashboardController { status: this.status, log: this.log, displayPreview: this.displayPreview, - systemCardName: getDashboardSystemCardName(), - editingSystemCardName: this.editingSystemCardName, - activeTextSettingEditorKind: this.activeTextSettingEditorKind, - activeTextSettingTitle: this.getActiveTextSettingTitle(), - activeTextSettingValue: this.getActiveTextSettingValue(), + activeTextSettingId: this.activeTextSetting?.id ?? null, + activeTextSettingTitle: this.activeTextSetting?.editorTitle ?? "", + activeTextSettingValue: this.activeTextSetting?.get() ?? "", evenAppConflictMessage: this.evenAppConflictMessage, evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0, }; @@ -218,49 +209,13 @@ class DashboardController { } setSystemCardName(name: string): void { - const savedName = setDashboardSystemCardName(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(); - } + this.updateTextSetting(systemCardNameSetting, name); } setActiveTextSettingValue(value: string): void { noteDashboardPhoneTextInput(); - switch (this.activeTextSettingEditorKind) { - case "dashboard-name": - 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(); + if (!this.activeTextSetting) return; + this.updateTextSetting(this.activeTextSetting, value); } async connect(): Promise { @@ -505,21 +460,8 @@ class DashboardController { this.updateDisplayPreviewFromImage(image); } - private startSystemNameEdit(): void { - this.editingSystemCardName = true; - 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"; + private startTextSettingEdit(setting: ConfigSettingString): void { + this.activeTextSetting = setting; this.emit(); } @@ -535,7 +477,7 @@ class DashboardController { } } - setDashboardVoiceControlEnabled(enabled); + voiceControlEnabledSetting.set(enabled); this.appendLog(`Voice control ${enabled ? "enabled" : "disabled"}.`); if (enabled) { this.startVoiceControlIfEnabled(); @@ -550,39 +492,19 @@ class DashboardController { } private endTextSettingEdit(): void { - const finishedKind = this.activeTextSettingEditorKind; - this.editingSystemCardName = false; - this.activeTextSettingEditorKind = null; + const finishedSetting = this.activeTextSetting; + this.activeTextSetting = null; this.emit(); - if (finishedKind === "nightscout-site-url" || finishedKind === "nightscout-api-token") { + if (finishedSetting === nightscoutSiteUrlSetting || finishedSetting === nightscoutApiTokenSetting) { void this.refreshNightscoutAfterSettingsChange(); } } - private getActiveTextSettingTitle(): string { - switch (this.activeTextSettingEditorKind) { - case "dashboard-name": - return "Dashboard name"; - case "nightscout-site-url": - 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 ""; + private updateTextSetting(setting: ConfigSettingString, value: string): void { + if (setting.get() !== value) { + setting.set(value); + this.emit(); + this.previewOrRenderAfterTextSettingChange(setting.label); } } @@ -639,7 +561,7 @@ class DashboardController { const forceTiledCommit = consumeDashboardTiledWakePaint(); const fingerprint = image.fingerprint(); const imageTiles = image.toEvenHubTiles(); - if (isDashboardCompressionRatioEstimationEnabled()) { + if (estimateCompressionRatiosSetting.get()) { this.logCompressionEstimate(imageTiles); } const tiles = imageTiles.map((tile) => tile.bmp); @@ -735,7 +657,7 @@ class DashboardController { private startVoiceControlIfEnabled(): void { if (!this.communicator) return; - if (!isDashboardVoiceControlEnabled()) return; + if (!voiceControlEnabledSetting.get()) return; this.updateConnectedForegroundNotification(); voiceControlBridge.start(this.communicator.getNativeCommunicator(), "wakeword"); } diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts index 9f51c1ac..3b44518c 100644 --- a/app/native/nightscout-bridge.ts +++ b/app/native/nightscout-bridge.ts @@ -1,4 +1,4 @@ -import { loadNightscoutSettings } from "../ui/dashboard-settings"; +import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings"; export type NightscoutPoint = { timestampMs: number; @@ -181,8 +181,9 @@ export class NightscoutBridge { private async refresh(): Promise { try { const nowMs = Date.now(); - const settings = loadNightscoutSettings(); - if (!settings.siteUrl || !settings.apiToken) { + const siteUrl = nightscoutSiteUrlSetting.get(); + const apiToken = nightscoutApiTokenSetting.get(); + if (!siteUrl || !apiToken) { this.state = { ...DEFAULT_NIGHTSCOUT_STATE, status: "Configure Nightscout site URL and API token.", @@ -192,22 +193,22 @@ export class NightscoutBridge { return; } 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([ fetchJson( - `${settings.siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`, + `${siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`, ), fetchJson( - `${settings.siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`, + `${siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`, ), fetchJson( - `${settings.siteUrl}/api/v1/status.json?${tokenQuery}`, + `${siteUrl}/api/v1/status.json?${tokenQuery}`, ), fetchJson( - `${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( - `${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}`, ), ]); diff --git a/app/phone-ui/main-page.ts b/app/phone-ui/main-page.ts index 4fd726db..49ad4658 100644 --- a/app/phone-ui/main-page.ts +++ b/app/phone-ui/main-page.ts @@ -128,7 +128,7 @@ export function loaded(args: EventData) { } return } - if (propertyArgs.propertyName === 'activeTextSettingEditorKind') { + if (propertyArgs.propertyName === 'activeTextSettingId') { if (model.isTextSettingEditorActive) { focusSystemNameField(page) } diff --git a/app/phone-ui/main-view-model.ts b/app/phone-ui/main-view-model.ts index 48b5df1e..34a1df53 100644 --- a/app/phone-ui/main-view-model.ts +++ b/app/phone-ui/main-view-model.ts @@ -1,5 +1,5 @@ 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"; @@ -8,9 +8,7 @@ export class MainViewModel extends Observable { private _log = ""; private _displayPreview: ImageSource | null = null; private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation(); - private _systemCardName = "Faceclaw"; - private _editingSystemCardName = false; - private _activeTextSettingEditorKind: TextSettingEditorKind | null = null; + private _activeTextSettingId: string | null = null; private _activeTextSettingTitle = ""; private _activeTextSettingValue = ""; private _evenAppConflictMessage = ""; @@ -25,9 +23,7 @@ export class MainViewModel extends Observable { this.log = snapshot.log; this.displayPreview = snapshot.displayPreview; this.phase = snapshot.phase; - this.systemCardName = snapshot.systemCardName; - this.editingSystemCardName = snapshot.editingSystemCardName; - this.activeTextSettingEditorKind = snapshot.activeTextSettingEditorKind; + this.activeTextSettingId = snapshot.activeTextSettingId; this.activeTextSettingTitle = snapshot.activeTextSettingTitle; this.activeTextSettingValue = snapshot.activeTextSettingValue; this.evenAppConflictMessage = snapshot.evenAppConflictMessage; @@ -133,41 +129,14 @@ export class MainViewModel extends Observable { return this._showLog ? "Hide Log" : "Show Log"; } - get systemCardName(): string { - return this._systemCardName; + get activeTextSettingId(): string | null { + return this._activeTextSettingId; } - set systemCardName(value: string) { - if (this._systemCardName !== value) { - this._systemCardName = value; - this.notifyPropertyChange("systemCardName", 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); + set activeTextSettingId(value: string | null) { + if (this._activeTextSettingId !== value) { + this._activeTextSettingId = value; + this.notifyPropertyChange("activeTextSettingId", value); this.notifyPropertyChange("textSettingEditorVisibility", this.textSettingEditorVisibility); this.notifyPropertyChange("isTextSettingEditorActive", this.isTextSettingEditorActive); } @@ -196,7 +165,7 @@ export class MainViewModel extends Observable { } get isTextSettingEditorActive(): boolean { - return this._activeTextSettingEditorKind !== null; + return this._activeTextSettingId !== null; } get textSettingEditorVisibility(): "visible" | "collapse" { diff --git a/app/ui/apps/debug-log.ts b/app/ui/apps/debug-log.ts index c14a0ad5..79a58917 100644 --- a/app/ui/apps/debug-log.ts +++ b/app/ui/apps/debug-log.ts @@ -1,6 +1,6 @@ import takeRight from "lodash/takeRight"; 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 { GrayImage } from "~/graphics/image"; diff --git a/app/ui/apps/music-controller.ts b/app/ui/apps/music-controller.ts index b78aa448..404e2f5a 100644 --- a/app/ui/apps/music-controller.ts +++ b/app/ui/apps/music-controller.ts @@ -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 { GrayImage } from "../../graphics/image"; import { wrapText } from "../../graphics/textwrap"; diff --git a/app/ui/apps/nightscout.ts b/app/ui/apps/nightscout.ts index b48bec38..be6a3364 100644 --- a/app/ui/apps/nightscout.ts +++ b/app/ui/apps/nightscout.ts @@ -1,6 +1,6 @@ import { BdfFont, getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/bdffont"; 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 { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge"; import { formatAgeShortFromTimestamp, formatTimestamp } from "~/util/date-util"; diff --git a/app/ui/dashboard-plugin.ts b/app/ui/dashboard-plugin.ts new file mode 100644 index 00000000..47ac3bcd --- /dev/null +++ b/app/ui/dashboard-plugin.ts @@ -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; + } +} diff --git a/app/ui/dashboard-plugins.ts b/app/ui/dashboard-plugins.ts index 9927ee7b..f2689745 100644 --- a/app/ui/dashboard-plugins.ts +++ b/app/ui/dashboard-plugins.ts @@ -1,72 +1,38 @@ -import { GrayImage } from "../graphics/image"; -import { type MediaControllerState } from "../native/media-controller"; import { type DashboardPluginId } from "./dashboard-settings"; -import { Layer } from "./layers"; +import { DashboardPlugin } from "./dashboard-plugin"; import { NightscoutDashboardPlugin } from "./apps/nightscout"; -import { NightscoutState } from "~/native/nightscout-bridge"; import { MusicControllerDashboardPlugin } from "./apps/music-controller"; import { DebugLogDashboardPlugin } from "./apps/debug-log"; -export type DashboardPluginState = { - logLines: string[]; - media: MediaControllerState; - nightscout: NightscoutState; - nightscoutConfigured: boolean; -}; +export { DashboardPlugin } from "./dashboard-plugin"; +export type { DashboardPluginCardBounds, DashboardPluginCardRenderArgs, DashboardPluginState } from "./dashboard-plugin"; -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; +let dashboardPlugins: DashboardPlugin[] | null = null; +function getDashboardPlugins(): DashboardPlugin[] { + if (!dashboardPlugins) { + dashboardPlugins = [ + { + id: "blank", + label: "Blank", + renderCard: () => {}, + createFullscreenLayer: () => null, + }, + new DebugLogDashboardPlugin(), + new MusicControllerDashboardPlugin(), + new NightscoutDashboardPlugin(), + ]; } + 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( - DASHBOARD_PLUGINS.map((plugin) => [plugin.id, plugin]), -); export function listDashboardPlugins(): DashboardPlugin[] { - return [...DASHBOARD_PLUGINS]; + return [...getDashboardPlugins()]; } export function getDashboardPlugin(pluginId: DashboardPluginId): DashboardPlugin { + const PLUGIN_MAP = new Map( + getDashboardPlugins().map((plugin) => [plugin.id, plugin]), + ); return PLUGIN_MAP.get(pluginId) ?? PLUGIN_MAP.get("blank")!; } diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 352df492..e220e7d2 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -1,6 +1,12 @@ 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 const dashboardSlotIds: DashboardSlotId[] = ["bottom-left", "bottom-right"]; export type DashboardPluginId = "blank" | "input-debug-log" | "music-controller" | "nightscout"; export type DashboardSlotConfig = Record; @@ -18,29 +24,126 @@ export type SystemCardSettingKey = keyof SystemCardSettings; export type ScreenTimeoutSetting = "15s" | "30s" | "1m" | "never"; export type WakeModeSetting = "tiled" | "synchronized"; -export const DEFAULT_SYSTEM_CARD_NAME = "Faceclaw"; -export const DEFAULT_SCREEN_TIMEOUT: ScreenTimeoutSetting = "30s"; -export const DEFAULT_WAKE_MODE: WakeModeSetting = "tiled"; -export const DEFAULT_VOICE_CONTROL_ENABLED = false; -export const DEFAULT_ESTIMATE_COMPRESSION_RATIOS_ENABLED = false; -const SYSTEM_CARD_NAME_KEY = "dashboard.systemCardName"; -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 = { - showFaceclawLogo: "dashboard.systemCard.showFaceclawLogo", - showBatteryIndicators: "dashboard.systemCard.showBatteryIndicators", - showAndroidNotifications: "dashboard.systemCard.showAndroidNotifications", - showSignalStrength: "dashboard.systemCard.showSignalStrength", +type ConfigSettingOptions = { + id: TId; + label: string; + storageKey: string; + defaultValue: TValue; + formatValue?: (value: TValue) => string; }; -const NIGHTSCOUT_SITE_URL_KEY = "integrations.nightscout.siteUrl"; -const NIGHTSCOUT_API_TOKEN_KEY = "integrations.nightscout.apiToken"; -const SLOT_KEYS: Record = { - "bottom-left": "dashboard.slot.bottomLeft", - "bottom-right": "dashboard.slot.bottomRight", + +export abstract class ConfigSetting { + readonly id: TId; + readonly label: string; + protected readonly storageKey: string; + protected readonly defaultValue: TValue; + private readonly valueFormatter: (value: TValue) => string; + + protected constructor(options: ConfigSettingOptions) { + 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 extends ConfigSetting { + constructor(options: ConfigSettingOptions) { + 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 = ConfigSettingOptions & { + values: readonly TValue[]; + normalize?: (value: string | null | undefined) => TValue; }; +export class ConfigSettingEnum extends ConfigSetting { + readonly values: readonly TValue[]; + private readonly normalizer: (value: string | null | undefined) => TValue; + + constructor(options: ConfigSettingEnumOptions) { + 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 = ConfigSettingOptions & { + editorTitle?: string; + glassesEditTitle?: string; + normalize?: (value: string | null | undefined) => string; +}; + +export class ConfigSettingString extends ConfigSetting { + readonly editorTitle: string; + readonly glassesEditTitle: string; + private readonly normalizer: (value: string | null | undefined) => string; + + constructor(options: ConfigSettingStringOptions) { + 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([ "blank", "input-debug-log", @@ -48,136 +151,123 @@ const KNOWN_PLUGIN_IDS = new Set([ "nightscout", ]); -const DEFAULT_SLOT_CONFIG: DashboardSlotConfig = { - "bottom-left": "input-debug-log", - "bottom-right": "blank", + +export const bottomLeftSlotSetting = new ConfigSettingEnum({ + 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({ + id: "bottom-right-slot", + label: "Bottom right slot", + storageKey: "dashboard.slot.bottomRight", + defaultValue: "blank", + values: Array.from(KNOWN_PLUGIN_IDS), +}); + +export const dashboardSlotSettings: Record> = { + "bottom-left": bottomLeftSlotSetting, + "bottom-right": bottomRightSlotSetting, }; -const DEFAULT_SYSTEM_CARD_SETTINGS: SystemCardSettings = { - showFaceclawLogo: true, - showBatteryIndicators: true, - showAndroidNotifications: true, - showSignalStrength: true, -}; +export const systemCardNameSetting = new ConfigSettingString({ + id: "dashboard-name", + label: "Dashboard name", + storageKey: "dashboard.systemCardName", + defaultValue: "Faceclaw", + editorTitle: "Dashboard name", + glassesEditTitle: "Edit dashboard name", + normalize: normalizeSystemCardName, + formatValue: (value) => value || "Faceclaw", +}); -export function getDashboardSlotIds(): DashboardSlotId[] { - return ["bottom-left", "bottom-right"]; -} +export const showFaceclawLogoSetting = new ConfigSettingBoolean({ + id: "showFaceclawLogo", + label: "Show Faceclaw Logo", + storageKey: "dashboard.systemCard.showFaceclawLogo", + defaultValue: true, +}); -export function getDefaultDashboardSlotConfig(): DashboardSlotConfig { - return { ...DEFAULT_SLOT_CONFIG }; -} +export const showBatteryIndicatorsSetting = new ConfigSettingBoolean({ + id: "showBatteryIndicators", + label: "Show Battery Indicators", + storageKey: "dashboard.systemCard.showBatteryIndicators", + defaultValue: true, +}); -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 const showAndroidNotificationsSetting = new ConfigSettingBoolean({ + id: "showAndroidNotifications", + label: "Show Android Notifications", + storageKey: "dashboard.systemCard.showAndroidNotifications", + defaultValue: true, +}); -export function saveDashboardSlotPlugin(slot: DashboardSlotId, pluginId: DashboardPluginId): void { - ApplicationSettings.setString(SLOT_KEYS[slot], pluginId); -} +export const showSignalStrengthSetting = new ConfigSettingBoolean({ + id: "showSignalStrength", + label: "Show Signal Strength", + storageKey: "dashboard.systemCard.showSignalStrength", + defaultValue: true, +}); -export function saveDashboardSlotConfig(config: DashboardSlotConfig): void { - for (const slot of getDashboardSlotIds()) { - saveDashboardSlotPlugin(slot, config[slot]); - } -} +export const screenTimeoutSetting = new ConfigSettingEnum({ + id: "screen-timeout", + label: "Screen timeout", + storageKey: "display.screenTimeout", + defaultValue: "30s", + values: ["15s", "30s", "1m", "never"], + formatValue: screenTimeoutLabel, +}); -export function loadSystemCardName(): string { - return normalizeSystemCardName(ApplicationSettings.getString(SYSTEM_CARD_NAME_KEY, DEFAULT_SYSTEM_CARD_NAME)); -} +export const wakeModeSetting = new ConfigSettingEnum({ + 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 { - const normalized = normalizeSystemCardName(name); - ApplicationSettings.setString(SYSTEM_CARD_NAME_KEY, normalized); - return normalized; -} +export const voiceControlEnabledSetting = new ConfigSettingBoolean({ + id: "voice-control-enabled", + label: "Enable", + storageKey: "voice.enabled", + defaultValue: false, +}); -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, - ), - showSignalStrength: ApplicationSettings.getBoolean( - SYSTEM_CARD_SETTING_KEYS.showSignalStrength, - DEFAULT_SYSTEM_CARD_SETTINGS.showSignalStrength, - ), - }; -} +export const estimateCompressionRatiosSetting = new ConfigSettingBoolean({ + id: "estimate-compression-ratios", + label: "Estimate compression ratios", + storageKey: "debug.estimateCompressionRatios", + defaultValue: false, +}); -export function saveSystemCardSetting(key: SystemCardSettingKey, value: boolean): void { - ApplicationSettings.setBoolean(SYSTEM_CARD_SETTING_KEYS[key], value); -} +export const nightscoutSiteUrlSetting = new ConfigSettingString({ + 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 { - return normalizeScreenTimeoutSetting(ApplicationSettings.getString(SCREEN_TIMEOUT_KEY, DEFAULT_SCREEN_TIMEOUT)); -} +export const nightscoutApiTokenSetting = new ConfigSettingString({ + 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 { - 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 { +export function screenTimeoutSettingToMs(value: ScreenTimeoutSetting): number | null { switch (value) { case "15s": return 15_000; @@ -194,35 +284,15 @@ export function screenTimeoutLabel(value: ScreenTimeoutSetting): string { 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 { return { - siteUrl: normalizeNightscoutSiteUrl(ApplicationSettings.getString(NIGHTSCOUT_SITE_URL_KEY, "")), - apiToken: normalizeNightscoutApiToken(ApplicationSettings.getString(NIGHTSCOUT_API_TOKEN_KEY, "")), + siteUrl: nightscoutSiteUrlSetting.get(), + apiToken: nightscoutApiTokenSetting.get(), }; } -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 isNightscoutSettingsConfigured(): boolean { + return nightscoutSiteUrlSetting.get().length > 0 && nightscoutApiTokenSetting.get().length > 0; } export function normalizePluginId( @@ -248,24 +318,112 @@ function normalizeNightscoutApiToken(apiToken: string | null | undefined): strin return (apiToken ?? "").replace(/[\x00-\x1f]+/g, "").trim(); } -function normalizeScreenTimeoutSetting(value: string | null | undefined): ScreenTimeoutSetting { - switch (value) { - case "15s": - case "30s": - case "1m": - case "never": - return value; - default: - return DEFAULT_SCREEN_TIMEOUT; - } +function emptySettingDisplay(value: string): string { + return value || "(empty)"; } -function normalizeWakeModeSetting(value: string | null | undefined): WakeModeSetting { - switch (value) { - case "tiled": - case "synchronized": - return value; - default: - return DEFAULT_WAKE_MODE; +function maskToken(token: string): string { + if (!token) return "(empty)"; + return token.length <= 6 ? "******" : `${token.slice(0, 2)}...${token.slice(-4)}`; +} + + +type SettingsMenuOptions = { + style?: "cycle"|"submenu" + onChange?: (newValue: T, oldValue: T) => void +} + +export function enumSettingMenuItem( + setting: ConfigSettingEnum, + opts?: SettingsMenuOptions +): 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( + setting: ConfigSettingBoolean, + opts?: SettingsMenuOptions +): 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( + setting: ConfigSettingString, + opts?: SettingsMenuOptions +): 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(); + } } } diff --git a/app/ui/dashboard.ts b/app/ui/dashboard.ts index a5a34d99..52b22773 100644 --- a/app/ui/dashboard.ts +++ b/app/ui/dashboard.ts @@ -1,57 +1,43 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; -import { getDefaultMediumFont, getDefaultSmallFont } from "../graphics/bdffont"; -import { loadPngAsGrayImage } from "../graphics/imagefile"; +import { getDefaultSmallFont } from "../graphics/bdffont"; import { type RawInputEvent } from "../native/faceclaw-communicator"; import { mediaControllerBridge } from "../native/media-controller"; import { nightscoutBridge } from "../native/nightscout-bridge"; import { EventSourceType, OsEventTypeList } from "../g2/events"; +import { getDashboardPlugin, isBlankDashboardPlugin, type DashboardPluginCardBounds, type DashboardPluginState } from "./dashboard-plugins"; import { - getDashboardPlugin, - isBlankDashboardPlugin, - listDashboardPlugins, - type DashboardPluginCardBounds, - type DashboardPluginState, -} from "./dashboard-plugins"; -import { - getDashboardSlotIds, + estimateCompressionRatiosSetting, isNightscoutSettingsConfigured, - loadDashboardSlotConfig, - loadEstimateCompressionRatiosEnabled, - loadNightscoutSettings, - loadScreenTimeoutSetting, - loadSystemCardSettings, - loadSystemCardName, - loadVoiceControlEnabled, - loadWakeModeSetting, - nextScreenTimeoutSetting, - nextWakeModeSetting, - saveDashboardSlotPlugin, - saveEstimateCompressionRatiosEnabled, - saveNightscoutApiToken, - saveNightscoutSiteUrl, - saveScreenTimeoutSetting, - saveWakeModeSetting, - screenTimeoutLabel, - screenTimeoutMs, - saveSystemCardSetting, - saveSystemCardName, - saveVoiceControlEnabled, - wakeModeLabel, + nightscoutApiTokenSetting, + nightscoutSiteUrlSetting, + screenTimeoutSettingToMs, + screenTimeoutSetting, + systemCardNameSetting, + voiceControlEnabledSetting, + wakeModeSetting, type DashboardSlotId, - type NightscoutSettings, - type ScreenTimeoutSetting, - type SystemCardSettingKey, - type WakeModeSetting, + DashboardPluginId, + bottomRightSlotSetting, + bottomLeftSlotSetting, + dashboardSlotSettings, + dashboardSlotIds, + enumSettingMenuItem, + toggleSettingMenuItem, + showFaceclawLogoSetting, + showBatteryIndicatorsSetting, + showAndroidNotificationsSetting, + showSignalStrengthSetting, + textSettingMenuItem, } from "./dashboard-settings"; 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 { NotificationsListLayer, SingleNotificationLayer } from "./notifications"; import { TranscribeLayer } from "./apps/transcribe"; import { TelepromptLayer } from "./apps/teleprompt"; import { ScreenTestLayer } from "./apps/screen-test"; import { getDashboardLogo } from "~/graphics/logo"; -import { drawSystemCard, getDisplayedSystemCardName } from "./dashboard/system-card"; +import { drawSystemCard } from "./dashboard/system-card"; type DashboardCardId = "system" | DashboardSlotId; export type DashboardBatteryLevels = { @@ -60,20 +46,21 @@ export type DashboardBatteryLevels = { 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[], screenOn: true, lastInputAtMs: Date.now(), - slotConfig: loadDashboardSlotConfig(), - systemCardName: loadSystemCardName(), - systemCardSettings: loadSystemCardSettings(), - screenTimeout: loadScreenTimeoutSetting(), - wakeMode: loadWakeModeSetting(), - voiceControlEnabled: loadVoiceControlEnabled(), - estimateCompressionRatiosEnabled: loadEstimateCompressionRatiosEnabled(), tiledWakePaintPending: false, telepromptDocumentText: null as string | null, - nightscoutSettings: loadNightscoutSettings(), battery: { headset: null, headsetCharging: null, @@ -83,10 +70,7 @@ export let dashboardState = { const dashboardActions: LayerActions = { disconnect: () => {}, - startSystemNameEdit: () => {}, - endSystemNameEdit: () => {}, - startNightscoutSiteUrlEdit: () => {}, - startNightscoutApiTokenEdit: () => {}, + startTextSettingEdit: () => {}, endTextSettingEdit: () => {}, setVoiceControlEnabled: () => {}, setStopwatchRenderActive: () => {}, @@ -143,7 +127,7 @@ export async function receiveInput(event: RawInputEvent): Promise { if (!dashboardState.screenOn) { if (inputEvent.type === "double-click") { dashboardState.screenOn = true; - dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; + dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled"; if (dashboardLayers.isAtBase()) { dashboardLayers.push(createRootMenuLayer()); } @@ -190,60 +174,8 @@ export function consumeDashboardTiledWakePaint(): boolean { 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 { - const timeoutMs = screenTimeoutMs(dashboardState.screenTimeout); + const timeoutMs = screenTimeoutSettingToMs(screenTimeoutSetting.get()); if (timeoutMs === null || !dashboardState.screenOn) return false; if (nowMs - dashboardState.lastInputAtMs < timeoutMs) return false; dashboardState.screenOn = false; @@ -270,7 +202,7 @@ export function openAndroidNotificationFromSleep(notificationKey: string, nowMs dashboardState.lastInputAtMs = nowMs; dashboardState.screenOn = true; - dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; + dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled"; dashboardLayers.clearToBase(); dashboardLayers.push(createRootMenuLayer()); dashboardLayers.push(new SingleNotificationLayer(notificationKey)); @@ -282,7 +214,7 @@ export function resetDashboardSleepTimerAndWake(nowMs = Date.now()): boolean { if (dashboardState.screenOn) return false; dashboardState.screenOn = true; - dashboardState.tiledWakePaintPending = dashboardState.wakeMode === "tiled"; + dashboardState.tiledWakePaintPending = wakeModeSetting.get() === "tiled"; dashboardLayers.clearToBase(); dashboardLayers.push(createRootMenuLayer()); return true; @@ -295,6 +227,15 @@ export function setDashboardBatteryLevels(levels: Partial !isBlankDashboardPlugin(dashboardState.slotConfig[slot])) + ...dashboardSlotIds + .filter((slot) => !isBlankDashboardPlugin(getPluginIdForSlot(slot))) .map((slot) => ({ label: pluginLabelForSlot(slot), onSelect: (ctx: LayerContext) => { @@ -452,11 +393,11 @@ function createSystemMenuLayer(): MenuLayer { } function openDashboardSlot(slot: DashboardSlotId, ctx: LayerContext): void { - const pluginId = dashboardState.slotConfig[slot]; + const pluginId = getPluginIdForSlot(slot); if (isBlankDashboardPlugin(pluginId)) { return; } - if (pluginId === "nightscout" && !isNightscoutSettingsConfigured(dashboardState.nightscoutSettings)) { + if (pluginId === "nightscout" && !isNightscoutSettingsConfigured()) { ctx.stack.push(createNightscoutSettingsMenuLayer()); return; } @@ -503,73 +444,23 @@ function createDisplaySettingsMenuLayer(): MenuLayer { return new MenuLayer( "Settings > Display", [ - { - label: "Screen timeout", - onSelect: () => { - setScreenTimeout(nextScreenTimeoutSetting(dashboardState.screenTimeout)); + enumSettingMenuItem(screenTimeoutSetting, { + onChange: (newValue, oldValue) => { + dashboardState.lastInputAtMs = Date.now(); }, - render: ({ image, x, y, width }) => { - drawRightValueMenuItem(image, dashboardFont, x, y, width, "Screen timeout", screenTimeoutLabel(dashboardState.screenTimeout)); - }, - }, - { - 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, - ); - }, - }, + }), + enumSettingMenuItem(wakeModeSetting), + toggleSettingMenuItem(estimateCompressionRatiosSetting), ], 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 { return new MenuLayer( "Settings > Voice", [ - { - 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); - }, - }, + toggleSettingMenuItem(voiceControlEnabledSetting), ], TOP_LEFT_MENU_LAYOUT, ); @@ -585,14 +476,8 @@ function createDashboardSettingsMenuLayer(): MenuLayer { 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 + 3, `${slotMenuLabel(slot)}: ${pluginLabelForSlot(slot)}`, 200); - }, + ...dashboardSlotIds.map((slot) => enumSettingMenuItem(dashboardSlotSettings[slot], { + style: "submenu", })), ], TOP_LEFT_MENU_LAYOUT, @@ -603,37 +488,16 @@ function createSystemCardSettingsMenuLayer(): MenuLayer { return new MenuLayer( "Settings > Dashboard > System Card", [ - { - label: "Name", - onSelect: (ctx) => { - void ctx.actions.startSystemNameEdit(); - ctx.stack.push(new EditSystemNameLayer()); - }, - 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"), + textSettingMenuItem(systemCardNameSetting), + toggleSettingMenuItem(showFaceclawLogoSetting), + toggleSettingMenuItem(showBatteryIndicatorsSetting), + toggleSettingMenuItem(showAndroidNotificationsSetting), + toggleSettingMenuItem(showSignalStrengthSetting), ], 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 { return new MenuLayer( "Settings > Integrations", @@ -653,95 +517,13 @@ function createNightscoutSettingsMenuLayer(): MenuLayer { return new MenuLayer( "Settings > Integrations > 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 + 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); - }, - }, + textSettingMenuItem(nightscoutSiteUrlSetting), + textSettingMenuItem(nightscoutApiTokenSetting), ], 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 { paint(): GrayImage { @@ -776,7 +558,7 @@ function getPluginState(): DashboardPluginState { logLines: dashboardState.logLines, media: mediaControllerBridge.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 { - 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)}`; + return getDashboardPlugin(getPluginIdForSlot(slot)).label; } const dashboardLayers = new LayerStack(new DashboardLayer(), dashboardActions); diff --git a/app/ui/dashboard/system-card.ts b/app/ui/dashboard/system-card.ts index 5160ca50..2c8c2c97 100644 --- a/app/ui/dashboard/system-card.ts +++ b/app/ui/dashboard/system-card.ts @@ -7,7 +7,7 @@ import { type DashboardPluginCardBounds } from "../dashboard-plugins"; import { dashboardState } from "../dashboard"; import { getDefaultMediumFont, getDefaultSmallFont } from "~/graphics/bdffont"; 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 SYSTEM_CARD_ITEM_HEIGHT = 38; @@ -29,14 +29,14 @@ function drawSystemCardFlowItems(image: GrayImage, bounds: DashboardPluginCardBo const right = bounds.x + bounds.width - 10; const bottom = bounds.y + bounds.height - 6; 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; for (const icon of readActiveNotificationIcons(maxNotificationIcons)) { items.push({ type: "notification", icon }); } } items.push(...collectBatteryItems()); - if (dashboardState.systemCardSettings.showSignalStrength) { + if (showSignalStrengthSetting.get()) { for (const icon of readSystemStatusIcons()) { items.push({ type: "notification", icon }); } @@ -74,7 +74,7 @@ function systemCardFlowItemWidth(item: SystemCardFlowItem): number { } function collectBatteryItems(): SystemCardFlowItem[] { - if (!dashboardState.systemCardSettings.showBatteryIndicators) return []; + if (!showBatteryIndicatorsSetting.get()) return []; const phone = readPhoneBatteryState(); const items: SystemCardFlowItem[] = []; addBatteryItem(items, "Phone", phone.battery, phone.charging); @@ -114,20 +114,15 @@ function pad2(value: number): string { 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 { const now = new Date(); const logo = getDashboardLogo(); - if (logo && dashboardState.systemCardSettings.showFaceclawLogo) { + if (logo && showFaceclawLogoSetting.get()) { image.bitBlt(logo, bounds.x + 10, bounds.y + 10); } - const infoX = logo && dashboardState.systemCardSettings.showFaceclawLogo ? bounds.x + 92 : bounds.x + 10; - image.drawText(mediumFont, infoX, bounds.y + 10, getDisplayedSystemCardName(), 200); + const infoX = logo && showFaceclawLogoSetting.get() ? bounds.x + 92 : bounds.x + 10; + image.drawText(mediumFont, infoX, bounds.y + 10, systemCardNameSetting.get(), 200); image.drawText(mediumFont, infoX, bounds.y + 32, formatDashboardDate(now), 200); drawSystemCardFlowItems(image, bounds); } diff --git a/app/ui/layers.ts b/app/ui/layers.ts index 6557951f..820f7962 100644 --- a/app/ui/layers.ts +++ b/app/ui/layers.ts @@ -1,5 +1,6 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { BdfFont } from "../graphics/bdffont"; +import { type ConfigSettingString } from "./dashboard-settings"; export type DashboardInputEvent = | { type: "click"; source: "ring" | "left-arm" | "right-arm" } @@ -10,10 +11,7 @@ export type DashboardInputEvent = export type LayerActions = { disconnect: () => Promise | void; - startSystemNameEdit: () => Promise | void; - endSystemNameEdit: () => Promise | void; - startNightscoutSiteUrlEdit: () => Promise | void; - startNightscoutApiTokenEdit: () => Promise | void; + startTextSettingEdit: (setting: ConfigSettingString) => Promise | void; endTextSettingEdit: () => Promise | void; setVoiceControlEnabled: (enabled: boolean) => Promise | void; setStopwatchRenderActive: (active: boolean) => Promise | void;