import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:shared_preferences/shared_preferences.dart'; const animationSpeedKey = 'pipelines.animation-speed.v1'; const minAnimationSpeed = 0.5; const maxAnimationSpeed = 2.0; abstract interface class AnimationSpeedStore { Future load(); Future save(double speed); } class SharedAnimationSpeedStore implements AnimationSpeedStore { const SharedAnimationSpeedStore(); @override Future load() async { try { return (await SharedPreferences.getInstance()).getDouble( animationSpeedKey, ); } catch (_) { return null; } } @override Future save(double speed) async { try { return await (await SharedPreferences.getInstance()).setDouble( animationSpeedKey, speed, ); } catch (_) { return false; } } } /// A device-local animation clock. Larger factors play animations faster. /// /// Flutter divides scheduler frame timestamps by timeDilation, including /// native routes, implicit animations and physics. Its setter resets the epoch /// to preserve continuity for in-flight animations. Values below one are valid. /// Durations in Motion must NOT also be scaled. Real timers, networking and /// retry delays keep wall-clock time; existing reduced-motion handling remains. class AnimationSpeedController extends ChangeNotifier { AnimationSpeedController({AnimationSpeedStore? store}) : _store = store ?? const SharedAnimationSpeedStore(); static final instance = AnimationSpeedController(); final AnimationSpeedStore _store; double _speed = 1; int _revision = 0; bool _disposed = false; bool saveFailed = false; double get speed => _speed; Future restore() async { final revision = _revision; final value = await _store.load(); if (_disposed || revision != _revision || value == null || !value.isFinite) { return; } setSpeed(value); } void setSpeed(double value) { if (_disposed || !value.isFinite) return; _revision++; _speed = value.clamp(minAnimationSpeed, maxAnimationSpeed); saveFailed = false; timeDilation = 1 / _speed; notifyListeners(); } Future save() async { final revision = _revision; final saved = await _store.save(_speed); if (_disposed || revision != _revision) return; saveFailed = !saved; notifyListeners(); } Future reset() async { setSpeed(1); await save(); } @override void dispose() { _disposed = true; super.dispose(); } }