Merge branch 'master' of http://git.zhenyangtang.com.cn/ZYT/zyt
This commit is contained in:
@@ -37,8 +37,10 @@ from PySide6.QtCore import (
|
||||
QTimer,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QAbstractScrollArea,
|
||||
QGraphicsOpacityEffect,
|
||||
QPlainTextEdit,
|
||||
QStackedWidget,
|
||||
QWidget,
|
||||
)
|
||||
@@ -75,15 +77,35 @@ def reduced_motion() -> bool:
|
||||
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
|
||||
|
||||
|
||||
def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
"""Park an animation on its target so Python does not collect it early."""
|
||||
def _stop(target: QObject, key: str) -> None:
|
||||
"""Retire a replaced animation without firing its completion callback."""
|
||||
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {}
|
||||
previous = running.get(key)
|
||||
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
|
||||
|
||||
|
||||
@@ -107,7 +129,10 @@ def animate(
|
||||
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()
|
||||
@@ -117,18 +142,24 @@ def animate(
|
||||
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)
|
||||
_own(owner if owner is not None else target, key or prop.decode(), animation)
|
||||
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
|
||||
return animation
|
||||
|
||||
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect:
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None:
|
||||
effect = widget.graphicsEffect()
|
||||
if not isinstance(effect, QGraphicsOpacityEffect):
|
||||
# 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
|
||||
|
||||
@@ -146,9 +177,17 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
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 isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect):
|
||||
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
|
||||
@@ -156,6 +195,13 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
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,
|
||||
*,
|
||||
@@ -165,10 +211,20 @@ def fade_in(
|
||||
) -> 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(
|
||||
@@ -193,9 +249,11 @@ def fade_out(
|
||||
) -> 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
|
||||
@@ -208,6 +266,9 @@ def fade_out(
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
|
||||
if effect is None:
|
||||
done()
|
||||
return
|
||||
animate(
|
||||
effect,
|
||||
b"opacity",
|
||||
@@ -229,13 +290,17 @@ def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
|
||||
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():
|
||||
widget.show()
|
||||
_stop(widget, "enter")
|
||||
widget.move(origin)
|
||||
fade_in(widget, duration=duration)
|
||||
return
|
||||
fade_in(widget, duration=duration)
|
||||
if rise:
|
||||
origin = widget.pos()
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
if previous is None:
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
animate(
|
||||
widget,
|
||||
b"pos",
|
||||
@@ -260,7 +325,7 @@ def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None
|
||||
return
|
||||
stack.setCurrentIndex(index)
|
||||
page = stack.currentWidget()
|
||||
if page is None or reduced_motion():
|
||||
if page is None:
|
||||
return
|
||||
enter(page, rise=rise)
|
||||
|
||||
@@ -274,50 +339,121 @@ 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 = QPropertyAnimation(self._bar, b"value", self)
|
||||
self._animation = _ScrollAnimation(self._bar, b"value", self)
|
||||
self._animation.setEasingCurve(EASE_ENTER)
|
||||
self._animation.setDuration(SCROLL_MS)
|
||||
# Keyboard, programmatic and drag movements must not be fought over: when
|
||||
# nothing is animating, the wheel target follows wherever the bar went.
|
||||
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 self._animation.state() != QAbstractAnimation.State.Running:
|
||||
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
|
||||
del watched
|
||||
if event.type() is not QEvent.Type.Wheel or reduced_motion():
|
||||
event_type = event.type()
|
||||
if event_type in self._INTERRUPT_EVENTS:
|
||||
self._cancel()
|
||||
return False
|
||||
delta = event.angleDelta().y() or event.angleDelta().x()
|
||||
if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
||||
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))
|
||||
target = self._target - round(delta / 120.0 * SCROLL_STEP)
|
||||
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 False
|
||||
return target != current
|
||||
self._target = target
|
||||
self._animation.stop()
|
||||
self._animation.setStartValue(self._bar.value())
|
||||
self._animation.setStartValue(current)
|
||||
self._animation.setEndValue(target)
|
||||
self._animation.start()
|
||||
return True
|
||||
@@ -328,7 +464,7 @@ def install_smooth_scroll(
|
||||
*,
|
||||
orientation: Qt.Orientation = Qt.Orientation.Vertical,
|
||||
) -> None:
|
||||
"""Give a scroll area eased wheel scrolling."""
|
||||
"""Ease discrete wheels on pixel-based areas; preserve native gestures."""
|
||||
|
||||
if getattr(area, "_doctor_smooth_scroll", None) is not None:
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user