Skip to main content

waft_widgets/widgets/
desktop_text_selection_toolbar_layout_delegate.rs

1//! Flutter counterpart: `widgets/desktop_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/// Positions the toolbar at [`anchor`](Self::anchor) if it fits, otherwise moves it so that it
10/// just fits fully on-screen.
11///
12/// See also:
13///
14///   * `desktopTextSelectionControls`, which uses this to position itself.
15///   * `cupertinoDesktopTextSelectionControls`, which uses this to position itself.
16///   * [`crate::TextSelectionToolbarLayoutDelegate`], which does a similar layout for the
17///     mobile text selection toolbars.
18#[derive(Debug)]
19pub struct DesktopTextSelectionToolbarLayoutDelegate {
20    /// The point at which to render the menu, if possible.
21    ///
22    /// Should be provided in local coordinates.
23    pub anchor: Offset,
24}
25
26impl DesktopTextSelectionToolbarLayoutDelegate {
27    /// Creates an instance of [`DesktopTextSelectionToolbarLayoutDelegate`].
28    pub fn new(anchor: Offset) -> DesktopTextSelectionToolbarLayoutDelegate {
29        DesktopTextSelectionToolbarLayoutDelegate { anchor }
30    }
31}
32
33impl SingleChildLayoutDelegate for DesktopTextSelectionToolbarLayoutDelegate {
34    fn get_constraints_for_child(&self, constraints: BoxConstraints) -> BoxConstraints {
35        constraints.loosen()
36    }
37
38    fn get_position_for_child(&self, size: Size, child_size: Size) -> Offset {
39        let overhang = Offset::new(
40            self.anchor.dx() + child_size.width() - size.width(),
41            self.anchor.dy() + child_size.height() - size.height(),
42        );
43        Offset::new(
44            if overhang.dx() > 0.0 {
45                self.anchor.dx() - overhang.dx()
46            } else {
47                self.anchor.dx()
48            },
49            if overhang.dy() > 0.0 {
50                self.anchor.dy() - overhang.dy()
51            } else {
52                self.anchor.dy()
53            },
54        )
55    }
56
57    fn should_relayout(&self, old_delegate: &dyn SingleChildLayoutDelegate) -> bool {
58        old_delegate
59            .as_any()
60            .downcast_ref::<DesktopTextSelectionToolbarLayoutDelegate>()
61            .is_none_or(|old| self.anchor != old.anchor)
62    }
63
64    fn as_any(&self) -> &dyn Any {
65        self
66    }
67}
68
69impl fmt::Display for DesktopTextSelectionToolbarLayoutDelegate {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        write!(f, "DesktopTextSelectionToolbarLayoutDelegate")
72    }
73}