diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java index 091bb459..0e062a67 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.java @@ -388,11 +388,11 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen if (statusBarNotification == null || statusBarNotification.getNotification() == null) { return false; } - // The dashboard's own persistent foreground notification is noise, but - // Timer expiry notifications deliberately flow through the same mirror - // and modal path as notifications from other Android apps. - if (service.getPackageName().equals(statusBarNotification.getPackageName()) - && !FaceclawTimerNotifications.isTimerNotification(statusBarNotification)) { + // Our own notifications stay out of the mirror: the foreground-service + // one is noise, and the Timers app rings on the glasses itself (its + // phone notification is for the phone), so mirroring it would stack a + // notification modal over the ringing screen. + if (service.getPackageName().equals(statusBarNotification.getPackageName())) { return false; } Notification notification = statusBarNotification.getNotification(); diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerNotifications.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerNotifications.java index d751879c..38430d47 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerNotifications.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerNotifications.java @@ -12,12 +12,18 @@ import android.os.Build; import com.tns.NativeScriptActivity; -/** Android alarm + notification bridge used by the on-glasses Timer app. */ +/** + * Android alarm + notification bridge used by the on-glasses Timers app, for + * countdown timers and alarms alike: one AlarmManager alarm per item posts a + * phone notification at the moment of expiry, even when the app process is + * asleep or gone. + */ public final class FaceclawTimerNotifications { public static final String CHANNEL_ID = "faceclaw-timers"; static final String ACTION_EXPIRE = "com.faceclaw.app.action.TIMER_EXPIRE"; static final String EXTRA_TIMER_ID = "timerId"; - static final String EXTRA_DURATION_LABEL = "durationLabel"; + static final String EXTRA_TITLE = "title"; + static final String EXTRA_TEXT = "text"; private static final String TIMER_TAG_PREFIX = "faceclaw-timer:"; private static final String PREFS_NAME = "faceclaw-timer-notifications"; @@ -26,10 +32,10 @@ public final class FaceclawTimerNotifications { private FaceclawTimerNotifications() {} /** - * Schedule an Android alarm as the durable path. The worker also keeps a + * Schedule an Android alarm as the durable path. The engine also keeps a * normal JS timeout for prompt delivery while the process is awake. */ - public static void schedule(Context context, long timerId, long triggerAtMs, String durationLabel) { + public static void schedule(Context context, long timerId, long triggerAtMs, String title, String text) { Context appContext = context.getApplicationContext(); preferences(appContext).edit().putBoolean(firedKey(timerId), false).apply(); @@ -37,7 +43,7 @@ public final class FaceclawTimerNotifications { if (manager == null) { return; } - PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, durationLabel); + PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, title, text); long triggerAt = Math.max(System.currentTimeMillis(), triggerAtMs); try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !manager.canScheduleExactAlarms()) { @@ -58,7 +64,7 @@ public final class FaceclawTimerNotifications { Context appContext = context.getApplicationContext(); AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { - alarmManager.cancel(expiryPendingIntent(appContext, timerId, "")); + alarmManager.cancel(expiryPendingIntent(appContext, timerId, "", "")); } NotificationManager notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE); @@ -68,17 +74,17 @@ public final class FaceclawTimerNotifications { preferences(appContext).edit().remove(firedKey(timerId)).apply(); } - /** Worker-timeout path. Cancels the backup alarm and posts at most once. */ - public static void fireNow(Context context, long timerId, String durationLabel) { + /** Engine-timeout path. Cancels the backup alarm and posts at most once. */ + public static void fireNow(Context context, long timerId, String title, String text) { Context appContext = context.getApplicationContext(); AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE); if (alarmManager != null) { - alarmManager.cancel(expiryPendingIntent(appContext, timerId, durationLabel)); + alarmManager.cancel(expiryPendingIntent(appContext, timerId, title, text)); } - showExpiredOnce(appContext, timerId, durationLabel); + showExpiredOnce(appContext, timerId, title, text); } - static synchronized void showExpiredOnce(Context context, long timerId, String durationLabel) { + static synchronized void showExpiredOnce(Context context, long timerId, String title, String text) { SharedPreferences preferences = preferences(context); String firedKey = firedKey(timerId); if (preferences.getBoolean(firedKey, false)) { @@ -103,10 +109,11 @@ public final class FaceclawTimerNotifications { Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new Notification.Builder(context, CHANNEL_ID) : new Notification.Builder(context); - String label = durationLabel == null || durationLabel.trim().isEmpty() ? "Timer" : durationLabel + " timer"; + String contentTitle = title == null || title.trim().isEmpty() ? "Timer finished" : title; + String contentText = text == null || text.trim().isEmpty() ? "Time's up" : text; Notification notification = builder - .setContentTitle("Timer finished") - .setContentText(label + " is up") + .setContentTitle(contentTitle) + .setContentText(contentText) .setSmallIcon(context.getApplicationInfo().icon) .setContentIntent(contentIntent) .setCategory(Notification.CATEGORY_ALARM) @@ -122,7 +129,7 @@ public final class FaceclawTimerNotifications { } } - /** Only Timer notifications from our own package should enter the mirror. */ + /** Identifies this bridge's notifications among our own package's (see the listener service). */ public static boolean isTimerNotification(android.service.notification.StatusBarNotification item) { if (item == null || item.getNotification() == null) { return false; @@ -156,12 +163,14 @@ public final class FaceclawTimerNotifications { private static PendingIntent expiryPendingIntent( Context context, long timerId, - String durationLabel + String title, + String text ) { Intent intent = new Intent(context, FaceclawTimerReceiver.class); intent.setAction(ACTION_EXPIRE); intent.putExtra(EXTRA_TIMER_ID, timerId); - intent.putExtra(EXTRA_DURATION_LABEL, durationLabel == null ? "" : durationLabel); + intent.putExtra(EXTRA_TITLE, title == null ? "" : title); + intent.putExtra(EXTRA_TEXT, text == null ? "" : text); int flags = PendingIntent.FLAG_UPDATE_CURRENT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { flags |= PendingIntent.FLAG_IMMUTABLE; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerReceiver.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerReceiver.java index 42b271e7..1d18585c 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerReceiver.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawTimerReceiver.java @@ -4,7 +4,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -/** Receives durable timer alarms even if the NativeScript worker is asleep. */ +/** Receives durable timer/alarm expiries even if the NativeScript side is asleep. */ public class FaceclawTimerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { @@ -15,7 +15,8 @@ public class FaceclawTimerReceiver extends BroadcastReceiver { if (timerId == 0) { return; } - String durationLabel = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_DURATION_LABEL); - FaceclawTimerNotifications.showExpiredOnce(context, timerId, durationLabel); + String title = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TITLE); + String text = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TEXT); + FaceclawTimerNotifications.showExpiredOnce(context, timerId, title, text); } } diff --git a/CHANGELOG b/CHANGELOG index 09cfa5a0..b6ae075e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -7,11 +7,12 @@ * Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing) * Content beneath an open context menu is dimmed * Add a keyboard-input button to the phone home screen +* Add a light sensor demo to the Developer app +* Move Calculator, Microphones, Nightscout, and Roam apps to Prototpyes folder by default * Navigate app: Location indicator rotates based on the compass * Navigate app: Add saved home/work and recent address settings * Navigate app: Darken the map background color -* Add a light sensor demo to the Developer app -* Move Calculator, Microphones, Nightscout, and Roam apps to Prototpyes folder by default +* Timer app: Fully rewritten, with new better UI ## 0.6.4 - 2026-09-02 * Context menus are centered and include window title diff --git a/app/apps/timer/index.ts b/app/apps/timer/index.ts index a2cf51b8..fa6bcdc1 100644 --- a/app/apps/timer/index.ts +++ b/app/apps/timer/index.ts @@ -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; diff --git a/app/apps/timer/timer-app.ts b/app/apps/timer/timer-app.ts new file mode 100644 index 00000000..0828e581 --- /dev/null +++ b/app/apps/timer/timer-app.ts @@ -0,0 +1,1354 @@ +/** + * The Timers app window: one screen for countdown timers, the stopwatch and + * alarms. See notes/timers-app-design.md for the design. + * + * Layout is stage + list. The right ~40% is a list of rows under three + * section headers (TIMERS / STOPWATCH / ALARMS); the selected row is shown + * large on the left stage. Scroll moves the selection, click does the + * obvious thing for the selected row (pause, resume, start, stop, toggle, + * dismiss), tap-then-hold opens the row's context menu, double-click leaves + * the app. Pickers (the duration dial, the fine-tune fields, the alarm time + * fields) and a ringing item's buttons are transient states of the same + * screen and double-click cancels them. + * + * All state lives in the engine (timer-engine.ts); this file only paints it + * and turns gestures into engine calls. + */ +import { GrayImage, type UiFont } from "../../graphics/image"; +import { getFont } from "../../graphics/bdffont"; +import { ensurePreinstalledFonts, installedFontPath } from "../../graphics/installed-fonts"; +import { truncateText } from "../../graphics/textwrap"; +import { TtfFont } from "../../graphics/ttf-font"; +import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/ui-fonts"; +import { timeFormatSetting } from "../../ui/dashboard-settings"; +import { + GESTURE_CLICK, + GESTURE_DOUBLE_CLICK, + GESTURE_SCROLL, + GESTURE_SHORT_THEN_LONG_PRESS, + gestureHints, + type InputEvent, +} from "../../ui/gestures"; +import { type Layer, type LayerContext } from "../../ui/layers"; +import { + drawListScrollbar, + drawRightValueMenuItem, + drawSelectionHighlight, + drawToggleMenuItem, + scrollToKeepSelectionVisible, + type MenuItem, +} from "../../ui/menu"; +import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics"; +import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window"; +import { shell } from "../../ui/shell/shell"; +import { WindowMenuLayer } from "../../ui/window-menu"; +import { clamp } from "../../util/numeric-util"; +import { + soonestRunningTimerRemainingMs, + timerEngine, + timersSnoozeSetting, + timersSoundSetting, + timersWakeSetting, + type RingingItem, + type SnoozeMinutes, +} from "./timer-engine"; +import { + alarmNextRingMs, + DAY_BITS, + DAY_FULL_NAMES, + DAY_LETTERS, + DEFAULT_TIMER_DURATION_MS, + DURATION_LADDER_MS, + EVERY_DAY_MASK, + formatClockAt, + formatCountdown, + formatDays, + formatDurationWords, + formatElapsed, + formatSpanWords, + formatTimeOfDay, + nearestLadderIndex, + sortAlarms, + sortTimers, + stopwatchElapsedMs, + stopwatchIsRunning, + timerDisplayName, + timerPhase, + timerRemainingMs, + timerProgress, + WEEKDAYS_MASK, + WEEKEND_MASK, + type Alarm, + type CountdownTimer, +} from "./timer-model"; + +export const TIMER_WINDOW_ID = "timer"; +export const TIMER_SURFACE_ID = "window:timer"; + +/** Width of the list column, as a share of the viewport, and its bounds. */ +const LIST_SHARE = 0.4; +const LIST_MIN_WIDTH = 190; +const LIST_MAX_WIDTH = 240; +const LIST_TOP = 6; +const STAGE_X = 10; +/** Gap between the stage's right edge and the list's divider. */ +const STAGE_LIST_GAP = 14; +/** Brightness factor for the list while a picker owns the stage. */ +const LIST_DIM = 0.4; +/** Big-digit sizes tried largest first until the text fits the stage. */ +const DIGIT_SIZES = [96, 80, 64, 52, 40]; +/** Field digits in the pickers. */ +const FIELD_DIGIT_SIZE = 56; +const MINUTE_MS = 60_000; + +type RowKind = "header" | "timer" | "new-timer" | "stopwatch" | "alarm" | "new-alarm"; + +type Row = { + key: string; + kind: RowKind; + title?: string; + timer?: CountdownTimer; + alarm?: Alarm; +}; + +/** + * Screen state beyond the selection. "list" is the resting state; the rest + * are pickers that own the stage and the scroll wheel until they finish or + * a double-click cancels them. + */ +type Mode = + | { kind: "list" } + | { kind: "dial"; index: number; label: string } + | { kind: "fine"; hours: number; minutes: number; seconds: number; field: number; label: string } + | { kind: "alarm-time"; alarmId: number | null; hour: number; minute: number; field: number }; + +type LabelTarget = { kind: "timer" | "alarm"; id: number } | { kind: "new-timer" }; + +function timerKey(timer: CountdownTimer): string { + return `timer:${timer.id}`; +} + +function alarmKey(alarm: Alarm): string { + return `alarm:${alarm.id}`; +} + +function ringingKey(item: RingingItem): string { + return item.kind === "timer" ? timerKey(item.timer) : alarmKey(item.alarm); +} + +function twelveHour(): boolean { + return timeFormatSetting.get() === "12h"; +} + +function smallFont(): UiFont { + return getDefaultSmallFont(); +} + +function mediumFont(): UiFont { + return getDefaultMediumFont(); +} + +// --------------------------------------------------------------------------- +// Big digits + +let digitFontsEnsured = false; + +/** The bundled Roboto Bold at a pixel size, or the largest bitmap face off-Android. */ +function digitFont(sizePx: number): UiFont { + if (!digitFontsEnsured) { + digitFontsEnsured = true; + try { + ensurePreinstalledFonts(); + } catch (error) { + console.warn(`timers digit font preinstall failed: ${error}`); + } + } + return TtfFont.load(installedFontPath("Roboto-Bold.ttf"), sizePx) ?? getFont("terminus32"); +} + +/** The biggest digit font whose rendering of `text` fits `maxWidth`. */ +function fittingDigitFont(text: string, maxWidth: number, sizes: readonly number[] = DIGIT_SIZES): UiFont { + let font = digitFont(sizes[0]!); + for (const size of sizes) { + font = digitFont(size); + if (font.measureText(text) <= maxWidth) return font; + } + return font; +} + +// --------------------------------------------------------------------------- +// The layer + +export class TimersLayer implements Layer { + readonly acceptsDirectional = true; + + private selectionKey = ""; + private scrollRow = 0; + private mode: Mode = { kind: "list" }; + /** Which of the ringing stage's two buttons is highlighted. */ + private ringButton = 0; + /** Where the next text input (a label) goes; null means the selected item. */ + private labelTarget: LabelTarget | null = null; + /** Ringing items already jumped to, so a second ring doesn't re-pin. */ + private seenRinging = new Set(); + /** Set the first time this layer paints, to land the selection sensibly. */ + private initialised = false; + /** Feedback shown on the stage after a picker refuses (e.g. zero duration). */ + private notice = ""; + + // ------------------------------------------------------------------------- + // Rows + + private buildRows(now: number): Row[] { + const state = timerEngine.state; + const rows: Row[] = [{ key: "h:timers", kind: "header", title: "TIMERS" }]; + for (const timer of sortTimers(state.timers, now)) rows.push({ key: timerKey(timer), kind: "timer", timer }); + rows.push({ key: "new-timer", kind: "new-timer" }); + rows.push({ key: "h:stopwatch", kind: "header", title: "STOPWATCH" }, { key: "stopwatch", kind: "stopwatch" }); + rows.push({ key: "h:alarms", kind: "header", title: "ALARMS" }); + for (const alarm of sortAlarms(state.alarms)) rows.push({ key: alarmKey(alarm), kind: "alarm", alarm }); + rows.push({ key: "new-alarm", kind: "new-alarm" }); + return rows; + } + + /** The most urgent row: ringing, then a running timer, a running stopwatch, else New timer. */ + private defaultSelection(rows: Row[]): string { + const ringing = timerEngine.ringingItems()[0]; + if (ringing) return ringingKey(ringing); + const running = rows.find((row) => row.timer && timerPhase(row.timer) === "running"); + if (running) return running.key; + if (stopwatchIsRunning(timerEngine.state.stopwatch)) return "stopwatch"; + return "new-timer"; + } + + /** Keep the selection on a real, selectable row after the rows change. */ + private reconcileSelection(rows: Row[]): number { + if (!this.initialised) { + this.initialised = true; + this.selectionKey = this.defaultSelection(rows); + for (const item of timerEngine.ringingItems()) this.seenRinging.add(ringingKey(item)); + } + let index = rows.findIndex((row) => row.key === this.selectionKey); + if (index < 0) { + // The row went away (a dismissed timer, a deleted alarm): stay in place. + index = clamp(this.scrollRow, 0, rows.length - 1); + while (index < rows.length && rows[index]!.kind === "header") index++; + if (index >= rows.length) index = rows.findIndex((row) => row.kind !== "header"); + this.selectionKey = rows[index]!.key; + } + return index; + } + + private selectedRow(rows: Row[]): Row { + return rows[this.reconcileSelection(rows)]!; + } + + private moveSelection(rows: Row[], delta: number): void { + const count = rows.length; + let index = this.reconcileSelection(rows); + for (let step = 0; step < count; step++) { + index = (index + delta + count) % count; + if (rows[index]!.kind !== "header") break; + } + this.selectionKey = rows[index]!.key; + } + + /** Called on every engine change: jump to a newly ringing item. */ + onEngineChanged(): void { + const ringing = timerEngine.ringingItems(); + const keys = new Set(ringing.map(ringingKey)); + for (const key of Array.from(this.seenRinging)) { + if (!keys.has(key)) this.seenRinging.delete(key); + } + for (const item of ringing) { + const key = ringingKey(item); + if (this.seenRinging.has(key)) continue; + this.seenRinging.add(key); + this.selectionKey = key; + this.ringButton = 0; + this.mode = { kind: "list" }; + this.notice = ""; + } + } + + private ringingOf(row: Row): RingingItem | null { + if (row.timer && row.timer.rungAtMs !== null) return { kind: "timer", timer: row.timer }; + if (row.alarm && row.alarm.ringingSinceMs !== null) return { kind: "alarm", alarm: row.alarm }; + return null; + } + + // ------------------------------------------------------------------------- + // Input + + async handleInput(event: InputEvent, _ctx: LayerContext): Promise { + timerEngine.check(); + const now = Date.now(); + const rows = this.buildRows(now); + switch (this.mode.kind) { + case "dial": + this.handleDialInput(event, this.mode); + return; + case "fine": + this.handleFineInput(event, this.mode); + return; + case "alarm-time": + this.handleAlarmTimeInput(event, this.mode); + return; + default: + this.handleListInput(event, rows); + } + } + + private handleListInput(event: InputEvent, rows: Row[]): void { + const row = this.selectedRow(rows); + const ringing = this.ringingOf(row); + switch (event.type) { + case "scroll-up": + case "swipe-up": + if (ringing) this.ringButton = 0; + else this.moveSelection(rows, -1); + return; + case "scroll-down": + case "swipe-down": + if (ringing) this.ringButton = 1; + else this.moveSelection(rows, 1); + return; + case "swipe-left": + if (ringing) this.ringButton = 0; + else shell.yieldFocusToSidebar(); + return; + case "swipe-right": + if (ringing) this.ringButton = 1; + else this.activateRow(row); + return; + case "click": + this.activateRow(row); + return; + case "double-click": + shell.yieldFocusToSidebar(); + return; + default: + return; + } + } + + /** Click on a row: its primary action. */ + private activateRow(row: Row): void { + this.notice = ""; + switch (row.kind) { + case "timer": { + const timer = row.timer!; + switch (timerPhase(timer)) { + case "running": + timerEngine.pauseTimer(timer.id); + return; + case "paused": + timerEngine.resumeTimer(timer.id); + return; + case "rung": + if (this.ringButton === 0) timerEngine.removeTimer(timer.id); + else timerEngine.restartTimer(timer.id); + return; + } + } + case "new-timer": + this.openDial(""); + return; + case "stopwatch": + timerEngine.stopwatchToggle(); + return; + case "alarm": { + const alarm = row.alarm!; + if (alarm.ringingSinceMs !== null) { + if (this.ringButton === 0) timerEngine.dismissAlarm(alarm.id); + else timerEngine.snoozeAlarm(alarm.id); + return; + } + timerEngine.setAlarmEnabled(alarm.id, !alarm.enabled); + return; + } + case "new-alarm": + this.openAlarmTime(null); + return; + default: + return; + } + } + + private openDial(label: string): void { + const last = timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS; + this.mode = { kind: "dial", index: nearestLadderIndex(last), label }; + } + + private openFine(label: string, durationMs: number): void { + const totalSeconds = Math.round(durationMs / 1000); + this.mode = { + kind: "fine", + hours: Math.min(23, Math.floor(totalSeconds / 3600)), + minutes: Math.floor(totalSeconds / 60) % 60, + seconds: totalSeconds % 60, + field: 0, + label, + }; + } + + private openAlarmTime(alarm: Alarm | null): void { + this.mode = { + kind: "alarm-time", + alarmId: alarm?.id ?? null, + hour: alarm?.hour ?? 7, + minute: alarm?.minute ?? 0, + field: 0, + }; + } + + private startTimer(durationMs: number, label: string): void { + const timer = timerEngine.startTimer(durationMs, label); + this.selectionKey = timerKey(timer); + this.mode = { kind: "list" }; + this.notice = ""; + } + + private handleDialInput(event: InputEvent, mode: Extract): void { + switch (event.type) { + case "scroll-up": + case "swipe-up": + mode.index = Math.min(DURATION_LADDER_MS.length - 1, mode.index + 1); + return; + case "scroll-down": + case "swipe-down": + mode.index = Math.max(0, mode.index - 1); + return; + case "click": + case "swipe-right": + this.startTimer(DURATION_LADDER_MS[mode.index]!, mode.label); + return; + case "double-click": + case "swipe-left": + this.mode = { kind: "list" }; + return; + default: + return; + } + } + + private handleFineInput(event: InputEvent, mode: Extract): void { + const adjust = (delta: number) => { + if (mode.field === 0) mode.hours = (mode.hours + delta + 24) % 24; + else if (mode.field === 1) mode.minutes = (mode.minutes + delta + 60) % 60; + else mode.seconds = (mode.seconds + delta + 60) % 60; + this.notice = ""; + }; + switch (event.type) { + case "scroll-up": + case "swipe-up": + adjust(1); + return; + case "scroll-down": + case "swipe-down": + adjust(-1); + return; + case "swipe-right": + mode.field = Math.min(2, mode.field + 1); + return; + case "swipe-left": + mode.field = Math.max(0, mode.field - 1); + return; + case "click": { + if (mode.field < 2) { + mode.field++; + return; + } + const durationMs = ((mode.hours * 60 + mode.minutes) * 60 + mode.seconds) * 1000; + if (durationMs <= 0) { + this.notice = "Choose a duration longer than zero"; + mode.field = 0; + return; + } + this.startTimer(durationMs, mode.label); + return; + } + case "double-click": + if (mode.field > 0) mode.field--; + else this.mode = { kind: "list" }; + return; + default: + return; + } + } + + /** Field count of the alarm time picker: hour, minute tens, minute ones, and AM/PM in 12-hour mode. */ + private alarmFieldCount(): number { + return twelveHour() ? 4 : 3; + } + + private handleAlarmTimeInput(event: InputEvent, mode: Extract): void { + const fields = this.alarmFieldCount(); + const adjust = (delta: number) => { + const tens = Math.floor(mode.minute / 10); + const ones = mode.minute % 10; + if (mode.field === 0) { + if (twelveHour()) { + // Step within the current half of the day (1..12 wraps without flipping AM/PM). + const pm = mode.hour >= 12; + const hour12 = ((mode.hour + 11) % 12) + 1; + const next = ((hour12 - 1 + delta + 12) % 12) + 1; + mode.hour = (next % 12) + (pm ? 12 : 0); + } else { + mode.hour = (mode.hour + delta + 24) % 24; + } + } else if (mode.field === 1) { + mode.minute = ((tens + delta + 6) % 6) * 10 + ones; + } else if (mode.field === 2) { + mode.minute = tens * 10 + ((ones + delta + 10) % 10); + } else { + mode.hour = (mode.hour + 12) % 24; + } + }; + switch (event.type) { + case "scroll-up": + case "swipe-up": + adjust(1); + return; + case "scroll-down": + case "swipe-down": + adjust(-1); + return; + case "swipe-right": + mode.field = Math.min(fields - 1, mode.field + 1); + return; + case "swipe-left": + mode.field = Math.max(0, mode.field - 1); + return; + case "click": { + if (mode.field < fields - 1) { + mode.field++; + return; + } + if (mode.alarmId === null) { + const alarm = timerEngine.addAlarm(mode.hour, mode.minute, 0, ""); + this.selectionKey = alarmKey(alarm); + } else { + timerEngine.setAlarmTime(mode.alarmId, mode.hour, mode.minute); + } + this.mode = { kind: "list" }; + return; + } + case "double-click": + if (mode.field > 0) mode.field--; + else this.mode = { kind: "list" }; + return; + default: + return; + } + } + + /** A mirror touch: on the list, select the row under it. */ + hitTest(x: number, y: number, ctx: LayerContext): boolean { + if (this.mode.kind !== "list") return false; + const { width, height } = ctx.stack.getBaseSize(); + const listX = width - listWidthFor(width); + if (x < listX) return false; + const rows = this.buildRows(Date.now()); + this.reconcileSelection(rows); + const rowHeight = listRowHeight(smallFont()); + const index = this.scrollRow + Math.floor((y - LIST_TOP) / rowHeight); + const row = rows[index]; + if (!row || row.kind === "header" || y < LIST_TOP || y > height) return true; + if (this.selectionKey === row.key) { + this.activateRow(row); + } else { + this.selectionKey = row.key; + this.ringButton = 0; + } + return true; + } + + // ------------------------------------------------------------------------- + // Text input (labels) + + receiveTextInput(text: string): void { + const label = text.trim(); + const target = this.labelTarget; + this.labelTarget = null; + if (target?.kind === "new-timer" || (!target && (this.mode.kind === "dial" || this.mode.kind === "fine"))) { + if (this.mode.kind === "dial" || this.mode.kind === "fine") this.mode.label = label; + return; + } + if (target?.kind === "timer") { + timerEngine.setTimerLabel(target.id, label); + return; + } + if (target?.kind === "alarm") { + timerEngine.setAlarmLabel(target.id, label); + return; + } + const row = this.selectedRow(this.buildRows(Date.now())); + if (row.timer) timerEngine.setTimerLabel(row.timer.id, label); + else if (row.alarm) timerEngine.setAlarmLabel(row.alarm.id, label); + } + + /** Aim the shell's text-entry dialog at a label, then open it. */ + private askForLabel(target: LabelTarget): void { + this.labelTarget = target; + shell.startVoiceInput(); + } + + // ------------------------------------------------------------------------- + // Context menus + + menuItems(): MenuItem[] { + if (this.mode.kind === "alarm-time") return []; + if (this.mode.kind === "dial" || this.mode.kind === "fine") return this.pickerMenuItems(this.mode); + const now = Date.now(); + const row = this.selectedRow(this.buildRows(now)); + const items: MenuItem[] = []; + switch (row.kind) { + case "timer": + items.push(...this.timerMenuItems(row.timer!)); + break; + case "new-timer": + for (const durationMs of timerEngine.state.recentDurationsMs) { + items.push({ + label: `Start ${formatDurationWords(durationMs)}`, + onSelect: (ctx) => { + ctx.stack.pop(); + this.startTimer(durationMs, ""); + }, + }); + } + items.push({ + label: "Fine-tune a duration", + onSelect: (ctx) => { + ctx.stack.pop(); + this.openFine("", timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS); + }, + }); + break; + case "stopwatch": + items.push(...this.stopwatchMenuItems()); + break; + case "alarm": + items.push(...this.alarmMenuItems(row.alarm!)); + break; + default: + break; + } + items.push({ + label: "Settings", + onSelect: (ctx) => ctx.stack.push(new WindowMenuLayer("Timers settings", this.settingsMenuItems())), + }); + return items; + } + + private pickerMenuItems(mode: Extract): MenuItem[] { + const items: MenuItem[] = []; + if (mode.kind === "dial") { + items.push({ + label: "Fine-tune (h:mm:ss)", + onSelect: (ctx) => { + ctx.stack.pop(); + this.openFine(mode.label, DURATION_LADDER_MS[mode.index]!); + }, + }); + } + items.push({ + label: mode.label ? `Label: ${mode.label}` : "Set a label", + onSelect: (ctx) => { + ctx.stack.pop(); + this.askForLabel({ kind: "new-timer" }); + }, + }); + items.push({ + label: "Cancel", + onSelect: (ctx) => { + ctx.stack.pop(); + this.mode = { kind: "list" }; + }, + }); + return items; + } + + private timerMenuItems(timer: CountdownTimer): MenuItem[] { + const phase = timerPhase(timer); + const items: MenuItem[] = []; + if (phase === "rung") { + items.push( + { label: "Dismiss", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.removeTimer(timer.id); } }, + { label: "Again", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.restartTimer(timer.id); } }, + ); + } + items.push({ + label: "+1 minute", + onSelect: (ctx) => { + ctx.stack.pop(); + timerEngine.addTimerTime(timer.id, MINUTE_MS); + }, + }); + if (phase === "running") { + items.push({ label: "Pause", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.pauseTimer(timer.id); } }); + } else if (phase === "paused") { + items.push({ label: "Resume", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.resumeTimer(timer.id); } }); + } + if (phase !== "rung") { + items.push({ label: "Restart", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.restartTimer(timer.id); } }); + } + items.push({ + label: timer.label ? `Label: ${timer.label}` : "Set a label", + onSelect: (ctx) => { + ctx.stack.pop(); + this.askForLabel({ kind: "timer", id: timer.id }); + }, + }); + if (phase !== "rung") { + items.push({ label: "Delete", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.removeTimer(timer.id); } }); + } + return items; + } + + private stopwatchMenuItems(): MenuItem[] { + const stopwatch = timerEngine.state.stopwatch; + const running = stopwatchIsRunning(stopwatch); + const items: MenuItem[] = []; + if (running) { + items.push({ label: "Lap", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.stopwatchLap(); } }); + } + items.push({ + label: running ? "Stop" : "Start", + onSelect: (ctx) => { + ctx.stack.pop(); + timerEngine.stopwatchToggle(); + }, + }); + items.push({ + label: "Reset", + disabled: () => stopwatchElapsedMs(timerEngine.state.stopwatch, Date.now()) === 0, + onSelect: (ctx) => { + ctx.stack.pop(); + timerEngine.stopwatchReset(); + }, + }); + return items; + } + + private alarmMenuItems(alarm: Alarm): MenuItem[] { + const items: MenuItem[] = []; + if (alarm.ringingSinceMs !== null) { + items.push( + { label: "Dismiss", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.dismissAlarm(alarm.id); } }, + { + label: `Snooze ${timersSnoozeSetting.get()} min`, + onSelect: (ctx) => { ctx.stack.pop(); timerEngine.snoozeAlarm(alarm.id); }, + }, + ); + } else { + items.push({ + label: alarm.enabled ? "Turn off" : "Turn on", + onSelect: (ctx) => { + ctx.stack.pop(); + timerEngine.setAlarmEnabled(alarm.id, !alarm.enabled); + }, + }); + } + items.push({ + label: "Change time", + onSelect: (ctx) => { + ctx.stack.pop(); + this.openAlarmTime(alarm); + }, + }); + items.push({ + label: `Repeat: ${formatDays(alarm.days)}`, + onSelect: (ctx) => ctx.stack.push(new WindowMenuLayer("Repeat", this.repeatMenuItems(alarm.id))), + }); + items.push({ + label: alarm.label ? `Label: ${alarm.label}` : "Set a label", + onSelect: (ctx) => { + ctx.stack.pop(); + this.askForLabel({ kind: "alarm", id: alarm.id }); + }, + }); + items.push({ label: "Delete", onSelect: (ctx) => { ctx.stack.pop(); timerEngine.deleteAlarm(alarm.id); } }); + return items; + } + + /** Repeat presets, then one toggle per weekday; the menu stays open while toggling. */ + private repeatMenuItems(alarmId: number): MenuItem[] { + const days = () => timerEngine.findAlarm(alarmId)?.days ?? 0; + const preset = (label: string, mask: number): MenuItem => ({ + label, + onSelect: (ctx) => { + ctx.stack.pop(); + timerEngine.setAlarmDays(alarmId, mask); + }, + }); + const items: MenuItem[] = [ + preset("Once", 0), + preset("Weekdays", WEEKDAYS_MASK), + preset("Weekends", WEEKEND_MASK), + preset("Every day", EVERY_DAY_MASK), + ]; + for (let index = 0; index < 7; index++) { + const bit = DAY_BITS[index]!; + items.push({ + label: DAY_FULL_NAMES[index]!, + onSelect: () => timerEngine.setAlarmDays(alarmId, days() ^ bit), + render: (args) => + drawToggleMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, (days() & bit) !== 0, args.selected), + }); + } + return items; + } + + private settingsMenuItems(): MenuItem[] { + const toggle = (label: string, get: () => boolean, set: (value: boolean) => void): MenuItem => ({ + label, + onSelect: () => set(!get()), + render: (args) => drawToggleMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, get(), args.selected), + }); + return [ + toggle(timersSoundSetting.label, () => timersSoundSetting.get(), (value) => timersSoundSetting.set(value)), + toggle(timersWakeSetting.label, () => timersWakeSetting.get(), (value) => timersWakeSetting.set(value)), + { + label: timersSnoozeSetting.label, + onSelect: () => { + const values = timersSnoozeSetting.values; + const next = values[(values.indexOf(timersSnoozeSetting.get()) + 1) % values.length] as SnoozeMinutes; + timersSnoozeSetting.set(next); + }, + render: (args) => + drawRightValueMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, timersSnoozeSetting.displayValue()), + }, + toggle("12-hour clock", () => twelveHour(), (value) => timeFormatSetting.set(value ? "12h" : "24h")), + ]; + } + + // ------------------------------------------------------------------------- + // Painting + + paint(ctx: LayerContext): GrayImage { + timerEngine.check(); + const now = Date.now(); + const { width, height } = ctx.stack.getBaseSize(); + const image = new GrayImage(width, height, 0); + const rows = this.buildRows(now); + const selectedIndex = this.reconcileSelection(rows); + const listWidth = listWidthFor(width); + const listX = width - listWidth; + const picking = this.mode.kind !== "list"; + + this.paintList(image, rows, selectedIndex, listX, listWidth, height, ctx.stack.isFocused(), picking ? LIST_DIM : 1, now); + image.drawLine(listX - 7, 8, listX - 7, height - 8, picking ? 20 : 40); + + const stage = { x: STAGE_X, y: 0, width: listX - 7 - STAGE_LIST_GAP - STAGE_X, height }; + switch (this.mode.kind) { + case "dial": + this.paintDial(image, stage, this.mode, now); + break; + case "fine": + this.paintFine(image, stage, this.mode); + break; + case "alarm-time": + this.paintAlarmTime(image, stage, this.mode, now); + break; + default: + this.paintStage(image, stage, rows[selectedIndex]!, now, ctx.stack.isFocused()); + } + return image; + } + + private paintList( + image: GrayImage, + rows: Row[], + selectedIndex: number, + listX: number, + listWidth: number, + height: number, + focused: boolean, + dim: number, + now: number, + ): void { + const font = smallFont(); + const rowHeight = listRowHeight(font); + const visible = Math.max(1, Math.floor((height - 2 * LIST_TOP) / rowHeight)); + this.scrollRow = scrollToKeepSelectionVisible(this.scrollRow, selectedIndex, visible, rows.length); + const shade = (value: number) => Math.round(value * dim); + const textX = listX + 8; + const textWidth = listWidth - 24; + const last = Math.min(rows.length, this.scrollRow + visible); + for (let index = this.scrollRow; index < last; index++) { + const row = rows[index]!; + const y = LIST_TOP + (index - this.scrollRow) * rowHeight; + const textY = y + LIST_ROW_TEXT_INSET; + if (row.kind === "header") { + image.drawText(font, textX, textY, row.title!, shade(90)); + continue; + } + const selected = index === selectedIndex; + if (selected && dim === 1) { + drawSelectionHighlight(image, listX, y, listWidth - 12, rowHeight - 1, focused, 6); + } + const bright = shade(selected ? 250 : 210); + const soft = shade(selected ? 170 : 130); + switch (row.kind) { + case "timer": { + const timer = row.timer!; + const phase = timerPhase(timer); + const digits = phase === "rung" ? "0:00" : formatCountdown(timerRemainingMs(timer, now)); + const digitsValue = phase === "rung" ? (Math.floor(now / 1000) % 2 ? bright : soft) : phase === "paused" ? soft : bright; + image.drawText(font, textX, textY, digits, digitsValue); + const digitsWidth = font.measureText(digits) + 8; + const nameWidth = textWidth - digitsWidth - (phase === "paused" ? 12 : 0); + if (nameWidth > 12) { + image.drawText(font, textX + digitsWidth, textY, truncateText(font, timerDisplayName(timer), nameWidth), soft); + } + if (phase === "paused") drawPauseMark(image, listX + listWidth - 22, y + Math.floor(rowHeight / 2) - 5, soft); + break; + } + case "new-timer": + image.drawText(font, textX, textY, "+ New timer", shade(selected ? 220 : 150)); + break; + case "stopwatch": { + const stopwatch = timerEngine.state.stopwatch; + const running = stopwatchIsRunning(stopwatch); + const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, now), false); + image.drawText(font, textX, textY, "Stopwatch", running ? bright : soft); + image.drawText(font, listX + listWidth - 16 - font.measureText(elapsed), textY, elapsed, running ? bright : soft); + break; + } + case "alarm": { + const alarm = row.alarm!; + const on = alarm.enabled; + const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour()); + image.drawText(font, textX, textY, time, on ? bright : soft); + const timeWidth = font.measureText(time) + 8; + const daysWidth = textWidth - timeWidth - 14; + if (daysWidth > 12) { + image.drawText(font, textX + timeWidth, textY, truncateText(font, alarm.label || formatDays(alarm.days), daysWidth), on ? soft : shade(80)); + } + const dotX = listX + listWidth - 22; + const dotY = y + Math.floor(rowHeight / 2) - 4; + if (alarm.ringingSinceMs !== null || on) image.fillRoundedRect(dotX, dotY, 8, 8, on ? shade(220) : shade(90), 4); + else image.drawRoundedRect(dotX, dotY, 8, 8, shade(90), 4); + break; + } + case "new-alarm": + image.drawText(font, textX, textY, "+ New alarm", shade(selected ? 220 : 150)); + break; + default: + break; + } + } + if (rows.length > visible) { + drawListScrollbar(image, listX + listWidth - 7, LIST_TOP, visible * rowHeight - 4, this.scrollRow, visible, rows.length); + } + } + + private paintStage(image: GrayImage, stage: StageRect, row: Row, now: number, focused: boolean): void { + switch (row.kind) { + case "timer": + this.paintTimerStage(image, stage, row.timer!, now, focused); + return; + case "new-timer": { + const last = timerEngine.state.recentDurationsMs[0] ?? DEFAULT_TIMER_DURATION_MS; + const block = new StageBlock(stage); + block.title(image, "New timer", 200); + block.digits(image, formatCountdown(last), 110); + block.line(image, `${formatDurationWords(last)} last time`, 120); + block.hints(image, [[GESTURE_CLICK, "choose duration"], [GESTURE_SHORT_THEN_LONG_PRESS, "recent"]]); + return; + } + case "stopwatch": + this.paintStopwatchStage(image, stage, now); + return; + case "alarm": + this.paintAlarmStage(image, stage, row.alarm!, now, focused); + return; + case "new-alarm": { + const block = new StageBlock(stage); + block.title(image, "New alarm", 200); + block.digits(image, twelveHour() ? "7:00" : "07:00", 110); + block.line(image, "Rings once unless you set a repeat", 120); + block.hints(image, [[GESTURE_CLICK, "set time"]]); + return; + } + default: + return; + } + } + + private paintTimerStage(image: GrayImage, stage: StageRect, timer: CountdownTimer, now: number, focused: boolean): void { + const block = new StageBlock(stage); + const phase = timerPhase(timer); + if (phase === "rung") { + const flash = Math.floor(now / 1000) % 2 === 0; + block.title(image, "Time's up", flash ? 255 : 170); + block.digits(image, `+${formatCountdown(now - timer.rungAtMs!)}`, 200); + block.line(image, `${timerDisplayName(timer)} · rang at ${formatClockAt(timer.rungAtMs!, twelveHour())}`, 150); + block.buttons(image, ["Dismiss", "Again"], this.ringButton, focused); + block.hints(image, [[GESTURE_SCROLL, "choose"], [GESTURE_CLICK, "select"]]); + return; + } + const remaining = timerRemainingMs(timer, now); + block.title(image, phase === "paused" ? `${timerDisplayName(timer)} · Paused` : timerDisplayName(timer), 200); + block.digits(image, formatCountdown(remaining), phase === "paused" ? 150 : 250); + block.progress(image, timerProgress(timer, now), phase === "paused" ? 120 : 200); + const info = + phase === "paused" + ? `${formatDurationWords(timer.durationMs)} timer · ${formatCountdown(remaining)} left` + : `${formatDurationWords(timer.durationMs)} timer · ends ${formatClockAt(timer.endsAtMs!, twelveHour())}`; + block.line(image, info, 150); + block.hints(image, [[GESTURE_CLICK, phase === "paused" ? "resume" : "pause"], [GESTURE_SHORT_THEN_LONG_PRESS, "options"]]); + } + + private paintStopwatchStage(image: GrayImage, stage: StageRect, now: number): void { + const stopwatch = timerEngine.state.stopwatch; + const running = stopwatchIsRunning(stopwatch); + const elapsed = stopwatchElapsedMs(stopwatch, now); + const block = new StageBlock(stage); + block.title(image, running ? "Stopwatch · Running" : elapsed > 0 ? "Stopwatch · Stopped" : "Stopwatch", 200); + // Tenths only while stopped: the display updates once a second while running. + block.digits(image, formatElapsed(elapsed, !running), running ? 250 : elapsed > 0 ? 200 : 130); + const laps = stopwatch.lapsMs; + if (laps.length > 0) { + const font = smallFont(); + const shown = laps.slice(-Math.max(1, Math.min(4, block.linesLeft()))); + for (let index = 0; index < shown.length; index++) { + const lapIndex = laps.length - shown.length + index; + const total = shown[index]!; + const split = total - (lapIndex > 0 ? laps[lapIndex - 1]! : 0); + block.columns(image, font, [`Lap ${lapIndex + 1}`, formatElapsed(split, true), formatElapsed(total, true)], index === shown.length - 1 ? 190 : 130); + } + } else { + block.line(image, running ? "" : "Laps appear here", 110); + } + block.hints(image, [[GESTURE_CLICK, running ? "stop" : "start"], [GESTURE_SHORT_THEN_LONG_PRESS, running ? "lap" : "reset"]]); + } + + private paintAlarmStage(image: GrayImage, stage: StageRect, alarm: Alarm, now: number, focused: boolean): void { + const block = new StageBlock(stage); + const ringing = alarm.ringingSinceMs !== null; + const flash = Math.floor(now / 1000) % 2 === 0; + block.title(image, ringing ? (alarm.label ? `Alarm · ${alarm.label}` : "Alarm") : alarm.label || "Alarm", ringing ? (flash ? 255 : 170) : 200); + const time = formatTimeOfDay(alarm.hour, alarm.minute, false); + const suffix = twelveHour() ? (alarm.hour < 12 ? "AM" : "PM") : ""; + block.digits(image, twelveHour() ? formatTimeOfDay(alarm.hour, alarm.minute, true).replace(/ [AP]M$/, "") : time, alarm.enabled ? 250 : 130, suffix); + block.days(image, alarm.days, alarm.enabled ? 230 : 110); + if (ringing) { + block.buttons(image, ["Dismiss", `Snooze ${timersSnoozeSetting.get()}m`], this.ringButton, focused); + block.hints(image, [[GESTURE_SCROLL, "choose"], [GESTURE_CLICK, "select"]]); + return; + } + let status: string; + if (!alarm.enabled) status = "Off"; + else if (alarm.snoozedUntilMs !== null) status = `Snoozed until ${formatClockAt(alarm.snoozedUntilMs, twelveHour())}`; + else { + const next = alarmNextRingMs(alarm, now); + status = next === null ? "Off" : `Rings in ${formatSpanWords(next - now)}`; + } + block.line(image, status, 150); + block.hints(image, [[GESTURE_CLICK, alarm.enabled ? "turn off" : "turn on"], [GESTURE_SHORT_THEN_LONG_PRESS, "edit"]]); + } + + private paintDial(image: GrayImage, stage: StageRect, mode: Extract, now: number): void { + const durationMs = DURATION_LADDER_MS[mode.index]!; + const block = new StageBlock(stage); + block.title(image, mode.label ? `New timer · ${mode.label}` : "New timer", 200); + block.digits(image, formatCountdown(durationMs), 250); + block.line(image, `${formatDurationWords(durationMs)} · ends ${formatClockAt(now + durationMs, twelveHour())}`, 150); + block.hints(image, [[GESTURE_SCROLL, "duration"], [GESTURE_CLICK, "start"], [GESTURE_DOUBLE_CLICK, "cancel"]]); + } + + private paintFine(image: GrayImage, stage: StageRect, mode: Extract): void { + const block = new StageBlock(stage); + block.title(image, mode.label ? `New timer · ${mode.label}` : "New timer", 200); + block.fields(image, [pad2(mode.hours), pad2(mode.minutes), pad2(mode.seconds)], [":", ":"], mode.field, ["hours", "min", "sec"]); + block.line(image, this.notice, 190); + block.hints(image, [[GESTURE_SCROLL, "adjust"], [GESTURE_CLICK, mode.field < 2 ? "next" : "start"], [GESTURE_DOUBLE_CLICK, "back"]]); + } + + private paintAlarmTime(image: GrayImage, stage: StageRect, mode: Extract, now: number): void { + const block = new StageBlock(stage); + block.title(image, mode.alarmId === null ? "New alarm" : "Alarm time", 200); + const tens = String(Math.floor(mode.minute / 10)); + const ones = String(mode.minute % 10); + if (twelveHour()) { + const hour12 = ((mode.hour + 11) % 12) + 1; + block.fields(image, [String(hour12), tens, ones, mode.hour < 12 ? "AM" : "PM"], [":", "", " "], mode.field, ["hour", "", "min", ""]); + } else { + block.fields(image, [pad2(mode.hour), tens, ones], [":", ""], mode.field, ["hour", "", "min"]); + } + const preview = alarmNextRingMs( + { id: 0, hour: mode.hour, minute: mode.minute, days: 0, label: "", enabled: true, snoozedUntilMs: null, ringingSinceMs: null, lastFiredAtMs: null }, + now, + ); + block.line(image, preview === null ? "" : `Rings in ${formatSpanWords(preview - now)}`, 150); + const last = this.alarmFieldCount() - 1; + block.hints(image, [[GESTURE_SCROLL, "adjust"], [GESTURE_CLICK, mode.field < last ? "next" : "save"], [GESTURE_DOUBLE_CLICK, "back"]]); + } +} + +// --------------------------------------------------------------------------- +// Stage layout helpers + +type StageRect = { x: number; y: number; width: number; height: number }; + +/** + * Lays the stage out top to bottom: a title line, the big digits, then + * whatever lines follow, with the gesture hints pinned to the bottom. Keeps + * a cursor so each element stacks under the previous one. + */ +class StageBlock { + private cursorY: number; + private readonly hintsTop: number; + + constructor(private readonly rect: StageRect) { + this.cursorY = rect.y + 12; + this.hintsTop = rect.y + rect.height - 10 - lineStep(smallFont()); + } + + title(image: GrayImage, text: string, value: number): void { + const font = mediumFont(); + image.drawText(font, this.rect.x + 4, this.cursorY, truncateText(font, text, this.rect.width - 8), value); + this.cursorY += font.lineHeight + 10; + } + + /** The big number, centred; `suffix` (AM/PM) sits beside it in the medium font. */ + digits(image: GrayImage, text: string, value: number, suffix = ""): void { + const suffixFont = mediumFont(); + const suffixWidth = suffix ? suffixFont.measureText(suffix) + 10 : 0; + const font = fittingDigitFont(text, this.rect.width - 8 - suffixWidth); + const textWidth = font.measureText(text); + const x = this.rect.x + Math.max(0, Math.floor((this.rect.width - textWidth - suffixWidth) / 2)); + image.drawText(font, x, this.cursorY, text, value); + if (suffix) { + image.drawText(suffixFont, x + textWidth + 10, this.cursorY + font.ascent - suffixFont.ascent, suffix, Math.round(value * 0.8)); + } + this.cursorY += font.lineHeight + 8; + } + + progress(image: GrayImage, fraction: number, value: number): void { + const x = this.rect.x + 6; + const width = this.rect.width - 12; + image.fillRoundedRect(x, this.cursorY, width, 6, 40, 3); + const filled = Math.round(width * clamp(fraction, 0, 1)); + if (filled > 0) image.fillRoundedRect(x, this.cursorY, Math.max(6, filled), 6, value, 3); + this.cursorY += 14; + } + + line(image: GrayImage, text: string, value: number): void { + if (!text) return; + const font = smallFont(); + image.drawText(font, this.rect.x + 6, this.cursorY, truncateText(font, text, this.rect.width - 12), value); + this.cursorY += lineStep(font); + } + + /** How many small-font lines fit between the cursor and the hints. */ + linesLeft(): number { + return Math.floor((this.hintsTop - 6 - this.cursorY) / lineStep(smallFont())); + } + + /** A three-column row (lap table). */ + columns(image: GrayImage, font: UiFont, cells: string[], value: number): void { + if (this.cursorY + font.lineHeight > this.hintsTop - 4) return; + const x = this.rect.x + 6; + const width = this.rect.width - 12; + const columnWidth = Math.floor(width / cells.length); + for (let index = 0; index < cells.length; index++) { + const text = cells[index]!; + const cellX = index === 0 ? x : x + index * columnWidth + columnWidth - font.measureText(text); + image.drawText(font, cellX, this.cursorY, text, value); + } + this.cursorY += lineStep(font); + } + + /** The seven weekday letters, lit for the days in `mask`; "Once" for none. */ + days(image: GrayImage, mask: number, value: number): void { + const font = smallFont(); + if (mask === 0) { + this.line(image, "Once", Math.round(value * 0.7)); + return; + } + const step = Math.min(26, Math.floor((this.rect.width - 12) / 7)); + const x = this.rect.x + 6; + for (let index = 0; index < 7; index++) { + const on = (mask & DAY_BITS[index]!) !== 0; + const letter = DAY_LETTERS[index]!; + const letterX = x + index * step + Math.floor((step - font.measureText(letter)) / 2); + if (on) image.fillRoundedRect(x + index * step + 1, this.cursorY - 2, step - 4, font.lineHeight + 4, 40, 4); + image.drawText(font, letterX, this.cursorY, letter, on ? value : Math.round(value * 0.35)); + } + this.cursorY += lineStep(font) + 4; + } + + /** Picker fields: boxed values with separators between and captions beneath. */ + fields(image: GrayImage, values: string[], separators: string[], activeField: number, captions: string[]): void { + const font = digitFont(FIELD_DIGIT_SIZE); + const sepFont = mediumFont(); + const small = smallFont(); + const padX = 8; + const widths = values.map((value) => font.measureText(value) + 2 * padX); + const sepWidths = separators.map((separator) => (separator ? sepFont.measureText(separator) + 8 : 6)); + const total = widths.reduce((sum, width) => sum + width, 0) + sepWidths.reduce((sum, width) => sum + width, 0); + let x = this.rect.x + Math.max(0, Math.floor((this.rect.width - total) / 2)); + const boxHeight = font.lineHeight + 4; + for (let index = 0; index < values.length; index++) { + const width = widths[index]!; + const active = index === activeField; + if (active) { + image.fillRoundedRect(x, this.cursorY - 2, width, boxHeight, 35, 6); + image.drawRoundedRect(x, this.cursorY - 2, width, boxHeight, 130, 6); + } + image.drawText(font, x + padX, this.cursorY, values[index]!, active ? 250 : 170); + const caption = captions[index] ?? ""; + if (caption) { + image.drawText(small, x + Math.floor((width - small.measureText(caption)) / 2), this.cursorY + boxHeight + 2, caption, 110); + } + x += width; + if (index < separators.length) { + const separator = separators[index]!; + if (separator.trim()) { + image.drawText(sepFont, x + 4, this.cursorY + font.ascent - sepFont.ascent, separator, 130); + } + x += sepWidths[index]!; + } + } + this.cursorY += boxHeight + 2 + small.lineHeight + 10; + } + + /** A row of buttons; the highlighted one is filled, the rest outlined. */ + buttons(image: GrayImage, labels: string[], selected: number, focused: boolean): void { + const font = smallFont(); + const gap = 12; + const height = font.lineHeight + 14; + const width = Math.floor((this.rect.width - 12 - gap * (labels.length - 1)) / labels.length); + const y = Math.max(this.cursorY + 4, this.hintsTop - 10 - height); + for (let index = 0; index < labels.length; index++) { + const x = this.rect.x + 6 + index * (width + gap); + const active = index === selected; + if (active) { + image.fillRoundedRect(x, y, width, height, focused ? 40 : 15, 8); + image.drawRoundedRect(x, y, width, height, 150, 8); + } else { + image.drawRoundedRect(x, y, width, height, 70, 8); + } + const label = labels[index]!; + image.drawText(font, x + Math.floor((width - font.measureText(label)) / 2), y + 7, label, active ? 250 : 170); + } + this.cursorY = y + height + 6; + } + + hints(image: GrayImage, pairs: Array<[string, string]>): void { + image.drawText(smallFont(), this.rect.x + 6, this.hintsTop, gestureHints(pairs), 110); + } +} + +function listWidthFor(viewportWidth: number): number { + return clamp(Math.round(viewportWidth * LIST_SHARE), LIST_MIN_WIDTH, LIST_MAX_WIDTH); +} + +function drawPauseMark(image: GrayImage, x: number, y: number, value: number): void { + image.fillRect(x, y, 3, 10, value); + image.fillRect(x + 5, y, 3, 10, value); +} + +function pad2(value: number): string { + return String(value).padStart(2, "0"); +} + +// --------------------------------------------------------------------------- +// Window + +export function createTimerAppWindow(options: InProcessAppOptions): InProcessWindow { + const layer = new TimersLayer(); + let tick: ReturnType | null = null; + let unsubscribe: (() => void) | null = null; + const stopTick = () => { + if (tick !== null) { + clearInterval(tick); + tick = null; + } + }; + const visible = () => shell.isScreenOn() && shell.foregroundWindow()?.windowId === TIMER_WINDOW_ID; + const app = createInProcessWindow({ + appId: "timer", + windowId: TIMER_WINDOW_ID, + title: "Timers", + iconLetter: "T", + icon: "timer", + closeable: true, + actions: options.actions, + baseLayer: layer, + menuItems: () => layer.menuItems(), + receiveTextInput: (text) => { + layer.receiveTextInput(text); + app.requestRender(); + }, + submitFrame: options.submitFrame, + setSurfaceVisible: options.setSurfaceVisible, + removeSurface: options.removeSurface, + reconfigureSurface: options.reconfigureSurface, + onClosed: () => { + stopTick(); + unsubscribe?.(); + unsubscribe = null; + options.onClosed(); + }, + }); + // Once a second while something on screen moves by itself and the window + // is actually visible; the shell's wake path repaints on its own. + tick = setInterval(() => { + if (visible() && timerEngine.isDynamic()) app.requestRender(); + }, 1000); + unsubscribe = timerEngine.onChange(() => { + layer.onEngineChanged(); + if (visible()) app.requestRender(); + }); + return app; +} + +// --------------------------------------------------------------------------- +// Tray icon + +let trayText: string | null = null; +let trayTick: ReturnType | null = null; + +/** + * Keep a small "soonest timer" readout in the top bar while a timer runs, + * so any app can glance at it. Minute granularity until the last minute, + * so the shell isn't repainted every second for an hour. + */ +export function startTimersTrayIcon(): void { + const sync = () => { + const remaining = soonestRunningTimerRemainingMs(timerEngine); + let text: string | null = null; + if (remaining !== null) { + text = remaining >= MINUTE_MS ? `${Math.ceil(remaining / MINUTE_MS)}m` : `${Math.max(0, Math.ceil(remaining / 1000))}s`; + } + if (text === trayText) return; + trayText = text; + shell.setTrayIcon("timer", text === null ? null : renderTrayIcon(text)); + if (text !== null && trayTick === null) { + trayTick = setInterval(sync, 1000); + } else if (text === null && trayTick !== null) { + clearInterval(trayTick); + trayTick = null; + } + }; + timerEngine.onChange(sync); + sync(); +} + +function renderTrayIcon(text: string): GrayImage { + const font = getFont("terminus12"); + const dial = 12; + const gap = 4; + const width = dial + gap + font.measureText(text); + const icon = new GrayImage(width, 16, 0); + // A little dial: a ring with a hand pointing up-right. + icon.drawRoundedRect(0, 2, dial, dial, 200, 6); + icon.drawLine(6, 8, 6, 5, 200); + icon.drawLine(6, 8, 8, 8, 200); + icon.drawText(font, dial + gap, 2, text, 220); + return icon; +} diff --git a/app/apps/timer/timer-app.worker.ts b/app/apps/timer/timer-app.worker.ts deleted file mode 100644 index 0e9d1433..00000000 --- a/app/apps/timer/timer-app.worker.ts +++ /dev/null @@ -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 | null; - lastSubmittedFingerprint: string; -}; - -type CountdownTimer = { - id: number; - durationMs: number; - endAtMs: number; - expired: boolean; - expiryTimeout: ReturnType | 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(); -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`; -} - diff --git a/app/apps/timer/timer-engine.ts b/app/apps/timer/timer-engine.ts new file mode 100644 index 00000000..78672b9a --- /dev/null +++ b/app/apps/timer/timer-engine.ts @@ -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({ + 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; + /** 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 | null = null; + private ringTimer: ReturnType | 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(); diff --git a/app/apps/timer/timer-model.ts b/app/apps/timer/timer-model.ts new file mode 100644 index 00000000..3afc6860 --- /dev/null +++ b/app/apps/timer/timer-model.ts @@ -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; +} diff --git a/app/assistant/timer-tools.ts b/app/assistant/timer-tools.ts index 088a271a..a9fe1171 100644 --- a/app/assistant/timer-tools.ts +++ b/app/assistant/timer-tools.ts @@ -1,76 +1,433 @@ /** - * Shell-side timer.* assistant tools. The Timer app's own tools are - * window-scoped ("open" tier), but "start a 5 minute timer" must work with no - * Timer window open — so these always-available wrappers launch the app, - * wait for its tools to register, and forward the call. Timer state lives in - * the app's worker, which outlives its window, so list/cancel also route - * through the app rather than answering "no timers" from the shell. + * The assistant's timer.* / stopwatch.* / alarm.* tools. They talk to the + * Timers app's engine directly (it boots with the shell), so every one works + * with no Timers window open; timer.set and alarm.set also bring the window + * forward so the wearer sees what was set. */ -import { toolRegistry, type ToolRegistry } from "./tool-registry"; -import { callAppToolWithLaunch } from "./launch-on-call"; +import { + alarmNextRingMs, + formatClockAt, + formatCountdown, + formatDays, + formatDurationWords, + formatElapsed, + formatSpanWords, + formatTimeOfDay, + MAX_TIMER_DURATION_MS, + parseRepeatDays, + parseTimeOfDay, + sortAlarms, + sortTimers, + stopwatchElapsedMs, + stopwatchIsRunning, + timerDisplayName, + timerPhase, + timerRemainingMs, + type Alarm, + type CountdownTimer, +} from "../apps/timer/timer-model"; +import { timerEngine } from "../apps/timer/timer-engine"; +import { timeFormatSetting } from "../ui/dashboard-settings"; +import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry"; let registered = false; -// Wrapper timeout: covers a first-launch worker spawn (up to the 5 s -// tool-appear wait in callAppToolWithLaunch) plus the forwarded call's own -// 10 s default budget. -const TIMER_WRAPPER_TIMEOUT_MS = 20_000; +function twelveHour(): boolean { + return timeFormatSetting.get() === "12h"; +} -export function registerTimerTools( - launchApp: (appId: string) => Promise, - registry: ToolRegistry = toolRegistry, -): void { +/** Timers in the order the app lists them, so "timer 2" means the same thing in both places. */ +function listedTimers(): CountdownTimer[] { + return sortTimers(timerEngine.state.timers, Date.now()); +} + +function listedAlarms(): Alarm[] { + return sortAlarms(timerEngine.state.alarms); +} + +function describeTimer(timer: CountdownTimer, number: number, now: number): string { + const name = timerDisplayName(timer); + switch (timerPhase(timer)) { + case "rung": + return `Timer ${number} (${name}): finished ${formatSpanWords(now - timer.rungAtMs!)} ago, still ringing until dismissed.`; + case "paused": + return `Timer ${number} (${name}): paused with ${formatCountdown(timerRemainingMs(timer, now))} left.`; + default: + return `Timer ${number} (${name}): ${formatCountdown(timerRemainingMs(timer, now))} left, ends at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`; + } +} + +function describeAlarm(alarm: Alarm, number: number, now: number): string { + const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour()); + const name = alarm.label ? ` (${alarm.label})` : ""; + if (alarm.ringingSinceMs !== null) return `Alarm ${number}: ${time}${name}, ringing now.`; + if (!alarm.enabled) return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}, off.`; + const next = alarmNextRingMs(alarm, now); + const when = next === null ? "" : `, rings in ${formatSpanWords(next - now)}`; + const snoozed = alarm.snoozedUntilMs !== null ? " (snoozed)" : ""; + return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}${when}${snoozed}.`; +} + +/** Resolve a 1-based "timer"/"alarm" argument, or the only item when omitted. */ +function pickItem(items: T[], raw: unknown, noun: string, describe: (item: T, number: number) => string): T | ToolResult { + if (items.length === 0) return { ok: false, error: `No ${noun}s are set.` }; + if (raw === undefined || raw === null) { + if (items.length === 1) return items[0]!; + return { + ok: false, + error: `There are ${items.length} ${noun}s; give the ${noun} number.\n${items.map(describe).join("\n")}`, + }; + } + const index = Math.floor(Number(raw)); + if (!Number.isFinite(index) || index < 1 || index > items.length) { + return { ok: false, error: `No ${noun} ${raw}; there are ${items.length} ${noun}s.` }; + } + return items[index - 1]!; +} + +function isResult(value: unknown): value is ToolResult { + return !!value && typeof value === "object" && "ok" in (value as object) && !("id" in (value as object)); +} + +function durationField(value: unknown, label: string): number { + if (value === undefined || value === null || value === "") return 0; + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`Invalid ${label} value: ${value}`); + return parsed; +} + +const NUMBER_ARG = (noun: string, listTool: string) => ({ + type: "number", + description: `1-based ${noun} number, as shown by ${listTool}. May be omitted when only one ${noun} exists.`, +}); + +export function registerTimerTools(launchApp: (appId: string) => Promise, registry: ToolRegistry = toolRegistry): void { if (registered) return; registered = true; + const showApp = () => { + void launchApp("timer").catch((error) => console.warn(`timer tool launch failed: ${error}`)); + }; + + // --- timers --- + registry.registerSystemTool( { name: "timer.set", description: - "Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds; at least one must be nonzero. Opens the Timer app if it isn't already open. Returns the timer's number and when it will finish.", + "Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds (at least one nonzero) and optionally a label such as \"pasta\". 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)." }, + label: { type: "string", description: "Optional short name for the timer." }, }, additionalProperties: false, }, - timeoutMs: TIMER_WRAPPER_TIMEOUT_MS, proactive: true, }, - (args) => callAppToolWithLaunch(registry, launchApp, "timer", "set_timer", args ?? {}), + (args) => { + const durationMs = Math.round( + ((durationField(args?.hours, "hours") * 60 + durationField(args?.minutes, "minutes")) * 60 + + durationField(args?.seconds, "seconds")) * + 1000, + ); + if (durationMs <= 0) return { ok: false, error: "timer.set requires a duration longer than zero." }; + if (durationMs > MAX_TIMER_DURATION_MS) return { ok: false, error: "Timers can run for at most 24 hours." }; + const label = typeof args?.label === "string" ? args.label.trim() : ""; + const timer = timerEngine.startTimer(durationMs, label); + showApp(); + const number = listedTimers().indexOf(timer) + 1; + return { + ok: true, + content: `Started a ${formatDurationWords(durationMs)} timer${label ? ` "${label}"` : ""} (timer ${number}), finishing at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`, + }; + }, ); registry.registerSystemTool( { name: "timer.list", description: - "List the countdown timers on the glasses: each timer's number, its original duration, and the time remaining (or that it has finished). Opens the Timer app if it isn't already open — timers keep running while its window is closed.", + "List the countdown timers on the glasses: each timer's number, name, time remaining (or paused / finished), and end time.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, - timeoutMs: TIMER_WRAPPER_TIMEOUT_MS, proactive: true, }, - () => callAppToolWithLaunch(registry, launchApp, "timer", "list_timers", {}), + () => { + const timers = listedTimers(); + if (timers.length === 0) return { ok: true, content: "No timers are set." }; + const now = Date.now(); + return { ok: true, content: timers.map((timer, index) => describeTimer(timer, index + 1, now)).join("\n") }; + }, ); registry.registerSystemTool( { name: "timer.cancel", description: - "Cancel a running countdown timer on the glasses, or dismiss a finished one. Give the timer number from timer.list; it may be omitted when only one timer exists. Pass all=true to clear every timer. Opens the Timer app if it isn't already open.", + "Cancel a countdown timer, or dismiss a finished one. Give the timer number from timer.list (omit it when only one exists), or all=true to clear every timer.", inputSchema: { type: "object", properties: { - timer: { type: "number", description: "1-based timer number, as shown by timer.list." }, + timer: NUMBER_ARG("timer", "timer.list"), all: { type: "boolean", description: "Clear all timers instead of a single one." }, }, additionalProperties: false, }, - timeoutMs: TIMER_WRAPPER_TIMEOUT_MS, proactive: true, }, - (args) => callAppToolWithLaunch(registry, launchApp, "timer", "cancel_timer", args ?? {}), + (args) => { + const timers = listedTimers(); + if (args?.all === true) { + if (timers.length === 0) return { ok: true, content: "No timers are set." }; + for (const timer of timers) timerEngine.removeTimer(timer.id); + return { ok: true, content: timers.length === 1 ? "Cleared the timer." : `Cleared ${timers.length} timers.` }; + } + const now = Date.now(); + const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now)); + if (isResult(picked)) return picked; + const description = describeTimer(picked, timers.indexOf(picked) + 1, now); + timerEngine.removeTimer(picked.id); + return { ok: true, content: `${timerPhase(picked) === "rung" ? "Dismissed" : "Canceled"}: ${description}` }; + }, + ); + + registry.registerSystemTool( + { + name: "timer.pause", + description: "Pause a running countdown timer, or resume a paused one. Give the timer number from timer.list (omit it when only one exists).", + inputSchema: { + type: "object", + properties: { + timer: NUMBER_ARG("timer", "timer.list"), + resume: { type: "boolean", description: "true to resume a paused timer instead of pausing." }, + }, + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const timers = listedTimers(); + const now = Date.now(); + const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now)); + if (isResult(picked)) return picked; + const phase = timerPhase(picked); + if (phase === "rung") return { ok: false, error: "That timer has already finished; dismiss it with timer.cancel." }; + const resume = args?.resume === true || phase === "paused"; + if (resume) timerEngine.resumeTimer(picked.id); + else timerEngine.pauseTimer(picked.id); + const updated = timerEngine.findTimer(picked.id)!; + return { ok: true, content: `${resume ? "Resumed" : "Paused"} ${describeTimer(updated, timers.indexOf(picked) + 1, Date.now())}` }; + }, + ); + + registry.registerSystemTool( + { + name: "timer.add_time", + description: "Add minutes to a countdown timer (a finished one restarts with just the added time). Give the timer number from timer.list (omit it when only one exists).", + inputSchema: { + type: "object", + properties: { + timer: NUMBER_ARG("timer", "timer.list"), + minutes: { type: "number", description: "Minutes to add (default 1)." }, + }, + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const timers = listedTimers(); + const now = Date.now(); + const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now)); + if (isResult(picked)) return picked; + const minutes = args?.minutes === undefined ? 1 : Number(args.minutes); + if (!Number.isFinite(minutes) || minutes <= 0) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` }; + timerEngine.addTimerTime(picked.id, Math.round(minutes * 60_000)); + const updated = timerEngine.findTimer(picked.id)!; + return { ok: true, content: `Added ${formatDurationWords(minutes * 60_000)}. ${describeTimer(updated, listedTimers().indexOf(updated) + 1, Date.now())}` }; + }, + ); + + registry.registerSystemTool( + { + name: "timer.dismiss", + description: "Stop whatever is ringing on the glasses right now: finished timers are cleared and ringing alarms dismissed.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + proactive: true, + }, + () => { + const count = timerEngine.dismissAllRinging(); + return { ok: true, content: count === 0 ? "Nothing is ringing." : `Dismissed ${count === 1 ? "it" : `${count} items`}.` }; + }, + ); + + // --- stopwatch --- + + registry.registerSystemTool( + { + name: "stopwatch.control", + description: + "Control the stopwatch on the glasses: action start, stop, lap, reset, or read (report the elapsed time and laps without changing anything).", + inputSchema: { + type: "object", + properties: { + action: { type: "string", enum: ["start", "stop", "lap", "reset", "read"], description: "What to do." }, + }, + required: ["action"], + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const action = String(args?.action ?? "read"); + switch (action) { + case "start": + timerEngine.stopwatchStart(); + showApp(); + break; + case "stop": + timerEngine.stopwatchStop(); + break; + case "lap": + if (!stopwatchIsRunning(timerEngine.state.stopwatch)) return { ok: false, error: "The stopwatch is not running." }; + timerEngine.stopwatchLap(); + break; + case "reset": + timerEngine.stopwatchReset(); + break; + case "read": + break; + default: + return { ok: false, error: `Unknown stopwatch action: ${action}` }; + } + const stopwatch = timerEngine.state.stopwatch; + const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, Date.now()), true); + const state = stopwatchIsRunning(stopwatch) ? "running" : "stopped"; + const laps = stopwatch.lapsMs.length > 0 ? ` Laps: ${stopwatch.lapsMs.map((lap) => formatElapsed(lap, true)).join(", ")}.` : ""; + return { ok: true, content: `Stopwatch ${state} at ${elapsed}.${laps}` }; + }, + ); + + // --- alarms --- + + registry.registerSystemTool( + { + name: "alarm.set", + description: + "Set an alarm on the glasses. Give the time of day (e.g. \"7:30\", \"7:30 am\", \"19:30\"), optional repeat days (day names, \"weekdays\", \"weekends\", \"every day\"; default once), and an optional label.", + inputSchema: { + type: "object", + properties: { + time: { type: "string", description: "Time of day, 12- or 24-hour." }, + days: { + type: "array", + items: { type: "string" }, + description: "Repeat days: day names or weekdays / weekends / every day. Omit for a one-off alarm.", + }, + label: { type: "string", description: "Optional short name for the alarm." }, + }, + required: ["time"], + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const time = parseTimeOfDay(String(args?.time ?? "")); + if (!time) return { ok: false, error: `Could not understand the time "${args?.time}". Use a form like 7:30 am or 19:30.` }; + const days = parseRepeatDays(args?.days); + if (days === null) return { ok: false, error: `Could not understand the repeat days ${JSON.stringify(args?.days)}.` }; + const label = typeof args?.label === "string" ? args.label.trim() : ""; + const alarm = timerEngine.addAlarm(time.hour, time.minute, days, label); + showApp(); + const now = Date.now(); + return { ok: true, content: `Set. ${describeAlarm(alarm, listedAlarms().indexOf(alarm) + 1, now)}` }; + }, + ); + + registry.registerSystemTool( + { + name: "alarm.list", + description: "List the alarms on the glasses: each alarm's number, time, repeat days, label, and whether it is on.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + proactive: true, + }, + () => { + const alarms = listedAlarms(); + if (alarms.length === 0) return { ok: true, content: "No alarms are set." }; + const now = Date.now(); + return { ok: true, content: alarms.map((alarm, index) => describeAlarm(alarm, index + 1, now)).join("\n") }; + }, + ); + + registry.registerSystemTool( + { + name: "alarm.enable", + description: "Turn an alarm on or off without deleting it. Give the alarm number from alarm.list (omit it when only one exists).", + inputSchema: { + type: "object", + properties: { + alarm: NUMBER_ARG("alarm", "alarm.list"), + enabled: { type: "boolean", description: "true to turn the alarm on, false to turn it off." }, + }, + required: ["enabled"], + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const alarms = listedAlarms(); + const now = Date.now(); + const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now)); + if (isResult(picked)) return picked; + timerEngine.setAlarmEnabled(picked.id, args?.enabled !== false); + const updated = timerEngine.findAlarm(picked.id)!; + return { ok: true, content: describeAlarm(updated, alarms.indexOf(picked) + 1, Date.now()) }; + }, + ); + + registry.registerSystemTool( + { + name: "alarm.delete", + description: "Delete an alarm. Give the alarm number from alarm.list (omit it when only one exists).", + inputSchema: { + type: "object", + properties: { alarm: NUMBER_ARG("alarm", "alarm.list") }, + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const alarms = listedAlarms(); + const now = Date.now(); + const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now)); + if (isResult(picked)) return picked; + const description = describeAlarm(picked, alarms.indexOf(picked) + 1, now); + timerEngine.deleteAlarm(picked.id); + return { ok: true, content: `Deleted: ${description}` }; + }, + ); + + registry.registerSystemTool( + { + name: "alarm.snooze", + description: "Snooze the alarm that is ringing now. Optionally give the snooze length in minutes (default: the Timers app's snooze setting).", + inputSchema: { + type: "object", + properties: { minutes: { type: "number", description: "Snooze length in minutes." } }, + additionalProperties: false, + }, + proactive: true, + }, + (args) => { + const ringing = timerEngine.state.alarms.filter((alarm) => alarm.ringingSinceMs !== null); + if (ringing.length === 0) return { ok: false, error: "No alarm is ringing." }; + const minutes = args?.minutes === undefined ? undefined : Number(args.minutes); + if (minutes !== undefined && (!Number.isFinite(minutes) || minutes <= 0)) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` }; + for (const alarm of ringing) timerEngine.snoozeAlarm(alarm.id, minutes); + const updated = timerEngine.findAlarm(ringing[0]!.id)!; + return { ok: true, content: `Snoozed until ${formatClockAt(updated.snoozedUntilMs!, twelveHour())}.` }; + }, ); } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 2028fde6..0a7450d7 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -56,7 +56,6 @@ import { registerNavigateTools } from "../assistant/navigate-tools"; import { registerRoamTools } from "../assistant/roam-tools"; import { assistantBridge } from "../assistant/bridge-client"; import { registerWindowTools } from "../assistant/window-tools"; -import { registerTimerTools } from "../assistant/timer-tools"; import { WorkerAppHost } from "../ui/shell/worker-window"; import { ALL_APPS } from "../apps/all-apps"; import { type AppContext, type AppDefinition, type AppLaunchParams, type TextEditorHost } from "../apps/app-definition"; @@ -326,8 +325,6 @@ class DashboardController { registerNavigateTools((appId) => this.launchApp(appId)); // roam.* tools launch the Roam app on demand likewise. registerRoamTools((appId) => this.launchApp(appId)); - // timer.* tools launch the Timer app on demand likewise. - registerTimerTools((appId) => this.launchApp(appId)); // apps.* tools mirror the launcher grid and sidebar (launch, focus, close). registerWindowTools({ apps: LAUNCHABLE_APPS, diff --git a/app/native/timer-notifications.ts b/app/native/timer-notifications.ts index f7524ee0..afcc398c 100644 --- a/app/native/timer-notifications.ts +++ b/app/native/timer-notifications.ts @@ -2,28 +2,35 @@ import { Utils } from "@nativescript/core"; declare const com: any; +/** + * Bridge to FaceclawTimerNotifications.java: the durable Android alarm and + * phone notification behind every Timers-app expiry (countdown timers and + * alarms alike, keyed by the item's id). The phone posts the notification at + * `triggerAtMs` even if the app process is asleep or gone. + */ + function getContext(): android.content.Context | null { if (!global.isAndroid) return null; return Utils.android.getApplicationContext() ?? null; } -/** Schedule the durable Android alarm backing one on-glasses timer. */ -export function scheduleTimerNotification(timerId: number, triggerAtMs: number, durationLabel: string): void { +/** Schedule (or move) the Android alarm that posts `title` / `text` at triggerAtMs. */ +export function scheduleTimerNotification(itemId: number, triggerAtMs: number, title: string, text: string): void { const context = getContext(); if (!context) return; - com.faceclaw.app.FaceclawTimerNotifications.schedule(context, timerId, triggerAtMs, durationLabel); + com.faceclaw.app.FaceclawTimerNotifications.schedule(context, itemId, triggerAtMs, title, text); } /** Cancel both a pending alarm and any already-posted notification. */ -export function cancelTimerNotification(timerId: number): void { +export function cancelTimerNotification(itemId: number): void { const context = getContext(); if (!context) return; - com.faceclaw.app.FaceclawTimerNotifications.cancel(context, timerId); + com.faceclaw.app.FaceclawTimerNotifications.cancel(context, itemId); } -/** Prompt worker-side expiry path; Java deduplicates it against the alarm. */ -export function fireTimerNotification(timerId: number, durationLabel: string): void { +/** The engine's own expiry path; Java deduplicates it against the alarm's. */ +export function fireTimerNotification(itemId: number, title: string, text: string): void { const context = getContext(); if (!context) return; - com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, timerId, durationLabel); + com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, itemId, title, text); } diff --git a/tests/timer-model.test.cjs b/tests/timer-model.test.cjs new file mode 100644 index 00000000..b5e45527 --- /dev/null +++ b/tests/timer-model.test.cjs @@ -0,0 +1,151 @@ +// Pins the Timers app's clock arithmetic: the duration dial's ladder, the +// countdown / stopwatch / span formatting the stage shows, alarm scheduling +// across days and repeat masks, and the argument parsing the assistant +// tools rely on. +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const model = require("../.test-build/app/apps/timer/timer-model.js"); + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; + +test("the duration ladder is strictly increasing and spans 10s to 24h", () => { + const ladder = model.DURATION_LADDER_MS; + assert.equal(ladder[0], 10_000); + assert.equal(ladder[ladder.length - 1], 24 * HOUR); + for (let index = 1; index < ladder.length; index++) { + assert.ok(ladder[index] > ladder[index - 1], `rung ${index} not increasing`); + } + assert.ok(ladder.includes(10 * MINUTE)); + assert.ok(ladder.includes(25 * MINUTE)); + assert.ok(ladder.includes(90 * MINUTE)); +}); + +test("nearestLadderIndex snaps to the closest rung", () => { + assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(10 * MINUTE)], 10 * MINUTE); + assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(11 * MINUTE + 20_000)], 11 * MINUTE); + assert.equal(model.nearestLadderIndex(0), 0); + assert.equal(model.nearestLadderIndex(1000 * HOUR), model.DURATION_LADDER_MS.length - 1); +}); + +test("countdown rounds up so 0:00 means finished; elapsed rounds down", () => { + assert.equal(model.formatCountdown(59_001), "1:00"); + assert.equal(model.formatCountdown(59_000), "0:59"); + assert.equal(model.formatCountdown(0), "0:00"); + assert.equal(model.formatCountdown(HOUR + 5 * MINUTE + 3000), "1:05:03"); + assert.equal(model.formatElapsed(59_950, false), "0:59"); + assert.equal(model.formatElapsed(59_950, true), "0:59.9"); + assert.equal(model.formatElapsed(HOUR, true), "1:00:00.0"); +}); + +test("durations and spans read naturally", () => { + assert.equal(model.formatDurationWords(20 * MINUTE), "20 min"); + assert.equal(model.formatDurationWords(90 * MINUTE), "1h 30m"); + assert.equal(model.formatDurationWords(45_000), "45s"); + assert.equal(model.formatDurationWords(2 * MINUTE + 30_000), "2m 30s"); + assert.equal(model.formatSpanWords(9 * HOUR + 12 * MINUTE), "9h 12m"); + assert.equal(model.formatSpanWords(12 * MINUTE), "12m"); + assert.equal(model.formatSpanWords(30 * HOUR), "1d 6h"); +}); + +test("time of day honours the 12/24-hour choice", () => { + assert.equal(model.formatTimeOfDay(7, 5, false), "7:05"); + assert.equal(model.formatTimeOfDay(19, 30, false), "19:30"); + assert.equal(model.formatTimeOfDay(0, 0, true), "12:00 AM"); + assert.equal(model.formatTimeOfDay(12, 0, true), "12:00 PM"); + assert.equal(model.formatTimeOfDay(19, 30, true), "7:30 PM"); +}); + +function alarm(hour, minute, days, extra = {}) { + return { id: 1, hour, minute, days, label: "", enabled: true, snoozedUntilMs: null, ringingSinceMs: null, lastFiredAtMs: null, ...extra }; +} + +/** Local-time constructor: Wednesday 2026-09-02 at hh:mm. */ +function wednesday(hour, minute) { + return new Date(2026, 8, 2, hour, minute, 0, 0).getTime(); +} + +test("a one-off alarm rings later today, else tomorrow", () => { + const now = wednesday(8, 0); + assert.equal(model.alarmNextRingMs(alarm(9, 30, 0), now), wednesday(9, 30)); + assert.equal(model.alarmNextRingMs(alarm(7, 0, 0), now), new Date(2026, 8, 3, 7, 0).getTime()); + // Exactly now counts as passed. + assert.equal(model.alarmNextRingMs(alarm(8, 0, 0), now), new Date(2026, 8, 3, 8, 0).getTime()); +}); + +test("a repeating alarm skips to its next enabled day", () => { + const now = wednesday(8, 0); + // Weekends only: Wednesday -> Saturday. + assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKEND_MASK), now), new Date(2026, 8, 5, 7, 0).getTime()); + // Weekdays, time already passed today: Thursday. + assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKDAYS_MASK), now), new Date(2026, 8, 3, 7, 0).getTime()); + // Only Wednesdays, time passed: a week from now. + assert.equal(model.alarmNextRingMs(alarm(7, 0, model.DAY_BITS[2]), now), new Date(2026, 8, 9, 7, 0).getTime()); +}); + +test("an alarm does not ring twice for the occurrence it last fired for", () => { + const now = wednesday(7, 0) + 20_000; + const fired = alarm(7, 0, model.EVERY_DAY_MASK, { lastFiredAtMs: wednesday(7, 0) }); + assert.equal(model.alarmNextRingMs(fired, now - 5 * MINUTE), new Date(2026, 8, 3, 7, 0).getTime()); +}); + +test("snooze and disabled override the schedule", () => { + const now = wednesday(8, 0); + assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { snoozedUntilMs: now + 10 * MINUTE }), now), now + 10 * MINUTE); + assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { enabled: false }), now), null); +}); + +test("repeat masks have readable names", () => { + assert.equal(model.formatDays(0), "Once"); + assert.equal(model.formatDays(model.WEEKDAYS_MASK), "Weekdays"); + assert.equal(model.formatDays(model.WEEKEND_MASK), "Weekends"); + assert.equal(model.formatDays(model.EVERY_DAY_MASK), "Every day"); + assert.equal(model.formatDays(model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]), "Mon Wed Fri"); +}); + +test("timers sort ringing first, then soonest running, then paused", () => { + const now = 1_000_000; + const running = { id: 1, label: "", durationMs: 600_000, endsAtMs: now + 300_000, pausedRemainingMs: null, rungAtMs: null, createdAtMs: 1 }; + const sooner = { ...running, id: 2, endsAtMs: now + 60_000 }; + const paused = { ...running, id: 3, endsAtMs: null, pausedRemainingMs: 10_000 }; + const rung = { ...running, id: 4, endsAtMs: null, rungAtMs: now - 5000 }; + assert.deepEqual(model.sortTimers([running, paused, rung, sooner], now).map((timer) => timer.id), [4, 2, 1, 3]); +}); + +test("tool arguments: times of day", () => { + assert.deepEqual(model.parseTimeOfDay("7:30"), { hour: 7, minute: 30 }); + assert.deepEqual(model.parseTimeOfDay("7:30 pm"), { hour: 19, minute: 30 }); + assert.deepEqual(model.parseTimeOfDay("12 am"), { hour: 0, minute: 0 }); + assert.deepEqual(model.parseTimeOfDay("12:15PM"), { hour: 12, minute: 15 }); + assert.deepEqual(model.parseTimeOfDay("19:30"), { hour: 19, minute: 30 }); + assert.deepEqual(model.parseTimeOfDay("noon"), { hour: 12, minute: 0 }); + assert.equal(model.parseTimeOfDay("25:00"), null); + assert.equal(model.parseTimeOfDay("13 pm"), null); + assert.equal(model.parseTimeOfDay("soon"), null); +}); + +test("tool arguments: repeat days", () => { + assert.equal(model.parseRepeatDays(undefined), 0); + assert.equal(model.parseRepeatDays(["weekdays"]), model.WEEKDAYS_MASK); + assert.equal(model.parseRepeatDays("every day"), model.EVERY_DAY_MASK); + assert.equal(model.parseRepeatDays(["mon", "Wednesday", "fri"]), model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]); + assert.equal(model.parseRepeatDays(["someday"]), null); +}); + +test("persisted state survives a round trip and shrugs off junk", () => { + const state = model.emptyTimersState(); + state.timers.push(model.createTimer(5 * MINUTE, "tea", 1000)); + state.alarms.push(model.createAlarm(7, 30, model.WEEKDAYS_MASK, "work", 1000)); + state.stopwatch = { accumulatedMs: 1234, runningSinceMs: null, lapsMs: [500, 1000] }; + state.recentDurationsMs = [5 * MINUTE]; + const restored = model.parseTimersState(model.serializeTimersState(state)); + assert.deepEqual(restored, state); + assert.deepEqual(model.parseTimersState("not json"), model.emptyTimersState()); + assert.deepEqual(model.parseTimersState(JSON.stringify({ timers: [{ id: "x" }], alarms: [null] })), model.emptyTimersState()); +}); + +test("recent durations stay short and deduplicated", () => { + assert.deepEqual(model.pushRecentDuration([1, 2, 3], 2), [2, 1, 3]); + assert.deepEqual(model.pushRecentDuration([1, 2, 3], 4), [4, 1, 2]); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index e4afb253..cbc4c641 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -24,6 +24,7 @@ "../app/apps/microphones/dsp.ts", "../app/apps/microphones/radar-dots.ts", "../app/apps/microphones/name-guess.ts", - "../app/apps/evenhub/containers.ts" + "../app/apps/evenhub/containers.ts", + "../app/apps/timer/timer-model.ts" ] }