diff --git a/lib/widgets/decorative_phase.dart b/lib/widgets/decorative_phase.dart new file mode 100644 index 000000000..3b975abdf --- /dev/null +++ b/lib/widgets/decorative_phase.dart @@ -0,0 +1,97 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +/// A looping phase in `[0, 1)` for continuous decorative motion, such as +/// equalizer bars and wavy tracks. +/// +/// Every running phase advances from one app-wide clock capped at 30 Hz, so +/// decoration schedules at most 30 frames a second instead of one per +/// display refresh. The clock runs only while a phase is running. Owners +/// stop their phase while paused, under reduced motion, and while a +/// disabled [TickerMode] hides them; a stopped phase holds its value and +/// resumes from it. +class DecorativePhase extends ChangeNotifier + implements ValueListenable { + DecorativePhase(this.loop); + + /// Time for one full cycle from 0 back to 0. + final Duration loop; + + /// Interval between clock ticks: 34 ms keeps the rate at or below 30 Hz. + static const interval = Duration(milliseconds: 34); + + static final _clock = _DecorativeClock(); + + /// Whether the shared clock has a running phase to advance. + @visibleForTesting + static bool get debugClockRunning => _clock.running; + + double _value = 0; + double _startValue = 0; + int? _startTick; + + @override + double get value => _value; + + bool get isRunning => _startTick != null; + + void start() { + if (isRunning) return; + _startValue = _value; + _startTick = _clock.ticks; + _clock.addListener(_tick); + } + + void stop() { + if (!isRunning) return; + _clock.removeListener(_tick); + _startTick = null; + } + + void _tick() { + final elapsed = interval * (_clock.ticks - _startTick!); + _value = (_startValue + elapsed.inMicroseconds / loop.inMicroseconds) % 1; + notifyListeners(); + } + + @override + void dispose() { + stop(); + super.dispose(); + } +} + +class _DecorativeClock extends ChangeNotifier { + Timer? _timer; + int _origin = 0; + int ticks = 0; + + bool get running => _timer != null; + + @override + void addListener(VoidCallback listener) { + super.addListener(listener); + // A late tick reports every interval that passed, so motion keeps its + // speed when the UI isolate is busy. + _timer ??= Timer.periodic(DecorativePhase.interval, (timer) { + ticks = _origin + timer.tick; + notifyListeners(); + _stopWhenIdle(); + }); + } + + @override + void removeListener(VoidCallback listener) { + super.removeListener(listener); + _stopWhenIdle(); + } + + // Listeners removed during a notification only count once it ends. + void _stopWhenIdle() { + if (hasListeners) return; + _timer?.cancel(); + _timer = null; + _origin = ticks; + } +} diff --git a/lib/widgets/expressive_seek_track.dart b/lib/widgets/expressive_seek_track.dart index 37666123d..421b7b272 100644 --- a/lib/widgets/expressive_seek_track.dart +++ b/lib/widgets/expressive_seek_track.dart @@ -1,9 +1,11 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:material_3_expressive/components/sliders/components/m3e_slider_track_painter.dart'; import 'package:material_3_expressive/material_3_expressive.dart'; +import 'package:mornye/widgets/decorative_phase.dart'; /// Expressive track motion around the native slider's seeking and accessibility. class ExpressiveSeekTrack extends StatefulWidget { @@ -21,11 +23,8 @@ class ExpressiveSeekTrack extends StatefulWidget { } class _ExpressiveSeekTrackState extends State - with TickerProviderStateMixin { - late final _phase = AnimationController( - vsync: this, - duration: const Duration(milliseconds: 1800), - ); + with SingleTickerProviderStateMixin { + final _phase = DecorativePhase(const Duration(milliseconds: 1800)); late final _amplitude = AnimationController( vsync: this, @@ -60,7 +59,7 @@ class _ExpressiveSeekTrackState extends State _phase.stop(); _amplitude.value = 0; } else if (widget.playing) { - if (!_phase.isAnimating) _phase.repeat(); + _phase.start(); _amplitude.forward(); } else { _amplitude.reverse(); @@ -93,7 +92,7 @@ class _ExpressiveSeekTrackState extends State } /// A wave tick changes paint only. In particular it must not invalidate the -/// SliderTheme dependency of the native slider on every display frame. +/// SliderTheme dependency of the native slider on every tick. class _AnimatedTrackRepaint extends SingleChildRenderObjectWidget { const _AnimatedTrackRepaint({required this.repaint, required super.child}); @@ -139,12 +138,12 @@ class _RenderAnimatedTrackRepaint extends RenderProxyBox { /// Uses the package's wave renderer without changing the slider gesture cycle. class ExpressiveSeekTrackShape extends RoundedRectSliderTrackShape { const ExpressiveSeekTrackShape({ - required Animation phase, + required ValueListenable phase, required Animation amplitude, }) : _phase = phase, _amplitude = amplitude; - final Animation _phase; + final ValueListenable _phase; final Animation _amplitude; double get phase => _phase.value * 2 * math.pi; diff --git a/lib/widgets/now_playing_indicator.dart b/lib/widgets/now_playing_indicator.dart index 00aad81e2..b64f0a043 100644 --- a/lib/widgets/now_playing_indicator.dart +++ b/lib/widgets/now_playing_indicator.dart @@ -1,11 +1,13 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:mornye/widgets/decorative_phase.dart'; /// Three equalizer bars that mark the current track in a list. /// /// The bars move while [playing] and freeze where they are once playback -/// pauses. Reduced motion keeps them still, and the ticker stops while a +/// pauses. Reduced motion keeps them still, and the motion stops while a /// disabled [TickerMode] hides the glyph, such as on a covered route. /// /// The glyph is decorative: the row it sits in carries the label, so it @@ -32,12 +34,8 @@ class NowPlayingIndicator extends StatefulWidget { State createState() => _NowPlayingIndicatorState(); } -class _NowPlayingIndicatorState extends State - with SingleTickerProviderStateMixin { - late final _controller = AnimationController( - vsync: this, - duration: const Duration(milliseconds: 2400), - ); +class _NowPlayingIndicatorState extends State { + final _phase = DecorativePhase(const Duration(milliseconds: 2400)); bool _motionEnabled = false; @override @@ -57,15 +55,15 @@ class _NowPlayingIndicatorState extends State void _syncAnimation() { if (_motionEnabled && widget.playing) { - if (!_controller.isAnimating) _controller.repeat(); + _phase.start(); } else { - _controller.stop(); + _phase.stop(); } } @override void dispose() { - _controller.dispose(); + _phase.dispose(); super.dispose(); } @@ -77,7 +75,7 @@ class _NowPlayingIndicatorState extends State child: RepaintBoundary( child: CustomPaint( size: Size.square(widget.size), - painter: _EqualizerPainter(progress: _controller, color: color), + painter: _EqualizerPainter(progress: _phase, color: color), ), ), ); @@ -88,7 +86,7 @@ class _EqualizerPainter extends CustomPainter { _EqualizerPainter({required this.progress, required this.color}) : super(repaint: progress); - final Animation progress; + final ValueListenable progress; final Color color; /// Two waves per bar, each a whole number of cycles per loop so the loop diff --git a/test/decorative_phase_test.dart b/test/decorative_phase_test.dart new file mode 100644 index 000000000..399936088 --- /dev/null +++ b/test/decorative_phase_test.dart @@ -0,0 +1,175 @@ +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart' show RenderRepaintBoundary; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mornye/widgets/decorative_phase.dart'; +import 'package:mornye/widgets/expressive_seek_track.dart'; +import 'package:mornye/widgets/now_playing_indicator.dart'; + +const _vsync = Duration(microseconds: 8333); + +/// Steps one second of 120 Hz display refreshes and counts those a frame was +/// requested for. +Future _framesInOneSecond(WidgetTester tester) async { + var frames = 0; + for (var vsync = 0; vsync < 120; vsync++) { + await tester.binding.delayed(_vsync); + if (tester.binding.hasScheduledFrame) frames++; + await tester.pump(); + } + return frames; +} + +Future> _pixels(WidgetTester tester, Finder finder) async { + final boundary = tester.renderObject( + find.descendant(of: finder, matching: find.byType(RepaintBoundary)).first, + ); + return (await tester.runAsync(() async { + final image = await boundary.toImage(); + try { + return (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!.buffer.asUint8List().toList(growable: false); + } finally { + image.dispose(); + } + }))!; +} + +Widget _host(Widget child, {bool reduceMotion = false, bool visible = true}) => + MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: TickerMode( + enabled: visible, + child: Scaffold(body: Center(child: child)), + ), + ), + ); + +void main() { + group('DecorativePhase', () { + testWidgets('advances at most 30 times a second at loop speed', ( + tester, + ) async { + final phase = DecorativePhase(const Duration(seconds: 2)); + addTearDown(phase.dispose); + var notifications = 0; + phase + ..addListener(() => notifications++) + ..start(); + expect(DecorativePhase.debugClockRunning, isTrue); + + await tester.binding.delayed(const Duration(seconds: 1)); + expect(notifications, inInclusiveRange(29, 30)); + // Each tick advances by the time that passed, so one second of a + // two second loop is half a cycle. + expect(phase.value, closeTo(0.5, 34 / 2000)); + + phase.stop(); + expect(DecorativePhase.debugClockRunning, isFalse); + final held = phase.value; + await tester.binding.delayed(const Duration(seconds: 1)); + expect(notifications, inInclusiveRange(29, 30)); + expect(phase.value, held); + + phase.start(); + await tester.binding.delayed(DecorativePhase.interval); + expect(phase.value, closeTo(held + 34 / 2000, 1e-9)); + phase.stop(); + }); + + testWidgets('shares one clock that runs while any phase runs', ( + tester, + ) async { + final first = DecorativePhase(const Duration(seconds: 1)); + final second = DecorativePhase(const Duration(seconds: 3)); + addTearDown(first.dispose); + addTearDown(second.dispose); + first.start(); + second.start(); + await tester.binding.delayed(const Duration(milliseconds: 340)); + expect(first.value, closeTo(0.34, 1e-9)); + expect(second.value, closeTo(0.34 / 3, 1e-9)); + + first.stop(); + expect(DecorativePhase.debugClockRunning, isTrue); + await tester.binding.delayed(const Duration(milliseconds: 340)); + expect(first.value, closeTo(0.34, 1e-9)); + expect(second.value, closeTo(0.68 / 3, 1e-9)); + + second.stop(); + expect(DecorativePhase.debugClockRunning, isFalse); + }); + }); + + group('NowPlayingIndicator', () { + testWidgets('moves at no more than 30 frames a second while playing', ( + tester, + ) async { + await tester.pumpWidget(_host(const NowPlayingIndicator(playing: true))); + final indicator = find.byType(NowPlayingIndicator); + final before = await _pixels(tester, indicator); + expect(await _framesInOneSecond(tester), inInclusiveRange(29, 30)); + await tester.binding.delayed(const Duration(milliseconds: 300)); + await tester.pump(); + expect(await _pixels(tester, indicator), isNot(orderedEquals(before))); + }); + + testWidgets('requests no frames while paused, hidden or reduced', ( + tester, + ) async { + for (final host in [ + _host(const NowPlayingIndicator(playing: false)), + _host(const NowPlayingIndicator(playing: true), visible: false), + _host(const NowPlayingIndicator(playing: true), reduceMotion: true), + ]) { + await tester.pumpWidget( + _host(const NowPlayingIndicator(playing: true)), + ); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pumpWidget(host); + await tester.pump(); + expect(DecorativePhase.debugClockRunning, isFalse); + expect(await _framesInOneSecond(tester), 0); + } + }); + }); + + group('ExpressiveSeekTrack', () { + Widget track({bool playing = true}) => ExpressiveSeekTrack( + playing: playing, + child: Slider(value: 0.5, onChanged: (_) {}), + ); + + testWidgets('waves at no more than 30 frames a second while playing', ( + tester, + ) async { + await tester.pumpWidget(_host(track())); + // Let the amplitude rise, which animates at the display rate. + await tester.pump(const Duration(milliseconds: 400)); + final wave = find.byType(ExpressiveSeekTrack); + final before = await _pixels(tester, wave); + expect(await _framesInOneSecond(tester), inInclusiveRange(29, 30)); + expect(await _pixels(tester, wave), isNot(orderedEquals(before))); + }); + + testWidgets('requests no frames once paused, hidden or reduced', ( + tester, + ) async { + for (final host in [ + _host(track(playing: false)), + _host(track(), visible: false), + _host(track(), reduceMotion: true), + ]) { + await tester.pumpWidget(_host(track())); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pumpWidget(host); + await tester.pumpAndSettle(); + expect(DecorativePhase.debugClockRunning, isFalse); + expect(await _framesInOneSecond(tester), 0); + } + }); + }); +}