Skip to main content

waft_widgets/widgets/
text_selection_toolbar_layout_delegate.rs

1//! Flutter counterpart: `widgets/text_selection_toolbar_layout_delegate.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5
6use waft_embedder::{Offset, Size};
7use waft_rendering::{BoxConstraints, SingleChildLayoutDelegate};
8
9/// A [`SingleChildLayoutDelegate`] for use with `CustomSingleChildLayout` that positions its
10/// child above [`anchor_above`](Self::anchor_above) if it fits, or otherwise below
11/// [`anchor_below`](Self::anchor_below).
12///
13/// Primarily intended for use with toolbars or context menus.
14///
15/// See also:
16///
17///   * `TextSelectionToolbar`, which uses this to position itself.
18///   * `CupertinoTextSelectionToolbar`, which also uses this to position itself.
19#[derive(Debug)]
20pub struct TextSelectionToolbarLayoutDelegate {
21    /// The location that the toolbar should attempt to position itself at.
22    ///
23    /// Should be provided in local coordinates.
24    pub anchor_above: Offset,
25    /// The fallback position that should be used if [`anchor_above`](Self::anchor_above)
26    /// doesn't work.
27    ///
28    /// Should be provided in local coordinates.
29    pub anchor_below: Offset,
30    /// Whether or not the child should be considered to fit above
31    /// [`anchor_above`](Self::anchor_above).
32    ///
33    /// Typically used to force the child to be drawn at `anchor_above` even when it doesn't
34    /// fit, such as when the Material `TextSelectionToolbar` draws an open overflow menu.
35    ///
36    /// If not provided, it will be calculated.
37    pub fits_above: Option<bool>,
38}
39
40impl TextSelectionToolbarLayoutDelegate {
41    /// Creates an instance of [`TextSelectionToolbarLayoutDelegate`].
42    pub fn new(anchor_above: Offset, anchor_below: Offset) -> TextSelectionToolbarLayoutDelegate {
43        TextSelectionToolbarLayoutDelegate {
44            anchor_above,
45            anchor_below,
46            fits_above: None,
47        }
48    }
49
50    /// Dart `TextSelectionToolbarLayoutDelegate(fitsAbove:)`.
51    pub fn fits_above(mut self, fits_above: bool) -> TextSelectionToolbarLayoutDelegate {
52        self.fits_above = Some(fits_above);
53        self
54    }
55
56    /// Return the distance from zero that centers `width` as closely as possible to `position`
57    /// from zero while fitting between zero and `max`.
58    pub fn center_on(position: f64, width: f64, max: f64) -> f64 {
59        if position - width / 2.0 < 0.0 {
60            return 0.0;
61        }
62        if position + width / 2.0 > max {
63            return max - width;
64        }
65        position - width / 2.0
66    }
67}
68
69impl SingleChildLayoutDelegate for TextSelectionToolbarLayoutDelegate {
70    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
71        constraints.loosen()
72    }
73
74    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
75        let fits_above = self
76            .fits_above
77            .unwrap_or(self.anchor_above.dy() >= child_size.height());
78        let anchor = if fits_above {
79            self.anchor_above
80        } else {
81            self.anchor_below
82        };
83        Offset::new(
84            Self::center_on(anchor.dx(), child_size.width(), size.width()),
85            if fits_above {
86                (self.anchor_above.dy() - child_size.height()).max(0.0)
87            } else {
88                anchor.dy()
89            },
90        )
91    }
92
93    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
94        old_delegate
95            .as_any()
96            .downcast_ref::<TextSelectionToolbarLayoutDelegate>()
97            .is_none_or(|old| {
98                self.anchor_above != old.anchor_above
99                    || self.anchor_below != old.anchor_below
100                    || self.fits_above != old.fits_above
101            })
102    }
103
104    fn as_any(&self) -> &dyn Any {
105        self
106    }
107}
108
109impl fmt::Display for TextSelectionToolbarLayoutDelegate {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(f, "TextSelectionToolbarLayoutDelegate")
112    }
113}