use std::any::Any;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;
use waft_animation::{
AnimationBehavior, AnimationController, AnimationLocalStatusListenersMixin, AnimationRef,
AnimationStatus, AnimationStatusListener, AnyAnimation, CurvedAnimation, Curves,
};
use waft_embedder::{
Canvas, Color, FillRule, Matrix4, Offset, Paint, PaintStyle, PathBuilder, PointerDeviceKind,
RRect, Radius, Rect, Size, Stroke, TargetPlatform, TextDirection, clamp_double,
};
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, Listenable, Listener, Timer,
};
use waft_foundation::{OptionRetained, PRECISION_ERROR_TOLERANCE};
use waft_gestures::DragDirection;
use waft_gestures::{
BaseTapData, BaseTapGestureRecognizer, BaseTapLeaf, BaseTapLeafData, DeviceGestureSettings,
Drag, DragData, DragDownDetails, DragEndDetails, DragGestureRecognizer, DragLeaf, DragLeafData,
DragStartBehavior, DragStartDetails, DragUpdateDetails, GestureBinding, GestureDisposition,
GestureRecognizer, GestureRecognizerData, GestureTapDownCallback,
HorizontalDragGestureRecognizerBase, K_PRESS_TIMEOUT, K_PRIMARY_BUTTON, OneSequenceData,
OneSequenceLeafData, PointerCancelEvent, PointerDownEvent, PointerEvent, PointerHoverEvent,
PointerPanZoomStartEvent, PointerScrollEvent, PointerUpEvent, PrimaryPointerData,
PrimaryPointerGestureRecognizer, PrimaryPointerLeaf, PrimaryPointerLeafData, RecognizerLeaf,
RecognizerLeafData, TapDownDetails, UNSET_TOUCH_SLOP, Velocity, VelocityEstimate,
VerticalDragGestureRecognizerBase,
};
use waft_painting::{
Axis, AxisDirection, EdgeInsets, EdgeInsetsGeometry, OutlinedBorderRef,
axis_direction_is_reversed, axis_direction_to_axis, draw_rrect,
};
use waft_rendering::{AnyRenderBox, CustomPainter};
use crate::framework::{
BuildContext, BuildOwner, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget,
WidgetRef, downcast_widget,
};
use crate::view::View;
use crate::widgets::basic::{
CustomPaint, Listener as PointerListener, MouseRegion, RepaintBoundary,
};
use crate::widgets::gesture_detector::{
GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
RawGestureDetector,
};
use crate::widgets::media_query::MediaQuery;
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::primary_scroll_controller::PrimaryScrollController;
use crate::widgets::scroll_activity::ScrollHoldController;
use crate::widgets::scroll_configuration::ScrollConfiguration;
use crate::widgets::scroll_controller::ScrollControllerRef;
use crate::widgets::scroll_metrics::ScrollMetrics;
use crate::widgets::scroll_notification::{
OverscrollNotification, ScrollEndNotification, ScrollNotification, ScrollNotificationPredicate,
ScrollUpdateNotification, default_scroll_notification_predicate,
};
use crate::widgets::scroll_position::ScrollMetricsNotification;
use crate::widgets::scrollable::Scrollable;
use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
use waft_foundation::Ref;
use waft_scheduler::{
FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
};
const K_MIN_THUMB_EXTENT: f64 = 18.0;
const K_MIN_INTERACTIVE_SIZE: f64 = 48.0;
const K_SCROLLBAR_THICKNESS: f64 = 6.0;
const K_SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(300);
const K_SCROLLBAR_TIME_TO_FADE: Duration = Duration::from_millis(600);
const K_DEFAULT_THUMB_COLOR: Color = Color::from_argb(0x66, 0xBC, 0xBC, 0xBC);
const K_DEFAULT_TRACK_COLOR: Color = Color::from_argb(0x08, 0x00, 0x00, 0x00);
const K_DEFAULT_TRACK_BORDER_COLOR: Color = Color::from_argb(0x1a, 0x00, 0x00, 0x00);
const K_TRANSPARENT: Color = Color::from_argb(0, 0, 0, 0);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ScrollbarOrientation {
Left,
Right,
Top,
Bottom,
}
impl ScrollbarOrientation {
fn is_vertical(self) -> bool {
matches!(
self,
ScrollbarOrientation::Left | ScrollbarOrientation::Right
)
}
}
pub struct ScrollbarPainter {
change_notifier: ChangeNotifierData,
color: Color,
track_color: Color,
track_border_color: Color,
track_radius: Option<Radius>,
text_direction: Option<TextDirection>,
thickness: f64,
fadeout_opacity_animation: AnimationRef<f64>,
main_axis_margin: f64,
cross_axis_margin: f64,
radius: Option<Radius>,
shape: Option<OutlinedBorderRef>,
padding: EdgeInsetsGeometry,
min_length: f64,
min_overscroll_length: f64,
scrollbar_orientation: Option<ScrollbarOrientation>,
ignore_pointer: bool,
track_rect: Option<Rect>,
resolved_padding: Option<EdgeInsets>,
thumb_rect: Option<Rect>,
thumb_offset: f64,
thumb_extent: f64,
last_metrics: Option<Rc<dyn ScrollMetrics>>,
last_axis_direction: Option<AxisDirection>,
}
impl ScrollbarPainter {
pub fn new(
app: &mut App,
color: Color,
fadeout_opacity_animation: AnimationRef<f64>,
) -> Ref<ScrollbarPainter> {
let this = app.create(ScrollbarPainter {
change_notifier: ChangeNotifierData::new(),
color,
track_color: K_TRANSPARENT,
track_border_color: K_TRANSPARENT,
track_radius: None,
text_direction: None,
thickness: K_SCROLLBAR_THICKNESS,
fadeout_opacity_animation: fadeout_opacity_animation.clone(),
main_axis_margin: 0.0,
cross_axis_margin: 0.0,
radius: None,
shape: None,
padding: EdgeInsetsGeometry::ZERO,
min_length: K_MIN_THUMB_EXTENT,
min_overscroll_length: K_MIN_THUMB_EXTENT,
scrollbar_orientation: None,
ignore_pointer: false,
track_rect: None,
resolved_padding: Some(EdgeInsets::ZERO),
thumb_rect: None,
thumb_offset: 0.0,
thumb_extent: 0.0,
last_metrics: None,
last_axis_direction: None,
});
fadeout_opacity_animation.add_listener(
app,
Listener::handle_method(this.handle(), Handle::<ScrollbarPainter>::notify_listeners),
);
this
}
pub fn color(self: Handle<Self>, app: &App) -> Color {
app.get(self).color
}
pub fn set_color(self: Handle<Self>, app: &mut App, value: Color) {
if self.color(app) == value {
return;
}
app.get_mut(self).color = value;
self.notify_listeners(app);
}
pub fn track_color(self: Handle<Self>, app: &App) -> Color {
app.get(self).track_color
}
pub fn set_track_color(self: Handle<Self>, app: &mut App, value: Color) {
if self.track_color(app) == value {
return;
}
app.get_mut(self).track_color = value;
self.notify_listeners(app);
}
pub fn track_border_color(self: Handle<Self>, app: &App) -> Color {
app.get(self).track_border_color
}
pub fn set_track_border_color(self: Handle<Self>, app: &mut App, value: Color) {
if self.track_border_color(app) == value {
return;
}
app.get_mut(self).track_border_color = value;
self.notify_listeners(app);
}
pub fn track_radius(self: Handle<Self>, app: &App) -> Option<Radius> {
app.get(self).track_radius
}
pub fn set_track_radius(self: Handle<Self>, app: &mut App, value: Option<Radius>) {
if self.track_radius(app) == value {
return;
}
app.get_mut(self).track_radius = value;
self.notify_listeners(app);
}
pub fn text_direction(self: Handle<Self>, app: &App) -> Option<TextDirection> {
app.get(self).text_direction
}
pub fn set_text_direction(self: Handle<Self>, app: &mut App, value: Option<TextDirection>) {
debug_assert!(value.is_some());
if self.text_direction(app) == value {
return;
}
let painter = app.get_mut(self);
painter.text_direction = value;
painter.resolved_padding = Some(painter.padding.resolve(value));
self.notify_listeners(app);
}
pub fn thickness(self: Handle<Self>, app: &App) -> f64 {
app.get(self).thickness
}
pub fn set_thickness(self: Handle<Self>, app: &mut App, value: f64) {
if self.thickness(app) == value {
return;
}
app.get_mut(self).thickness = value;
self.notify_listeners(app);
}
pub fn fadeout_opacity_animation(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
app.get(self).fadeout_opacity_animation.handle()
}
pub fn main_axis_margin(self: Handle<Self>, app: &App) -> f64 {
app.get(self).main_axis_margin
}
pub fn set_main_axis_margin(self: Handle<Self>, app: &mut App, value: f64) {
if self.main_axis_margin(app) == value {
return;
}
app.get_mut(self).main_axis_margin = value;
self.notify_listeners(app);
}
pub fn cross_axis_margin(self: Handle<Self>, app: &App) -> f64 {
app.get(self).cross_axis_margin
}
pub fn set_cross_axis_margin(self: Handle<Self>, app: &mut App, value: f64) {
if self.cross_axis_margin(app) == value {
return;
}
app.get_mut(self).cross_axis_margin = value;
self.notify_listeners(app);
}
pub fn radius(self: Handle<Self>, app: &App) -> Option<Radius> {
app.get(self).radius
}
pub fn set_radius(self: Handle<Self>, app: &mut App, value: Option<Radius>) {
debug_assert!(app.get(self).shape.is_none() || value.is_none());
if self.radius(app) == value {
return;
}
app.get_mut(self).radius = value;
self.notify_listeners(app);
}
pub fn shape(self: Handle<Self>, app: &App) -> Option<OutlinedBorderRef> {
app.get(self).shape.clone()
}
pub fn set_shape(self: Handle<Self>, app: &mut App, value: Option<OutlinedBorderRef>) {
debug_assert!(app.get(self).radius.is_none() || value.is_none());
if app.get(self).shape == value {
return;
}
app.get_mut(self).shape = value;
self.notify_listeners(app);
}
pub fn padding(self: Handle<Self>, app: &App) -> EdgeInsetsGeometry {
app.get(self).padding
}
pub fn set_padding(self: Handle<Self>, app: &mut App, value: EdgeInsetsGeometry) {
if self.padding(app) == value {
return;
}
let painter = app.get_mut(self);
painter.padding = value;
let text_direction = painter.text_direction;
painter.resolved_padding = Some(painter.padding.resolve(text_direction));
self.notify_listeners(app);
}
pub fn min_length(self: Handle<Self>, app: &App) -> f64 {
app.get(self).min_length
}
pub fn set_min_length(self: Handle<Self>, app: &mut App, value: f64) {
if self.min_length(app) == value {
return;
}
app.get_mut(self).min_length = value;
self.notify_listeners(app);
}
pub fn min_overscroll_length(self: Handle<Self>, app: &App) -> f64 {
app.get(self).min_overscroll_length
}
pub fn set_min_overscroll_length(self: Handle<Self>, app: &mut App, value: f64) {
if self.min_overscroll_length(app) == value {
return;
}
app.get_mut(self).min_overscroll_length = value;
self.notify_listeners(app);
}
pub fn scrollbar_orientation(self: Handle<Self>, app: &App) -> Option<ScrollbarOrientation> {
app.get(self).scrollbar_orientation
}
pub fn set_scrollbar_orientation(
self: Handle<Self>,
app: &mut App,
value: Option<ScrollbarOrientation>,
) {
if self.scrollbar_orientation(app) == value {
return;
}
app.get_mut(self).scrollbar_orientation = value;
self.notify_listeners(app);
}
pub fn ignore_pointer(self: Handle<Self>, app: &App) -> bool {
app.get(self).ignore_pointer
}
pub fn set_ignore_pointer(self: Handle<Self>, app: &mut App, value: bool) {
if self.ignore_pointer(app) == value {
return;
}
app.get_mut(self).ignore_pointer = value;
self.notify_listeners(app);
}
fn track_extent(self: Handle<Self>, app: &App) -> f64 {
self.metrics(app).viewport_dimension() - self.total_track_main_axis_offsets(app)
}
fn traversable_track_extent(self: Handle<Self>, app: &App) -> f64 {
self.track_extent(app) - (2.0 * self.main_axis_margin(app))
}
fn total_track_main_axis_offsets(self: Handle<Self>, app: &App) -> f64 {
let padding = self.resolved_padding(app);
if self.is_vertical(app) {
padding.vertical()
} else {
padding.horizontal()
}
}
fn leading_track_main_axis_offset(self: Handle<Self>, app: &App) -> f64 {
let padding = self.resolved_padding(app);
match self.resolved_orientation(app) {
ScrollbarOrientation::Left | ScrollbarOrientation::Right => padding.top,
ScrollbarOrientation::Top | ScrollbarOrientation::Bottom => padding.left,
}
}
fn leading_thumb_main_axis_offset(self: Handle<Self>, app: &App) -> f64 {
self.leading_track_main_axis_offset(app) + self.main_axis_margin(app)
}
fn resolved_padding(self: Handle<Self>, app: &App) -> EdgeInsets {
app.get(self)
.resolved_padding
.expect("the padding resolves when it or the text direction is set")
}
fn metrics(self: Handle<Self>, app: &App) -> Rc<dyn ScrollMetrics> {
app.get(self)
.last_metrics
.clone()
.expect("update() supplies the metrics before the painter reads them")
}
fn set_thumb_extent(self: Handle<Self>, app: &mut App) {
let metrics = self.metrics(app);
let total_track_main_axis_offsets = self.total_track_main_axis_offsets(app);
let fraction_visible = clamp_double(
(metrics.extent_inside() - total_track_main_axis_offsets)
/ (self.total_content_extent(app) - total_track_main_axis_offsets),
0.0,
1.0,
);
let traversable_track_extent = self.traversable_track_extent(app);
let thumb_extent = traversable_track_extent
.min(self.min_overscroll_length(app))
.max(traversable_track_extent * fraction_visible);
let fraction_overscrolled = 1.0 - metrics.extent_inside() / metrics.viewport_dimension();
let safe_min_length = self.min_length(app).min(traversable_track_extent);
let new_min_length = if self.before_extent(app) > 0.0 && self.after_extent(app) > 0.0 {
safe_min_length
} else {
safe_min_length * (1.0 - clamp_double(fraction_overscrolled, 0.0, 0.2) / 0.2)
};
app.get_mut(self).thumb_extent =
clamp_double(thumb_extent, new_min_length, traversable_track_extent);
}
fn last_metrics_are_scrollable(self: Handle<Self>, app: &App) -> bool {
let metrics = self.metrics(app);
metrics.min_scroll_extent() != metrics.max_scroll_extent()
}
fn is_vertical(self: Handle<Self>, app: &App) -> bool {
matches!(
app.get(self).last_axis_direction,
Some(AxisDirection::Down) | Some(AxisDirection::Up)
)
}
fn is_reversed(self: Handle<Self>, app: &App) -> bool {
matches!(
app.get(self).last_axis_direction,
Some(AxisDirection::Up) | Some(AxisDirection::Left)
)
}
fn before_extent(self: Handle<Self>, app: &App) -> f64 {
let metrics = self.metrics(app);
if self.is_reversed(app) {
metrics.extent_after()
} else {
metrics.extent_before()
}
}
fn after_extent(self: Handle<Self>, app: &App) -> f64 {
let metrics = self.metrics(app);
if self.is_reversed(app) {
metrics.extent_before()
} else {
metrics.extent_after()
}
}
fn total_content_extent(self: Handle<Self>, app: &App) -> f64 {
let metrics = self.metrics(app);
metrics.max_scroll_extent() - metrics.min_scroll_extent() + metrics.viewport_dimension()
}
fn resolved_orientation(self: Handle<Self>, app: &App) -> ScrollbarOrientation {
match self.scrollbar_orientation(app) {
Some(orientation) => orientation,
None => {
if self.is_vertical(app) {
if self.text_direction(app) == Some(TextDirection::Ltr) {
ScrollbarOrientation::Right
} else {
ScrollbarOrientation::Left
}
} else {
ScrollbarOrientation::Bottom
}
}
}
}
fn debug_assert_is_valid_orientation(
self: Handle<Self>,
app: &App,
orientation: ScrollbarOrientation,
) {
debug_assert!(
self.is_vertical(app) == orientation.is_vertical(),
"The given ScrollbarOrientation: {orientation:?} is incompatible with the current \
AxisDirection: {:?}.",
app.get(self).last_axis_direction
);
}
pub fn update(
self: Handle<Self>,
app: &mut App,
metrics: Rc<dyn ScrollMetrics>,
axis_direction: AxisDirection,
) {
if let Some(last) = app.get(self).last_metrics.clone()
&& last.extent_before() == metrics.extent_before()
&& last.extent_inside() == metrics.extent_inside()
&& last.extent_after() == metrics.extent_after()
&& app.get(self).last_axis_direction == Some(axis_direction)
{
return;
}
let old_metrics = app.get(self).last_metrics.clone();
let painter = app.get_mut(self);
painter.last_metrics = Some(metrics.clone());
painter.last_axis_direction = Some(axis_direction);
if !need_paint(old_metrics.as_deref()) && !need_paint(Some(&*metrics)) {
return;
}
self.notify_listeners(app);
}
pub fn update_thickness(
self: Handle<Self>,
app: &mut App,
next_thickness: f64,
next_radius: Radius,
) {
self.set_thickness(app, next_thickness);
self.set_radius(app, Some(next_radius));
}
fn paint_thumb(self: Handle<Self>, app: &App) -> Paint {
let color = self.color(app);
let opacity = self.fadeout_opacity_animation(app).value(app);
Paint {
color: color
.with_values(Some(color.a * opacity), None, None, None, None)
.into(),
..Paint::default()
}
}
fn paint_track(self: Handle<Self>, app: &App, is_border: bool) -> Paint {
let opacity = self.fadeout_opacity_animation(app).value(app);
if is_border {
let color = self.track_border_color(app);
return Paint {
color: color
.with_values(Some(color.a * opacity), None, None, None, None)
.into(),
style: PaintStyle::Stroke(Stroke::new(1.0)),
..Paint::default()
};
}
let color = self.track_color(app);
Paint {
color: color
.with_values(Some(color.a * opacity), None, None, None, None)
.into(),
..Paint::default()
}
}
fn paint_scrollbar(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
debug_assert!(
self.text_direction(app).is_some(),
"A TextDirection must be provided before a Scrollbar can be painted."
);
let orientation = self.resolved_orientation(app);
self.debug_assert_is_valid_orientation(app, orientation);
let thickness = self.thickness(app);
let cross_axis_margin = self.cross_axis_margin(app);
let padding = self.resolved_padding(app);
let track_extent = self.track_extent(app);
let thumb_extent = app.get(self).thumb_extent;
let thumb_offset = app.get(self).thumb_offset;
let leading_track_main_axis_offset = self.leading_track_main_axis_offset(app);
let (x, y, thumb_size, track_size, track_offset, border_start, border_end) =
match orientation {
ScrollbarOrientation::Left => {
let thumb_size = Size::new(thickness, thumb_extent);
let track_size = Size::new(thickness + 2.0 * cross_axis_margin, track_extent);
let x = cross_axis_margin + padding.left;
let y = thumb_offset;
let track_offset =
Offset::new(x - cross_axis_margin, leading_track_main_axis_offset);
let border_start = track_offset + Offset::new(track_size.width(), 0.0);
let border_end = Offset::new(
track_offset.dx() + track_size.width(),
track_offset.dy() + track_extent,
);
(
x,
y,
thumb_size,
track_size,
track_offset,
border_start,
border_end,
)
}
ScrollbarOrientation::Right => {
let thumb_size = Size::new(thickness, thumb_extent);
let track_size = Size::new(thickness + 2.0 * cross_axis_margin, track_extent);
let x = size.width() - thickness - cross_axis_margin - padding.right;
let y = thumb_offset;
let track_offset =
Offset::new(x - cross_axis_margin, leading_track_main_axis_offset);
let border_start = track_offset;
let border_end =
Offset::new(track_offset.dx(), track_offset.dy() + track_extent);
(
x,
y,
thumb_size,
track_size,
track_offset,
border_start,
border_end,
)
}
ScrollbarOrientation::Top => {
let thumb_size = Size::new(thumb_extent, thickness);
let track_size = Size::new(track_extent, thickness + 2.0 * cross_axis_margin);
let x = thumb_offset;
let y = cross_axis_margin + padding.top;
let track_offset =
Offset::new(leading_track_main_axis_offset, y - cross_axis_margin);
let border_start = track_offset + Offset::new(0.0, track_size.height());
let border_end = Offset::new(
track_offset.dx() + track_extent,
track_offset.dy() + track_size.height(),
);
(
x,
y,
thumb_size,
track_size,
track_offset,
border_start,
border_end,
)
}
ScrollbarOrientation::Bottom => {
let thumb_size = Size::new(thumb_extent, thickness);
let track_size = Size::new(track_extent, thickness + 2.0 * cross_axis_margin);
let x = thumb_offset;
let y = size.height() - thickness - cross_axis_margin - padding.bottom;
let track_offset =
Offset::new(leading_track_main_axis_offset, y - cross_axis_margin);
let border_start = track_offset;
let border_end =
Offset::new(track_offset.dx() + track_extent, track_offset.dy());
(
x,
y,
thumb_size,
track_size,
track_offset,
border_start,
border_end,
)
}
};
let track_rect = track_offset & track_size;
let thumb_rect = Offset::new(x, y) & thumb_size;
let painter = app.get_mut(self);
painter.track_rect = Some(track_rect);
painter.thumb_rect = Some(thumb_rect);
if self.fadeout_opacity_animation(app).value(app) == 0.0 {
return;
}
match self.track_radius(app) {
None => canvas.draw_rect(track_rect, &self.paint_track(app, false)),
Some(track_radius) => draw_rrect(
canvas,
RRect::from_rect_and_radius(track_rect, track_radius),
&self.paint_track(app, false),
),
}
let mut border = PathBuilder::new();
border.move_to(border_start);
border.line_to(border_end);
canvas.draw_path(
&border.build(),
FillRule::NonZero,
&self.paint_track(app, true),
);
if let Some(radius) = self.radius(app) {
draw_rrect(
canvas,
RRect::from_rect_and_radius(thumb_rect, radius),
&self.paint_thumb(app),
);
return;
}
let Some(shape) = self.shape(app) else {
canvas.draw_rect(thumb_rect, &self.paint_thumb(app));
return;
};
let text_direction = self.text_direction(app);
if shape.prefer_paint_interior() {
shape.paint_interior(canvas, thumb_rect, &self.paint_thumb(app), text_direction);
} else {
let outer_path = shape.get_outer_path(thumb_rect, text_direction);
canvas.draw_path(
outer_path.as_valo(),
outer_path.fill_type,
&self.paint_thumb(app),
);
}
shape.paint(canvas, thumb_rect, text_direction);
}
pub fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
if app.get(self).last_axis_direction.is_none()
|| !need_paint(app.get(self).last_metrics.as_deref())
{
return;
}
if self.traversable_track_extent(app) <= 0.0 {
return;
}
if self.metrics(app).max_scroll_extent().is_infinite() {
return;
}
self.set_thumb_extent(app);
let thumb_extent = app.get(self).thumb_extent;
let metrics = self.metrics(app);
let thumb_position_offset = self.get_scroll_to_track(app, &*metrics, thumb_extent);
app.get_mut(self).thumb_offset =
thumb_position_offset + self.leading_thumb_main_axis_offset(app);
self.paint_scrollbar(app, canvas, size);
}
pub fn get_track_to_scroll(self: Handle<Self>, app: &App, thumb_offset_local: f64) -> f64 {
let metrics = self.metrics(app);
let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
let thumb_movable_extent = self.traversable_track_extent(app) - app.get(self).thumb_extent;
scrollable_extent * thumb_offset_local / thumb_movable_extent
}
pub fn get_thumb_scroll_offset(self: Handle<Self>, app: &App) -> f64 {
let metrics = self.metrics(app);
debug_assert!(
metrics.max_scroll_extent().is_finite() && metrics.min_scroll_extent().is_finite()
);
let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
let max_fraction = metrics.max_scroll_extent() / scrollable_extent;
let min_fraction = metrics.min_scroll_extent() / scrollable_extent;
let fraction_past = if scrollable_extent > 0.0 {
clamp_double(
metrics.pixels() / scrollable_extent,
min_fraction,
max_fraction,
)
} else {
0.0
};
fraction_past * (self.traversable_track_extent(app) - app.get(self).thumb_extent)
}
fn get_scroll_to_track(
self: Handle<Self>,
app: &App,
metrics: &dyn ScrollMetrics,
thumb_extent: f64,
) -> f64 {
let scrollable_extent = metrics.max_scroll_extent() - metrics.min_scroll_extent();
let fraction_past = if scrollable_extent > 0.0 {
clamp_double(
(metrics.pixels() - metrics.min_scroll_extent()) / scrollable_extent,
0.0,
1.0,
)
} else {
0.0
};
let fraction_past = if self.is_reversed(app) {
1.0 - fraction_past
} else {
fraction_past
};
fraction_past * (self.traversable_track_extent(app) - thumb_extent)
}
pub fn should_repaint(self: Handle<Self>, app: &App, old_delegate: Handle<Self>) -> bool {
let (new, old) = (app.get(self), app.get(old_delegate));
let same_shape = new.shape == old.shape;
new.color != old.color
|| new.track_color != old.track_color
|| new.track_border_color != old.track_border_color
|| new.text_direction != old.text_direction
|| new.thickness != old.thickness
|| new.fadeout_opacity_animation != old.fadeout_opacity_animation
|| new.main_axis_margin != old.main_axis_margin
|| new.cross_axis_margin != old.cross_axis_margin
|| new.radius != old.radius
|| new.track_radius != old.track_radius
|| !same_shape
|| new.padding != old.padding
|| new.min_length != old.min_length
|| new.min_overscroll_length != old.min_overscroll_length
|| new.scrollbar_orientation != old.scrollbar_orientation
|| new.ignore_pointer != old.ignore_pointer
}
pub fn hit_test(self: Handle<Self>, app: &App, position: Option<Offset>) -> Option<bool> {
app.get(self).thumb_rect?;
let track_rect = app.get(self).track_rect.expect("a thumb implies a track");
if self.ignore_pointer(app)
|| self.fadeout_opacity_animation(app).value(app) == 0.0
|| !self.last_metrics_are_scrollable(app)
{
return Some(false);
}
Some(track_rect.contains(position.expect("a hit test has a position")))
}
pub fn hit_test_interactive(
self: Handle<Self>,
app: &App,
position: Offset,
kind: PointerDeviceKind,
for_hover: bool,
) -> bool {
let Some(interactive_rect) = app.get(self).track_rect else {
return false;
};
if self.ignore_pointer(app) {
return false;
}
if !self.last_metrics_are_scrollable(app) {
return false;
}
let thumb_rect = app.get(self).thumb_rect.expect("a track implies a thumb");
let padded_rect = interactive_rect.expand_to_include(Rect::from_circle(
thumb_rect.center(),
K_MIN_INTERACTIVE_SIZE / 2.0,
));
if self.fadeout_opacity_animation(app).value(app) == 0.0 {
if for_hover && kind == PointerDeviceKind::Mouse {
return padded_rect.contains(position);
}
return false;
}
match kind {
PointerDeviceKind::Touch | PointerDeviceKind::Trackpad => {
padded_rect.contains(position)
}
PointerDeviceKind::Mouse
| PointerDeviceKind::Stylus
| PointerDeviceKind::InvertedStylus
| PointerDeviceKind::Unknown => interactive_rect.contains(position),
}
}
pub fn hit_test_only_thumb_interactive(
self: Handle<Self>,
app: &App,
position: Offset,
kind: PointerDeviceKind,
) -> bool {
let Some(thumb_rect) = app.get(self).thumb_rect else {
return false;
};
if self.ignore_pointer(app) {
return false;
}
if self.fadeout_opacity_animation(app).value(app) == 0.0 {
return false;
}
if !self.last_metrics_are_scrollable(app) {
return false;
}
match kind {
PointerDeviceKind::Touch | PointerDeviceKind::Trackpad => {
let touch_thumb_rect = thumb_rect.expand_to_include(Rect::from_circle(
thumb_rect.center(),
K_MIN_INTERACTIVE_SIZE / 2.0,
));
touch_thumb_rect.contains(position)
}
PointerDeviceKind::Mouse
| PointerDeviceKind::Stylus
| PointerDeviceKind::InvertedStylus
| PointerDeviceKind::Unknown => thumb_rect.contains(position),
}
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
let animation = self.fadeout_opacity_animation(app);
animation.remove_listener(
app,
&Listener::handle_method(self, Handle::<ScrollbarPainter>::notify_listeners),
);
ChangeNotifierData::dispose(app, self);
}
}
impl ChangeNotifier for ScrollbarPainter {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl Debug for ScrollbarPainter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ScrollbarPainter")
}
}
fn need_paint(metrics: Option<&dyn ScrollMetrics>) -> bool {
metrics.is_some_and(|metrics| {
metrics.max_scroll_extent() - metrics.min_scroll_extent() > PRECISION_ERROR_TOLERANCE
})
}
#[derive(Clone)]
pub struct ScrollbarPainterRef {
painter: Ref<ScrollbarPainter>,
repaint: Rc<dyn Listenable>,
}
impl ScrollbarPainterRef {
pub fn new(painter: Ref<ScrollbarPainter>) -> ScrollbarPainterRef {
ScrollbarPainterRef {
repaint: Rc::new(painter.clone()),
painter,
}
}
pub fn painter(&self) -> Handle<ScrollbarPainter> {
self.painter.handle()
}
}
impl CustomPainter for ScrollbarPainterRef {
fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
Some(&self.repaint)
}
fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
self.painter.paint(app, canvas, size);
}
fn should_repaint(&self, app: &App, old_delegate: &dyn CustomPainter) -> bool {
let old_delegate = old_delegate
.as_any()
.downcast_ref::<ScrollbarPainterRef>()
.expect("Dart's covariant parameter");
self.painter.should_repaint(app, old_delegate.painter())
}
fn hit_test(&self, app: &App, position: Offset) -> Option<bool> {
self.painter.hit_test(app, Some(position))
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Debug for ScrollbarPainterRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ScrollbarPainter")
}
}
pub struct RawScrollbarData {
pub key: Option<KeyRef>,
pub child: WidgetRef,
pub controller: Option<ScrollControllerRef>,
pub thumb_visibility: Option<bool>,
pub shape: Option<OutlinedBorderRef>,
pub radius: Option<Radius>,
pub thickness: Option<f64>,
pub thumb_color: Option<Color>,
pub min_thumb_length: f64,
pub min_overscroll_length: Option<f64>,
pub track_visibility: Option<bool>,
pub track_radius: Option<Radius>,
pub track_color: Option<Color>,
pub track_border_color: Option<Color>,
pub fade_duration: Duration,
pub time_to_fade: Duration,
pub press_duration: Duration,
pub notification_predicate: ScrollNotificationPredicate,
pub interactive: Option<bool>,
pub scrollbar_orientation: Option<ScrollbarOrientation>,
pub main_axis_margin: f64,
pub cross_axis_margin: f64,
pub padding: Option<EdgeInsetsGeometry>,
}
impl RawScrollbarData {
pub fn new(child: WidgetRef) -> RawScrollbarData {
RawScrollbarData {
key: None,
child,
controller: None,
thumb_visibility: None,
shape: None,
radius: None,
thickness: None,
thumb_color: None,
min_thumb_length: K_MIN_THUMB_EXTENT,
min_overscroll_length: None,
track_visibility: None,
track_radius: None,
track_color: None,
track_border_color: None,
fade_duration: K_SCROLLBAR_FADE_DURATION,
time_to_fade: K_SCROLLBAR_TIME_TO_FADE,
press_duration: Duration::ZERO,
notification_predicate: Rc::new(default_scroll_notification_predicate),
interactive: None,
scrollbar_orientation: None,
main_axis_margin: 0.0,
cross_axis_margin: 0.0,
padding: None,
}
}
}
impl Debug for RawScrollbarData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawScrollbar")
.field("child", &self.child)
.finish_non_exhaustive()
}
}
#[macro_export]
macro_rules! raw_scrollbar_accessors {
() => {
fn raw_scrollbar_data(&self) -> &$crate::RawScrollbarData {
&self.raw_scrollbar
}
fn raw_scrollbar_data_mut(&mut self) -> &mut $crate::RawScrollbarData {
&mut self.raw_scrollbar
}
};
}
#[macro_export]
macro_rules! raw_scrollbar_setters {
($name:ident) => {
pub fn key(mut self, key: $crate::KeyRef) -> $name {
self.raw_scrollbar.key = Some(key);
self
}
pub fn controller(mut self, controller: $crate::ScrollControllerRef) -> $name {
self.raw_scrollbar.controller = Some(controller);
self
}
pub fn thumb_visibility(mut self, thumb_visibility: bool) -> $name {
debug_assert!(
thumb_visibility || !self.raw_scrollbar.track_visibility.unwrap_or(false),
"A scrollbar track cannot be drawn without a scrollbar thumb."
);
self.raw_scrollbar.thumb_visibility = Some(thumb_visibility);
self
}
pub fn track_visibility(mut self, track_visibility: bool) -> $name {
debug_assert!(
!(self.raw_scrollbar.thumb_visibility == Some(false) && track_visibility),
"A scrollbar track cannot be drawn without a scrollbar thumb."
);
self.raw_scrollbar.track_visibility = Some(track_visibility);
self
}
pub fn shape(mut self, shape: impl Into<OutlinedBorderRef>) -> $name {
debug_assert!(self.raw_scrollbar.radius.is_none());
self.raw_scrollbar.shape = Some(shape.into());
self
}
pub fn radius(mut self, radius: waft_embedder::Radius) -> $name {
debug_assert!(self.raw_scrollbar.shape.is_none());
self.raw_scrollbar.radius = Some(radius);
self
}
pub fn thickness(mut self, thickness: f64) -> $name {
self.raw_scrollbar.thickness = Some(thickness);
self
}
pub fn thumb_color(mut self, thumb_color: waft_embedder::Color) -> $name {
self.raw_scrollbar.thumb_color = Some(thumb_color);
self
}
pub fn min_thumb_length(mut self, min_thumb_length: f64) -> $name {
debug_assert!(min_thumb_length >= 0.0);
debug_assert!(
self.raw_scrollbar
.min_overscroll_length
.is_none_or(|length| length <= min_thumb_length)
);
self.raw_scrollbar.min_thumb_length = min_thumb_length;
self
}
pub fn min_overscroll_length(mut self, min_overscroll_length: f64) -> $name {
debug_assert!(min_overscroll_length >= 0.0);
debug_assert!(min_overscroll_length <= self.raw_scrollbar.min_thumb_length);
self.raw_scrollbar.min_overscroll_length = Some(min_overscroll_length);
self
}
pub fn track_radius(mut self, track_radius: waft_embedder::Radius) -> $name {
self.raw_scrollbar.track_radius = Some(track_radius);
self
}
pub fn track_color(mut self, track_color: waft_embedder::Color) -> $name {
self.raw_scrollbar.track_color = Some(track_color);
self
}
pub fn track_border_color(mut self, track_border_color: waft_embedder::Color) -> $name {
self.raw_scrollbar.track_border_color = Some(track_border_color);
self
}
pub fn fade_duration(mut self, fade_duration: std::time::Duration) -> $name {
self.raw_scrollbar.fade_duration = fade_duration;
self
}
pub fn time_to_fade(mut self, time_to_fade: std::time::Duration) -> $name {
self.raw_scrollbar.time_to_fade = time_to_fade;
self
}
pub fn press_duration(mut self, press_duration: std::time::Duration) -> $name {
self.raw_scrollbar.press_duration = press_duration;
self
}
pub fn notification_predicate(
mut self,
notification_predicate: $crate::ScrollNotificationPredicate,
) -> $name {
self.raw_scrollbar.notification_predicate = notification_predicate;
self
}
pub fn interactive(mut self, interactive: bool) -> $name {
self.raw_scrollbar.interactive = Some(interactive);
self
}
pub fn scrollbar_orientation(
mut self,
scrollbar_orientation: $crate::ScrollbarOrientation,
) -> $name {
self.raw_scrollbar.scrollbar_orientation = Some(scrollbar_orientation);
self
}
pub fn main_axis_margin(mut self, main_axis_margin: f64) -> $name {
self.raw_scrollbar.main_axis_margin = main_axis_margin;
self
}
pub fn cross_axis_margin(mut self, cross_axis_margin: f64) -> $name {
self.raw_scrollbar.cross_axis_margin = cross_axis_margin;
self
}
pub fn padding(mut self, padding: waft_painting::EdgeInsetsGeometry) -> $name {
self.raw_scrollbar.padding = Some(padding);
self
}
};
}
pub trait RawScrollbarLeaf: StatefulWidget {
fn raw_scrollbar_data(&self) -> &RawScrollbarData;
fn raw_scrollbar_data_mut(&mut self) -> &mut RawScrollbarData;
}
pub struct RawScrollbar {
raw_scrollbar: RawScrollbarData,
}
impl RawScrollbar {
pub fn new<K>(child: impl IntoWidget<K>) -> RawScrollbar {
RawScrollbar {
raw_scrollbar: RawScrollbarData::new(child.into_widget()),
}
}
crate::raw_scrollbar_setters!(RawScrollbar);
}
impl RawScrollbarLeaf for RawScrollbar {
crate::raw_scrollbar_accessors!();
}
impl Debug for RawScrollbar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(&self.raw_scrollbar, f)
}
}
impl StatefulWidget for RawScrollbar {
type State = RawScrollbarState;
fn key(&self) -> Option<&KeyRef> {
self.raw_scrollbar.key.as_ref()
}
fn create_state(&self) -> RawScrollbarState {
RawScrollbarState {
state: StateData::new(),
ticker_provider: TickerProviderStateMixinData::new(),
raw_scrollbar_state: RawScrollbarStateData::new(),
}
}
}
pub struct RawScrollbarStateData {
start_drag_scrollbar_axis_offset: Option<Offset>,
last_drag_update_offset: Option<Offset>,
start_drag_thumb_offset: Option<f64>,
cached_controller: Option<ScrollControllerRef>,
fadeout_timer: Option<Timer>,
fadeout_animation_controller: Option<Ref<AnimationController>>,
fadeout_opacity_animation: Option<Ref<CurvedAnimation>>,
scrollbar_painter: Option<Ref<ScrollbarPainter>>,
scrollbar_painter_key: GlobalKey,
hover_is_active: bool,
thumb_drag: Option<Rc<dyn Drag>>,
max_scroll_extent_permits_scrolling: bool,
thumb_hold: Option<Rc<dyn ScrollHoldController>>,
axis: Option<Axis>,
gesture_detector_key: GlobalKey,
}
impl RawScrollbarStateData {
pub fn new() -> RawScrollbarStateData {
RawScrollbarStateData {
start_drag_scrollbar_axis_offset: None,
last_drag_update_offset: None,
start_drag_thumb_offset: None,
cached_controller: None,
fadeout_timer: None,
fadeout_animation_controller: None,
fadeout_opacity_animation: None,
scrollbar_painter: None,
scrollbar_painter_key: GlobalKey::new(),
hover_is_active: false,
thumb_drag: None,
max_scroll_extent_permits_scrolling: false,
thumb_hold: None,
axis: None,
gesture_detector_key: GlobalKey::new(),
}
}
}
impl Default for RawScrollbarStateData {
fn default() -> RawScrollbarStateData {
RawScrollbarStateData::new()
}
}
#[macro_export]
macro_rules! raw_scrollbar_state_accessors {
() => {
fn raw_scrollbar_state_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::RawScrollbarStateData {
&app.get(self).raw_scrollbar_state
}
fn raw_scrollbar_state_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::RawScrollbarStateData {
&mut app.get_mut(self).raw_scrollbar_state
}
fn raw_scrollbar_state_bag(&mut self) -> &mut $crate::RawScrollbarStateData {
&mut self.raw_scrollbar_state
}
};
}
pub trait RawScrollbarStateLeaf: State + TickerProviderStateMixin + TickerProviderObject
where
Self::Widget: RawScrollbarLeaf,
{
fn raw_scrollbar_state_data(self: Handle<Self>, app: &App) -> &RawScrollbarStateData;
fn raw_scrollbar_state_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut RawScrollbarStateData;
fn raw_scrollbar_state_bag(&mut self) -> &mut RawScrollbarStateData;
fn show_scrollbar(self: Handle<Self>, app: &mut App) -> bool {
self.widget(app)
.raw_scrollbar_data()
.thumb_visibility
.unwrap_or(false)
}
fn enable_gestures(self: Handle<Self>, app: &mut App) -> bool {
self.widget(app)
.raw_scrollbar_data()
.interactive
.unwrap_or(true)
}
fn update_scrollbar_painter(self: Handle<Self>, app: &mut App) {
RawScrollbarState::update_scrollbar_painter(self, app);
}
fn get_scrollbar_direction(self: Handle<Self>, app: &App) -> Option<Axis> {
self.raw_scrollbar_state_data(app).axis
}
fn handle_thumb_press(self: Handle<Self>, app: &mut App) {
RawScrollbarState::handle_thumb_press(self, app);
}
fn handle_thumb_press_start(self: Handle<Self>, app: &mut App, local_position: Offset) {
RawScrollbarState::handle_thumb_press_start(self, app, local_position);
}
fn handle_thumb_press_update(self: Handle<Self>, app: &mut App, local_position: Offset) {
RawScrollbarState::handle_thumb_press_update(self, app, local_position);
}
fn handle_thumb_press_end(
self: Handle<Self>,
app: &mut App,
local_position: Offset,
velocity: Velocity,
) {
RawScrollbarState::handle_thumb_press_end(self, app, local_position, velocity);
}
fn handle_track_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
RawScrollbarState::handle_track_tap_down(self, app, details);
}
fn handle_hover(self: Handle<Self>, app: &mut App, event: &PointerHoverEvent) {
RawScrollbarState::handle_hover(self, app, event);
}
fn handle_hover_exit(self: Handle<Self>, app: &mut App) {
RawScrollbarState::handle_hover_exit(self, app);
}
}
pub struct RawScrollbarState {
state: StateData<RawScrollbar>,
ticker_provider: TickerProviderStateMixinData,
raw_scrollbar_state: RawScrollbarStateData,
}
impl RawScrollbarState {
pub fn scrollbar_painter<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &App,
) -> Handle<ScrollbarPainter>
where
S::Widget: RawScrollbarLeaf,
{
this.raw_scrollbar_state_data(app)
.scrollbar_painter
.handle()
.expect("initState creates the painter")
}
pub fn fadeout_animation_controller<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &App,
) -> Handle<AnimationController>
where
S::Widget: RawScrollbarLeaf,
{
this.raw_scrollbar_state_data(app)
.fadeout_animation_controller
.handle()
.expect("initState creates the controller")
}
fn effective_scroll_controller<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
) -> Option<ScrollControllerRef>
where
S::Widget: RawScrollbarLeaf,
{
if let Some(controller) = this.widget(app).raw_scrollbar_data().controller.clone() {
return Some(controller);
}
let context = this.context(app);
PrimaryScrollController::maybe_of(app, context)
}
fn show_track<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
where
S::Widget: RawScrollbarLeaf,
{
this.show_scrollbar(app)
&& this
.widget(app)
.raw_scrollbar_data()
.track_visibility
.unwrap_or(false)
}
pub fn init_state<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
let fade_duration = this.widget(app).raw_scrollbar_data().fade_duration;
let controller = AnimationController::new(
app,
None,
Some(fade_duration),
None,
0.0,
1.0,
AnimationBehavior::Normal,
this,
);
AnimationLocalStatusListenersMixin::add_status_listener(
controller.handle(),
app,
AnimationStatusListener::handle_method(this, validate_interactions::<S>),
);
let opacity =
CurvedAnimation::new(app, controller.erase(), Curves::fast_out_slow_in(), None);
this.raw_scrollbar_state_data_mut(app)
.fadeout_animation_controller = Some(controller);
this.raw_scrollbar_state_data_mut(app)
.fadeout_opacity_animation = Some(opacity.clone());
let widget = this.widget(app).raw_scrollbar_data();
let color = widget.thumb_color.unwrap_or(K_DEFAULT_THUMB_COLOR);
let thickness = widget.thickness.unwrap_or(K_SCROLLBAR_THICKNESS);
let radius = widget.radius;
let track_radius = widget.track_radius;
let scrollbar_orientation = widget.scrollbar_orientation;
let main_axis_margin = widget.main_axis_margin;
let shape = widget.shape.clone();
let cross_axis_margin = widget.cross_axis_margin;
let min_length = widget.min_thumb_length;
let min_overscroll_length = widget.min_overscroll_length.unwrap_or(min_length);
let painter = ScrollbarPainter::new(app, color, opacity.into_erased());
painter.set_thickness(app, thickness);
painter.set_radius(app, radius);
painter.set_track_radius(app, track_radius);
painter.set_scrollbar_orientation(app, scrollbar_orientation);
painter.set_main_axis_margin(app, main_axis_margin);
painter.set_shape(app, shape);
painter.set_cross_axis_margin(app, cross_axis_margin);
painter.set_min_length(app, min_length);
painter.set_min_overscroll_length(app, min_overscroll_length);
this.raw_scrollbar_state_data_mut(app).scrollbar_painter = Some(painter);
}
pub fn did_change_dependencies<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_schedule_check_has_valid_scroll_position(this, app);
}
fn debug_schedule_check_has_valid_scroll_position<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
) where
S::Widget: RawScrollbarLeaf,
{
if !cfg!(debug_assertions) || !this.show_scrollbar(app) {
return;
}
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app: &mut App, _duration| {
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
}),
View::maybe_id_of(app, this.context(app)),
);
}
fn debug_check_has_valid_scroll_position<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
) where
S::Widget: RawScrollbarLeaf,
{
if !cfg!(debug_assertions) || !this.mounted(app) {
return;
}
let scroll_controller = RawScrollbarState::effective_scroll_controller(this, app);
let try_primary = this.widget(app).raw_scrollbar_data().controller.is_none();
let controller_for_error = if try_primary {
"PrimaryScrollController"
} else {
"provided ScrollController"
};
let when = if this
.widget(app)
.raw_scrollbar_data()
.thumb_visibility
.unwrap_or(false)
{
"Scrollbar.thumbVisibility is true"
} else if this.enable_gestures(app) {
"the scrollbar is interactive"
} else {
"using the Scrollbar"
};
assert!(
scroll_controller.is_some(),
"A ScrollController is required when {when}. {}",
if try_primary {
"The Scrollbar was not provided a ScrollController, and attempted to use the \
PrimaryScrollController, but none was found."
} else {
""
}
);
let scroll_controller = scroll_controller.expect("asserted above");
assert!(
scroll_controller.has_clients(app),
"The Scrollbar's ScrollController has no ScrollPosition attached.\n\
A Scrollbar cannot be painted without a ScrollPosition. \n\
The Scrollbar attempted to use the {controller_for_error}. This ScrollController \
should be associated with the ScrollView that the Scrollbar is being applied to.\n\
{}",
if try_primary {
"If a ScrollController has not been provided, the PrimaryScrollController is \
used by default on mobile platforms for ScrollViews with an Axis.vertical \
scroll direction.\n\
To use the PrimaryScrollController explicitly, set ScrollView.primary to true \
on the Scrollable widget."
} else {
"When providing your own ScrollController, ensure both the Scrollbar and the \
Scrollable widget use the same one."
}
);
assert!(
scroll_controller.positions(app).len() == 1,
"The {controller_for_error} is attached to more than one ScrollPosition.\n\
The Scrollbar requires a single ScrollPosition in order to be painted.\n\
When {when}, the associated ScrollController must only have one ScrollPosition \
attached.\n\
{}",
if try_primary {
"If a ScrollController has not been provided, the PrimaryScrollController is \
used by default on mobile platforms for ScrollViews with an Axis.vertical \
scroll direction.\n\
More than one ScrollView may have tried to use the PrimaryScrollController of \
the current context. ScrollView.primary can override this behavior."
} else {
"The provided ScrollController cannot be shared by multiple ScrollView widgets."
}
);
}
pub fn update_scrollbar_painter<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
let context = this.context(app);
let text_direction = crate::widgets::basic::Directionality::of(app, context);
let show_track = RawScrollbarState::show_track(this, app);
let enable_gestures = this.enable_gestures(app);
let painter = RawScrollbarState::scrollbar_painter(this, app);
let widget = this.widget(app).raw_scrollbar_data();
let color = widget.thumb_color.unwrap_or(K_DEFAULT_THUMB_COLOR);
let track_radius = widget.track_radius;
let track_color = if show_track {
widget.track_color.unwrap_or(K_DEFAULT_TRACK_COLOR)
} else {
K_TRANSPARENT
};
let track_border_color = if show_track {
widget
.track_border_color
.unwrap_or(K_DEFAULT_TRACK_BORDER_COLOR)
} else {
K_TRANSPARENT
};
let thickness = widget.thickness.unwrap_or(K_SCROLLBAR_THICKNESS);
let radius = widget.radius;
let padding = widget.padding;
let scrollbar_orientation = widget.scrollbar_orientation;
let main_axis_margin = widget.main_axis_margin;
let shape = widget.shape.clone();
let cross_axis_margin = widget.cross_axis_margin;
let min_length = widget.min_thumb_length;
let min_overscroll_length = widget.min_overscroll_length.unwrap_or(min_length);
let padding = padding
.unwrap_or_else(|| EdgeInsetsGeometry::from(MediaQuery::padding_of(app, context)))
.resolve(Some(text_direction));
painter.set_color(app, color);
painter.set_track_radius(app, track_radius);
painter.set_track_color(app, track_color);
painter.set_track_border_color(app, track_border_color);
painter.set_text_direction(app, Some(text_direction));
painter.set_thickness(app, thickness);
painter.set_radius(app, radius);
painter.set_padding(app, EdgeInsetsGeometry::from(padding));
painter.set_scrollbar_orientation(app, scrollbar_orientation);
painter.set_main_axis_margin(app, main_axis_margin);
painter.set_shape(app, shape);
painter.set_cross_axis_margin(app, cross_axis_margin);
painter.set_min_length(app, min_length);
painter.set_min_overscroll_length(app, min_overscroll_length);
painter.set_ignore_pointer(app, !enable_gestures);
}
pub fn did_update_widget<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
old_widget: &S::Widget,
) where
S::Widget: RawScrollbarLeaf,
{
let thumb_visibility = this.widget(app).raw_scrollbar_data().thumb_visibility;
if thumb_visibility == old_widget.raw_scrollbar_data().thumb_visibility {
return;
}
let controller = RawScrollbarState::fadeout_animation_controller(this, app);
if thumb_visibility.unwrap_or(false) {
RawScrollbarState::debug_schedule_check_has_valid_scroll_position(this, app);
RawScrollbarState::cancel_fadeout_timer(this, app);
controller.animate_to(app, 1.0, None, Curves::linear());
} else {
controller.reverse(app, None);
}
}
fn cancel_fadeout_timer<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
if let Some(timer) = this.raw_scrollbar_state_data(app).fadeout_timer {
timer.cancel(app);
this.raw_scrollbar_state_data_mut(app).fadeout_timer = None;
}
}
fn maybe_start_fadeout_timer<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
if this.show_scrollbar(app) {
return;
}
RawScrollbarState::cancel_fadeout_timer(this, app);
let time_to_fade = this.widget(app).raw_scrollbar_data().time_to_fade;
let timer = Timer::new(
app,
time_to_fade,
Listener::new(move |app: &mut App| {
RawScrollbarState::fadeout_timer_fired(this, app);
}),
);
this.raw_scrollbar_state_data_mut(app).fadeout_timer = Some(timer);
}
fn fadeout_timer_fired<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::fadeout_animation_controller(this, app).reverse(app, None);
this.raw_scrollbar_state_data_mut(app).fadeout_timer = None;
}
fn dispose_thumb_drag<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
this.raw_scrollbar_state_data_mut(app).thumb_drag = None;
}
fn dispose_thumb_hold<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
this.raw_scrollbar_state_data_mut(app).thumb_hold = None;
}
fn get_primary_delta<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
local_position: Offset,
) -> Option<f64>
where
S::Widget: RawScrollbarLeaf,
{
let data = this.raw_scrollbar_state_data(app);
let cached_controller = data
.cached_controller
.handle()
.expect("a press caches the controller");
let start_drag_scrollbar_axis_offset = data
.start_drag_scrollbar_axis_offset
.expect("a drag records its start");
let last_drag_update_offset = data
.last_drag_update_offset
.expect("a drag records its last update");
let start_drag_thumb_offset = data
.start_drag_thumb_offset
.expect("a drag records the thumb offset");
let position = cached_controller.position(app);
let (primary_delta_from_drag_start, primary_delta_from_last_drag_update) =
match position.axis_direction(app) {
AxisDirection::Up => (
start_drag_scrollbar_axis_offset.dy() - local_position.dy(),
last_drag_update_offset.dy() - local_position.dy(),
),
AxisDirection::Right => (
local_position.dx() - start_drag_scrollbar_axis_offset.dx(),
local_position.dx() - last_drag_update_offset.dx(),
),
AxisDirection::Down => (
local_position.dy() - start_drag_scrollbar_axis_offset.dy(),
local_position.dy() - last_drag_update_offset.dy(),
),
AxisDirection::Left => (
start_drag_scrollbar_axis_offset.dx() - local_position.dx(),
last_drag_update_offset.dx() - local_position.dx(),
),
};
let painter = RawScrollbarState::scrollbar_painter(this, app);
let mut scroll_offset_global = painter
.get_track_to_scroll(app, start_drag_thumb_offset + primary_delta_from_drag_start);
let pixels = position.pixels(app);
if (primary_delta_from_drag_start > 0.0 && scroll_offset_global < pixels)
|| (primary_delta_from_drag_start < 0.0 && scroll_offset_global > pixels)
{
scroll_offset_global =
pixels + painter.get_track_to_scroll(app, primary_delta_from_last_drag_update);
}
if scroll_offset_global == pixels {
return None;
}
let metrics = position.copy_with(app);
let physics_adjustment = position
.physics(app)
.apply_boundary_conditions(&*metrics, scroll_offset_global);
let mut new_position = scroll_offset_global - physics_adjustment;
let context = this.context(app);
match ScrollConfiguration::of(app, context).get_platform(app, context) {
TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::MacOS
| TargetPlatform::Windows => {
new_position = clamp_double(
new_position,
position.min_scroll_extent(app),
position.max_scroll_extent(app),
);
}
TargetPlatform::IOS | TargetPlatform::Android => {}
}
let is_reversed = axis_direction_is_reversed(position.axis_direction(app));
Some(if is_reversed {
new_position - pixels
} else {
pixels - new_position
})
}
pub fn handle_thumb_press<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
let controller = RawScrollbarState::effective_scroll_controller(this, app);
this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
if this.get_scrollbar_direction(app).is_none() {
return;
}
RawScrollbarState::cancel_fadeout_timer(this, app);
let position = controller.expect("a valid scroll position").position(app);
let hold = position.hold(
app,
Listener::new(move |app: &mut App| {
RawScrollbarState::dispose_thumb_hold(this, app);
}),
);
this.raw_scrollbar_state_data_mut(app).thumb_hold = Some(hold);
}
pub fn handle_thumb_press_start<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
local_position: Offset,
) where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
if this.get_scrollbar_direction(app).is_none() {
return;
}
RawScrollbarState::cancel_fadeout_timer(this, app);
RawScrollbarState::fadeout_animation_controller(this, app).forward(app, None);
debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
let position = this
.raw_scrollbar_state_data(app)
.cached_controller
.handle()
.expect("a press caches the controller")
.position(app);
let render_box = RawScrollbarState::painter_render_box(this, app);
let details = DragStartDetails::new(
render_box.local_to_global(app, local_position, None),
Some(local_position),
None,
None,
);
let drag = position.drag(
app,
details,
Listener::new(move |app: &mut App| {
RawScrollbarState::dispose_thumb_drag(this, app);
}),
);
this.raw_scrollbar_state_data_mut(app).thumb_drag = Some(drag);
debug_assert!(this.raw_scrollbar_state_data(app).thumb_hold.is_none());
let thumb_offset =
RawScrollbarState::scrollbar_painter(this, app).get_thumb_scroll_offset(app);
let data = this.raw_scrollbar_state_data_mut(app);
data.start_drag_scrollbar_axis_offset = Some(local_position);
data.last_drag_update_offset = Some(local_position);
data.start_drag_thumb_offset = Some(thumb_offset);
}
pub fn handle_thumb_press_update<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
local_position: Offset,
) where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
if this.raw_scrollbar_state_data(app).last_drag_update_offset == Some(local_position) {
return;
}
let position = this
.raw_scrollbar_state_data(app)
.cached_controller
.handle()
.expect("a press caches the controller")
.position(app);
let metrics = position.copy_with(app);
if !position.physics(app).should_accept_user_offset(&*metrics) {
return;
}
let Some(direction) = this.get_scrollbar_direction(app) else {
return;
};
debug_assert!(
this.raw_scrollbar_state_data(app).thumb_hold.is_none()
|| this.raw_scrollbar_state_data(app).thumb_drag.is_none()
);
let Some(thumb_drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() else {
return;
};
let Some(primary_delta) = RawScrollbarState::get_primary_delta(this, app, local_position)
else {
return;
};
let delta = match direction {
Axis::Horizontal => Offset::new(primary_delta, 0.0),
Axis::Vertical => Offset::new(0.0, primary_delta),
};
let render_box = RawScrollbarState::painter_render_box(this, app);
let scroll_details = DragUpdateDetails::new(
render_box.local_to_global(app, local_position, None),
Some(local_position),
None,
delta,
Some(primary_delta),
None,
);
thumb_drag.update(app, scroll_details);
this.raw_scrollbar_state_data_mut(app)
.last_drag_update_offset = Some(local_position);
}
pub fn handle_thumb_press_end<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
local_position: Offset,
velocity: Velocity,
) where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
let Some(direction) = this.get_scrollbar_direction(app) else {
return;
};
RawScrollbarState::maybe_start_fadeout_timer(this, app);
let data = this.raw_scrollbar_state_data_mut(app);
data.cached_controller = None;
data.last_drag_update_offset = None;
debug_assert!(
this.raw_scrollbar_state_data(app).thumb_hold.is_none()
|| this.raw_scrollbar_state_data(app).thumb_drag.is_none()
);
let Some(thumb_drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() else {
return;
};
let context = this.context(app);
let platform = ScrollConfiguration::of(app, context).get_platform(app, context);
let adjusted_velocity = match platform {
TargetPlatform::IOS | TargetPlatform::Android => -velocity,
_ => Velocity::ZERO,
};
let render_box = RawScrollbarState::painter_render_box(this, app);
let details = DragEndDetails::new(
render_box.local_to_global(app, local_position, None),
Some(local_position),
adjusted_velocity,
Some(match direction {
Axis::Horizontal => adjusted_velocity.pixels_per_second.dx(),
Axis::Vertical => adjusted_velocity.pixels_per_second.dy(),
}),
);
thumb_drag.end(app, details);
debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
let data = this.raw_scrollbar_state_data_mut(app);
data.start_drag_scrollbar_axis_offset = None;
data.last_drag_update_offset = None;
data.start_drag_thumb_offset = None;
data.cached_controller = None;
}
pub fn handle_track_tap_down<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
details: TapDownDetails,
) where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
let controller = RawScrollbarState::effective_scroll_controller(this, app);
this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
let position = controller.expect("a valid scroll position").position(app);
let metrics = position.copy_with(app);
if !position.physics(app).should_accept_user_offset(&*metrics) {
return;
}
let thumb_offset = app
.get(RawScrollbarState::scrollbar_painter(this, app))
.thumb_offset;
let local_position = details.local_position;
let scroll_direction = match axis_direction_to_axis(position.axis_direction(app)) {
Axis::Vertical => {
if local_position.dy() > thumb_offset {
AxisDirection::Down
} else {
AxisDirection::Up
}
}
Axis::Horizontal => {
if local_position.dx() > thumb_offset {
AxisDirection::Right
} else {
AxisDirection::Left
}
}
};
let notification_context = position
.context(app)
.notification_context(app)
.expect("a laid-out scrollable has a notification context");
let state = Scrollable::maybe_of(app, notification_context, None);
let intent = ScrollIntent {
direction: scroll_direction,
r#type: ScrollIncrementType::Page,
};
debug_assert!(state.is_some());
let scroll_increment =
ScrollAction::get_directional_increment(app, state.expect("a scrollable"), &intent);
position.move_to(
app,
position.pixels(app) + scroll_increment,
Some(Duration::from_millis(100)),
Some(Curves::ease_in_out()),
None,
);
}
fn should_update_painter<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
notification_axis: Axis,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
let Some(scroll_controller) = RawScrollbarState::effective_scroll_controller(this, app)
else {
return true;
};
if scroll_controller.positions(app).len() > 1 {
return false;
}
!scroll_controller.has_clients(app)
|| scroll_controller.position(app).axis(app) == notification_axis
}
fn handle_scroll_metrics_notification<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
notification: &ScrollMetricsNotification,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
let predicate = this
.widget(app)
.raw_scrollbar_data()
.notification_predicate
.clone();
if !predicate(¬ification.as_scroll_update()) {
return false;
}
let controller = RawScrollbarState::fadeout_animation_controller(this, app);
if this.show_scrollbar(app) && !controller.status(app).is_forward_or_completed() {
controller.forward(app, None);
}
let metrics = notification.metrics.clone();
if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
let axis_direction = metrics.axis_direction();
RawScrollbarState::scrollbar_painter(this, app).update(
app,
metrics.clone(),
axis_direction,
);
}
if Some(metrics.axis()) != this.raw_scrollbar_state_data(app).axis {
let axis = metrics.axis();
this.set_state(app, |state| {
state.raw_scrollbar_state_bag().axis = Some(axis);
});
}
let permits = metrics.max_scroll_extent() > 0.0;
if this
.raw_scrollbar_state_data(app)
.max_scroll_extent_permits_scrolling
!= permits
{
this.set_state(app, |state| {
let data = state.raw_scrollbar_state_bag();
data.max_scroll_extent_permits_scrolling =
!data.max_scroll_extent_permits_scrolling;
});
}
false
}
fn handle_scroll_notification<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
notification: &dyn ScrollNotification,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
let predicate = this
.widget(app)
.raw_scrollbar_data()
.notification_predicate
.clone();
if !predicate(notification) {
return false;
}
let metrics = notification.metrics().clone();
let controller = RawScrollbarState::fadeout_animation_controller(this, app);
if metrics.max_scroll_extent() <= metrics.min_scroll_extent() {
if controller.status(app).is_forward_or_completed() {
controller.reverse(app, None);
}
if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
let axis_direction = metrics.axis_direction();
RawScrollbarState::scrollbar_painter(this, app).update(
app,
metrics,
axis_direction,
);
}
return false;
}
let any = notification.as_any();
if any.is::<ScrollUpdateNotification>() || any.is::<OverscrollNotification>() {
if !controller.status(app).is_forward_or_completed() {
controller.forward(app, None);
}
RawScrollbarState::cancel_fadeout_timer(this, app);
if RawScrollbarState::should_update_painter(this, app, metrics.axis()) {
let axis_direction = metrics.axis_direction();
RawScrollbarState::scrollbar_painter(this, app).update(
app,
metrics,
axis_direction,
);
}
} else if any.is::<ScrollEndNotification>()
&& this.raw_scrollbar_state_data(app).thumb_drag.is_none()
{
RawScrollbarState::maybe_start_fadeout_timer(this, app);
}
false
}
fn global_to_scrollbar<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
offset: Offset,
) -> Offset
where
S::Widget: RawScrollbarLeaf,
{
RawScrollbarState::painter_render_box(this, app).global_to_local(app, offset, None)
}
fn painter_render_box<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> AnyRenderBox
where
S::Widget: RawScrollbarLeaf,
{
let key = this
.raw_scrollbar_state_data(app)
.scrollbar_painter_key
.clone();
let context = key
.current_context(app)
.expect("the CustomPaint is in the tree");
context
.find_render_object(app)
.expect("the CustomPaint has a render object")
.as_box()
.expect("the key is on the scrollbar's CustomPaint")
}
fn handle_thumb_drag_cancel<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
let key = this
.raw_scrollbar_state_data(app)
.gesture_detector_key
.clone();
if key.current_context(app).is_none() {
return;
}
debug_assert!(
this.raw_scrollbar_state_data(app).thumb_hold.is_none()
|| this.raw_scrollbar_state_data(app).thumb_drag.is_none()
);
if let Some(hold) = this.raw_scrollbar_state_data(app).thumb_hold.clone() {
hold.cancel(app);
}
if let Some(drag) = this.raw_scrollbar_state_data(app).thumb_drag.clone() {
drag.cancel(app);
}
debug_assert!(this.raw_scrollbar_state_data(app).thumb_hold.is_none());
debug_assert!(this.raw_scrollbar_state_data(app).thumb_drag.is_none());
}
fn can_handle_scroll_gestures<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
where
S::Widget: RawScrollbarLeaf,
{
if !this.enable_gestures(app) {
return false;
}
let Some(controller) = RawScrollbarState::effective_scroll_controller(this, app) else {
return false;
};
if controller.positions(app).len() != 1 {
return false;
}
let position = controller.position(app);
position.has_content_dimensions(app)
&& position.max_scroll_extent(app) - position.min_scroll_extent(app)
> PRECISION_ERROR_TOLERANCE
}
fn gestures<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
) -> GestureRecognizerFactories
where
S::Widget: RawScrollbarLeaf,
{
let mut gestures: GestureRecognizerFactories = Vec::new();
if !RawScrollbarState::can_handle_scroll_gestures(this, app) {
return gestures;
}
let painter_key = this
.raw_scrollbar_state_data(app)
.scrollbar_painter_key
.clone();
let owner = this
.context(app)
.owner(app)
.expect("a mounted element has a build owner");
let controller =
RawScrollbarState::effective_scroll_controller(this, app).expect("checked above");
match controller.position(app).axis(app) {
Axis::Horizontal => {
let key = painter_key.clone();
gestures.push((
std::any::TypeId::of::<HorizontalThumbDragGestureRecognizer>(),
GestureRecognizerFactoryWithHandlers::new(
move |app: &mut App| {
HorizontalThumbDragGestureRecognizer::new(app, owner, key.clone())
},
move |app: &mut App, instance| {
init_thumb_drag_gesture_recognizer(this, app, instance);
},
)
.into_factory(),
));
}
Axis::Vertical => {
let key = painter_key.clone();
gestures.push((
std::any::TypeId::of::<VerticalThumbDragGestureRecognizer>(),
GestureRecognizerFactoryWithHandlers::new(
move |app: &mut App| {
VerticalThumbDragGestureRecognizer::new(app, owner, key.clone())
},
move |app: &mut App, instance| {
init_thumb_drag_gesture_recognizer(this, app, instance);
},
)
.into_factory(),
));
}
}
let key = painter_key;
gestures.push((
std::any::TypeId::of::<TrackTapGestureRecognizer>(),
GestureRecognizerFactoryWithHandlers::new(
move |app: &mut App| TrackTapGestureRecognizer::new(app, owner, key.clone()),
move |app: &mut App, instance: Handle<TrackTapGestureRecognizer>| {
instance.set_on_tap_down(
app,
Some(Rc::new(move |app: &mut App, details| {
this.handle_track_tap_down(app, details);
})),
);
},
)
.into_factory(),
));
gestures
}
pub fn is_pointer_over_track<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
position: Offset,
kind: PointerDeviceKind,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
if !RawScrollbarState::has_painter_context(this, app) {
return false;
}
let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
let painter = RawScrollbarState::scrollbar_painter(this, app);
painter.hit_test_interactive(app, local_offset, kind, false)
&& !painter.hit_test_only_thumb_interactive(app, local_offset, kind)
}
pub fn is_pointer_over_thumb<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
position: Offset,
kind: PointerDeviceKind,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
if !RawScrollbarState::has_painter_context(this, app) {
return false;
}
let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
RawScrollbarState::scrollbar_painter(this, app).hit_test_only_thumb_interactive(
app,
local_offset,
kind,
)
}
pub fn is_pointer_over_scrollbar<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
position: Offset,
kind: PointerDeviceKind,
) -> bool
where
S::Widget: RawScrollbarLeaf,
{
if !RawScrollbarState::has_painter_context(this, app) {
return false;
}
let local_offset = RawScrollbarState::global_to_scrollbar(this, app, position);
RawScrollbarState::scrollbar_painter(this, app).hit_test_interactive(
app,
local_offset,
kind,
true,
)
}
fn has_painter_context<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App) -> bool
where
S::Widget: RawScrollbarLeaf,
{
let key = this
.raw_scrollbar_state_data(app)
.scrollbar_painter_key
.clone();
key.current_context(app).is_some()
}
pub fn handle_hover<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
event: &PointerHoverEvent,
) where
S::Widget: RawScrollbarLeaf,
{
if RawScrollbarState::is_pointer_over_scrollbar(this, app, event.position, event.kind) {
this.raw_scrollbar_state_data_mut(app).hover_is_active = true;
RawScrollbarState::fadeout_animation_controller(this, app).forward(app, None);
RawScrollbarState::cancel_fadeout_timer(this, app);
} else if this.raw_scrollbar_state_data(app).hover_is_active {
this.raw_scrollbar_state_data_mut(app).hover_is_active = false;
RawScrollbarState::maybe_start_fadeout_timer(this, app);
}
}
pub fn handle_hover_exit<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
this.raw_scrollbar_state_data_mut(app).hover_is_active = false;
RawScrollbarState::maybe_start_fadeout_timer(this, app);
}
fn pointer_signal_event_delta<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
event: &PointerScrollEvent,
) -> f64
where
S::Widget: RawScrollbarLeaf,
{
let position = this
.raw_scrollbar_state_data(app)
.cached_controller
.handle()
.expect("a pointer signal caches the controller")
.position(app);
let mut delta = if position.axis(app) == Axis::Horizontal {
event.scroll_delta.dx()
} else {
event.scroll_delta.dy()
};
if axis_direction_is_reversed(position.axis_direction(app)) {
delta *= -1.0;
}
delta
}
fn target_scroll_offset_for_pointer_scroll<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
delta: f64,
) -> f64
where
S::Widget: RawScrollbarLeaf,
{
let position = this
.raw_scrollbar_state_data(app)
.cached_controller
.handle()
.expect("a pointer signal caches the controller")
.position(app);
(position.pixels(app) + delta)
.max(position.min_scroll_extent(app))
.min(position.max_scroll_extent(app))
}
fn handle_pointer_scroll<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
event: &PointerEvent,
) where
S::Widget: RawScrollbarLeaf,
{
let PointerEvent::Scroll(event) = event else {
debug_assert!(false, "the pointer signal resolver replays a scroll event");
return;
};
let controller = RawScrollbarState::effective_scroll_controller(this, app);
this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
let delta = RawScrollbarState::pointer_signal_event_delta(this, app, event);
let target_scroll_offset =
RawScrollbarState::target_scroll_offset_for_pointer_scroll(this, app, delta);
let position = controller.expect("a cached controller").position(app);
if delta != 0.0 && target_scroll_offset != position.pixels(app) {
position.pointer_scroll(app, delta);
}
}
fn received_pointer_signal<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
event: &PointerEvent,
) where
S::Widget: RawScrollbarLeaf,
{
let controller = RawScrollbarState::effective_scroll_controller(this, app);
this.raw_scrollbar_state_data_mut(app).cached_controller = controller.clone();
let painter = RawScrollbarState::scrollbar_painter(this, app);
let hit = painter
.hit_test(app, Some(event.local_position()))
.unwrap_or(false);
let Some(controller) = controller else {
return;
};
if !hit
|| !controller.has_clients(app)
|| this.raw_scrollbar_state_data(app).thumb_drag.is_some()
{
return;
}
let position = controller.position(app);
match event {
PointerEvent::Scroll(scroll) => {
let metrics = position.copy_with(app);
if !position.physics(app).should_accept_user_offset(&*metrics) {
return;
}
let delta = RawScrollbarState::pointer_signal_event_delta(this, app, scroll);
let target_scroll_offset =
RawScrollbarState::target_scroll_offset_for_pointer_scroll(this, app, delta);
if delta != 0.0 && target_scroll_offset != position.pixels(app) {
let resolver = GestureBinding::instance(app).pointer_signal_resolver(app);
resolver.register(
app,
event,
Rc::new(move |app: &mut App, event: &PointerEvent| {
RawScrollbarState::handle_pointer_scroll(this, app, event);
}),
);
}
}
PointerEvent::ScrollInertiaCancel(_) => {
position.jump_to(app, position.pixels(app));
}
_ => {}
}
}
pub fn dispose<S: RawScrollbarStateLeaf>(this: Handle<S>, app: &mut App)
where
S::Widget: RawScrollbarLeaf,
{
let fadeout_animation_controller =
RawScrollbarState::fadeout_animation_controller(this, app);
fadeout_animation_controller.dispose(app);
RawScrollbarState::cancel_fadeout_timer(this, app);
let scrollbar_painter = RawScrollbarState::scrollbar_painter(this, app);
scrollbar_painter.dispose(app);
if let Some(opacity) = this
.raw_scrollbar_state_data(app)
.fadeout_opacity_animation
.handle()
{
opacity.dispose(app);
}
}
pub fn build<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
_context: BuildContext,
) -> WidgetRef
where
S::Widget: RawScrollbarLeaf,
{
this.update_scrollbar_painter(app);
let data = this.raw_scrollbar_state_data(app);
let painter_key = data.scrollbar_painter_key.clone();
let gesture_detector_key = data.gesture_detector_key.clone();
let painter = data
.scrollbar_painter
.clone()
.expect("initState creates the painter");
let child = this.widget(app).raw_scrollbar_data().child.clone();
let gestures = RawScrollbarState::gestures(this, app);
let custom_paint = CustomPaint::new()
.key(painter_key.into())
.foreground_painter(ScrollbarPainterRef::new(painter))
.child(RepaintBoundary::new().child(child));
let mouse_region = MouseRegion::new()
.on_exit(Rc::new(move |app: &mut App, event| match event.kind {
PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad => {
if this.enable_gestures(app) {
this.handle_hover_exit(app);
}
}
PointerDeviceKind::Stylus
| PointerDeviceKind::InvertedStylus
| PointerDeviceKind::Unknown
| PointerDeviceKind::Touch => {}
}))
.on_hover(Rc::new(move |app: &mut App, event| match event.kind {
PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad => {
if this.enable_gestures(app) {
this.handle_hover(app, &event);
}
}
PointerDeviceKind::Stylus
| PointerDeviceKind::InvertedStylus
| PointerDeviceKind::Unknown
| PointerDeviceKind::Touch => {}
}))
.child(custom_paint);
let gesture_detector = RawGestureDetector::new()
.key(gesture_detector_key.into())
.gestures(gestures)
.child(mouse_region);
let listener = PointerListener::new()
.on_pointer_signal(Rc::new(move |app: &mut App, event| {
RawScrollbarState::received_pointer_signal(this, app, &event);
}))
.child(gesture_detector);
NotificationListener::<ScrollMetricsNotification>::new(
NotificationListener::<dyn ScrollNotification>::new(
RepaintBoundary::new().child(listener),
)
.on_notification(
move |app: &mut App, notification: &dyn ScrollNotification| {
RawScrollbarState::handle_scroll_notification(this, app, notification)
},
)
.into_widget(),
)
.on_notification(
move |app: &mut App, notification: &ScrollMetricsNotification| {
RawScrollbarState::handle_scroll_metrics_notification(this, app, notification)
},
)
.into_widget()
}
}
fn validate_interactions<S: RawScrollbarStateLeaf>(
this: Handle<S>,
app: &mut App,
status: AnimationStatus,
) where
S::Widget: RawScrollbarLeaf,
{
if status.is_dismissed() {
return;
}
if RawScrollbarState::effective_scroll_controller(this, app).is_none()
|| !this.enable_gestures(app)
{
return;
}
let controller = RawScrollbarState::fadeout_animation_controller(this, app);
if controller.status(app) == AnimationStatus::Forward
&& this
.widget(app)
.raw_scrollbar_data()
.thumb_visibility
.unwrap_or(false)
{
return;
}
RawScrollbarState::debug_check_has_valid_scroll_position(this, app);
}
fn init_thumb_drag_gesture_recognizer<S, R>(this: Handle<S>, app: &mut App, instance: Handle<R>)
where
S: RawScrollbarStateLeaf,
S::Widget: RawScrollbarLeaf,
R: DragGestureRecognizer + ThumbDragGestureRecognizer,
{
instance.set_on_down(
app,
Some(Rc::new(move |app: &mut App, _details: DragDownDetails| {
this.handle_thumb_press(app);
})),
);
instance.set_on_start(
app,
Some(Rc::new(move |app: &mut App, details: DragStartDetails| {
let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
this.handle_thumb_press_start(app, local);
})),
);
instance.set_on_update(
app,
Some(Rc::new(move |app: &mut App, details: DragUpdateDetails| {
let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
this.handle_thumb_press_update(app, local);
})),
);
instance.set_on_end(
app,
Some(Rc::new(move |app: &mut App, details: DragEndDetails| {
let local = RawScrollbarState::global_to_scrollbar(this, app, details.global_position);
this.handle_thumb_press_end(app, local, details.velocity);
})),
);
instance.set_on_cancel(
app,
Some(Listener::new(move |app: &mut App| {
RawScrollbarState::handle_thumb_drag_cancel(this, app);
})),
);
instance.set_thumb_gesture_settings(app, DeviceGestureSettings::new(Some(0.0)));
instance.set_drag_start_behavior(app, DragStartBehavior::Down);
}
impl State for RawScrollbarState {
type Widget = RawScrollbar;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
RawScrollbarState::init_state(self, app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
RawScrollbarState::did_change_dependencies(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RawScrollbar) {
RawScrollbarState::did_update_widget(self, app, old_widget);
}
fn dispose(self: Handle<Self>, app: &mut App) {
RawScrollbarState::dispose(self, app);
TickerProviderStateMixin::dispose(self, app);
}
fn activate(self: Handle<Self>, app: &mut App) {
TickerProviderStateMixin::activate(self, app);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
RawScrollbarState::build(self, app, context)
}
}
impl RawScrollbarStateLeaf for RawScrollbarState {
crate::raw_scrollbar_state_accessors!();
}
impl TickerProviderObject for RawScrollbarState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
TickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl TickerProviderStateMixin for RawScrollbarState {
fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
&app.get(self).ticker_provider
}
fn ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TickerProviderStateMixinData {
&mut app.get_mut(self).ticker_provider
}
}
impl Debug for RawScrollbarState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RawScrollbarState")
}
}
fn get_local_offset(
app: &App,
owner: Handle<BuildOwner>,
scrollbar_painter_key: &GlobalKey,
position: Offset,
) -> Option<Offset> {
let element = owner.global_key_element(app, scrollbar_painter_key)?;
let render_box = element
.find_render_object(app)?
.as_box()
.expect("the key is on the scrollbar's CustomPaint");
Some(render_box.global_to_local(app, position, None))
}
fn painter_of(
app: &App,
owner: Handle<BuildOwner>,
custom_paint_key: &GlobalKey,
) -> Option<Handle<ScrollbarPainter>> {
let element = owner.global_key_element(app, custom_paint_key)?;
let custom_paint = downcast_widget::<CustomPaint>(&**element.widget(app))?;
custom_paint
.foreground_painter
.as_ref()?
.as_any()
.downcast_ref::<ScrollbarPainterRef>()
.map(ScrollbarPainterRef::painter)
}
fn is_thumb_event(
app: &App,
owner: Handle<BuildOwner>,
custom_paint_key: &GlobalKey,
event: &PointerDownEvent,
) -> bool {
let Some(painter) = painter_of(app, owner, custom_paint_key) else {
return false;
};
let Some(local_offset) = get_local_offset(app, owner, custom_paint_key, event.position) else {
return false;
};
painter.hit_test_only_thumb_interactive(app, local_offset, event.kind)
}
fn is_track_event(
app: &App,
owner: Handle<BuildOwner>,
custom_paint_key: &GlobalKey,
event: &PointerDownEvent,
) -> bool {
let Some(painter) = painter_of(app, owner, custom_paint_key) else {
return false;
};
let Some(local_offset) = get_local_offset(app, owner, custom_paint_key, event.position) else {
return false;
};
let kind = event.kind;
painter.hit_test_interactive(app, local_offset, kind, false)
&& !painter.hit_test_only_thumb_interactive(app, local_offset, kind)
}
pub trait ThumbDragGestureRecognizer: Sized + 'static {
fn set_thumb_gesture_settings(
self: Handle<Self>,
app: &mut App,
settings: DeviceGestureSettings,
);
}
macro_rules! thumb_drag_gesture_recognizer_leaf {
($name:ident, $description:literal) => {
impl $name {
pub fn new(
app: &mut App,
owner: Handle<BuildOwner>,
custom_paint_key: GlobalKey,
) -> Ref<$name> {
app.create($name {
recognizer: GestureRecognizerData::new(),
one_sequence: OneSequenceData::new(),
drag: DragData::new(),
owner,
custom_paint_key,
})
}
}
impl ThumbDragGestureRecognizer for $name {
fn set_thumb_gesture_settings(
self: Handle<Self>,
app: &mut App,
settings: DeviceGestureSettings,
) {
app.get_mut(self)
.recognizer
.set_gesture_settings(Some(settings));
}
}
impl RecognizerLeafData for $name {
fn recognizer(&self) -> &GestureRecognizerData {
&self.recognizer
}
fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
&mut self.recognizer
}
}
impl OneSequenceLeafData for $name {
fn one_sequence(&self) -> &OneSequenceData {
&self.one_sequence
}
fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
&mut self.one_sequence
}
}
impl DragLeafData for $name {
fn drag(&self) -> &DragData {
&self.drag
}
fn drag_mut(&mut self) -> &mut DragData {
&mut self.drag
}
}
impl RecognizerLeaf for $name {
fn handle_non_allowed_pointer(
self: Handle<Self>,
app: &mut App,
_event: &PointerDownEvent,
) {
waft_gestures::OneSequenceGestureRecognizer::handle_non_allowed_pointer(self, app);
}
fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
let recognizer = app.get(self);
is_thumb_event(app, recognizer.owner, &recognizer.custom_paint_key, event)
&& DragGestureRecognizer::is_pointer_allowed(self, app, event)
}
fn is_pointer_pan_zoom_allowed(
self: Handle<Self>,
_app: &App,
_event: &PointerPanZoomStartEvent,
) -> bool {
false
}
fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
DragGestureRecognizer::add_allowed_pointer(self, app, event);
}
fn add_allowed_pointer_pan_zoom(
self: Handle<Self>,
app: &mut App,
event: PointerPanZoomStartEvent,
) {
DragGestureRecognizer::add_allowed_pointer_pan_zoom(self, app, event);
}
fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
DragGestureRecognizer::handle_event(self, app, event);
}
fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
DragGestureRecognizer::accept_gesture(self, app, pointer);
}
fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
DragGestureRecognizer::reject_gesture(self, app, pointer);
}
fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, pointer: i64) {
DragGestureRecognizer::did_stop_tracking_last_pointer(self, app, pointer);
}
fn dispose(self: Handle<Self>, app: &mut App) {
DragGestureRecognizer::dispose(self, app);
}
fn debug_description(self: Handle<Self>) -> &'static str {
$description
}
}
};
}
pub struct VerticalThumbDragGestureRecognizer {
recognizer: GestureRecognizerData,
one_sequence: OneSequenceData,
drag: DragData,
owner: Handle<BuildOwner>,
custom_paint_key: GlobalKey,
}
thumb_drag_gesture_recognizer_leaf!(VerticalThumbDragGestureRecognizer, "vertical thumb drag");
impl DragLeaf for VerticalThumbDragGestureRecognizer {
fn is_fling_gesture(
self: Handle<Self>,
app: &App,
estimate: &VelocityEstimate,
kind: PointerDeviceKind,
) -> bool {
VerticalDragGestureRecognizerBase::is_fling_gesture(self, app, estimate, kind)
}
fn consider_fling(
self: Handle<Self>,
app: &App,
estimate: &VelocityEstimate,
kind: PointerDeviceKind,
) -> Option<DragEndDetails> {
VerticalDragGestureRecognizerBase::consider_fling(self, app, estimate, kind)
}
fn has_sufficient_global_distance_to_accept(
self: Handle<Self>,
app: &App,
pointer_device_kind: PointerDeviceKind,
device_touch_slop: Option<f64>,
) -> bool {
VerticalDragGestureRecognizerBase::has_sufficient_global_distance_to_accept(
self,
app,
pointer_device_kind,
device_touch_slop,
)
}
fn get_delta_for_details(self: Handle<Self>, app: &App, delta: Offset) -> Offset {
VerticalDragGestureRecognizerBase::get_delta_for_details(self, app, delta)
}
fn get_primary_value_from_offset(self: Handle<Self>, app: &App, value: Offset) -> Option<f64> {
VerticalDragGestureRecognizerBase::get_primary_value_from_offset(self, app, value)
}
fn get_primary_drag_axis(self: Handle<Self>, app: &App) -> Option<DragDirection> {
VerticalDragGestureRecognizerBase::get_primary_drag_axis(self, app)
}
}
pub struct HorizontalThumbDragGestureRecognizer {
recognizer: GestureRecognizerData,
one_sequence: OneSequenceData,
drag: DragData,
owner: Handle<BuildOwner>,
custom_paint_key: GlobalKey,
}
thumb_drag_gesture_recognizer_leaf!(
HorizontalThumbDragGestureRecognizer,
"horizontal thumb drag"
);
impl DragLeaf for HorizontalThumbDragGestureRecognizer {
fn is_fling_gesture(
self: Handle<Self>,
app: &App,
estimate: &VelocityEstimate,
kind: PointerDeviceKind,
) -> bool {
HorizontalDragGestureRecognizerBase::is_fling_gesture(self, app, estimate, kind)
}
fn consider_fling(
self: Handle<Self>,
app: &App,
estimate: &VelocityEstimate,
kind: PointerDeviceKind,
) -> Option<DragEndDetails> {
HorizontalDragGestureRecognizerBase::consider_fling(self, app, estimate, kind)
}
fn has_sufficient_global_distance_to_accept(
self: Handle<Self>,
app: &App,
pointer_device_kind: PointerDeviceKind,
device_touch_slop: Option<f64>,
) -> bool {
HorizontalDragGestureRecognizerBase::has_sufficient_global_distance_to_accept(
self,
app,
pointer_device_kind,
device_touch_slop,
)
}
fn get_delta_for_details(self: Handle<Self>, app: &App, delta: Offset) -> Offset {
HorizontalDragGestureRecognizerBase::get_delta_for_details(self, app, delta)
}
fn get_primary_value_from_offset(self: Handle<Self>, app: &App, value: Offset) -> Option<f64> {
HorizontalDragGestureRecognizerBase::get_primary_value_from_offset(self, app, value)
}
fn get_primary_drag_axis(self: Handle<Self>, app: &App) -> Option<DragDirection> {
HorizontalDragGestureRecognizerBase::get_primary_drag_axis(self, app)
}
}
pub struct TrackTapGestureRecognizer {
recognizer: GestureRecognizerData,
one_sequence: OneSequenceData,
primary: PrimaryPointerData,
base_tap: BaseTapData,
owner: Handle<BuildOwner>,
custom_paint_key: GlobalKey,
on_tap_down: Option<GestureTapDownCallback>,
}
impl TrackTapGestureRecognizer {
pub fn new(
app: &mut App,
owner: Handle<BuildOwner>,
custom_paint_key: GlobalKey,
) -> Ref<TrackTapGestureRecognizer> {
app.create(TrackTapGestureRecognizer {
recognizer: GestureRecognizerData::new(),
one_sequence: OneSequenceData::new(),
primary: PrimaryPointerData::new(
Some(K_PRESS_TIMEOUT),
Some(UNSET_TOUCH_SLOP),
Some(UNSET_TOUCH_SLOP),
),
base_tap: BaseTapData::new(),
owner,
custom_paint_key,
on_tap_down: None,
})
}
pub fn on_tap_down(self: Handle<Self>, app: &App) -> Option<GestureTapDownCallback> {
app.get(self).on_tap_down.clone()
}
pub fn set_on_tap_down(
self: Handle<Self>,
app: &mut App,
callback: Option<GestureTapDownCallback>,
) {
app.get_mut(self).on_tap_down = callback;
}
}
impl RecognizerLeafData for TrackTapGestureRecognizer {
fn recognizer(&self) -> &GestureRecognizerData {
&self.recognizer
}
fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
&mut self.recognizer
}
}
impl OneSequenceLeafData for TrackTapGestureRecognizer {
fn one_sequence(&self) -> &OneSequenceData {
&self.one_sequence
}
fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
&mut self.one_sequence
}
}
impl PrimaryPointerLeafData for TrackTapGestureRecognizer {
fn primary(&self) -> &PrimaryPointerData {
&self.primary
}
fn primary_mut(&mut self) -> &mut PrimaryPointerData {
&mut self.primary
}
}
impl BaseTapLeafData for TrackTapGestureRecognizer {
fn base_tap(&self) -> &BaseTapData {
&self.base_tap
}
fn base_tap_mut(&mut self) -> &mut BaseTapData {
&mut self.base_tap
}
}
impl RecognizerLeaf for TrackTapGestureRecognizer {
fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
BaseTapGestureRecognizer::add_allowed_pointer(self, app, event);
}
fn handle_non_allowed_pointer(self: Handle<Self>, app: &mut App, event: &PointerDownEvent) {
PrimaryPointerGestureRecognizer::handle_non_allowed_pointer(self, app, event);
}
fn start_tracking_pointer(
self: Handle<Self>,
app: &mut App,
pointer: i64,
transform: Option<Matrix4>,
) {
BaseTapGestureRecognizer::start_tracking_pointer(self, app, pointer, transform);
}
fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
PrimaryPointerGestureRecognizer::handle_event(self, app, event);
}
fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, pointer: i64) {
PrimaryPointerGestureRecognizer::did_stop_tracking_last_pointer(self, app, pointer);
}
fn dispose(self: Handle<Self>, app: &mut App) {
PrimaryPointerGestureRecognizer::dispose(self, app);
}
fn resolve(self: Handle<Self>, app: &mut App, disposition: GestureDisposition) {
BaseTapGestureRecognizer::resolve(self, app, disposition);
}
fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
BaseTapGestureRecognizer::accept_gesture(self, app, pointer);
}
fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
BaseTapGestureRecognizer::reject_gesture(self, app, pointer);
}
fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
let recognizer = app.get(self);
is_track_event(app, recognizer.owner, &recognizer.custom_paint_key, event)
&& recognizer.on_tap_down.is_some()
&& event.buttons == K_PRIMARY_BUTTON
&& GestureRecognizer::is_pointer_allowed(self, app, event)
}
fn debug_description(self: Handle<Self>) -> &'static str {
"track tap"
}
}
impl PrimaryPointerLeaf for TrackTapGestureRecognizer {
fn handle_primary_pointer(self: Handle<Self>, app: &mut App, event: PointerEvent) {
BaseTapGestureRecognizer::handle_primary_pointer(self, app, event);
}
fn did_exceed_deadline(self: Handle<Self>, app: &mut App) {
BaseTapGestureRecognizer::did_exceed_deadline(self, app);
}
}
impl BaseTapLeaf for TrackTapGestureRecognizer {
fn handle_tap_down(self: Handle<Self>, app: &mut App, down: &PointerDownEvent) {
if down.buttons != K_PRIMARY_BUTTON {
return;
}
let details = TapDownDetails::new(
down.position,
Some(down.local_position()),
Some(GestureRecognizer::kind_for_pointer(self, app, down.pointer)),
);
if let Some(callback) = app.get(self).on_tap_down.clone() {
GestureRecognizer::invoke_callback(self, app, "onTapDown", |app| {
callback(app, details)
});
}
}
fn handle_tap_up(
self: Handle<Self>,
_app: &mut App,
_down: &PointerDownEvent,
_up: &PointerUpEvent,
) {
}
fn handle_tap_cancel(
self: Handle<Self>,
_app: &mut App,
_down: &PointerDownEvent,
_cancel: Option<&PointerCancelEvent>,
_reason: &str,
) {
}
}
#[cfg(test)]
mod tests {
use waft_embedder::TextDirection;
use waft_foundation::OptionRetained;
use waft_gestures::HitTestResult;
use waft_painting::EdgeInsets;
use waft_rendering::{BoxHitTestEntry, RenderCustomPaint, RendererBinding};
use super::*;
use crate::testing::{WidgetTester, test_widgets};
use crate::widgets::basic::{Directionality, SizedBox};
use crate::widgets::media_query::MediaQueryData;
use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
use crate::widgets::scroll_view::ListView;
const ITEM_EXTENT: f64 = 50.0;
const ITEM_COUNT: usize = 40;
const VIEW_WIDTH: f64 = WidgetTester::SIZE.width();
const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
fn mount(tester: &mut WidgetTester) -> (GlobalKey, Handle<ScrollController>) {
let key = GlobalKey::new();
let controller = tester.update(ScrollController::default);
let list = ListView::new()
.controller(controller.erase())
.children((0..ITEM_COUNT).map(|_| SizedBox::new().height(ITEM_EXTENT).into_widget()));
let scrollbar = RawScrollbar::new(list)
.key(key.clone().into())
.controller(controller.erase());
let tree: WidgetRef = MediaQuery::new(
MediaQueryData::new()
.size(WidgetTester::SIZE)
.padding(EdgeInsets::ZERO),
scrollbar,
)
.into_widget();
tester.pump_widget(Directionality::new(TextDirection::Ltr, tree));
tester.pump_by(Duration::from_millis(16));
(key, controller.handle())
}
fn painter(app: &mut App, key: &GlobalKey) -> Handle<ScrollbarPainter> {
let state = key
.current_state::<RawScrollbarState>(app)
.expect("the scrollbar is mounted");
RawScrollbarState::scrollbar_painter(state, app)
}
fn scroll_a_little(tester: &mut WidgetTester, controller: Handle<ScrollController>) {
tester.update(|app| controller.jump_to(app, 10.0));
for _ in 1..4 {
tester.pump_by(Duration::from_millis(100));
}
}
#[test]
fn a_raw_scrollbar_paints_a_thumb_whose_extent_follows_the_metrics_and_fades_after_the_timer() {
test_widgets(|tester| {
let (key, controller) = mount(tester);
scroll_a_little(tester, controller);
let painter = tester.update(|app| painter(app, &key));
{
let app = tester.cell.borrow();
let thumb = app.get(painter).thumb_rect.expect("the thumb is painted");
let content = ITEM_EXTENT * ITEM_COUNT as f64;
assert!(
(thumb.height() - VIEW_HEIGHT * (VIEW_HEIGHT / content)).abs() < 0.5,
"the thumb extent is the visible fraction of the track: {thumb:?}"
);
assert!(
painter.fadeout_opacity_animation(&app).value(&app) > 0.0,
"a scroll fades the thumb in"
);
}
tester.pump_by(K_SCROLLBAR_TIME_TO_FADE + Duration::from_millis(1));
for _ in 0..8 {
tester.pump_by(Duration::from_millis(60));
}
let app = tester.cell.borrow();
assert_eq!(
painter.fadeout_opacity_animation(&app).value(&app),
0.0,
"the thumb has faded out"
);
});
}
#[test]
fn a_disposed_raw_scrollbar_frees_its_fade_and_painter() {
test_widgets(|tester| {
let (key, _controller) = mount(tester);
let (fade, controller, painter) = {
let app = tester.cell.borrow();
let state = key
.current_state::<RawScrollbarState>(&app)
.expect("the scrollbar is mounted");
let data = RawScrollbarState::raw_scrollbar_state_data(state, &app);
(
data.fadeout_opacity_animation
.handle()
.expect("made in init_state"),
data.fadeout_animation_controller
.handle()
.expect("made in init_state"),
data.scrollbar_painter.handle().expect("made in init_state"),
)
};
tester.pump_widget(SizedBox::new());
let app = tester.cell.borrow();
assert!(!app.contains(fade));
assert!(!app.contains(controller));
assert!(!app.contains(painter));
});
}
#[test]
fn a_hit_on_the_painted_scrollbar_stops_at_the_custom_paint() {
test_widgets(|tester| {
let (key, controller) = mount(tester);
scroll_a_little(tester, controller);
let mut app = tester.cell.borrow_mut();
let painter = painter(&mut app, &key);
let thumb = app.get(painter).thumb_rect.expect("the thumb is painted");
let boxes_at = |app: &mut App, position: Offset| -> Vec<AnyRenderBox> {
let mut result = HitTestResult::new();
let views = RendererBinding::instance(app).render_views(app);
let [view] = views.as_slice() else {
panic!("the View widget registered one render view: {views:?}");
};
view.hit_test(app, &mut result, position);
result
.path()
.iter()
.filter_map(|entry| {
let target: &dyn Any = entry.target();
target
.downcast_ref::<BoxHitTestEntry>()
.map(BoxHitTestEntry::target)
})
.collect()
};
let is_custom_paint = |app: &App, hit: &AnyRenderBox| {
hit.as_object().downcast::<RenderCustomPaint>(app).is_some()
};
let on_thumb = boxes_at(&mut app, thumb.center());
assert!(
is_custom_paint(&app, &on_thumb[0]),
"the painter absorbs the hit, so nothing below its CustomPaint is hit: {on_thumb:?}"
);
let beside_thumb = boxes_at(&mut app, Offset::new(20.0, thumb.center().dy()));
assert!(
!is_custom_paint(&app, &beside_thumb[0]) && beside_thumb.len() > on_thumb.len(),
"a hit off the track goes on to the scrollable underneath: {beside_thumb:?}"
);
});
}
#[test]
fn dragging_the_raw_scrollbar_thumb_moves_the_scroll_position() {
test_widgets(|tester| {
let (key, controller) = mount(tester);
let mut app = tester.cell.borrow_mut();
let state = key
.current_state::<RawScrollbarState>(&app)
.expect("the scrollbar is mounted");
assert_eq!(
state.get_scrollbar_direction(&app),
Some(Axis::Vertical),
"the metrics notification tells the scrollbar its axis"
);
state.handle_thumb_press(&mut app);
state.handle_thumb_press_start(&mut app, Offset::new(VIEW_WIDTH - 3.0, 5.0));
state.handle_thumb_press_update(&mut app, Offset::new(VIEW_WIDTH - 3.0, 25.0));
let content = ITEM_EXTENT * ITEM_COUNT as f64;
let scrollable = content - VIEW_HEIGHT;
let thumb_extent = VIEW_HEIGHT * (VIEW_HEIGHT / content);
let expected = 20.0 * scrollable / (VIEW_HEIGHT - thumb_extent);
assert!(
(controller.offset(&app) - expected).abs() < 0.5,
"a 20 pixel thumb drag scrolls the track fraction: {}",
controller.offset(&app)
);
state.handle_thumb_press_end(
&mut app,
Offset::new(VIEW_WIDTH - 3.0, 25.0),
Velocity::ZERO,
);
assert!(
app.get(state).raw_scrollbar_state.thumb_drag.is_none(),
"the drag is released"
);
});
}
#[test]
fn a_raw_scrollbar_hides_its_thumb_when_the_child_cannot_scroll() {
test_widgets(|tester| {
let key = GlobalKey::new();
let controller = tester.update(ScrollController::default);
let list = ListView::new()
.controller(controller.erase())
.children([SizedBox::new().height(ITEM_EXTENT).into_widget()]);
let scrollbar = RawScrollbar::new(list)
.key(key.clone().into())
.controller(controller.erase());
let tree: WidgetRef =
MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), scrollbar)
.into_widget();
tester.pump_widget(Directionality::new(TextDirection::Ltr, tree));
let painter = tester.update(|app| painter(app, &key));
let app = tester.cell.borrow();
assert_eq!(
painter.fadeout_opacity_animation(&app).value(&app),
0.0,
"a scroll view with nothing to scroll never fades the thumb in"
);
});
}
}