Add configuration options to the glanceboard system card and music card

This commit is contained in:
James Babcock committed 2026-10-13 16:41:14 -07:00
1 parent 13da595de0
commit df95cc4064
12 files changed
+367 -107

No files matched your search

+5
View File
@@ -15,6 +15,11 @@ export function isTerminalWidgetConfigured(): boolean {
return isGlanceWidgetConfigured("terminal");
}
/** Whether the system card can show: it is in a slot and the Glanceboard is enabled. */
export function isSystemCardWidgetInUse(): boolean {
return getBooleanSetting("glanceboard.enabled", false) && isGlanceWidgetConfigured("system-card");
}
/**
* Whether the T3 Code widget can show: it is in a slot and the Glanceboard is
* enabled (the T3 worker holds its server connections open only then).
+34 -6
View File
@@ -5,7 +5,7 @@ import { enumSettingMenuItem, onAnySettingChanged, toggleSettingMenuItem } from
import { uiFontOverridePickerMenuItem } from "../../ui/font-picker";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, type MenuItem } from "../../ui/menu";
import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, submenuItem, type MenuItem } from "../../ui/menu";
import { Menu } from "../../ui/menu-core";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
@@ -27,7 +27,8 @@ import {
type GlanceSlotChoice,
} from "./glanceboard-settings";
import { resolveGlanceRegions, slotDividers } from "./layout";
import { glanceWidgetSpans } from "./widgets";
import { type GlanceWidgetDefinition } from "./widget";
import { findGlanceWidget, glanceWidgetSpans } from "./widgets";
export const GLANCEBOARD_WINDOW_ID = "glanceboard";
export const GLANCEBOARD_SURFACE_ID = "window:glanceboard";
@@ -300,10 +301,14 @@ function openSlotPicker(ctx: LayerContext, slotIndex: number): void {
openModalMenu(ctx, setting.label, items, Math.max(0, setting.values.indexOf(current)));
}
/** Settings: layout, sleep gestures, duration, slot lines, widget font, and stereo depth. */
/**
* Settings: layout, sleep gestures, duration, slot lines, widget font, and
* stereo depth, then a row per widget on the board for its own settings.
*/
function openGlanceSettings(ctx: LayerContext): void {
const items: MenuItem[] = [
enumSettingMenuItem(glanceLayoutSetting),
const items = (): MenuItem[] => [
// The layout decides which slots (and so which widgets) are on the board.
enumSettingMenuItem(glanceLayoutSetting, { onChange: () => layer.setItems(items()) }),
enumSettingMenuItem(glanceTapDurationSetting),
toggleSettingMenuItem(glanceShowOnLongPressSetting),
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
@@ -314,8 +319,31 @@ function openGlanceSettings(ctx: LayerContext): void {
"Typeface for the Glanceboard's widgets. Same as UI font follows the Font setting in Settings > Customization.",
}),
enumSettingMenuItem(glanceDepthSetting),
...widgetSettingsMenuItems(),
];
ctx.stack.push(new MenuLayer("Glanceboard settings", items, pageMenuLayout(ctx.stack.getBaseSize().width)));
const layer = new MenuLayer("Glanceboard settings", items(), pageMenuLayout(ctx.stack.getBaseSize().width));
ctx.stack.push(layer);
}
/**
* One row per widget on the board, in slot order: a submenu of the widget's
* settings, or a disabled row for a widget that has none.
*/
function widgetSettingsMenuItems(): MenuItem[] {
const widgets = new Set<GlanceWidgetDefinition>();
for (const setting of glanceSlotSettings()) {
const widget = findGlanceWidget(setting.get());
if (widget) widgets.add(widget);
}
return Array.from(widgets, (widget): MenuItem => {
const settingsMenuItems = widget.settingsMenuItems;
if (!settingsMenuItems) {
return { label: widget.label, description: `${widget.label} has no settings.`, disabled: true, onSelect: () => {} };
}
return submenuItem(widget.label, (ctx) => {
ctx.stack.push(new MenuLayer(`${widget.label} settings`, settingsMenuItems(), pageMenuLayout(ctx.stack.getBaseSize().width)));
}, { description: `Settings for the ${widget.label} widget.` });
});
}
/** The live board in the window; any click or double-click returns to the list. */
+7
View File
@@ -1,4 +1,5 @@
import { type GrayImage } from "../../graphics/image";
import { type MenuItem } from "../../ui/menu";
/**
* A Glanceboard widget: a small self-contained view that paints into a slot
@@ -39,5 +40,11 @@ export type GlanceWidgetDefinition = {
* gets the taller canvas; the divider between the slots is not drawn.
*/
tall?: boolean;
/**
* The rows of this widget's submenu in the Glanceboard app's Settings. A
* widget without settings still gets a row there (disabled) while it is
* on the board.
*/
settingsMenuItems?: () => MenuItem[];
create: () => GlanceWidget;
};
+4 -4
View File
@@ -1,21 +1,21 @@
import { type GlanceWidgetDefinition, type GlanceWidgetId } from "../widget";
import { CalendarWidget } from "./calendar-widget";
import { CompassWidget } from "./compass-widget";
import { MusicWidget } from "./music-widget";
import { MusicWidget, musicSettingsMenuItems } from "./music-widget";
import { NightscoutWidget } from "./nightscout-widget";
import { SystemCardWidget } from "./system-card";
import { SystemCardWidget, systemCardSettingsMenuItems } from "./system-card";
import { T3CodeWidget } from "./t3code-widget";
import { TerminalWidget } from "./terminal-widget";
/** Every widget a board slot can hold. */
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
{ id: "system-card", label: "System card", create: () => new SystemCardWidget() },
{ id: "system-card", label: "System card", settingsMenuItems: systemCardSettingsMenuItems, create: () => new SystemCardWidget() },
{ id: "calendar", label: "Calendar", tall: true, create: () => new CalendarWidget() },
{ id: "terminal", label: "Terminal", tall: true, create: () => new TerminalWidget() },
{ id: "t3code", label: "T3 Code", tall: true, create: () => new T3CodeWidget() },
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
{ id: "compass", label: "Compass", create: () => new CompassWidget() },
{ id: "music", label: "Music", create: () => new MusicWidget() },
{ id: "music", label: "Music", settingsMenuItems: musicSettingsMenuItems, create: () => new MusicWidget() },
];
export function findGlanceWidget(id: GlanceWidgetId | (string & {})): GlanceWidgetDefinition | null {
+29 -6
View File
@@ -2,6 +2,8 @@ import { GrayImage } from "../../../graphics/image";
import { renderIcon } from "../../../graphics/icons";
import { truncateText } from "../../../graphics/textwrap";
import { mediaControllerBridge, type MediaControllerState } from "../../../native/media-controller";
import { ConfigSettingBoolean, onAnySettingChanged, toggleSettingMenuItem } from "../../../ui/dashboard-settings";
import { type MenuItem } from "../../../ui/menu";
import { clamp } from "../../../util/numeric-util";
import { glanceFont } from "../glance-font";
import { type GlanceWidget } from "../widget";
@@ -36,17 +38,33 @@ function idleNoteImage(): GrayImage | null {
return note;
}
const ART_X = PAD;
const ART_TEXT_GAP = 12;
const PROGRESS_BAR_HEIGHT = 5;
export const musicShowAlbumArtSetting = new ConfigSettingBoolean({
id: "glanceboard-music-show-album-art",
label: "Show album art",
storageKey: "glanceboard.music.showAlbumArt",
defaultValue: true,
description:
"Show the album art beside the track details. When off, the title, artist, album and progress bar use the full width of the card.",
});
/** The music card's submenu in Glanceboard > Settings. */
export function musicSettingsMenuItems(): MenuItem[] {
return [toggleSettingMenuItem(musicShowAlbumArtSetting)];
}
/**
* Now playing: album art, title/artist/album and a progress bar for the
* active Android media session, the Music app's header at card size. The
* media bridge runs for the whole session; the widget subscribes and ticks
* once a second only while something is playing.
* Now playing: album art (unless turned off), title/artist/album and a
* progress bar for the active Android media session, the Music app's header
* at card size. The media bridge runs for the whole session; the widget
* subscribes and ticks once a second only while something is playing.
*/
export class MusicWidget implements GlanceWidget {
private media: MediaControllerState = mediaControllerBridge.snapshot();
private unsubscribe: (() => void) | null = null;
private unsubscribeSettings: (() => void) | null = null;
private progressTimer: ReturnType<typeof setInterval> | null = null;
private art: GrayImage | null = null;
/** The artVersion `art` was fetched for; -1 = not fetched yet. */
@@ -62,11 +80,14 @@ export class MusicWidget implements GlanceWidget {
}
requestRender();
});
this.unsubscribeSettings = onAnySettingChanged(requestRender);
}
stop(): void {
this.unsubscribe?.();
this.unsubscribe = null;
this.unsubscribeSettings?.();
this.unsubscribeSettings = null;
this.stopProgressTimer();
}
@@ -93,10 +114,12 @@ export class MusicWidget implements GlanceWidget {
return;
}
// Without the art, the text and progress bar keep its rows and take its columns.
const artY = Math.max(PAD, ((image.height - ART_SIZE) / 2) | 0);
this.drawArt(image, media, artY);
const showArt = musicShowAlbumArtSetting.get();
if (showArt) this.drawArt(image, media, artY);
const textX = ART_X + ART_SIZE + 12;
const textX = showArt ? ART_X + ART_SIZE + ART_TEXT_GAP : PAD;
const textWidth = image.width - textX - PAD;
let y = artY;
image.drawText(medium, textX, y, truncateText(medium, media.title || "Unknown title", textWidth), 230);
+248 -79
View File
@@ -1,11 +1,13 @@
import {
BATTERY_ICON_WIDTH,
DENSE_BATTERY_BLOCK_HEIGHT,
denseBatteriesWidth,
drawBattery,
drawDenseBatteries,
type BatteryDevice,
} from "../../../graphics/battery";
import { type GrayImage, type UiFont } from "../../../graphics/image";
import { ensureLocationPermission, hasLocationPermission } from "../../../native/location-permissions";
import { onAndroidNotificationPosted, readActiveNotificationIcons } from "../../../native/notification-icons";
import { readPhoneBatteryState } from "../../../native/phone-battery";
import { weatherBridge } from "../../../native/weather";
@@ -13,13 +15,16 @@ import { formatClockDate, formatClockTime } from "../../../ui/clock-format";
import {
batteryDisplayModeSetting,
batteryIndicatorVisible,
ConfigSettingBoolean,
glassesBatteryVisibilitySetting,
onAnySettingChanged,
phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting,
toggleSettingMenuItem,
watchBatteryVisibilitySetting,
type BatteryIndicatorVisibility,
} from "../../../ui/dashboard-settings";
import { type MenuItem } from "../../../ui/menu";
import { shell } from "../../../ui/shell/shell";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../../util/render-freshness";
import { truncateText } from "../../../graphics/textwrap";
@@ -36,20 +41,113 @@ const NOTIFICATION_ICON_SIZE = 24;
const NOTIFICATION_ICON_GAP = 4;
const BATTERY_ITEM_GAP = 12;
const BATTERY_LABEL_VALUE = 150;
/** Gap between the battery block and the weather reading below it. */
const WEATHER_GAP = 6;
/** Gap between the battery block and the weather reading stacked after it. */
const SIDE_BLOCK_GAP = 6;
/** Rows between the time and the date. */
const CLOCK_LINE_GAP = 2;
/** Rows between the clock and the timers, and between the timers and the notification icons. */
const TIMERS_GAP = 4;
const TIMER_NAME_GAP = 8;
type BatteryItem = { label: string; device: BatteryDevice; percent: number; charging: boolean };
/** A block drawn against the card's right edge: its left edge and its rows. */
type RightBlock = { left: number; top: number; bottom: number };
type Rect = { x: number; y: number; width: number; height: number };
/** A side-column block, measured so it can be placed against either edge before it is drawn. */
type SideBlock = { width: number; height: number; draw: (image: GrayImage, left: number, top: number) => void };
/** The main column's horizontal extent on some rows. */
type Span = { left: number; right: number };
export const systemCardShowTimeSetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-show-time",
label: "Time",
storageKey: "glanceboard.systemCard.showTime",
defaultValue: true,
description: "Show the clock on the system card.",
});
export const systemCardShowDateSetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-show-date",
label: "Date",
storageKey: "glanceboard.systemCard.showDate",
defaultValue: true,
description: "Show the date on the system card, under the time.",
});
export const systemCardShowBatterySetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-show-battery",
label: "Battery",
storageKey: "glanceboard.systemCard.showBattery",
defaultValue: true,
description:
"Show battery indicators on the system card. Their style and which devices appear follow Settings > Customization > Battery indicators.",
});
export const systemCardShowNotificationsSetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-show-notifications",
label: "Notifications",
storageKey: "glanceboard.systemCard.showNotifications",
defaultValue: true,
description: "Show the icons of the phone's notifications along the edge of the system card.",
});
export const systemCardFlipHorizontalSetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-flip-horizontal",
label: "Flip layout horizontally",
storageKey: "glanceboard.systemCard.flipHorizontal",
defaultValue: false,
description:
"Mirror the system card left to right: time, date, timers and notifications on the right, batteries and weather on the left.",
});
export const systemCardFlipVerticalSetting = new ConfigSettingBoolean({
id: "glanceboard-system-card-flip-vertical",
label: "Flip layout vertically",
storageKey: "glanceboard.systemCard.flipVertical",
defaultValue: false,
description:
"Mirror the system card top to bottom: notifications along the top; time, date, batteries and weather along the bottom.",
});
/**
* The system card's submenu in Glanceboard > Settings. Weather is the
* Weather app's "Show on system card" setting under a shorter label.
*/
export function systemCardSettingsMenuItems(): MenuItem[] {
return [
toggleSettingMenuItem(systemCardShowTimeSetting),
toggleSettingMenuItem(systemCardShowDateSetting),
toggleSettingMenuItem(systemCardShowBatterySetting),
toggleSettingMenuItem(weatherShowOnSystemCardSetting, {
label: "Weather",
onChange: (_ctx, enabled) => {
if (enabled) requestWeatherLocationAccess();
},
}),
toggleSettingMenuItem(systemCardShowNotificationsSetting),
toggleSettingMenuItem(systemCardFlipHorizontalSetting),
toggleSettingMenuItem(systemCardFlipVerticalSetting),
];
}
/**
* Weather switched on without location access: ask for it now, as the
* Weather app's own toggle does, since the background refresh has no screen
* to prompt from.
*/
function requestWeatherLocationAccess(): void {
if (hasLocationPermission()) return;
void ensureLocationPermission().then((granted) => {
if (granted) void weatherBridge.refreshNow();
}).catch((error) => console.warn(`Weather permission: ${error}`));
}
/**
* Date and time, the phone's notification icons, the phone/watch/G2/R1
* battery indicators (the Wear OS watch's only while one is reachable), the
* current weather (when the Weather app's "Show on system card" is on), and
* the Timers app's countdowns: the top bar's contents plus timers, laid out
* for a card. Battery style and per-device visibility
* follow Settings > Customization > Battery indicators, so the card agrees with
* current weather, and the Timers app's countdowns: the top bar's contents
* plus timers, laid out for a card. Every part but the timers can be turned
* off, and the layout mirrored either way, in the card's submenu of
* Glanceboard > Settings. Battery style and per-device visibility follow
* Settings > Customization > Battery indicators, so the card agrees with
* the bar. Countdowns tick once a second only while one is running.
*/
export class SystemCardWidget implements GlanceWidget {
@@ -120,35 +218,93 @@ export class SystemCardWidget implements GlanceWidget {
const medium = glanceFont.medium();
const small = glanceFont.small();
const now = new Date();
const { width, height } = image;
// Clock and date down the left; batteries take the right edge, with the
// weather right-aligned beneath them. Text on the left stops short of
// whichever of those shares its rows.
const battery = drawBatteryBlock(image, small, image.width - PAD, PAD);
const weatherTop = battery.bottom > battery.top ? battery.bottom + WEATHER_GAP : PAD;
const weather = drawWeatherBlock(image, medium, image.width - PAD, weatherTop, now.getTime());
const textRight = (top: number, bottom: number): number =>
weather && weather.top < bottom && weather.bottom > top ? Math.min(battery.left, weather.left) : battery.left;
const textWidth = Math.max(0, textRight(PAD, PAD + large.lineHeight) - BATTERY_ITEM_GAP - PAD);
// Unflipped, the time and date run down the left from the top, the
// batteries and then the weather stack down the right edge, and the
// notification icons take the bottom row, with the timers in the band
// between the date and the icons. The flips mirror where each block sits
// (positions below are given for the unflipped card), not what is inside
// it: the time stays above the date, and timers read soonest first.
const flipX = systemCardFlipHorizontalSetting.get();
const flipY = systemCardFlipVerticalSetting.get();
const placeX = (x: number, w: number): number => (flipX ? width - x - w : x);
const placeY = (y: number, h: number): number => (flipY ? height - y - h : y);
const sideBlocks: SideBlock[] = [];
const batteryItems = systemCardShowBatterySetting.get() ? collectBatteryItems() : [];
if (batteryItems.length) sideBlocks.push(batteryBlock(small, batteryItems));
const weather = weatherShowOnSystemCardSetting.get() ? weatherBlock(medium, now.getTime()) : null;
if (weather) sideBlocks.push(weather);
const side: Rect[] = [];
let sideOffset = PAD;
for (const block of sideBlocks) {
const rect = {
x: placeX(width - PAD - block.width, block.width),
y: placeY(sideOffset, block.height),
width: block.width,
height: block.height,
};
block.draw(image, rect.x, rect.y);
side.push(rect);
sideOffset += block.height + SIDE_BLOCK_GAP;
}
// Text in the main column stops short of whichever side blocks share its
// rows, and hugs the card's outer edge.
const span = (top: number, bottom: number): Span => {
let left = PAD;
let right = width - PAD;
for (const rect of side) {
if (rect.y >= bottom || rect.y + rect.height <= top) continue;
if (flipX) left = Math.max(left, rect.x + rect.width + BATTERY_ITEM_GAP);
else right = Math.min(right, rect.x - BATTERY_ITEM_GAP);
}
return { left, right };
};
const lineX = ({ left, right }: Span, lineWidth: number): number => (flipX ? right - lineWidth : left);
const showTime = systemCardShowTimeSetting.get();
const showDate = systemCardShowDateSetting.get();
const timeText = formatClockTime(now);
const timeFont = large.measureText(timeText) <= textWidth ? large : medium;
let y = PAD;
image.drawText(timeFont, PAD, y, timeText, 230);
y += timeFont.lineHeight + 2;
image.drawText(medium, PAD, y, formatClockDate(now), 170);
y += medium.lineHeight + 4;
const dateText = formatClockDate(now);
const clockHeight = (timeFont: UiFont): number =>
(showTime ? timeFont.lineHeight : 0) + (showTime && showDate ? CLOCK_LINE_GAP : 0) + (showDate ? medium.lineHeight : 0);
// The time drops to the medium font when the large one would run into a side block.
let timeFont = large;
if (showTime) {
const top = placeY(PAD, clockHeight(large));
const { left, right } = span(top, top + large.lineHeight);
if (large.measureText(timeText) > right - left) timeFont = medium;
}
const clockSize = clockHeight(timeFont);
let y = placeY(PAD, clockSize);
if (showTime) {
image.drawText(timeFont, lineX(span(y, y + timeFont.lineHeight), timeFont.measureText(timeText)), y, timeText, 230);
y += timeFont.lineHeight + CLOCK_LINE_GAP;
}
if (showDate) {
image.drawText(medium, lineX(span(y, y + medium.lineHeight), medium.measureText(dateText)), y, dateText, 170);
}
// Notification icons along the bottom, as many as fit; the Timers app's
// countdowns take the band between the date and the icons.
const iconY = image.height - PAD - NOTIFICATION_ICON_SIZE;
const timersWidth = Math.max(0, textRight(y, iconY - 4) - BATTERY_ITEM_GAP - PAD);
drawTimers(image, small, PAD, y, timersWidth, iconY - 4, now.getTime());
const maxIcons = Math.max(0, ((image.width - 2 * PAD + NOTIFICATION_ICON_GAP) / (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP)) | 0);
if (maxIcons > 0) {
const showNotifications = systemCardShowNotificationsSetting.get();
const bandTop = clockSize > 0 ? PAD + clockSize + TIMERS_GAP : PAD;
const bandBottom = height - PAD - (showNotifications ? NOTIFICATION_ICON_SIZE + TIMERS_GAP : 0);
drawTimers(image, small, {
top: placeY(bandTop, bandBottom - bandTop),
height: bandBottom - bandTop,
fromBottom: flipY,
alignRight: flipX,
span,
}, now.getTime());
// Notification icons, as many as fit, the first nearest the main column's edge.
const maxIcons = Math.max(0, ((width - 2 * PAD + NOTIFICATION_ICON_GAP) / (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP)) | 0);
if (showNotifications && maxIcons > 0) {
const { icons, stale } = readActiveNotificationIcons(maxIcons, renderPassAllowsStaleData());
if (stale) noteStaleDataUsed();
const iconY = placeY(height - PAD - NOTIFICATION_ICON_SIZE, NOTIFICATION_ICON_SIZE);
for (let index = 0; index < icons.length; index++) {
image.drawImage(icons[index]!, PAD + index * (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP), iconY);
image.drawImage(icons[index]!, placeX(PAD + index * (NOTIFICATION_ICON_SIZE + NOTIFICATION_ICON_GAP), NOTIFICATION_ICON_SIZE), iconY);
}
}
}
@@ -180,59 +336,62 @@ function collectBatteryItems(): BatteryItem[] {
}
/**
* The battery indicators right-aligned at `right`, in the configured style.
* Side-by-side styles put the label beside the gauge (or percentage) on one
* line; stacked styles centre the label above it; the dense style swaps
* labels for device icons and stacks two indicators per column, as in the
* top bar. Returns the block's extent (zero-height at `right` when nothing
* is shown).
* The battery indicators in the configured style. Side-by-side styles put
* the label beside the gauge (or percentage) on one line; stacked styles
* centre the label above it; the dense style swaps labels for device icons
* and stacks two indicators per column, as in the top bar.
*/
function drawBatteryBlock(image: GrayImage, font: UiFont, right: number, top: number): RightBlock {
const items = collectBatteryItems();
if (!items.length) return { left: right, top, bottom: top };
function batteryBlock(font: UiFont, items: readonly BatteryItem[]): SideBlock {
const mode = batteryDisplayModeSetting.get();
if (mode === "dense") {
return { left: drawDenseBatteries(image, items, right, top), top, bottom: top + DENSE_BATTERY_BLOCK_HEIGHT };
const width = denseBatteriesWidth(items);
return {
width,
height: DENSE_BATTERY_BLOCK_HEIGHT,
draw: (image, left, top) => {
drawDenseBatteries(image, items, left + width, top);
},
};
}
const percentage = mode === "percentage" || mode === "stacked-percentage";
const stacked = mode === "stacked" || mode === "stacked-percentage";
const gaugeHeight = drawBattery(0, false).height;
const valueHeight = percentage ? font.lineHeight : Math.max(font.lineHeight, gaugeHeight);
let x = right;
for (let index = items.length - 1; index >= 0; index--) {
const item = items[index]!;
const percentText = `${item.percent}%`;
const cells = items.map((item) => {
const labelWidth = font.measureText(item.label);
const valueWidth = percentage ? font.measureText(percentText) : BATTERY_ICON_WIDTH;
if (stacked) {
const itemWidth = Math.max(labelWidth, valueWidth);
x -= itemWidth;
image.drawText(font, x + (((itemWidth - labelWidth) / 2) | 0), top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + (((itemWidth - valueWidth) / 2) | 0), top + font.lineHeight + 2, item, percentage, gaugeHeight);
} else {
x -= labelWidth + 5 + valueWidth;
image.drawText(font, x, top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + labelWidth + 5, top, item, percentage, gaugeHeight);
}
x -= BATTERY_ITEM_GAP;
}
return { left: x + BATTERY_ITEM_GAP, top, bottom: top + (stacked ? font.lineHeight + 2 : 0) + valueHeight };
const valueWidth = percentage ? font.measureText(`${item.percent}%`) : BATTERY_ICON_WIDTH;
return { item, labelWidth, valueWidth, width: stacked ? Math.max(labelWidth, valueWidth) : labelWidth + 5 + valueWidth };
});
return {
width: cells.reduce((total, cell) => total + cell.width, 0) + BATTERY_ITEM_GAP * (cells.length - 1),
height: (stacked ? font.lineHeight + 2 : 0) + valueHeight,
draw: (image, left, top) => {
let x = left;
for (const { item, labelWidth, valueWidth, width } of cells) {
if (stacked) {
image.drawText(font, x + (((width - labelWidth) / 2) | 0), top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + (((width - valueWidth) / 2) | 0), top + font.lineHeight + 2, item, percentage, gaugeHeight);
} else {
image.drawText(font, x, top, item.label, BATTERY_LABEL_VALUE);
drawBatteryValue(image, font, x + labelWidth + 5, top, item, percentage, gaugeHeight);
}
x += width + BATTERY_ITEM_GAP;
}
},
};
}
/**
* The current weather's condition icon and temperature, right-aligned at
* `right` from `top`, while the system-card weather setting is on and a
* fresh reading exists. Returns the block's extent, or null when not drawn.
*/
function drawWeatherBlock(image: GrayImage, font: UiFont, right: number, top: number, nowMs: number): RightBlock | null {
if (!weatherShowOnSystemCardSetting.get()) return null;
/** The current weather's condition icon and temperature, or null without a fresh reading. */
function weatherBlock(font: UiFont, nowMs: number): SideBlock | null {
const reading = weatherReading(weatherBridge.snapshot(), nowMs);
if (!reading) return null;
const iconSize = font.lineHeight + 4;
const height = Math.max(iconSize, font.lineHeight);
const left = right - Math.ceil(measureWeatherReading(reading, font, iconSize));
drawWeatherReading(image, reading, font, iconSize, left, top, height, 200);
return { left, top, bottom: top + height };
return {
width: Math.ceil(measureWeatherReading(reading, font, iconSize)),
height,
draw: (image, left, top) => drawWeatherReading(image, reading, font, iconSize, left, top, height, 200),
};
}
function drawBatteryValue(
@@ -262,26 +421,36 @@ function drawBatteryValue(
/**
* The Timers app's countdowns, soonest first: remaining time (or "Done" once
* rung, inverted so it is noticed; "paused" for a paused one) and the
* timer's name, one per line while they fit between `top` and `bottom`.
* timer's name, one per line, as many as fit in the band. The lines sit
* against the band's top (or its bottom), each as wide as the main column
* allows on its rows and hugging its left (or right) edge.
*/
function drawTimers(image: GrayImage, font: UiFont, x: number, top: number, width: number, bottom: number, nowMs: number): void {
const timers = sortTimers(timerEngine.timers(), nowMs);
function drawTimers(
image: GrayImage,
font: UiFont,
band: { top: number; height: number; fromBottom: boolean; alignRight: boolean; span: (top: number, bottom: number) => Span },
nowMs: number,
): void {
const step = lineStep(font);
let y = top;
const fit = band.height < font.lineHeight ? 0 : 1 + Math.floor((band.height - font.lineHeight) / step);
const timers = sortTimers(timerEngine.timers(), nowMs).slice(0, fit);
if (!timers.length) return;
let y = band.fromBottom ? band.top + band.height - (timers.length - 1) * step - font.lineHeight : band.top;
for (const timer of timers) {
if (y + font.lineHeight > bottom) break;
const { left, right } = band.span(y, y + font.lineHeight);
const phase = timerPhase(timer);
const clock = phase === "rung" ? "Done" : formatCountdown(timerRemainingMs(timer, nowMs));
const clockWidth = font.measureText(clock);
const nameOffset = font.measureText(clock) + TIMER_NAME_GAP;
const fullName = phase === "paused" ? `${timerDisplayName(timer)} (paused)` : timerDisplayName(timer);
const name = truncateText(font, fullName, Math.max(0, right - left - nameOffset));
const x = band.alignRight ? right - nameOffset - font.measureText(name) : left;
if (phase === "rung") {
image.fillRect(x - 2, y - 1, clockWidth + 4, font.lineHeight + 2, 230);
image.fillRect(x - 2, y - 1, nameOffset - TIMER_NAME_GAP + 4, font.lineHeight + 2, 230);
image.drawText(font, x, y, clock, 1);
} else {
image.drawText(font, x, y, clock, phase === "paused" ? 120 : 200);
}
const nameX = x + clockWidth + 8;
const name = phase === "paused" ? `${timerDisplayName(timer)} (paused)` : timerDisplayName(timer);
image.drawText(font, nameX, y, truncateText(font, name, Math.max(0, x + width - nameX)), 160);
image.drawText(font, x + nameOffset, y, name, 160);
y += step;
}
}