File size: 2,281 Bytes
2c3c408 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | from __future__ import annotations
from typing import TYPE_CHECKING
from .scalar import ScalarOffset
from .._animator import Animation
from .._animator import EasingFunction
from .._types import CallbackType
from ..geometry import Offset
if TYPE_CHECKING:
from ..widget import Widget
from .styles import Styles
class ScalarAnimation(Animation):
def __init__(
self,
widget: Widget,
styles: Styles,
start_time: float,
attribute: str,
value: ScalarOffset,
duration: float | None,
speed: float | None,
easing: EasingFunction,
on_complete: CallbackType | None = None,
):
assert (
speed is not None or duration is not None
), "One of speed or duration required"
self.widget = widget
self.styles = styles
self.start_time = start_time
self.attribute = attribute
self.final_value = value
self.easing = easing
self.on_complete = on_complete
size = widget.outer_size
viewport = widget.app.size
self.start: Offset = getattr(styles, attribute).resolve(size, viewport)
self.destination: Offset = value.resolve(size, viewport)
if speed is not None:
distance = self.start.get_distance_to(self.destination)
self.duration = distance / speed
else:
assert duration is not None, "Duration expected to be non-None"
self.duration = duration
def __call__(self, time: float) -> bool:
factor = min(1.0, (time - self.start_time) / self.duration)
eased_factor = self.easing(factor)
if eased_factor >= 1:
setattr(self.styles, self.attribute, self.final_value)
return True
offset = self.start + (self.destination - self.start) * eased_factor
current = self.styles._rules[self.attribute]
if current != offset:
setattr(self.styles, f"{self.attribute}", offset)
return False
def __eq__(self, other: object) -> bool:
if isinstance(other, ScalarAnimation):
return (
self.final_value == other.final_value
and self.duration == other.duration
)
return False
|