import 'dart:async'; import 'package:flutter/widgets.dart'; /// One clock shared by every live elapsed-time label (a running run's or /// stage's duration). /// /// It runs a single timer, only while some label watches a start instant and /// the app is visible, and wakes when the soonest watched duration next /// changes its displayed text: every second under an hour (`3m 5s`), on the /// minute under a day (`1h 2m`) and on the hour after that (`2d 3h`). Labels /// rebuild themselves on a tick; nothing else in the tree does. class ElapsedClock with WidgetsBindingObserver { /// [now] reads the time; tests pass a fake clock. ElapsedClock({DateTime Function()? now}) : _read = now ?? DateTime.now; /// The clock the app's labels share. static final ElapsedClock shared = ElapsedClock(); final DateTime Function() _read; final Map _watchers = {}; Timer? _timer; bool _observing = false; bool _hidden = false; /// The boundary the last tick was due at. The next tick is scheduled from /// it when the wall clock lags the timer (a test's fake timers), so a tick /// always moves on to the next boundary rather than re-arming for the same /// one. DateTime? _reached; DateTime get now => _read(); /// Whether a tick is scheduled (a label watches and the app is visible). @visibleForTesting bool get ticking => _timer != null; /// Calls [onTick] whenever a duration measured from [since] may have /// changed its text, until [unwatch] with the same [key]. void watch(Object key, DateTime since, VoidCallback onTick) { _watchers[key] = (since: since, onTick: onTick); if (!_observing) { _hidden = switch (WidgetsBinding.instance.lifecycleState) { AppLifecycleState.hidden || AppLifecycleState.paused || AppLifecycleState.detached => true, _ => false, }; WidgetsBinding.instance.addObserver(this); _observing = true; } _schedule(); } void unwatch(Object key) { if (_watchers.remove(key) == null) return; if (_watchers.isNotEmpty) { _schedule(); return; } _stop(); _reached = null; if (_observing) { WidgetsBinding.instance.removeObserver(this); _observing = false; } } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { _hidden = false; _notify(); _schedule(); } else if (state == AppLifecycleState.hidden || // Not inactive: a desktop window that lost focus is still visible. state == AppLifecycleState.paused || state == AppLifecycleState.detached) { _hidden = true; _stop(); } } void _schedule() { _stop(); if (_hidden || _watchers.isEmpty) return; final wall = _read(); final reached = _reached; final from = reached != null && reached.isAfter(wall) ? reached : wall; Duration? delay; for (final watcher in _watchers.values) { final next = elapsedTextChangesIn(from.difference(watcher.since)); if (delay == null || next < delay) delay = next; } final due = from.add(delay!); _timer = Timer(delay, () { _timer = null; _reached = due; _notify(); _schedule(); }); } void _notify() { for (final watcher in [..._watchers.values]) { watcher.onTick(); } } void _stop() { _timer?.cancel(); _timer = null; } } /// How long until an elapsed duration shown at `formatDuration` precision /// (seconds under an hour, minutes under a day, then hours) shows new text. /// A negative elapsed (clock skew) reads `0s` until it reaches one second. @visibleForTesting Duration elapsedTextChangesIn(Duration elapsed) { if (elapsed.isNegative) return -elapsed + const Duration(seconds: 1); final unit = elapsed < const Duration(hours: 1) ? const Duration(seconds: 1) : elapsed < const Duration(days: 1) ? const Duration(minutes: 1) : const Duration(hours: 1); final into = elapsed.inMicroseconds % unit.inMicroseconds; return Duration(microseconds: unit.inMicroseconds - into); } /// Supplies the [ElapsedClock] below it; [ElapsedClock.shared] without one. class ElapsedClockScope extends InheritedWidget { const ElapsedClockScope({ super.key, required this.clock, required super.child, }); final ElapsedClock clock; static ElapsedClock of(BuildContext context) => context.dependOnInheritedWidgetOfExactType()?.clock ?? ElapsedClock.shared; @override bool updateShouldNotify(ElapsedClockScope oldWidget) => clock != oldWidget.clock; }