"""One shared, display-rate animation clock. Every animated thing (spectrum analysis, cover, wavy bar, lyrics scroll, the floating shape) runs off this single timer so frames stay in lock-step instead of two timers beating against each other. Subscribers receive `dt` in seconds and should animate by time, not by tick count, so jitter never shows as stutter. """ from __future__ import annotations import time from PyQt6.QtCore import Qt, QTimer from PyQt6.QtGui import QGuiApplication class FrameClock: _timer: QTimer | None = None _pre: dict = {} # run first (data producers, e.g. spectrum) _subs: dict = {} # then painters _last = 0.0 dt = 1 / 60 @classmethod def _ensure(cls): if cls._timer is None: cls._timer = QTimer() cls._timer.setTimerType(Qt.TimerType.PreciseTimer) hz = 60.0 try: scr = QGuiApplication.primaryScreen() if scr is not None and scr.refreshRate() > 30: hz = min(scr.refreshRate(), 165.0) except Exception: # noqa: BLE001 pass cls._timer.setInterval(max(5, int(1000 / hz))) cls._timer.timeout.connect(cls._tick) @classmethod def subscribe(cls, fn, pre=False): cls._ensure() (cls._pre if pre else cls._subs)[fn] = True if not cls._timer.isActive(): cls._last = time.monotonic() cls._timer.start() @classmethod def unsubscribe(cls, fn): cls._pre.pop(fn, None) cls._subs.pop(fn, None) if not cls._pre and not cls._subs and cls._timer: cls._timer.stop() @classmethod def is_subscribed(cls, fn) -> bool: return fn in cls._pre or fn in cls._subs @classmethod def _tick(cls): now = time.monotonic() dt = now - cls._last cls._last = now # clamp: after a stall don't jump animations forward cls.dt = dt = max(1 / 240, min(dt, 1 / 20)) for fn in list(cls._pre): fn(dt) for fn in list(cls._subs): fn(dt)