waft_widgets/widgets/
text_selection_toolbar_layout_delegate.rs1use std::any::Any;
4use std::fmt::{self, Debug};
5
6use waft_embedder::{Offset, Size};
7use waft_rendering::{BoxConstraints, SingleChildLayoutDelegate};
8
9#[derive(Debug)]
20pub struct TextSelectionToolbarLayoutDelegate {
21 pub anchor_above: Offset,
25 pub anchor_below: Offset,
30 pub fits_above: Option<bool>,
38}
39
40impl TextSelectionToolbarLayoutDelegate {
41 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 pub fn fits_above(mut self, fits_above: bool) -> TextSelectionToolbarLayoutDelegate {
52 self.fits_above = Some(fits_above);
53 self
54 }
55
56 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}