Skip to main content

xrack_layout/
tooltip.rs

1use crate::{LayoutContext, LayoutNode, Point, Rect, Size, TextMeasurer, linear};
2use std::{
3    collections::BTreeMap,
4    time::{Duration, Instant},
5};
6use xrack_runtime::{Color, Length, Node, RowKey, is_window_overlay};
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub(crate) enum Source {
10    #[default]
11    Pointer,
12    Focus,
13    Touch,
14}
15
16#[derive(Clone, Copy, Debug)]
17enum Anchor {
18    Pointer(Point),
19    Focus,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub(crate) struct TooltipKey {
24    owner: Vec<usize>,
25    slot: usize,
26    row: Option<RowKey>,
27    source: Source,
28}
29
30impl TooltipKey {
31    fn new(scene: &Node, path: &[usize], source: Source) -> Option<Self> {
32        let (slot, _) = attached(scene.at_path(path)?)?;
33        Some(Self {
34            owner: path.to_vec(),
35            slot,
36            row: scene.row_key_at(path),
37            source,
38        })
39    }
40
41    fn node<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
42        if scene.row_key_at(&self.owner) != self.row {
43            return None;
44        }
45        scene
46            .at_path(&self.owner)?
47            .child_at(self.slot)
48            .filter(|node| has_content(node))
49    }
50}
51
52fn attached(owner: &Node) -> Option<(usize, &Node)> {
53    owner
54        .materialized_children()
55        .find(|(_, node)| has_content(node))
56}
57
58#[doc(hidden)]
59pub fn tooltip_text(owner: &Node) -> Option<&str> {
60    let text = attached(owner)?.1.text("text")?.trim();
61    (!text.is_empty()).then_some(text)
62}
63
64fn has_content(node: &Node) -> bool {
65    node.kind == "Tooltip"
66        && node.is_visible()
67        && (node
68            .text("text")
69            .is_some_and(|text| !text.trim().is_empty())
70            || node.children.iter().any(Node::is_visible))
71}
72
73pub(crate) fn hovered(
74    scene: &Node,
75    layout: &LayoutNode,
76    scope: &[usize],
77    point: Point,
78    source: Source,
79) -> Option<TooltipKey> {
80    fn path_at(node: &Node, item: &LayoutNode, point: Point, path: &mut Vec<usize>) -> bool {
81        if !item.contains_subtree_point(point) {
82            return false;
83        }
84        for (index, child, layout) in item.children_in_paint_order(node).rev() {
85            if is_window_overlay(child.kind) {
86                continue;
87            }
88            path.push(index);
89            if path_at(child, layout, point, path) {
90                return true;
91            }
92            path.pop();
93        }
94        item.map_from_window(point)
95            .is_some_and(|point| item.bounds.contains(point))
96    }
97    let mut path = scope.to_vec();
98    if !path_at(
99        scene.at_path(scope)?,
100        layout.at_path(scope)?,
101        point,
102        &mut path,
103    ) {
104        return None;
105    }
106    find_owner(scene, &path, scope.len(), source)
107}
108
109pub(crate) fn focused(scene: &Node, path: &[usize], scope: &[usize]) -> Option<TooltipKey> {
110    if !path.starts_with(scope) {
111        return None;
112    }
113    find_owner(scene, path, scope.len(), Source::Focus)
114}
115
116fn find_owner(
117    scene: &Node,
118    path: &[usize],
119    min_depth: usize,
120    source: Source,
121) -> Option<TooltipKey> {
122    (min_depth..=path.len())
123        .rev()
124        .find_map(|depth| TooltipKey::new(scene, &path[..depth], source))
125}
126
127#[derive(Clone, Copy, Debug)]
128enum Phase {
129    Waiting(Instant),
130    Showing { since: Instant, anchor: Anchor },
131    Suppressed,
132}
133
134#[derive(Clone, Debug, Default)]
135pub(crate) struct TooltipState {
136    pub(crate) source: Source,
137    key: Option<TooltipKey>,
138    phase: Option<Phase>,
139    deadline: Option<Instant>,
140    suppress_next: bool,
141}
142
143fn after(now: Instant, millis: i64) -> Instant {
144    now.checked_add(Duration::from_millis(millis.max(0) as u64))
145        .unwrap_or_else(|| now + Duration::from_secs(86_400))
146}
147
148impl TooltipState {
149    pub(crate) fn touch_key(&self, layout: &LayoutNode, scope: &[usize]) -> Option<TooltipKey> {
150        self.key
151            .as_ref()
152            .filter(|key| {
153                key.owner.starts_with(scope)
154                    && layout.at_path(&key.owner).is_some_and(|owner| {
155                        let bounds = owner.visible_window_bounds(owner.bounds);
156                        owner.visible && bounds.width > 0.0 && bounds.height > 0.0
157                    })
158            })
159            .cloned()
160    }
161
162    pub(crate) fn show_touch(&mut self, key: TouchTooltip, now: Instant) {
163        *self = Self {
164            source: Source::Touch,
165            key: Some(key.0),
166            phase: Some(Phase::Showing {
167                since: now,
168                anchor: Anchor::Focus,
169            }),
170            ..Self::default()
171        };
172    }
173
174    pub(crate) fn focus_source(&mut self) {
175        self.source = Source::Focus;
176        self.suppress_next = false;
177    }
178    pub(crate) fn dismiss(&mut self) -> bool {
179        let was_visible = self.visible();
180        self.phase = Some(Phase::Suppressed);
181        self.deadline = None;
182        self.suppress_next = self.key.is_none();
183        was_visible
184    }
185
186    pub(crate) fn pointer_left(&mut self) -> bool {
187        if self.source != Source::Pointer {
188            return false;
189        }
190        let visible = self.visible();
191        self.key = None;
192        self.phase = None;
193        self.deadline = None;
194        self.suppress_next = false;
195        visible
196    }
197
198    fn visible(&self) -> bool {
199        matches!(self.phase, Some(Phase::Showing { .. }))
200    }
201
202    pub(crate) fn deadline(&self) -> Option<Instant> {
203        self.deadline
204    }
205
206    pub(crate) fn advance(
207        &mut self,
208        scene: &Node,
209        key: Option<TooltipKey>,
210        pointer: Option<Point>,
211        blocked: bool,
212        now: Instant,
213    ) -> bool {
214        let was_visible = self.visible();
215        let changed = self.key != key;
216        self.deadline = None;
217        let suppress = std::mem::take(&mut self.suppress_next) || blocked;
218        if changed {
219            self.key = key;
220            self.phase = Some(Phase::Waiting(now));
221        }
222        let Some(key) = &self.key else {
223            self.phase = None;
224            return was_visible;
225        };
226        let Some(node) = key.node(scene) else {
227            self.phase = None;
228            return was_visible;
229        };
230        if suppress {
231            self.phase = Some(Phase::Suppressed);
232        }
233        if let Some(Phase::Waiting(since)) = self.phase {
234            let show = after(since, node.int("delay").unwrap_or(600));
235            if now < show {
236                self.deadline = Some(show);
237            } else {
238                let anchor = match key.source {
239                    Source::Focus | Source::Touch => Anchor::Focus,
240                    Source::Pointer => pointer.map_or(Anchor::Focus, Anchor::Pointer),
241                };
242                self.phase = Some(Phase::Showing { since: now, anchor });
243            }
244        }
245        if let Some(Phase::Showing { since, .. }) = self.phase
246            && let Some(timeout) = node.int("timeout").filter(|timeout| *timeout >= 0)
247        {
248            let hide = after(since, timeout);
249            if now >= hide {
250                self.phase = Some(Phase::Suppressed);
251            } else {
252                self.deadline = Some(hide);
253            }
254        }
255        self.visible() != was_visible || changed && was_visible
256    }
257
258    pub(crate) fn popup<'a>(
259        &self,
260        scene: &'a Node,
261        layout: &LayoutNode,
262        scope: &[usize],
263    ) -> Option<TooltipPopup<'a>> {
264        let Some(Phase::Showing { anchor, .. }) = self.phase else {
265            return None;
266        };
267        let key = self.key.as_ref()?;
268        if !key.owner.starts_with(scope) {
269            return None;
270        }
271        let node = key.node(scene)?;
272        let owner = layout.at_path(&key.owner)?;
273        let bounds = owner.visible_window_bounds(owner.bounds);
274        if !owner.visible || bounds.width <= 0.0 || bounds.height <= 0.0 {
275            return None;
276        }
277        Some(TooltipPopup {
278            node,
279            anchor,
280            owner: bounds,
281            layout_direction: node
282                .layout_direction()
283                .or(owner.layout_direction_override()),
284        })
285    }
286}
287
288#[doc(hidden)]
289#[derive(PartialEq, Eq)]
290pub struct TouchTooltip(TooltipKey);
291
292impl TouchTooltip {
293    pub(crate) fn at(
294        scene: &Node,
295        layout: &LayoutNode,
296        scope: &[usize],
297        point: Point,
298        now: Instant,
299    ) -> Option<(Self, Instant)> {
300        let key = hovered(scene, layout, scope, point, Source::Touch)?;
301        let node = key.node(scene)?;
302        if node.int("timeout") == Some(0) {
303            return None;
304        }
305        // A tooltip with no hover delay still requires a deliberate touch hold.
306        let deadline = after(now, node.int("delay").unwrap_or(600).max(500));
307        Some((Self(key), deadline))
308    }
309}
310
311pub struct TooltipPopup<'a> {
312    pub node: &'a Node,
313    anchor: Anchor,
314    owner: Rect,
315    layout_direction: Option<xrack_runtime::LayoutDirection>,
316}
317
318/// Place a tooltip surface in window coordinates, using the normal text and layout engine.
319pub fn layout_tooltip(
320    popup: TooltipPopup<'_>,
321    viewport: Rect,
322    text: &mut impl TextMeasurer,
323) -> (Node, LayoutNode) {
324    let TooltipPopup {
325        node,
326        anchor,
327        owner,
328        layout_direction,
329    } = popup;
330    let area = viewport.inset(6.0);
331    let mut surface = Node::new("VerticalLayout", None);
332    if let Some(opacity) = node.properties.get("opacity") {
333        surface.properties.insert("opacity", opacity.clone());
334    }
335    surface.properties.insert(
336        "background",
337        node.properties
338            .get("background")
339            .cloned()
340            .unwrap_or_else(|| Color(0x25334bff).into()),
341    );
342    surface.properties.insert(
343        "padding",
344        Length(f64::from(
345            node.length("padding").unwrap_or(8.0).clamp(0.0, 32.0),
346        ))
347        .into(),
348    );
349    surface
350        .properties
351        .insert("border-radius", Length(5.0).into());
352    surface
353        .properties
354        .insert("border-width", Length(1.0).into());
355    surface
356        .properties
357        .insert("border-color", Color(0x627596ff).into());
358    if let Some(value) = node.text("text") {
359        let mut label = Node::new("Text", None);
360        label.properties.insert("text", value.to_owned().into());
361        for name in [
362            "font",
363            "font-size",
364            "font-family",
365            "font-weight",
366            "font-italic",
367        ] {
368            if let Some(value) = node.properties.get(name) {
369                label.properties.insert(name, value.clone());
370            }
371        }
372        if label.font_size().is_none() && text.default_font_size().is_none() {
373            label.properties.insert("font-size", Length(14.0).into());
374        }
375        if let Some(color) = node.color("color") {
376            label.properties.insert("color", color.into());
377        }
378        surface.children.push(label);
379    } else {
380        surface.children.clone_from(&node.children);
381    }
382
383    let cap = node
384        .relative_length("max-width", area.width)
385        .unwrap_or(320.0)
386        .clamp(0.0, area.width);
387    let width = node
388        .relative_length("width", area.width)
389        .unwrap_or_else(|| {
390            linear::measure(&surface, Size::new(cap, area.height), text)
391                .x
392                .preferred
393        })
394        .clamp(0.0, cap);
395    let height = node
396        .relative_length("height", area.height)
397        .unwrap_or_else(|| {
398            linear::measure(&surface, Size::new(width, area.height), text)
399                .y
400                .preferred
401        })
402        .clamp(0.0, area.height);
403    let (x, below, above) = match anchor {
404        Anchor::Pointer(point) => (point.x + 12.0, point.y + 18.0, point.y - 8.0),
405        Anchor::Focus => (
406            owner.x + (owner.width - width) * 0.5,
407            owner.y + owner.height + 8.0,
408            owner.y - 8.0,
409        ),
410    };
411    let bottom = area.y + area.height;
412    let y = if below + height <= bottom || bottom - below >= above - area.y {
413        below
414    } else {
415        above - height
416    };
417    let bounds = Rect::new(
418        x.clamp(area.x, (area.x + area.width - width).max(area.x)),
419        y.clamp(area.y, (bottom - height).max(area.y)),
420        width,
421        height,
422    );
423    let mut context = LayoutContext {
424        row_key: None,
425        layout_direction,
426        anchor: None,
427        resolved_list_scroll: None,
428        row_layouts: None,
429        ancestor_shapes: None,
430        space: None,
431        text,
432        offsets: &BTreeMap::new(),
433        input: None,
434        path: Vec::new(),
435        viewport,
436    };
437    let layout = context.place(&surface, bounds, area, true, true, None);
438    (surface, layout)
439}