Files
zyt/app/src/doctor_workstation/ui/motion.py
T

501 lines
17 KiB
Python
Executable File

"""Motion tokens and helpers.
The product had two `QGraphicsOpacityEffect` uses and no `QPropertyAnimation`
at all, so every state change was an instant cut: pages replaced each other
between one frame and the next, drawers appeared fully formed, toasts blinked
in and out. Nothing was slow - it just gave the eye no continuity to follow,
which is what reads as "not smooth" however fast the code underneath is.
Everything here is short. A workstation is used all day, so transitions are
tuned to be felt rather than watched: 110-260 ms, ease-out on entry, and travel
measured in single-digit pixels. Anything longer starts costing the user time.
Qt stylesheets have no `transition` property, so this is `QPropertyAnimation`
throughout. Two rules keep that safe:
* an animation must be owned, or PySide garbage-collects it mid-flight and the
widget freezes half-faded - :func:`_own` parks it on the target;
* a `QGraphicsOpacityEffect` forces the whole widget subtree through an
offscreen render path, which would make a table scroll badly for the rest of
the session - every fade here removes its effect when it finishes.
"""
from __future__ import annotations
import os
from collections.abc import Callable
from typing import Any
from PySide6.QtCore import (
QAbstractAnimation,
QEasingCurve,
QEvent,
QObject,
QPoint,
QPropertyAnimation,
Qt,
QTimer,
)
from PySide6.QtWidgets import (
QAbstractItemView,
QAbstractScrollArea,
QGraphicsOpacityEffect,
QPlainTextEdit,
QStackedWidget,
QWidget,
)
#: Durations in milliseconds.
FAST = 110 # hover-scale feedback, small fades
BASE = 170 # the default: page and panel transitions
SLOW = 260 # large travel, e.g. a drawer crossing the workspace
#: Entering elements decelerate; elements that move between two known places
#: ease in and out; large travel gets a longer tail so it never looks linear.
EASE_ENTER = QEasingCurve.Type.OutCubic
EASE_MOVE = QEasingCurve.Type.InOutCubic
EASE_TRAVEL = QEasingCurve.Type.OutQuint
#: How far an entering surface rises, in device-independent pixels. Kept small
#: on purpose: a page that slides a long way reads as a slideshow, not an app.
RISE = 8
def reduced_motion() -> bool:
"""Whether animation should be skipped entirely.
Off by default under the offscreen platform so widget grabs in tests and in
the packaging smoke checks capture a settled frame rather than a frame from
the middle of a fade. ``DOCTOR_MOTION=on`` / ``off`` overrides either way.
"""
override = os.getenv("DOCTOR_MOTION", "").strip().lower()
if override in {"off", "0", "false", "none", "reduce"}:
return True
if override in {"on", "1", "true", "full"}:
return False
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
def _stop(target: QObject, key: str) -> None:
"""Retire a replaced animation without firing its completion callback."""
running = getattr(target, "_doctor_motion", {})
previous = running.pop(key, None)
if previous is not None:
previous.stop()
previous.setParent(None)
previous.deleteLater()
def _own(target: QObject, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
"""Park an animation on its target so Python does not collect it early."""
_stop(target, key)
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", {})
running[key] = animation
target._doctor_motion = running
def release() -> None:
if running.get(key) is animation:
running.pop(key)
# A callback can hold the last Python reference to the owner. Detach
# first so releasing that callback during deferred deletion cannot
# recursively delete this animation through its former parent.
animation.setParent(None)
animation.deleteLater()
animation.finished.connect(release)
return animation
def animate(
target: Any,
prop: bytes,
start: Any,
end: Any,
*,
duration: int = BASE,
easing: QEasingCurve.Type = EASE_ENTER,
key: str | None = None,
owner: QWidget | None = None,
on_finished: Callable[[], None] | None = None,
) -> QPropertyAnimation | None:
"""Animate one Qt property, or apply the end value outright if motion is off.
``owner`` keeps the animation alive independently of ``target``. Fades
animate a ``QGraphicsOpacityEffect`` that is deleted the moment the fade
ends, so parenting the animation to the effect would destroy the animation
from inside its own ``finished`` emission.
"""
animation_owner = owner if owner is not None else target
animation_key = key or prop.decode()
if reduced_motion():
_stop(animation_owner, animation_key)
target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end)
if on_finished is not None:
on_finished()
return None
animation = QPropertyAnimation(target, prop, owner if owner is not None else target)
animation.setDuration(duration)
animation.setEasingCurve(easing)
animation.setStartValue(start)
animation.setEndValue(end)
_own(animation_owner, animation_key, animation)
if on_finished is not None:
animation.finished.connect(on_finished)
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
return animation
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None:
effect = widget.graphicsEffect()
# Do not replace a caller's shadow or opacity effect: Qt deletes it when
# another effect is attached. Only effects created here belong to a fade.
if effect is not None and effect is not getattr(widget, "_doctor_opacity_effect", None):
return None
if effect is None:
effect = QGraphicsOpacityEffect(widget)
effect.setOpacity(1.0)
widget.setGraphicsEffect(effect)
widget._doctor_opacity_effect = effect
effect.setEnabled(True)
return effect
def _drop_effect(widget: QWidget) -> None:
"""Detach the opacity effect once a fade is done.
Leaving it attached keeps the widget on Qt's offscreen composite path, which
is exactly the sort of quiet, permanent frame-rate tax this module exists to
avoid introducing.
The detach is deferred by one event-loop turn on purpose. ``finished`` is
emitted from inside the animation, and ``setGraphicsEffect(None)`` deletes
the old effect immediately - tearing down the object graph underneath a
signal that is still being delivered.
"""
effect = getattr(widget, "_doctor_opacity_effect", None)
revision = getattr(widget, "_doctor_fade_revision", 0)
def detach() -> None:
try:
if (
effect is not None
and widget.graphicsEffect() is effect
and getattr(widget, "_doctor_fade_revision", 0) == revision
):
widget._doctor_opacity_effect = None
widget.setGraphicsEffect(None)
except RuntimeError: # the widget went away while the fade was running
pass
QTimer.singleShot(0, detach)
def _restart_fade(widget: QWidget) -> None:
_stop(widget, "fade")
# A completed fade may still have deferred cleanup waiting in the queue.
# It must not remove an effect now being used by a subsequent fade.
widget._doctor_fade_revision = getattr(widget, "_doctor_fade_revision", 0) + 1
def fade_in(
widget: QWidget,
*,
duration: int = BASE,
start: float = 0.0,
easing: QEasingCurve.Type = EASE_ENTER,
) -> None:
"""Fade a widget up to full opacity, showing it first if needed."""
existing = widget.graphicsEffect()
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
start = float(existing.opacity())
_restart_fade(widget)
if reduced_motion():
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
existing.setOpacity(1.0)
_drop_effect(widget)
widget.show()
return
effect = _opacity_effect(widget)
if effect is None:
widget.show()
return
effect.setOpacity(start)
widget.show()
animate(
effect,
b"opacity",
start,
1.0,
duration=duration,
easing=easing,
key="fade",
owner=widget,
on_finished=lambda: _drop_effect(widget),
)
def fade_out(
widget: QWidget,
*,
duration: int = FAST,
hide: bool = True,
on_finished: Callable[[], None] | None = None,
) -> None:
"""Fade a widget down, optionally hiding it when the fade completes."""
_restart_fade(widget)
if reduced_motion():
if hide:
widget.hide()
_drop_effect(widget)
if on_finished is not None:
on_finished()
return
effect = _opacity_effect(widget)
def done() -> None:
if hide:
widget.hide()
_drop_effect(widget)
if on_finished is not None:
on_finished()
if effect is None:
done()
return
animate(
effect,
b"opacity",
float(effect.opacity()),
0.0,
duration=duration,
easing=EASE_MOVE,
key="fade",
owner=widget,
on_finished=done,
)
def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
"""Fade a surface in while it settles upward by a few pixels.
The rise is what makes a swap read as one surface replacing another rather
than as a repaint; keeping it under ten pixels stops it becoming a gesture
the user has to wait out.
"""
previous = getattr(widget, "_doctor_motion", {}).get("enter")
origin = previous.endValue() if previous is not None else widget.pos()
if reduced_motion():
_stop(widget, "enter")
widget.move(origin)
fade_in(widget, duration=duration)
return
fade_in(widget, duration=duration)
if rise:
if previous is None:
widget.move(origin + QPoint(0, rise))
animate(
widget,
b"pos",
widget.pos(),
origin,
duration=duration,
easing=EASE_ENTER,
key="enter",
)
def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None:
"""Change the current page of a stack with a short cross-fade.
``QStackedWidget`` swaps pages between two frames with nothing in between,
which is the single most-seen transition in this product - it happens on
every sidebar click and on every list that toggles to its empty state.
"""
if index < 0 or index >= stack.count() or stack.currentIndex() == index:
stack.setCurrentIndex(index)
return
stack.setCurrentIndex(index)
page = stack.currentWidget()
if page is None:
return
enter(page, rise=rise)
# --- Smooth scrolling -----------------------------------------------------
#: One wheel notch travels this far, and takes this long to get there. Qt's
#: default is an instant jump of three lines per notch, which on a long clinical
#: record is the single jerkiest thing in the interface.
SCROLL_STEP = 120
SCROLL_MS = 190
class _ScrollAnimation(QPropertyAnimation):
"""Identify animation writes so direct scrollbar changes can interrupt us."""
writing = False
def updateCurrentValue(self, value: Any) -> None: # noqa: N802 - Qt API
self.writing = True
try:
super().updateCurrentValue(value)
finally:
self.writing = False
class _SmoothScroller(QObject):
"""Animate a scroll area's wheel movement instead of jumping to it."""
_INTERRUPT_EVENTS = frozenset(
{
QEvent.Type.KeyPress,
QEvent.Type.MouseButtonPress,
QEvent.Type.TouchBegin,
QEvent.Type.Hide,
}
)
def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None:
super().__init__(area)
self._area = area
self._orientation = orientation
self._bar = (
area.verticalScrollBar()
if orientation is Qt.Orientation.Vertical
else area.horizontalScrollBar()
)
self._target = self._bar.value()
self._animation = _ScrollAnimation(self._bar, b"value", self)
self._animation.setEasingCurve(EASE_ENTER)
self._animation.setDuration(SCROLL_MS)
self._bar.valueChanged.connect(self._sync_target)
self._bar.sliderPressed.connect(self._cancel)
self._bar.actionTriggered.connect(self._cancel)
self._bar.rangeChanged.connect(self._cancel)
self._bar.installEventFilter(self)
area.installEventFilter(self)
area.viewport().installEventFilter(self)
def _cancel(self, *_: Any) -> None:
self._animation.stop()
self._target = self._bar.value()
def _sync_target(self, value: int) -> None:
if not self._animation.writing:
self._animation.stop()
self._target = value
def _uses_pixels(self) -> bool:
if isinstance(self._area, QAbstractItemView):
mode = (
self._area.verticalScrollMode()
if self._orientation == Qt.Orientation.Vertical
else self._area.horizontalScrollMode()
)
return mode == QAbstractItemView.ScrollMode.ScrollPerPixel
# QPlainTextEdit's vertical scrollbar counts text blocks, not pixels.
return not (
isinstance(self._area, QPlainTextEdit) and self._orientation == Qt.Orientation.Vertical
)
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API
event_type = event.type()
if event_type in self._INTERRUPT_EVENTS:
self._cancel()
return False
if event_type != QEvent.Type.Wheel:
return False
horizontal = self._orientation == Qt.Orientation.Horizontal
shifted = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
delta = event.angleDelta().x() if horizontal else event.angleDelta().y()
if horizontal and shifted and not delta:
delta = event.angleDelta().y()
if (
watched is not self._area.viewport()
or reduced_motion()
or not self._uses_pixels()
or not event.pixelDelta().isNull()
or event.phase() != Qt.ScrollPhase.NoScrollPhase
or event.modifiers()
& (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)
or (shifted and not horizontal)
or not delta
):
# Trackpads already provide continuous motion and native momentum.
# Mixing another easing curve into it adds lag and fights gestures.
self._cancel()
return False
lower, upper = self._bar.minimum(), self._bar.maximum()
# Re-clamp first: the range can shrink underneath a running animation
# when the content behind it reloads, which would otherwise leave the
# pending target past the end of the new content.
self._target = max(lower, min(upper, self._target))
current = self._bar.value()
step = -round(delta / 120.0 * SCROLL_STEP)
# Reverse immediately from the visible position, not the end of a
# backlog of wheel notches still travelling in the opposite direction.
origin = current if (self._target - current) * step < 0 else self._target
target = origin + step
target = max(lower, min(upper, target))
# At either end, hand the wheel back so an enclosing scroll area still
# gets it - swallowing it there is what makes nested panes feel stuck.
if target == self._target:
return target != current
self._target = target
self._animation.stop()
self._animation.setStartValue(current)
self._animation.setEndValue(target)
self._animation.start()
return True
def install_smooth_scroll(
area: QAbstractScrollArea,
*,
orientation: Qt.Orientation = Qt.Orientation.Vertical,
) -> None:
"""Ease discrete wheels on pixel-based areas; preserve native gestures."""
if getattr(area, "_doctor_smooth_scroll", None) is not None:
return
area._doctor_smooth_scroll = _SmoothScroller(area, orientation=orientation)
def press_feedback(widget: QWidget) -> None:
"""Mark a widget so the shared stylesheet can give it a pressed transform.
Qt has no CSS transitions, so the visual step itself lives in the palette's
pressed state; this only tags the widget as one that should get it.
"""
widget.setProperty("motionPress", True)
__all__ = [
"BASE",
"EASE_ENTER",
"EASE_MOVE",
"EASE_TRAVEL",
"FAST",
"RISE",
"SLOW",
"animate",
"enter",
"fade_in",
"fade_out",
"install_smooth_scroll",
"press_feedback",
"reduced_motion",
"switch_stack",
]