forked from Blendman974/faceclaw
Rewrite the Timer app
This commit is contained in:
1 parent
99a8b97169
commit
f601a62c75
14 files changed
+2990
-826
No files matched your search
+30
-10
@@ -1,17 +1,37 @@
|
||||
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
|
||||
import { type AppDefinition } from "../app-definition";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
import { registerTimerTools } from "../../assistant/timer-tools";
|
||||
import { timerEngine, timersWakeSetting } from "./timer-engine";
|
||||
import { createTimerAppWindow, startTimersTrayIcon, TIMER_SURFACE_ID, TIMER_WINDOW_ID } from "./timer-app";
|
||||
|
||||
/**
|
||||
* Timers, stopwatch and alarms. The clock engine boots with the shell so
|
||||
* timers and alarms fire (and the assistant's timer.* / alarm.* tools work)
|
||||
* with no window open; launching only opens the view on it.
|
||||
*/
|
||||
const timerApp: AppDefinition = {
|
||||
appId: "timer",
|
||||
title: "Timer",
|
||||
title: "Timers",
|
||||
icon: "timer",
|
||||
launch: (ctx) =>
|
||||
launchWorkerAppWindow(ctx, {
|
||||
createWorker: () => new Worker("./timer-app.worker"),
|
||||
windowId: "timer:main",
|
||||
title: "Timer",
|
||||
iconLetter: "T",
|
||||
icon: "timer",
|
||||
}),
|
||||
boot: (ctx) => {
|
||||
timerEngine.boot({
|
||||
playBuzzer: (payload) => ctx.actions.playBuzzerSequence(payload),
|
||||
onRing: () => {
|
||||
// Bring the ringing item on screen: focus the Timers window, then
|
||||
// wake the display if it is off (a setting, since a wearer may
|
||||
// prefer the phone notification alone while the glasses sleep).
|
||||
void ctx
|
||||
.launchApp("timer")
|
||||
.then(() => {
|
||||
if (timersWakeSetting.get() && !shell.isScreenOn()) shell.wake("window");
|
||||
})
|
||||
.catch((error) => console.error(`timers ring launch failed: ${error}`));
|
||||
},
|
||||
});
|
||||
startTimersTrayIcon();
|
||||
registerTimerTools((appId) => ctx.launchApp(appId));
|
||||
},
|
||||
launch: (ctx) => ctx.launchInProcessApp(TIMER_WINDOW_ID, TIMER_SURFACE_ID, createTimerAppWindow),
|
||||
};
|
||||
|
||||
export default timerApp;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,751 +0,0 @@
|
||||
/**
|
||||
* Timer app worker. The singleton window contains a stopwatch plus a list of
|
||||
* independently scheduled countdown timers. Android AlarmManager owns the
|
||||
* durable expiry path; worker timeouts keep the live UI prompt.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { type UiFont, GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
import { getFont } from "../../graphics/bdffont";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import {
|
||||
cancelTimerNotification,
|
||||
fireTimerNotification,
|
||||
scheduleTimerNotification,
|
||||
} from "../../native/timer-notifications";
|
||||
import { WindowMenu } from "../../ui/window-menu";
|
||||
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
|
||||
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
|
||||
declare const global: any;
|
||||
declare const com: any;
|
||||
|
||||
const RENDER_INTERVAL_MS = 100;
|
||||
const TIMER_ROW_HEIGHT = 34;
|
||||
const TIMER_LIST_TOP = 52;
|
||||
const FOOTER_HEIGHT = 34;
|
||||
|
||||
const largeFont = getFont("terminus32");
|
||||
const mediumFont = getFont("terminus24");
|
||||
// Resolved per use so a font-setting change applies without a worker restart.
|
||||
function smallFont(): UiFont {
|
||||
return getDefaultSmallFont();
|
||||
}
|
||||
|
||||
type TimerView = "stopwatch" | "timers" | "editor";
|
||||
|
||||
type TimerWindow = {
|
||||
windowId: string;
|
||||
surfaceId: string;
|
||||
title: string;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
foreground: boolean;
|
||||
/** Whether this window is the shell's input target (pushed with each message). */
|
||||
focused: boolean;
|
||||
/** Tap-then-hold window menu; created on first open. */
|
||||
menu: WindowMenu | null;
|
||||
view: TimerView;
|
||||
stopwatchAction: number;
|
||||
timerSelection: number;
|
||||
editorField: number;
|
||||
editorHours: number;
|
||||
editorMinutes: number;
|
||||
editorSeconds: number;
|
||||
editorMessage: string;
|
||||
renderTimer: ReturnType<typeof setInterval> | null;
|
||||
lastSubmittedFingerprint: string;
|
||||
};
|
||||
|
||||
type CountdownTimer = {
|
||||
id: number;
|
||||
durationMs: number;
|
||||
endAtMs: number;
|
||||
expired: boolean;
|
||||
expiryTimeout: ReturnType<typeof setTimeout> | null;
|
||||
};
|
||||
|
||||
const TIMER_TOOLS: ToolSpec[] = [
|
||||
{
|
||||
name: "set_timer",
|
||||
description:
|
||||
"Start a new countdown timer. Give the duration as hours/minutes/seconds; at least one must be nonzero. Returns the timer's number and when it will finish.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
hours: { type: "number", description: "Hours component of the duration (default 0)." },
|
||||
minutes: { type: "number", description: "Minutes component of the duration (default 0)." },
|
||||
seconds: { type: "number", description: "Seconds component of the duration (default 0)." },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
},
|
||||
{
|
||||
name: "list_timers",
|
||||
description:
|
||||
"List the countdown timers: each timer's number, its original duration, and the time remaining (or that it has finished).",
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
availability: "open",
|
||||
},
|
||||
{
|
||||
name: "cancel_timer",
|
||||
description:
|
||||
"Cancel a running countdown timer, or dismiss a finished one. Give the timer number from list_timers; it may be omitted when only one timer exists. Pass all=true to clear every timer.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
timer: { type: "number", description: "1-based timer number, as shown in the timer list." },
|
||||
all: { type: "boolean", description: "Clear all timers instead of a single one." },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability: "open",
|
||||
},
|
||||
];
|
||||
|
||||
const windows = new Map<string, TimerWindow>();
|
||||
const timers: CountdownTimer[] = [];
|
||||
let screenOn = true;
|
||||
let stopwatchAccumulatedMs = 0;
|
||||
let stopwatchRunningSinceMs: number | null = null;
|
||||
let nextTimerSerial = 1;
|
||||
|
||||
function post(message: WorkerAppReply): void {
|
||||
global.postMessage(message);
|
||||
}
|
||||
|
||||
// The host queues messages until this arrives: posts to a worker whose bundle
|
||||
// is still evaluating can be silently dropped (see WorkerAppHost). Top-level
|
||||
// evaluation is synchronous, so the handler below is installed before any
|
||||
// queued message can be delivered.
|
||||
post({ type: "worker-ready" });
|
||||
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "open-window":
|
||||
windows.set(message.windowId, {
|
||||
windowId: message.windowId,
|
||||
surfaceId: message.surfaceId,
|
||||
title: message.title,
|
||||
viewportWidth: message.viewport.width,
|
||||
viewportHeight: message.viewport.height,
|
||||
foreground: false,
|
||||
focused: false,
|
||||
menu: null,
|
||||
view: "stopwatch",
|
||||
stopwatchAction: 0,
|
||||
timerSelection: 0,
|
||||
editorField: 0,
|
||||
editorHours: 0,
|
||||
editorMinutes: 5,
|
||||
editorSeconds: 0,
|
||||
editorMessage: "",
|
||||
renderTimer: null,
|
||||
lastSubmittedFingerprint: "",
|
||||
});
|
||||
post({ type: "set-tools", windowId: message.windowId, tools: TIMER_TOOLS });
|
||||
syncExpiredTimers();
|
||||
break;
|
||||
case "close-window": {
|
||||
const window = windows.get(message.windowId);
|
||||
if (window?.renderTimer) clearInterval(window.renderTimer);
|
||||
windows.delete(message.windowId);
|
||||
break;
|
||||
}
|
||||
case "input": {
|
||||
const window = windows.get(message.windowId);
|
||||
if (!window) {
|
||||
frameTimings.finishFrame(message.frameId, "discarded: unknown timer window");
|
||||
break;
|
||||
}
|
||||
window.focused = message.focused;
|
||||
// Marks the main-thread -> worker hop, which is otherwise an
|
||||
// unexplained gap inside the shell's handle-input span.
|
||||
frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
|
||||
handleInput(window, message.event as InputEvent, message.frameId);
|
||||
break;
|
||||
}
|
||||
case "render": {
|
||||
const window = windows.get(message.windowId);
|
||||
if (!window) break;
|
||||
window.focused = message.focused;
|
||||
renderAndSubmit(window, 0);
|
||||
break;
|
||||
}
|
||||
case "foreground": {
|
||||
const window = windows.get(message.windowId);
|
||||
if (!window) break;
|
||||
window.foreground = message.foreground;
|
||||
window.focused = message.focused;
|
||||
updateRenderTimer(window);
|
||||
if (window.foreground) renderAndSubmit(window, 0);
|
||||
break;
|
||||
}
|
||||
case "screen":
|
||||
screenOn = message.on;
|
||||
for (const window of windows.values()) updateRenderTimer(window);
|
||||
break;
|
||||
case "tool-call": {
|
||||
let result: ToolResult;
|
||||
try {
|
||||
result = handleTimerTool(message.name, message.args);
|
||||
} catch (error) {
|
||||
result = { ok: false, error: String((error as Error)?.message ?? error) };
|
||||
}
|
||||
post({ type: "tool-result", callId: message.callId, result });
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tools
|
||||
|
||||
function handleTimerTool(name: string, args: any): ToolResult {
|
||||
syncExpiredTimers();
|
||||
switch (name) {
|
||||
case "set_timer": {
|
||||
const hours = toolDurationField(args?.hours, "hours");
|
||||
const minutes = toolDurationField(args?.minutes, "minutes");
|
||||
const seconds = toolDurationField(args?.seconds, "seconds");
|
||||
const durationMs = Math.round(((hours * 60 + minutes) * 60 + seconds) * 1000);
|
||||
if (durationMs <= 0) return { ok: false, error: "set_timer requires a duration longer than zero" };
|
||||
addTimer(durationMs);
|
||||
const timer = timers[timers.length - 1]!;
|
||||
refreshWindowsAfterToolChange();
|
||||
return {
|
||||
ok: true,
|
||||
content:
|
||||
`Started a ${formatDuration(durationMs)} timer (timer ${timers.length}), ` +
|
||||
`finishing at ${formatClock(timer.endAtMs)}.`,
|
||||
};
|
||||
}
|
||||
case "list_timers": {
|
||||
if (timers.length === 0) return { ok: true, content: "No timers are set." };
|
||||
return { ok: true, content: timers.map(describeTimer).join("\n") };
|
||||
}
|
||||
case "cancel_timer": {
|
||||
if (args?.all === true) {
|
||||
if (timers.length === 0) return { ok: true, content: "No timers are set." };
|
||||
const count = timers.length;
|
||||
for (const timer of [...timers]) removeTimer(timer);
|
||||
refreshWindowsAfterToolChange();
|
||||
return { ok: true, content: count === 1 ? "Cleared the timer." : `Cleared ${count} timers.` };
|
||||
}
|
||||
if (timers.length === 0) return { ok: true, content: "No timers are set." };
|
||||
let timer: CountdownTimer;
|
||||
if (args?.timer === undefined || args?.timer === null) {
|
||||
if (timers.length > 1) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `There are ${timers.length} timers; give the timer number.\n${timers.map(describeTimer).join("\n")}`,
|
||||
};
|
||||
}
|
||||
timer = timers[0]!;
|
||||
} else {
|
||||
const index = Math.floor(Number(args.timer));
|
||||
if (!Number.isFinite(index) || index < 1 || index > timers.length) {
|
||||
return { ok: false, error: `No timer ${args.timer}; there are ${timers.length} timers.` };
|
||||
}
|
||||
timer = timers[index - 1]!;
|
||||
}
|
||||
const description = describeTimer(timer);
|
||||
removeTimer(timer);
|
||||
refreshWindowsAfterToolChange();
|
||||
return { ok: true, content: `${timer.expired ? "Dismissed" : "Canceled"}: ${description}` };
|
||||
}
|
||||
default:
|
||||
return { ok: false, error: `Unknown timer tool: ${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
function toolDurationField(value: unknown, label: string): number {
|
||||
if (value === undefined || value === null) return 0;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
throw new Error(`Invalid ${label} value: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function describeTimer(timer: CountdownTimer): string {
|
||||
const number = timers.indexOf(timer) + 1;
|
||||
const duration = formatDuration(timer.durationMs);
|
||||
if (timer.expired) return `Timer ${number}: ${duration} timer, finished.`;
|
||||
return (
|
||||
`Timer ${number}: ${duration} timer, ${formatCountdown(timer.endAtMs - Date.now())} remaining ` +
|
||||
`(finishes at ${formatClock(timer.endAtMs)}).`
|
||||
);
|
||||
}
|
||||
|
||||
/** Repaint and re-gate every window after a tool call changed the timer list. */
|
||||
function refreshWindowsAfterToolChange(): void {
|
||||
for (const window of windows.values()) {
|
||||
window.timerSelection = clamp(window.timerSelection, 0, timers.length + 1);
|
||||
updateRenderTimer(window);
|
||||
if (window.foreground && screenOn) renderAndSubmit(window, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The window's context menu, created lazily. The timer has no entries of
|
||||
* its own, so tap-then-hold opens the shell's system menu in its place.
|
||||
*/
|
||||
function windowMenu(window: TimerWindow): WindowMenu {
|
||||
if (!window.menu) {
|
||||
window.menu = new WindowMenu({
|
||||
windowId: window.windowId,
|
||||
post,
|
||||
title: () => window.title,
|
||||
items: () => [],
|
||||
size: { width: window.viewportWidth, height: window.viewportHeight },
|
||||
paintBase: () => paintContent(window),
|
||||
isFocused: () => window.focused,
|
||||
});
|
||||
}
|
||||
return window.menu;
|
||||
}
|
||||
|
||||
function handleInput(window: TimerWindow, event: InputEvent, frameId: number): void {
|
||||
// An open window menu owns all input (it closes itself via pop).
|
||||
if (window.menu?.isOpen()) {
|
||||
window.menu
|
||||
.handleInput(event)
|
||||
.catch((error) => console.error(`timer menu input failed: ${error}`))
|
||||
.then(() => renderAndSubmit(window, frameId));
|
||||
return;
|
||||
}
|
||||
if (event.type === "short-then-long-press") {
|
||||
windowMenu(window).open();
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type === "double-click") {
|
||||
if (window.view === "editor") {
|
||||
window.view = "timers";
|
||||
window.editorMessage = "";
|
||||
updateRenderTimer(window);
|
||||
renderAndSubmit(window, frameId);
|
||||
} else {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer yielded focus");
|
||||
post({ type: "yield-focus", windowId: window.windowId });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.view === "stopwatch") {
|
||||
handleStopwatchInput(window, event, frameId);
|
||||
} else if (window.view === "timers") {
|
||||
handleTimersInput(window, event, frameId);
|
||||
} else {
|
||||
handleEditorInput(window, event, frameId);
|
||||
}
|
||||
}
|
||||
|
||||
function handleStopwatchInput(window: TimerWindow, event: InputEvent, frameId: number): void {
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
const delta = event.type === "scroll-down" ? 1 : -1;
|
||||
window.stopwatchAction = clamp(window.stopwatchAction + delta, 0, 2);
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "click") {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer stopwatch ignored input");
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.stopwatchAction === 0) {
|
||||
if (stopwatchRunningSinceMs === null) {
|
||||
stopwatchRunningSinceMs = Date.now();
|
||||
} else {
|
||||
stopwatchAccumulatedMs += Date.now() - stopwatchRunningSinceMs;
|
||||
stopwatchRunningSinceMs = null;
|
||||
}
|
||||
} else if (window.stopwatchAction === 1) {
|
||||
stopwatchAccumulatedMs = 0;
|
||||
stopwatchRunningSinceMs = null;
|
||||
} else {
|
||||
window.view = "timers";
|
||||
window.timerSelection = 0;
|
||||
}
|
||||
updateRenderTimer(window);
|
||||
renderAndSubmit(window, frameId);
|
||||
}
|
||||
|
||||
function handleTimersInput(window: TimerWindow, event: InputEvent, frameId: number): void {
|
||||
syncExpiredTimers();
|
||||
const itemCount = timers.length + 2; // Stopwatch navigation + New timer + timers.
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
const delta = event.type === "scroll-down" ? 1 : -1;
|
||||
window.timerSelection = clamp(window.timerSelection + delta, 0, itemCount - 1);
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "click") {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer list ignored input");
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.timerSelection === 0) {
|
||||
window.view = "stopwatch";
|
||||
} else if (window.timerSelection === 1) {
|
||||
openEditor(window);
|
||||
} else {
|
||||
const timer = timers[window.timerSelection - 2];
|
||||
if (timer) removeTimer(timer);
|
||||
window.timerSelection = clamp(window.timerSelection, 0, Math.max(0, timers.length + 1));
|
||||
}
|
||||
updateRenderTimer(window);
|
||||
renderAndSubmit(window, frameId);
|
||||
}
|
||||
|
||||
function handleEditorInput(window: TimerWindow, event: InputEvent, frameId: number): void {
|
||||
if (event.type === "scroll-up" || event.type === "scroll-down") {
|
||||
const delta = event.type === "scroll-up" ? 1 : -1;
|
||||
if (window.editorField === 0) {
|
||||
window.editorHours = clamp(window.editorHours + delta, 0, 23);
|
||||
} else if (window.editorField === 1) {
|
||||
window.editorMinutes = clamp(window.editorMinutes + delta, 0, 59);
|
||||
} else if (window.editorField === 2) {
|
||||
window.editorSeconds = clamp(window.editorSeconds + delta, 0, 59);
|
||||
} else {
|
||||
window.editorField = delta > 0 ? 2 : 3;
|
||||
}
|
||||
window.editorMessage = "";
|
||||
renderAndSubmit(window, frameId);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "click") {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer editor ignored input");
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.editorField < 3) {
|
||||
window.editorField += 1;
|
||||
} else {
|
||||
const durationMs =
|
||||
((window.editorHours * 60 + window.editorMinutes) * 60 + window.editorSeconds) * 1000;
|
||||
if (durationMs <= 0) {
|
||||
window.editorMessage = "Choose a duration";
|
||||
window.editorField = 0;
|
||||
} else {
|
||||
addTimer(durationMs);
|
||||
window.view = "timers";
|
||||
window.timerSelection = timers.length + 1;
|
||||
window.editorMessage = "";
|
||||
}
|
||||
}
|
||||
updateRenderTimer(window);
|
||||
renderAndSubmit(window, frameId);
|
||||
}
|
||||
|
||||
function openEditor(window: TimerWindow): void {
|
||||
window.view = "editor";
|
||||
window.editorField = 0;
|
||||
window.editorHours = 0;
|
||||
window.editorMinutes = 5;
|
||||
window.editorSeconds = 0;
|
||||
window.editorMessage = "";
|
||||
}
|
||||
|
||||
function addTimer(durationMs: number): void {
|
||||
// Millisecond epoch plus a small serial is unique across worker restarts and
|
||||
// still safely representable as a JavaScript/Java long bridge value.
|
||||
const id = Date.now() * 100 + (nextTimerSerial++ % 100);
|
||||
const endAtMs = Date.now() + durationMs;
|
||||
const timer: CountdownTimer = {
|
||||
id,
|
||||
durationMs,
|
||||
endAtMs,
|
||||
expired: false,
|
||||
expiryTimeout: null,
|
||||
};
|
||||
timers.push(timer);
|
||||
const durationLabel = formatDuration(durationMs);
|
||||
scheduleTimerNotification(id, endAtMs, durationLabel);
|
||||
timer.expiryTimeout = setTimeout(() => expireTimer(timer), Math.max(0, endAtMs - Date.now()));
|
||||
}
|
||||
|
||||
function expireTimer(timer: CountdownTimer, renderWindows = true): void {
|
||||
if (timer.expired) return;
|
||||
timer.expired = true;
|
||||
timer.expiryTimeout = null;
|
||||
fireTimerNotification(timer.id, formatDuration(timer.durationMs));
|
||||
for (const window of windows.values()) {
|
||||
post({ type: "set-attention", windowId: window.windowId, attention: true });
|
||||
updateRenderTimer(window);
|
||||
if (renderWindows && window.foreground && screenOn) renderAndSubmit(window, 0);
|
||||
}
|
||||
}
|
||||
|
||||
function removeTimer(timer: CountdownTimer): void {
|
||||
if (timer.expiryTimeout) clearTimeout(timer.expiryTimeout);
|
||||
cancelTimerNotification(timer.id);
|
||||
const index = timers.indexOf(timer);
|
||||
if (index >= 0) timers.splice(index, 1);
|
||||
}
|
||||
|
||||
function syncExpiredTimers(): void {
|
||||
const now = Date.now();
|
||||
for (const timer of timers) {
|
||||
// The caller is already about to paint, so avoid a nested render when a
|
||||
// sleeping/backgrounded timer is first observed as finished.
|
||||
if (!timer.expired && timer.endAtMs <= now) expireTimer(timer, false);
|
||||
}
|
||||
}
|
||||
|
||||
function updateRenderTimer(window: TimerWindow): void {
|
||||
const activeCountdowns = timers.some((timer) => !timer.expired);
|
||||
const dynamic =
|
||||
(window.view === "stopwatch" && stopwatchRunningSinceMs !== null) ||
|
||||
(window.view === "timers" && activeCountdowns);
|
||||
const shouldRun = dynamic && window.foreground && screenOn;
|
||||
if (shouldRun && window.renderTimer === null) {
|
||||
window.renderTimer = setInterval(() => {
|
||||
syncExpiredTimers();
|
||||
renderAndSubmit(window, 0);
|
||||
}, RENDER_INTERVAL_MS);
|
||||
} else if (!shouldRun && window.renderTimer !== null) {
|
||||
clearInterval(window.renderTimer);
|
||||
window.renderTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function paint(window: TimerWindow): Plane[] {
|
||||
return windowMenu(window).paint();
|
||||
}
|
||||
|
||||
function paintContent(window: TimerWindow): GrayImage {
|
||||
syncExpiredTimers();
|
||||
const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0);
|
||||
if (window.view === "stopwatch") {
|
||||
paintStopwatch(image, window);
|
||||
} else if (window.view === "timers") {
|
||||
paintTimers(image, window);
|
||||
} else {
|
||||
paintEditor(image, window);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
function paintStopwatch(image: GrayImage, window: TimerWindow): void {
|
||||
drawTabs(image, "stopwatch");
|
||||
const elapsed = stopwatchElapsedMs();
|
||||
const timeLabel = formatStopwatchElapsed(elapsed);
|
||||
const timeX = Math.max(0, Math.round((window.viewportWidth - largeFont.measureText(timeLabel)) / 2));
|
||||
image.drawText(largeFont, timeX, 66, timeLabel, 245);
|
||||
|
||||
const state = stopwatchRunningSinceMs === null ? (elapsed > 0 ? "Paused" : "Ready") : "Running";
|
||||
drawCenteredText(image, smallFont(), 112, state, 145);
|
||||
|
||||
const labels = [stopwatchRunningSinceMs === null ? "Start" : "Pause", "Reset", `Timers (${timers.length})`];
|
||||
drawButtonRow(image, labels, window.stopwatchAction, 154);
|
||||
drawFooter(image, `${GESTURE_SCROLL} action ${GESTURE_CLICK} select ${GESTURE_DOUBLE_CLICK} back`);
|
||||
}
|
||||
|
||||
function paintTimers(image: GrayImage, window: TimerWindow): void {
|
||||
drawTabs(image, "timers");
|
||||
const items = ["< Stopwatch", "+ New timer", ...timers.map(timerRowLabel)];
|
||||
const listBottom = image.height - FOOTER_HEIGHT;
|
||||
const visibleRows = Math.max(1, Math.floor((listBottom - TIMER_LIST_TOP) / TIMER_ROW_HEIGHT));
|
||||
const first = clamp(window.timerSelection - visibleRows + 1, 0, Math.max(0, items.length - visibleRows));
|
||||
|
||||
for (let row = 0; row < visibleRows; row++) {
|
||||
const index = first + row;
|
||||
if (index >= items.length) break;
|
||||
const y = TIMER_LIST_TOP + row * TIMER_ROW_HEIGHT;
|
||||
const selected = index === window.timerSelection;
|
||||
if (selected) {
|
||||
image.fillRoundedRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 34, 5);
|
||||
image.drawRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 105);
|
||||
}
|
||||
image.drawText(index >= 2 ? mediumFont : smallFont(), 32, y + (index >= 2 ? 2 : 7), items[index]!, selected ? 245 : 180);
|
||||
}
|
||||
|
||||
const selectedTimer = window.timerSelection >= 2 ? timers[window.timerSelection - 2] : null;
|
||||
const action = selectedTimer ? (selectedTimer.expired ? "dismiss" : "cancel") : "select";
|
||||
drawFooter(image, `${GESTURE_SCROLL} timer ${GESTURE_CLICK} ${action} ${GESTURE_DOUBLE_CLICK} back`);
|
||||
}
|
||||
|
||||
function paintEditor(image: GrayImage, window: TimerWindow): void {
|
||||
image.drawText(smallFont(), 24, 14, "New timer", 190);
|
||||
const fields = [pad2(window.editorHours), pad2(window.editorMinutes), pad2(window.editorSeconds)];
|
||||
const labels = ["hours", "minutes", "seconds"];
|
||||
const fieldWidth = 118;
|
||||
const gap = 22;
|
||||
const totalWidth = fieldWidth * 3 + gap * 2;
|
||||
const startX = Math.round((image.width - totalWidth) / 2);
|
||||
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const x = startX + index * (fieldWidth + gap);
|
||||
if (window.editorField === index) {
|
||||
image.fillRoundedRect(x, 57, fieldWidth, 68, 35, 6);
|
||||
image.drawRect(x, 57, fieldWidth, 68, 120);
|
||||
}
|
||||
drawCenteredIn(image, largeFont, x, fieldWidth, 65, fields[index]!, window.editorField === index ? 250 : 180);
|
||||
drawCenteredIn(image, smallFont(), x, fieldWidth, 105, labels[index]!, 125);
|
||||
if (index < 2) image.drawText(mediumFont, x + fieldWidth + 5, 71, ":", 130);
|
||||
}
|
||||
|
||||
const startSelected = window.editorField === 3;
|
||||
const buttonWidth = 160;
|
||||
const buttonX = Math.round((image.width - buttonWidth) / 2);
|
||||
if (startSelected) {
|
||||
image.fillRoundedRect(buttonX, 151, buttonWidth, 38, 40, 6);
|
||||
image.drawRect(buttonX, 151, buttonWidth, 38, 120);
|
||||
}
|
||||
drawCenteredIn(image, smallFont(), buttonX, buttonWidth, 162, "Start timer", startSelected ? 250 : 175);
|
||||
if (window.editorMessage) drawCenteredText(image, smallFont(), 202, window.editorMessage, 190);
|
||||
drawFooter(image, `${GESTURE_SCROLL} adjust ${GESTURE_CLICK} next ${GESTURE_DOUBLE_CLICK} cancel`);
|
||||
}
|
||||
|
||||
function drawTabs(image: GrayImage, active: "stopwatch" | "timers"): void {
|
||||
const stopwatch = "Stopwatch";
|
||||
const timerLabel = `Timers (${timers.length})`;
|
||||
const left = 24;
|
||||
const dividerX = left + smallFont().measureText(stopwatch) + 18;
|
||||
image.drawText(smallFont(), left, 15, stopwatch, active === "stopwatch" ? 245 : 105);
|
||||
image.drawLine(left, 35, dividerX - 12, 35, active === "stopwatch" ? 200 : 30);
|
||||
image.drawText(smallFont(), dividerX, 15, timerLabel, active === "timers" ? 245 : 105);
|
||||
image.drawLine(dividerX, 35, dividerX + smallFont().measureText(timerLabel), 35, active === "timers" ? 200 : 30);
|
||||
}
|
||||
|
||||
function drawButtonRow(image: GrayImage, labels: string[], selected: number, y: number): void {
|
||||
const gap = 12;
|
||||
const margin = 24;
|
||||
const width = Math.floor((image.width - margin * 2 - gap * (labels.length - 1)) / labels.length);
|
||||
for (let index = 0; index < labels.length; index++) {
|
||||
const x = margin + index * (width + gap);
|
||||
if (index === selected) {
|
||||
image.fillRoundedRect(x, y, width, 40, 38, 6);
|
||||
image.drawRect(x, y, width, 40, 115);
|
||||
}
|
||||
drawCenteredIn(image, smallFont(), x, width, y + 12, labels[index]!, index === selected ? 245 : 155);
|
||||
}
|
||||
}
|
||||
|
||||
function drawFooter(image: GrayImage, text: string): void {
|
||||
image.drawLine(16, image.height - FOOTER_HEIGHT, image.width - 16, image.height - FOOTER_HEIGHT, 35);
|
||||
drawCenteredText(image, smallFont(), image.height - 22, text, 115);
|
||||
}
|
||||
|
||||
function drawCenteredText(image: GrayImage, font: UiFont, y: number, text: string, value: number): void {
|
||||
image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, value);
|
||||
}
|
||||
|
||||
function drawCenteredIn(
|
||||
image: GrayImage,
|
||||
font: UiFont,
|
||||
x: number,
|
||||
width: number,
|
||||
y: number,
|
||||
text: string,
|
||||
value: number,
|
||||
): void {
|
||||
image.drawText(font, Math.round(x + (width - font.measureText(text)) / 2), y, text, value);
|
||||
}
|
||||
|
||||
function timerRowLabel(timer: CountdownTimer): string {
|
||||
const number = timers.indexOf(timer) + 1;
|
||||
if (timer.expired) return `${number}. 00:00 Finished`;
|
||||
return `${number}. ${formatCountdown(timer.endAtMs - Date.now())} Running`;
|
||||
}
|
||||
|
||||
function renderAndSubmit(window: TimerWindow, inputFrameId: number): void {
|
||||
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${window.windowId}`);
|
||||
try {
|
||||
const paintStartedAtMs = Date.now();
|
||||
const planes = frameTimings.span(frameId, "paint", () =>
|
||||
frameTimings.runWithFrame(frameId, () => paint(window)),
|
||||
);
|
||||
const paintMs = Date.now() - paintStartedAtMs;
|
||||
const fingerprint = planesFingerprint(planes);
|
||||
if (fingerprint === window.lastSubmittedFingerprint) {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer content unchanged");
|
||||
return;
|
||||
}
|
||||
const communicator = getActiveDisplay();
|
||||
if (!communicator) {
|
||||
frameTimings.finishFrame(frameId, "discarded: no active display");
|
||||
return;
|
||||
}
|
||||
const { image, draws } = frameTimings.span(frameId, "flatten", () => flattenPlanesWithDraws(planes));
|
||||
const buffer = frameTimings.span(frameId, "to8bpp", () => image.to8bppBuffer());
|
||||
communicator.submitSurfaceFrame(
|
||||
buffer.buffer,
|
||||
window.surfaceId,
|
||||
0,
|
||||
0,
|
||||
image.width,
|
||||
image.height,
|
||||
fingerprint,
|
||||
paintMs,
|
||||
frameId,
|
||||
frameTimings.span(frameId, "prepareFrameDraws", () => prepareFrameDraws(draws)),
|
||||
);
|
||||
window.lastSubmittedFingerprint = fingerprint;
|
||||
} catch (error) {
|
||||
frameTimings.finishFrame(frameId, "discarded: timer render failed");
|
||||
console.error(`timer worker render failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
function stopwatchElapsedMs(): number {
|
||||
const runningMs = stopwatchRunningSinceMs === null ? 0 : Date.now() - stopwatchRunningSinceMs;
|
||||
return stopwatchAccumulatedMs + runningMs;
|
||||
}
|
||||
|
||||
function pad2(value: number): string {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
function formatStopwatchElapsed(totalMs: number): string {
|
||||
const totalTenths = Math.floor(totalMs / 100);
|
||||
const tenths = totalTenths % 10;
|
||||
const totalSeconds = Math.floor(totalTenths / 10);
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
return hours > 0
|
||||
? `${hours}:${pad2(minutes)}:${pad2(seconds)}.${tenths}`
|
||||
: `${pad2(minutes)}:${pad2(seconds)}.${tenths}`;
|
||||
}
|
||||
|
||||
function formatCountdown(remainingMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${pad2(minutes)}:${pad2(seconds)}`;
|
||||
}
|
||||
|
||||
function formatClock(timestampMs: number): string {
|
||||
const date = new Date(timestampMs);
|
||||
let hours = date.getHours();
|
||||
const minutes = String(date.getMinutes()).padStart(2, "0");
|
||||
const meridiem = hours >= 12 ? "PM" : "AM";
|
||||
hours = hours % 12;
|
||||
if (hours === 0) hours = 12;
|
||||
return `${hours}:${minutes} ${meridiem}`;
|
||||
}
|
||||
|
||||
function formatDuration(durationMs: number): string {
|
||||
const totalSeconds = Math.round(durationMs / 1000);
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
/**
|
||||
* The Timers app's clock engine: a main-thread singleton that owns the
|
||||
* timers / stopwatch / alarms state, persists it, schedules the durable
|
||||
* Android alarms behind every expiry, rings the glasses buzzer, and tells
|
||||
* listeners (the window, the tray icon, the assistant tools) when anything
|
||||
* changes. It is booted at shell start, so everything here works with the
|
||||
* window closed; the window is only a view on it.
|
||||
*
|
||||
* Two expiry paths run side by side, as before: a JS deadline for prompt
|
||||
* on-glasses ringing while the process is awake, and an AlarmManager alarm
|
||||
* (see FaceclawTimerNotifications.java) that posts the phone notification
|
||||
* at the right moment even if the process is asleep or dead. The Java side
|
||||
* deduplicates the two.
|
||||
*/
|
||||
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import {
|
||||
cancelTimerNotification,
|
||||
fireTimerNotification,
|
||||
scheduleTimerNotification,
|
||||
} from "../../native/timer-notifications";
|
||||
import { buildSoundSequencePayload, findSoundEffect, effectPhrases } from "../../ui/sound-effects";
|
||||
import { timeFormatSetting } from "../../ui/dashboard-settings";
|
||||
import {
|
||||
alarmNextRingMs,
|
||||
createAlarm,
|
||||
createTimer,
|
||||
emptyTimersState,
|
||||
formatDurationWords,
|
||||
formatTimeOfDay,
|
||||
parseTimersState,
|
||||
pushRecentDuration,
|
||||
serializeTimersState,
|
||||
stopwatchElapsedMs,
|
||||
timerRemainingMs,
|
||||
type Alarm,
|
||||
type CountdownTimer,
|
||||
type TimersState,
|
||||
} from "./timer-model";
|
||||
|
||||
const STATE_KEY = "timers.state";
|
||||
|
||||
/**
|
||||
* An expiry that passed longer ago than this while the process was down
|
||||
* (phone off, app killed) is marked rung silently rather than blaring on
|
||||
* the glasses hours late; the phone notification already fired on time.
|
||||
*/
|
||||
const RING_GRACE_MS = 5 * 60_000;
|
||||
/** How often the buzzer repeats while something is ringing. */
|
||||
const RING_REPEAT_MS = 3_000;
|
||||
/** Stop buzzing an item this long after it started ringing (it stays "rung"). */
|
||||
const RING_MAX_MS = 2 * 60_000;
|
||||
/**
|
||||
* Upper bound between deadline checks even with nothing due, so a JS timer
|
||||
* delayed by Doze or a clock jump can't leave a due item unnoticed for long.
|
||||
*/
|
||||
const MAX_ARM_MS = 30_000;
|
||||
|
||||
export const timersSoundSetting = new ConfigSettingBoolean({
|
||||
id: "timersSound",
|
||||
label: "Sound on glasses",
|
||||
storageKey: "timers.soundOnGlasses",
|
||||
defaultValue: true,
|
||||
description: "Play the glasses buzzer while a timer or alarm is ringing.",
|
||||
});
|
||||
|
||||
export const timersWakeSetting = new ConfigSettingBoolean({
|
||||
id: "timersWake",
|
||||
label: "Wake glasses when ringing",
|
||||
storageKey: "timers.wakeGlasses",
|
||||
defaultValue: true,
|
||||
description: "Turn the display on and show the Timers app when a timer or alarm goes off.",
|
||||
});
|
||||
|
||||
export type SnoozeMinutes = "5" | "10" | "15";
|
||||
export const timersSnoozeSetting = new ConfigSettingEnum<SnoozeMinutes>({
|
||||
id: "timersSnooze",
|
||||
label: "Snooze length",
|
||||
storageKey: "timers.snoozeMinutes",
|
||||
defaultValue: "10",
|
||||
values: ["5", "10", "15"],
|
||||
formatValue: (value) => `${value} min`,
|
||||
});
|
||||
|
||||
export type RingingItem = { kind: "timer"; timer: CountdownTimer } | { kind: "alarm"; alarm: Alarm };
|
||||
|
||||
export type TimerEngineHooks = {
|
||||
/** Play one buzzer sequencer payload on the glasses (no-op when disconnected). */
|
||||
playBuzzer: (payload: Uint8Array) => Promise<void> | void;
|
||||
/** Something started ringing audibly: bring the app forward, wake the glasses. */
|
||||
onRing: (item: RingingItem) => void;
|
||||
};
|
||||
|
||||
const noopHooks: TimerEngineHooks = { playBuzzer: () => {}, onRing: () => {} };
|
||||
|
||||
export class TimerEngine {
|
||||
state: TimersState;
|
||||
private hooks: TimerEngineHooks = noopHooks;
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private deadlineTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private ringTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private booted = false;
|
||||
|
||||
constructor(private readonly now: () => number = () => Date.now()) {
|
||||
this.state = emptyTimersState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the side-effect hooks and reconcile persisted state against the
|
||||
* clock: anything that came due while the process was down rings (or is
|
||||
* marked rung silently past the grace window), and the Android alarms are
|
||||
* re-armed for what is still pending.
|
||||
*/
|
||||
boot(hooks: TimerEngineHooks): void {
|
||||
this.hooks = hooks;
|
||||
if (this.booted) return;
|
||||
this.booted = true;
|
||||
// Loaded here rather than at module evaluation, so the settings store is
|
||||
// certainly up before the first read.
|
||||
this.state = parseTimersState(getStringSetting(STATE_KEY, ""));
|
||||
this.check();
|
||||
for (const timer of this.state.timers) {
|
||||
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
|
||||
}
|
||||
for (const alarm of this.state.alarms) this.schedulePhoneAlarm(alarm);
|
||||
this.save();
|
||||
}
|
||||
|
||||
onChange(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** True while anything on screen changes by itself once a second. */
|
||||
isDynamic(): boolean {
|
||||
return (
|
||||
this.state.stopwatch.runningSinceMs !== null ||
|
||||
this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null) ||
|
||||
this.ringingItems().length > 0
|
||||
);
|
||||
}
|
||||
|
||||
ringingItems(): RingingItem[] {
|
||||
const items: RingingItem[] = [];
|
||||
for (const timer of this.state.timers) {
|
||||
if (timer.rungAtMs !== null) items.push({ kind: "timer", timer });
|
||||
}
|
||||
for (const alarm of this.state.alarms) {
|
||||
if (alarm.ringingSinceMs !== null) items.push({ kind: "alarm", alarm });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Timers
|
||||
|
||||
findTimer(id: number): CountdownTimer | undefined {
|
||||
return this.state.timers.find((timer) => timer.id === id);
|
||||
}
|
||||
|
||||
startTimer(durationMs: number, label = ""): CountdownTimer {
|
||||
const timer = createTimer(durationMs, label, this.now());
|
||||
this.state.timers.push(timer);
|
||||
this.state.recentDurationsMs = pushRecentDuration(this.state.recentDurationsMs, durationMs);
|
||||
this.schedulePhoneNotification(timer);
|
||||
this.commit();
|
||||
return timer;
|
||||
}
|
||||
|
||||
pauseTimer(id: number): void {
|
||||
const timer = this.findTimer(id);
|
||||
if (!timer || timer.endsAtMs === null || timer.rungAtMs !== null) return;
|
||||
timer.pausedRemainingMs = Math.max(0, timer.endsAtMs - this.now());
|
||||
timer.endsAtMs = null;
|
||||
cancelTimerNotification(timer.id);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
resumeTimer(id: number): void {
|
||||
const timer = this.findTimer(id);
|
||||
if (!timer || timer.pausedRemainingMs === null) return;
|
||||
timer.endsAtMs = this.now() + timer.pausedRemainingMs;
|
||||
timer.pausedRemainingMs = null;
|
||||
this.schedulePhoneNotification(timer);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
/** Add time to a timer; a rung timer becomes a running one with just the added time. */
|
||||
addTimerTime(id: number, deltaMs: number): void {
|
||||
const timer = this.findTimer(id);
|
||||
if (!timer) return;
|
||||
if (timer.rungAtMs !== null) {
|
||||
timer.rungAtMs = null;
|
||||
timer.durationMs = deltaMs;
|
||||
timer.endsAtMs = this.now() + deltaMs;
|
||||
cancelTimerNotification(timer.id);
|
||||
this.schedulePhoneNotification(timer);
|
||||
} else if (timer.pausedRemainingMs !== null) {
|
||||
timer.pausedRemainingMs += deltaMs;
|
||||
timer.durationMs += deltaMs;
|
||||
} else if (timer.endsAtMs !== null) {
|
||||
timer.endsAtMs += deltaMs;
|
||||
timer.durationMs += deltaMs;
|
||||
this.schedulePhoneNotification(timer);
|
||||
}
|
||||
this.commit();
|
||||
}
|
||||
|
||||
/** Start the timer over at its set duration ("Again" on a rung timer). */
|
||||
restartTimer(id: number): void {
|
||||
const timer = this.findTimer(id);
|
||||
if (!timer) return;
|
||||
timer.rungAtMs = null;
|
||||
timer.pausedRemainingMs = null;
|
||||
timer.endsAtMs = this.now() + timer.durationMs;
|
||||
cancelTimerNotification(timer.id);
|
||||
this.schedulePhoneNotification(timer);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
setTimerLabel(id: number, label: string): void {
|
||||
const timer = this.findTimer(id);
|
||||
if (!timer) return;
|
||||
timer.label = label.trim();
|
||||
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
/** Cancel a timer, or dismiss a rung one. */
|
||||
removeTimer(id: number): void {
|
||||
const index = this.state.timers.findIndex((timer) => timer.id === id);
|
||||
if (index < 0) return;
|
||||
cancelTimerNotification(id);
|
||||
this.state.timers.splice(index, 1);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Stopwatch
|
||||
|
||||
stopwatchToggle(): void {
|
||||
const stopwatch = this.state.stopwatch;
|
||||
const now = this.now();
|
||||
if (stopwatch.runningSinceMs === null) {
|
||||
stopwatch.runningSinceMs = now;
|
||||
} else {
|
||||
stopwatch.accumulatedMs += Math.max(0, now - stopwatch.runningSinceMs);
|
||||
stopwatch.runningSinceMs = null;
|
||||
}
|
||||
this.commit();
|
||||
}
|
||||
|
||||
stopwatchStart(): void {
|
||||
if (this.state.stopwatch.runningSinceMs === null) this.stopwatchToggle();
|
||||
}
|
||||
|
||||
stopwatchStop(): void {
|
||||
if (this.state.stopwatch.runningSinceMs !== null) this.stopwatchToggle();
|
||||
}
|
||||
|
||||
stopwatchLap(): void {
|
||||
const stopwatch = this.state.stopwatch;
|
||||
if (stopwatch.runningSinceMs === null) return;
|
||||
stopwatch.lapsMs.push(stopwatchElapsedMs(stopwatch, this.now()));
|
||||
this.commit();
|
||||
}
|
||||
|
||||
stopwatchReset(): void {
|
||||
this.state.stopwatch = { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] };
|
||||
this.commit();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Alarms
|
||||
|
||||
findAlarm(id: number): Alarm | undefined {
|
||||
return this.state.alarms.find((alarm) => alarm.id === id);
|
||||
}
|
||||
|
||||
addAlarm(hour: number, minute: number, days: number, label = ""): Alarm {
|
||||
const alarm = createAlarm(hour, minute, days, label, this.now());
|
||||
this.state.alarms.push(alarm);
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
return alarm;
|
||||
}
|
||||
|
||||
setAlarmTime(id: number, hour: number, minute: number): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm) return;
|
||||
alarm.hour = hour;
|
||||
alarm.minute = minute;
|
||||
alarm.enabled = true;
|
||||
alarm.snoozedUntilMs = null;
|
||||
alarm.ringingSinceMs = null;
|
||||
alarm.lastFiredAtMs = null;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
setAlarmDays(id: number, days: number): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm) return;
|
||||
alarm.days = days;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
setAlarmEnabled(id: number, enabled: boolean): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm) return;
|
||||
alarm.enabled = enabled;
|
||||
alarm.snoozedUntilMs = null;
|
||||
alarm.ringingSinceMs = null;
|
||||
if (enabled) alarm.lastFiredAtMs = null;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
setAlarmLabel(id: number, label: string): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm) return;
|
||||
alarm.label = label.trim();
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
deleteAlarm(id: number): void {
|
||||
const index = this.state.alarms.findIndex((alarm) => alarm.id === id);
|
||||
if (index < 0) return;
|
||||
cancelTimerNotification(id);
|
||||
this.state.alarms.splice(index, 1);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
snoozeAlarm(id: number, minutes = Number(timersSnoozeSetting.get())): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm || alarm.ringingSinceMs === null) return;
|
||||
alarm.ringingSinceMs = null;
|
||||
alarm.snoozedUntilMs = this.now() + minutes * 60_000;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
/** Stop a ringing alarm; a one-off alarm switches itself off. */
|
||||
dismissAlarm(id: number): void {
|
||||
const alarm = this.findAlarm(id);
|
||||
if (!alarm || alarm.ringingSinceMs === null) return;
|
||||
alarm.ringingSinceMs = null;
|
||||
alarm.snoozedUntilMs = null;
|
||||
if (alarm.days === 0) alarm.enabled = false;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
this.commit();
|
||||
}
|
||||
|
||||
/** Dismiss whatever is ringing (timers and alarms alike). Returns how many. */
|
||||
dismissAllRinging(): number {
|
||||
const items = this.ringingItems();
|
||||
for (const item of items) {
|
||||
if (item.kind === "timer") this.removeTimer(item.timer.id);
|
||||
else this.dismissAlarm(item.alarm.id);
|
||||
}
|
||||
return items.length;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Deadlines and ringing
|
||||
|
||||
/**
|
||||
* Fire anything due and re-arm for the next deadline. Called on every
|
||||
* change, on the deadline timer, and by the window before it paints, so a
|
||||
* timer never shows 0:00 without also being rung.
|
||||
*/
|
||||
check(): void {
|
||||
const now = this.now();
|
||||
let changed = false;
|
||||
for (const timer of this.state.timers) {
|
||||
if (timer.endsAtMs === null || timer.rungAtMs !== null || timer.endsAtMs > now) continue;
|
||||
timer.rungAtMs = timer.endsAtMs;
|
||||
timer.endsAtMs = null;
|
||||
changed = true;
|
||||
const late = now - timer.rungAtMs > RING_GRACE_MS;
|
||||
fireTimerNotification(timer.id, "Timer finished", timerNotificationText(timer));
|
||||
if (!late) this.startRinging({ kind: "timer", timer });
|
||||
}
|
||||
for (const alarm of this.state.alarms) {
|
||||
if (alarm.ringingSinceMs !== null) continue;
|
||||
const due = this.alarmDueMs(alarm, now);
|
||||
if (due === null || due > now) continue;
|
||||
alarm.ringingSinceMs = now;
|
||||
alarm.snoozedUntilMs = null;
|
||||
alarm.lastFiredAtMs = due;
|
||||
changed = true;
|
||||
const late = now - due > RING_GRACE_MS;
|
||||
fireTimerNotification(alarm.id, "Alarm", alarmNotificationText(alarm));
|
||||
if (late) {
|
||||
// Missed by too much to ring now: fall through to the next occurrence.
|
||||
alarm.ringingSinceMs = null;
|
||||
if (alarm.days === 0) alarm.enabled = false;
|
||||
this.schedulePhoneAlarm(alarm);
|
||||
} else {
|
||||
this.startRinging({ kind: "alarm", alarm });
|
||||
}
|
||||
}
|
||||
this.arm(now);
|
||||
this.syncRingLoop(now);
|
||||
if (changed) this.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* The occurrence an alarm should ring for next: the pending snooze, or the
|
||||
* first occurrence after (now - grace) that it has not already rung for.
|
||||
* Inside the grace window this returns a time in the past, which check()
|
||||
* fires; beyond it the missed occurrence is skipped.
|
||||
*/
|
||||
private alarmDueMs(alarm: Alarm, now: number): number | null {
|
||||
return alarmNextRingMs(alarm, now - RING_GRACE_MS);
|
||||
}
|
||||
|
||||
private startRinging(item: RingingItem): void {
|
||||
try {
|
||||
this.hooks.onRing(item);
|
||||
} catch (error) {
|
||||
console.warn(`timers onRing hook failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-arm the single deadline timer for the soonest pending expiry. */
|
||||
private arm(now: number): void {
|
||||
if (this.deadlineTimer !== null) {
|
||||
clearTimeout(this.deadlineTimer);
|
||||
this.deadlineTimer = null;
|
||||
}
|
||||
const deadlines: number[] = [];
|
||||
for (const timer of this.state.timers) {
|
||||
if (timer.rungAtMs === null && timer.endsAtMs !== null) deadlines.push(timer.endsAtMs);
|
||||
}
|
||||
for (const alarm of this.state.alarms) {
|
||||
if (alarm.ringingSinceMs !== null) continue;
|
||||
const due = this.alarmDueMs(alarm, now);
|
||||
if (due !== null) deadlines.push(due);
|
||||
}
|
||||
if (deadlines.length === 0) return;
|
||||
const delay = Math.min(MAX_ARM_MS, Math.max(0, Math.min(...deadlines) - now));
|
||||
this.deadlineTimer = setTimeout(() => {
|
||||
this.deadlineTimer = null;
|
||||
this.check();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/** Run the buzzer repeat loop while anything is (still audibly) ringing. */
|
||||
private syncRingLoop(now: number): void {
|
||||
const audible = this.ringingItems().some((item) => this.ringAgeMs(item, now) < RING_MAX_MS);
|
||||
if (audible && this.ringTimer === null) {
|
||||
this.playRingSound();
|
||||
this.ringTimer = setInterval(() => {
|
||||
const at = this.now();
|
||||
if (!this.ringingItems().some((item) => this.ringAgeMs(item, at) < RING_MAX_MS)) {
|
||||
this.syncRingLoop(at);
|
||||
return;
|
||||
}
|
||||
this.playRingSound();
|
||||
}, RING_REPEAT_MS);
|
||||
} else if (!audible && this.ringTimer !== null) {
|
||||
clearInterval(this.ringTimer);
|
||||
this.ringTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private ringAgeMs(item: RingingItem, now: number): number {
|
||||
const since = item.kind === "timer" ? item.timer.rungAtMs : item.alarm.ringingSinceMs;
|
||||
return since === null ? Infinity : Math.max(0, now - since);
|
||||
}
|
||||
|
||||
private playRingSound(): void {
|
||||
if (!timersSoundSetting.get()) return;
|
||||
const effect = findSoundEffect("alarm");
|
||||
if (!effect) return;
|
||||
const phrase = effectPhrases(effect.make())[0];
|
||||
if (!phrase) return;
|
||||
try {
|
||||
void this.hooks.playBuzzer(buildSoundSequencePayload(phrase));
|
||||
} catch (error) {
|
||||
console.warn(`timers buzzer failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Phone notifications
|
||||
|
||||
private schedulePhoneNotification(timer: CountdownTimer): void {
|
||||
if (timer.endsAtMs === null) return;
|
||||
scheduleTimerNotification(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer));
|
||||
}
|
||||
|
||||
/** (Re)arm or cancel the phone alarm for an alarm's next occurrence. */
|
||||
private schedulePhoneAlarm(alarm: Alarm): void {
|
||||
const due = alarm.ringingSinceMs === null ? this.alarmDueMs(alarm, this.now()) : null;
|
||||
if (due === null) {
|
||||
cancelTimerNotification(alarm.id);
|
||||
return;
|
||||
}
|
||||
scheduleTimerNotification(alarm.id, due, "Alarm", alarmNotificationText(alarm));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Change plumbing
|
||||
|
||||
private commit(): void {
|
||||
this.save();
|
||||
this.check();
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
try {
|
||||
setStringSetting(STATE_KEY, serializeTimersState(this.state));
|
||||
} catch (error) {
|
||||
console.warn(`timers state save failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
private notify(): void {
|
||||
for (const listener of Array.from(this.listeners)) {
|
||||
try {
|
||||
listener();
|
||||
} catch (error) {
|
||||
console.warn(`timers listener failed: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function timerNotificationText(timer: CountdownTimer): string {
|
||||
const duration = formatDurationWords(timer.durationMs);
|
||||
return timer.label ? `${timer.label} (${duration}) is up` : `${duration} timer is up`;
|
||||
}
|
||||
|
||||
function alarmNotificationText(alarm: Alarm): string {
|
||||
const time = formatTimeOfDay(alarm.hour, alarm.minute, timeFormatSetting.get() === "12h");
|
||||
return alarm.label ? `${time} · ${alarm.label}` : time;
|
||||
}
|
||||
|
||||
/** Remaining time of the timer that ends soonest, for the tray icon; null when none runs. */
|
||||
export function soonestRunningTimerRemainingMs(engine: TimerEngine, now = Date.now()): number | null {
|
||||
let soonest: number | null = null;
|
||||
for (const timer of engine.state.timers) {
|
||||
if (timer.endsAtMs === null || timer.rungAtMs !== null) continue;
|
||||
const remaining = timerRemainingMs(timer, now);
|
||||
if (soonest === null || remaining < soonest) soonest = remaining;
|
||||
}
|
||||
return soonest;
|
||||
}
|
||||
|
||||
export const timerEngine = new TimerEngine();
|
||||
@@ -0,0 +1,460 @@
|
||||
/**
|
||||
* Pure data model for the Timers app: countdown timers, the stopwatch, and
|
||||
* alarms, plus the formatting and scheduling arithmetic they need. No
|
||||
* NativeScript imports, so tests/timer-model.test.cjs can run it under plain
|
||||
* node. Side effects (persistence, Android alarms, the buzzer, waking the
|
||||
* glasses) live in timer-engine.ts; drawing lives in timer-app.ts.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
|
||||
/**
|
||||
* A countdown timer. Exactly one of the three phases holds at a time:
|
||||
* running (endsAtMs set), paused (pausedRemainingMs set), or rung
|
||||
* (rungAtMs set). A rung timer stays until dismissed so a missed one still
|
||||
* reads "Time's up".
|
||||
*/
|
||||
export type CountdownTimer = {
|
||||
/** Unique across restarts and safe as a Java long (see newItemId). */
|
||||
id: number;
|
||||
/** Wearer-given name; "" for an unlabelled timer (shown by duration). */
|
||||
label: string;
|
||||
durationMs: number;
|
||||
endsAtMs: number | null;
|
||||
pausedRemainingMs: number | null;
|
||||
rungAtMs: number | null;
|
||||
createdAtMs: number;
|
||||
};
|
||||
|
||||
export type StopwatchState = {
|
||||
/** Time accumulated over previous running stretches. */
|
||||
accumulatedMs: number;
|
||||
/** Start of the current running stretch, or null while stopped. */
|
||||
runningSinceMs: number | null;
|
||||
/** Cumulative elapsed time at each lap mark, oldest first. */
|
||||
lapsMs: number[];
|
||||
};
|
||||
|
||||
/** Day-of-week bits for Alarm.days, Monday first (Mon = bit 0 ... Sun = bit 6). */
|
||||
export const DAY_BITS = [1, 2, 4, 8, 16, 32, 64] as const;
|
||||
export const DAY_LETTERS = ["M", "T", "W", "T", "F", "S", "S"] as const;
|
||||
export const DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
|
||||
export const DAY_FULL_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] as const;
|
||||
export const WEEKDAYS_MASK = 1 | 2 | 4 | 8 | 16;
|
||||
export const WEEKEND_MASK = 32 | 64;
|
||||
export const EVERY_DAY_MASK = 127;
|
||||
|
||||
export type Alarm = {
|
||||
id: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
/** Repeat days as DAY_BITS; 0 means a one-off alarm (disabled after it rings). */
|
||||
days: number;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
/** Set while a snooze is pending; the alarm rings again at this time. */
|
||||
snoozedUntilMs: number | null;
|
||||
/** Set while ringing; cleared by dismiss or snooze. */
|
||||
ringingSinceMs: number | null;
|
||||
/**
|
||||
* For a repeating alarm: the occurrence most recently rung (or dismissed
|
||||
* from ringing), so the same occurrence does not ring twice after a
|
||||
* dismiss that lands before the minute is over.
|
||||
*/
|
||||
lastFiredAtMs: number | null;
|
||||
};
|
||||
|
||||
export type TimersState = {
|
||||
timers: CountdownTimer[];
|
||||
stopwatch: StopwatchState;
|
||||
alarms: Alarm[];
|
||||
/** Durations the wearer started most recently, newest first. */
|
||||
recentDurationsMs: number[];
|
||||
};
|
||||
|
||||
export function emptyTimersState(): TimersState {
|
||||
return {
|
||||
timers: [],
|
||||
stopwatch: { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] },
|
||||
alarms: [],
|
||||
recentDurationsMs: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** How many recent durations to keep for the "New timer" menu. */
|
||||
export const RECENT_DURATION_COUNT = 3;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ids
|
||||
|
||||
let idSerial = 1;
|
||||
|
||||
/**
|
||||
* Millisecond epoch plus a small serial: unique across restarts, ordered by
|
||||
* creation, and still exactly representable through the JS -> Java long
|
||||
* bridge.
|
||||
*/
|
||||
export function newItemId(nowMs: number): number {
|
||||
return nowMs * 100 + (idSerial++ % 100);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Duration ladder (the "New timer" dial)
|
||||
|
||||
const SECOND = 1000;
|
||||
const MINUTE = 60 * SECOND;
|
||||
const HOUR = 60 * MINUTE;
|
||||
|
||||
/**
|
||||
* The durations the dial scrolls through: fine steps where timers are
|
||||
* usually short, coarser steps as they get long, so anything from ten
|
||||
* seconds to a day is a few dozen scroll clicks away at most.
|
||||
*/
|
||||
export const DURATION_LADDER_MS: readonly number[] = (() => {
|
||||
const ladder: number[] = [10 * SECOND, 15 * SECOND, 20 * SECOND, 30 * SECOND, 45 * SECOND, MINUTE, 90 * SECOND];
|
||||
for (let minutes = 2; minutes <= 20; minutes++) ladder.push(minutes * MINUTE);
|
||||
for (let minutes = 25; minutes <= 60; minutes += 5) ladder.push(minutes * MINUTE);
|
||||
for (let minutes = 75; minutes <= 180; minutes += 15) ladder.push(minutes * MINUTE);
|
||||
for (let minutes = 210; minutes <= 360; minutes += 30) ladder.push(minutes * MINUTE);
|
||||
for (let hours = 7; hours <= 12; hours++) ladder.push(hours * HOUR);
|
||||
ladder.push(18 * HOUR, 24 * HOUR);
|
||||
return ladder;
|
||||
})();
|
||||
|
||||
/** Index of the ladder rung closest to a duration (ties go to the shorter). */
|
||||
export function nearestLadderIndex(durationMs: number): number {
|
||||
let best = 0;
|
||||
let bestDistance = Infinity;
|
||||
for (let index = 0; index < DURATION_LADDER_MS.length; index++) {
|
||||
const distance = Math.abs(DURATION_LADDER_MS[index]! - durationMs);
|
||||
if (distance < bestDistance) {
|
||||
best = index;
|
||||
bestDistance = distance;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export const DEFAULT_TIMER_DURATION_MS = 10 * MINUTE;
|
||||
export const MAX_TIMER_DURATION_MS = 24 * HOUR;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Timers
|
||||
|
||||
export function timerRemainingMs(timer: CountdownTimer, nowMs: number): number {
|
||||
if (timer.pausedRemainingMs !== null) return timer.pausedRemainingMs;
|
||||
if (timer.endsAtMs !== null) return Math.max(0, timer.endsAtMs - nowMs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
export type TimerPhase = "running" | "paused" | "rung";
|
||||
|
||||
export function timerPhase(timer: CountdownTimer): TimerPhase {
|
||||
if (timer.rungAtMs !== null) return "rung";
|
||||
if (timer.pausedRemainingMs !== null) return "paused";
|
||||
return "running";
|
||||
}
|
||||
|
||||
/** 0..1 progress toward the end (1 once rung). */
|
||||
export function timerProgress(timer: CountdownTimer, nowMs: number): number {
|
||||
if (timer.rungAtMs !== null || timer.durationMs <= 0) return 1;
|
||||
return Math.min(1, Math.max(0, 1 - timerRemainingMs(timer, nowMs) / timer.durationMs));
|
||||
}
|
||||
|
||||
export function createTimer(durationMs: number, label: string, nowMs: number): CountdownTimer {
|
||||
return {
|
||||
id: newItemId(nowMs),
|
||||
label,
|
||||
durationMs,
|
||||
endsAtMs: nowMs + durationMs,
|
||||
pausedRemainingMs: null,
|
||||
rungAtMs: null,
|
||||
createdAtMs: nowMs,
|
||||
};
|
||||
}
|
||||
|
||||
/** Running timers soonest first, then paused, then rung (oldest ring first). */
|
||||
export function sortTimers(timers: readonly CountdownTimer[], nowMs: number): CountdownTimer[] {
|
||||
const rank = (timer: CountdownTimer) => (timer.rungAtMs !== null ? 0 : timer.pausedRemainingMs !== null ? 2 : 1);
|
||||
return [...timers].sort((a, b) => {
|
||||
const rankDelta = rank(a) - rank(b);
|
||||
if (rankDelta !== 0) return rankDelta;
|
||||
if (a.rungAtMs !== null && b.rungAtMs !== null) return a.rungAtMs - b.rungAtMs;
|
||||
return timerRemainingMs(a, nowMs) - timerRemainingMs(b, nowMs) || a.createdAtMs - b.createdAtMs;
|
||||
});
|
||||
}
|
||||
|
||||
export function pushRecentDuration(recent: readonly number[], durationMs: number): number[] {
|
||||
return [durationMs, ...recent.filter((value) => value !== durationMs)].slice(0, RECENT_DURATION_COUNT);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stopwatch
|
||||
|
||||
export function stopwatchElapsedMs(stopwatch: StopwatchState, nowMs: number): number {
|
||||
const running = stopwatch.runningSinceMs === null ? 0 : Math.max(0, nowMs - stopwatch.runningSinceMs);
|
||||
return stopwatch.accumulatedMs + running;
|
||||
}
|
||||
|
||||
export function stopwatchIsRunning(stopwatch: StopwatchState): boolean {
|
||||
return stopwatch.runningSinceMs !== null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Alarms
|
||||
|
||||
export function createAlarm(hour: number, minute: number, days: number, label: string, nowMs: number): Alarm {
|
||||
return {
|
||||
id: newItemId(nowMs),
|
||||
hour,
|
||||
minute,
|
||||
days,
|
||||
label,
|
||||
enabled: true,
|
||||
snoozedUntilMs: null,
|
||||
ringingSinceMs: null,
|
||||
lastFiredAtMs: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Monday-first weekday index (0..6) of a Date, from JS's Sunday-first getDay. */
|
||||
export function mondayFirstDay(date: Date): number {
|
||||
return (date.getDay() + 6) % 7;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the alarm next goes off, given the current time: the pending snooze
|
||||
* if there is one, otherwise the next wall-clock occurrence of hour:minute
|
||||
* on an enabled day (any day for a one-off), strictly after `nowMs` and
|
||||
* after the occurrence it last rang for. Null when the alarm is disabled.
|
||||
* Wall-clock arithmetic runs in the local zone via Date, so DST changes
|
||||
* land on the right local time.
|
||||
*/
|
||||
export function alarmNextRingMs(alarm: Alarm, nowMs: number): number | null {
|
||||
if (!alarm.enabled) return null;
|
||||
if (alarm.snoozedUntilMs !== null) return alarm.snoozedUntilMs;
|
||||
const floor = Math.max(nowMs, alarm.lastFiredAtMs ?? 0);
|
||||
const start = new Date(nowMs);
|
||||
for (let dayOffset = 0; dayOffset <= 7; dayOffset++) {
|
||||
const candidate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + dayOffset, alarm.hour, alarm.minute, 0, 0);
|
||||
if (candidate.getTime() <= floor) continue;
|
||||
if (alarm.days !== 0 && !(alarm.days & DAY_BITS[mondayFirstDay(candidate)]!)) continue;
|
||||
return candidate.getTime();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Alarms by time of day, then by creation. */
|
||||
export function sortAlarms(alarms: readonly Alarm[]): Alarm[] {
|
||||
return [...alarms].sort((a, b) => a.hour * 60 + a.minute - (b.hour * 60 + b.minute) || a.id - b.id);
|
||||
}
|
||||
|
||||
export function formatDays(days: number): string {
|
||||
if (days === 0) return "Once";
|
||||
if (days === EVERY_DAY_MASK) return "Every day";
|
||||
if (days === WEEKDAYS_MASK) return "Weekdays";
|
||||
if (days === WEEKEND_MASK) return "Weekends";
|
||||
return DAY_NAMES.filter((_, index) => days & DAY_BITS[index]!).join(" ");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Formatting
|
||||
|
||||
function pad2(value: number): string {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
/** Countdown / elapsed digits: m:ss below an hour, h:mm:ss above. */
|
||||
export function formatClockDigits(totalSeconds: number): string {
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${minutes}:${pad2(seconds)}`;
|
||||
}
|
||||
|
||||
/** Remaining time as a countdown reads it: rounds up, so 0:00 means done. */
|
||||
export function formatCountdown(remainingMs: number): string {
|
||||
return formatClockDigits(Math.max(0, Math.ceil(remainingMs / 1000)));
|
||||
}
|
||||
|
||||
/** Elapsed time as a stopwatch reads it: rounds down, plus optional tenths. */
|
||||
export function formatElapsed(elapsedMs: number, tenths: boolean): string {
|
||||
const clamped = Math.max(0, elapsedMs);
|
||||
const digits = formatClockDigits(Math.floor(clamped / 1000));
|
||||
return tenths ? `${digits}.${Math.floor(clamped / 100) % 10}` : digits;
|
||||
}
|
||||
|
||||
/** A set duration in words: "20 min", "1h 30m", "45s", "2m 30s". */
|
||||
export function formatDurationWords(durationMs: number): string {
|
||||
const totalSeconds = Math.round(durationMs / 1000);
|
||||
const seconds = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
if (hours > 0) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
||||
if (minutes > 0) return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes} min`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
/** A span until something: "9h 12m", "12m", "45s". Coarse on purpose. */
|
||||
export function formatSpanWords(spanMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.round(spanMs / 1000));
|
||||
if (totalSeconds < 60) return `${totalSeconds}s`;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
if (hours === 0) return `${minutes}m`;
|
||||
if (hours < 24) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
||||
const days = Math.floor(hours / 24);
|
||||
const restHours = hours % 24;
|
||||
return restHours > 0 ? `${days}d ${restHours}h` : `${days}d`;
|
||||
}
|
||||
|
||||
/** Wall-clock time of day in the wearer's chosen format. */
|
||||
export function formatTimeOfDay(hour24: number, minute: number, twelveHour: boolean): string {
|
||||
const minutes = pad2(minute);
|
||||
if (!twelveHour) return `${hour24}:${minutes}`;
|
||||
const hour12 = ((hour24 + 11) % 12) + 1;
|
||||
return `${hour12}:${minutes} ${hour24 < 12 ? "AM" : "PM"}`;
|
||||
}
|
||||
|
||||
export function formatClockAt(timestampMs: number, twelveHour: boolean): string {
|
||||
const date = new Date(timestampMs);
|
||||
return formatTimeOfDay(date.getHours(), date.getMinutes(), twelveHour);
|
||||
}
|
||||
|
||||
/** Row/stage label for a timer: its label, else its set duration. */
|
||||
export function timerDisplayName(timer: CountdownTimer): string {
|
||||
return timer.label || formatDurationWords(timer.durationMs);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence shape
|
||||
|
||||
/**
|
||||
* Parse a persisted state blob defensively: anything malformed falls back to
|
||||
* a field default rather than failing the whole load, so a bad record loses
|
||||
* itself and nothing else.
|
||||
*/
|
||||
export function parseTimersState(raw: string | null | undefined): TimersState {
|
||||
const state = emptyTimersState();
|
||||
if (!raw) return state;
|
||||
let parsed: any;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return state;
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object") return state;
|
||||
if (Array.isArray(parsed.timers)) {
|
||||
for (const item of parsed.timers) {
|
||||
if (!item || typeof item !== "object" || !isFiniteNumber(item.id) || !isFiniteNumber(item.durationMs)) continue;
|
||||
state.timers.push({
|
||||
id: item.id,
|
||||
label: typeof item.label === "string" ? item.label : "",
|
||||
durationMs: item.durationMs,
|
||||
endsAtMs: isFiniteNumber(item.endsAtMs) ? item.endsAtMs : null,
|
||||
pausedRemainingMs: isFiniteNumber(item.pausedRemainingMs) ? item.pausedRemainingMs : null,
|
||||
rungAtMs: isFiniteNumber(item.rungAtMs) ? item.rungAtMs : null,
|
||||
createdAtMs: isFiniteNumber(item.createdAtMs) ? item.createdAtMs : 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
const stopwatch = parsed.stopwatch;
|
||||
if (stopwatch && typeof stopwatch === "object") {
|
||||
state.stopwatch = {
|
||||
accumulatedMs: isFiniteNumber(stopwatch.accumulatedMs) ? Math.max(0, stopwatch.accumulatedMs) : 0,
|
||||
runningSinceMs: isFiniteNumber(stopwatch.runningSinceMs) ? stopwatch.runningSinceMs : null,
|
||||
lapsMs: Array.isArray(stopwatch.lapsMs) ? stopwatch.lapsMs.filter(isFiniteNumber) : [],
|
||||
};
|
||||
}
|
||||
if (Array.isArray(parsed.alarms)) {
|
||||
for (const item of parsed.alarms) {
|
||||
if (!item || typeof item !== "object" || !isFiniteNumber(item.id)) continue;
|
||||
if (!isFiniteNumber(item.hour) || !isFiniteNumber(item.minute)) continue;
|
||||
state.alarms.push({
|
||||
id: item.id,
|
||||
hour: Math.min(23, Math.max(0, Math.floor(item.hour))),
|
||||
minute: Math.min(59, Math.max(0, Math.floor(item.minute))),
|
||||
days: isFiniteNumber(item.days) ? item.days & EVERY_DAY_MASK : 0,
|
||||
label: typeof item.label === "string" ? item.label : "",
|
||||
enabled: item.enabled !== false,
|
||||
snoozedUntilMs: isFiniteNumber(item.snoozedUntilMs) ? item.snoozedUntilMs : null,
|
||||
ringingSinceMs: isFiniteNumber(item.ringingSinceMs) ? item.ringingSinceMs : null,
|
||||
lastFiredAtMs: isFiniteNumber(item.lastFiredAtMs) ? item.lastFiredAtMs : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (Array.isArray(parsed.recentDurationsMs)) {
|
||||
state.recentDurationsMs = parsed.recentDurationsMs.filter(isFiniteNumber).slice(0, RECENT_DURATION_COUNT);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function serializeTimersState(state: TimersState): string {
|
||||
return JSON.stringify(state);
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tool-argument parsing (shared by the assistant tools)
|
||||
|
||||
/**
|
||||
* Parse a time of day from the forms an assistant is likely to pass:
|
||||
* "7:30", "07:30", "7:30 am", "7pm", "19:30", "noon", "midnight".
|
||||
* Returns null when unparseable.
|
||||
*/
|
||||
export function parseTimeOfDay(text: string): { hour: number; minute: number } | null {
|
||||
const trimmed = text.trim().toLowerCase();
|
||||
if (trimmed === "noon") return { hour: 12, minute: 0 };
|
||||
if (trimmed === "midnight") return { hour: 0, minute: 0 };
|
||||
const match = /^(\d{1,2})(?::(\d{2}))?\s*(a\.?m\.?|p\.?m\.?)?$/.exec(trimmed);
|
||||
if (!match) return null;
|
||||
let hour = parseInt(match[1]!, 10);
|
||||
const minute = match[2] ? parseInt(match[2], 10) : 0;
|
||||
const meridiem = match[3]?.replace(/\./g, "");
|
||||
if (minute > 59) return null;
|
||||
if (meridiem) {
|
||||
if (hour < 1 || hour > 12) return null;
|
||||
hour = hour % 12;
|
||||
if (meridiem === "pm") hour += 12;
|
||||
} else if (hour > 23) {
|
||||
return null;
|
||||
}
|
||||
return { hour, minute };
|
||||
}
|
||||
|
||||
/** Parse repeat days from names ("mon", "tuesday"), "weekdays", "weekends", "daily"/"every day", "once". */
|
||||
export function parseRepeatDays(values: readonly string[] | string | null | undefined): number | null {
|
||||
if (values === null || values === undefined) return 0;
|
||||
const list =
|
||||
typeof values === "string"
|
||||
? values.toLowerCase().replace(/every\s*day/g, "daily").split(/[,\s]+/)
|
||||
: values.map((value) => String(value).toLowerCase().replace(/every\s*day/g, "daily"));
|
||||
let mask = 0;
|
||||
for (const raw of list) {
|
||||
const value = String(raw).trim().toLowerCase();
|
||||
if (!value || value === "once" || value === "none") continue;
|
||||
if (value === "weekdays") {
|
||||
mask |= WEEKDAYS_MASK;
|
||||
continue;
|
||||
}
|
||||
if (value === "weekends" || value === "weekend") {
|
||||
mask |= WEEKEND_MASK;
|
||||
continue;
|
||||
}
|
||||
if (value === "daily" || value === "every day" || value === "everyday" || value === "all") {
|
||||
mask |= EVERY_DAY_MASK;
|
||||
continue;
|
||||
}
|
||||
const index = DAY_FULL_NAMES.findIndex((name) => name.toLowerCase().startsWith(value.slice(0, 3)));
|
||||
if (index < 0 || value.length < 2) return null;
|
||||
mask |= DAY_BITS[index]!;
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
Reference in new issue
Block a user