Skip to main content

fission_core/
hit_test.rs

1use crate::env::ScrollStateMap;
2use crate::ui::custom_render::downcast_render_object;
3use fission_diagnostics::prelude as diag;
4use fission_ir::{CoreIR, LayoutOp, Op, PaintOp, WidgetId};
5use fission_layout::{LayoutPoint, LayoutSnapshot};
6use glam::{Mat4, Vec4};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum FocusDirection {
10    Up,
11    Down,
12    Left,
13    Right,
14}
15
16pub fn hit_test(
17    ir: &CoreIR,
18    layout: &LayoutSnapshot,
19    scroll_map: &ScrollStateMap,
20    point: LayoutPoint,
21) -> Option<WidgetId> {
22    hit_test_internal(ir, layout, Some(scroll_map), point)
23}
24
25pub fn hit_test_with_scroll(
26    ir: &CoreIR,
27    layout: &LayoutSnapshot,
28    scroll_map: &ScrollStateMap,
29    point: LayoutPoint,
30) -> Option<WidgetId> {
31    hit_test_internal(ir, layout, Some(scroll_map), point)
32}
33
34fn hit_test_internal(
35    ir: &CoreIR,
36    layout: &LayoutSnapshot,
37    scroll_map: Option<&ScrollStateMap>,
38    point: LayoutPoint,
39) -> Option<WidgetId> {
40    let result = ir
41        .root
42        .and_then(|root| hit_test_recursive(root, ir, layout, scroll_map, point));
43
44    if let Some(id) = result {
45        diag::emit(
46            diag::DiagCategory::Input,
47            diag::DiagLevel::Debug,
48            diag::DiagEventKind::InputEvent {
49                kind: "hit_test_result".into(),
50                target: Some(id.as_u128()),
51                position: Some((point.x, point.y)),
52            },
53        );
54    }
55    result
56}
57
58fn hit_test_recursive(
59    node_id: WidgetId,
60    ir: &CoreIR,
61    layout: &LayoutSnapshot,
62    scroll_map: Option<&ScrollStateMap>,
63    point: LayoutPoint,
64) -> Option<WidgetId> {
65    let node = ir.nodes.get(&node_id)?;
66    let geom = layout.get_node_geometry(node_id)?;
67
68    let is_clip_container = matches!(
69        node.op,
70        Op::Layout(LayoutOp::Clip { .. }) | Op::Layout(LayoutOp::Scroll { .. })
71    );
72
73    if is_clip_container && !geom.rect.contains(point) {
74        return None;
75    }
76
77    let mut child_point = point;
78
79    if let (Some(map), Op::Layout(LayoutOp::Scroll { direction, .. })) = (scroll_map, &node.op) {
80        let offset = map.get_offset(node_id);
81        match direction {
82            fission_ir::FlexDirection::Column => {
83                child_point.y += offset;
84            }
85            fission_ir::FlexDirection::Row => {
86                child_point.x += offset;
87            }
88        }
89    }
90
91    if let Op::Layout(LayoutOp::Transform { transform }) = &node.op {
92        let mat = Mat4::from_cols_array(transform);
93        let inv = mat.inverse();
94        let local_x = point.x - geom.rect.origin.x;
95        let local_y = point.y - geom.rect.origin.y;
96        let p = Vec4::new(local_x, local_y, 0.0, 1.0);
97        let transformed = inv * p;
98        child_point = LayoutPoint::new(
99            transformed.x + geom.rect.origin.x,
100            transformed.y + geom.rect.origin.y,
101        );
102    }
103
104    for child_id in node.children.iter().rev() {
105        if let Some(hit) = hit_test_recursive(*child_id, ir, layout, scroll_map, child_point) {
106            return Some(hit);
107        }
108    }
109
110    // --- Custom render object hit-test ----------------------------------
111    // If this node has a custom render object, delegate to it before
112    // falling through to the standard semantics-based check.
113    if geom.rect.contains(point) {
114        if let Some(any_ro) = ir.custom_render_objects.get(&node_id) {
115            if let Some(render_obj) = downcast_render_object(any_ro) {
116                let local_point =
117                    LayoutPoint::new(point.x - geom.rect.origin.x, point.y - geom.rect.origin.y);
118                let result = render_obj.hit_test(local_point, geom.rect);
119                if result.hit {
120                    return Some(node_id);
121                }
122            }
123        }
124    }
125
126    if geom.rect.contains(point) && paint_op_blocks_hit_testing(&node.op) {
127        return Some(node_id);
128    }
129
130    let mut current_is_hit = false;
131    if geom.rect.contains(point) {
132        match &node.op {
133            Op::Layout(LayoutOp::Scroll { .. }) | Op::Layout(LayoutOp::Embed { .. }) => {
134                current_is_hit = true;
135            }
136            Op::Semantics(semantics) => {
137                if !semantics.actions.entries.is_empty()
138                    || semantics.focusable
139                    || semantics.draggable
140                    || semantics.scrollable_x
141                    || semantics.scrollable_y
142                {
143                    current_is_hit = true;
144                }
145            }
146            _ => {}
147        }
148    }
149
150    if current_is_hit {
151        Some(node_id)
152    } else {
153        None
154    }
155}
156
157fn paint_op_blocks_hit_testing(op: &Op) -> bool {
158    match op {
159        Op::Paint(PaintOp::DrawRect {
160            fill,
161            stroke,
162            shadow,
163            ..
164        }) => fill.is_some() || stroke.is_some() || shadow.is_some(),
165        Op::Paint(PaintOp::DrawText { text, .. }) => !text.is_empty(),
166        Op::Paint(PaintOp::DrawRichText { runs, .. }) => {
167            runs.iter().any(|run| !run.text.is_empty())
168        }
169        Op::Paint(PaintOp::DrawImage { .. }) => true,
170        Op::Paint(PaintOp::DrawPath { fill, stroke, .. })
171        | Op::Paint(PaintOp::DrawSvg { fill, stroke, .. }) => fill.is_some() || stroke.is_some(),
172        _ => false,
173    }
174}
175
176pub fn find_next_focus_node(
177    ir: &CoreIR,
178    current: Option<WidgetId>,
179    reverse: bool,
180) -> Option<WidgetId> {
181    // Identify current scope if focused node is provided
182    let (current_scope_id, current_is_barrier) = if let Some(id) = current {
183        let scope = find_parent_scope(id, ir);
184        let mut is_barrier = false;
185        if let Some(sid) = scope {
186            if let Some(node) = ir.nodes.get(&sid) {
187                if let Op::Semantics(s) = &node.op {
188                    is_barrier = s.is_focus_barrier;
189                }
190            }
191        }
192        (scope, is_barrier)
193    } else {
194        (None, false)
195    };
196
197    let nodes_in_scope = if current_is_barrier {
198        let scope_id = current_scope_id.unwrap();
199        let mut list = Vec::new();
200        // Start recursion on CHILDREN of the barrier root to avoid skipping it
201        if let Some(node) = ir.nodes.get(&scope_id) {
202            for child in &node.children {
203                collect_focusable_nodes(*child, ir, &mut list, true, 0);
204            }
205        }
206        sort_focusable_nodes(ir, list)
207    } else {
208        get_all_focusable_nodes(ir)
209    };
210
211    if nodes_in_scope.is_empty() {
212        return None;
213    }
214
215    let idx = if let Some(curr_id) = current {
216        nodes_in_scope.iter().position(|id| *id == curr_id)
217    } else {
218        None
219    };
220
221    match idx {
222        Some(i) => {
223            if reverse {
224                if i == 0 {
225                    Some(nodes_in_scope[nodes_in_scope.len() - 1])
226                } else {
227                    Some(nodes_in_scope[i - 1])
228                }
229            } else if i == nodes_in_scope.len() - 1 {
230                Some(nodes_in_scope[0])
231            } else {
232                Some(nodes_in_scope[i + 1])
233            }
234        }
235        None => {
236            if reverse {
237                Some(nodes_in_scope[nodes_in_scope.len() - 1])
238            } else {
239                Some(nodes_in_scope[0])
240            }
241        }
242    }
243}
244
245pub fn get_all_focusable_nodes(ir: &CoreIR) -> Vec<WidgetId> {
246    let mut list = Vec::new();
247    if let Some(root) = ir.root {
248        collect_focusable_nodes(root, ir, &mut list, false, 0);
249    }
250    sort_focusable_nodes(ir, list)
251}
252
253fn sort_focusable_nodes(ir: &CoreIR, mut list: Vec<(WidgetId, usize)>) -> Vec<WidgetId> {
254    list.sort_by(|(id_a, order_a), (id_b, order_b)| {
255        let idx_a = ir.nodes.get(id_a).and_then(|n| {
256            if let Op::Semantics(s) = &n.op {
257                s.focus_index
258            } else {
259                None
260            }
261        });
262        let idx_b = ir.nodes.get(id_b).and_then(|n| {
263            if let Op::Semantics(s) = &n.op {
264                s.focus_index
265            } else {
266                None
267            }
268        });
269
270        match (idx_a, idx_b) {
271            (Some(a), Some(b)) => a.cmp(&b).then(order_a.cmp(order_b)),
272            (Some(_), None) => std::cmp::Ordering::Less,
273            (None, Some(_)) => std::cmp::Ordering::Greater,
274            (None, None) => order_a.cmp(order_b),
275        }
276    });
277    list.into_iter().map(|(id, _)| id).collect()
278}
279
280fn collect_focusable_nodes(
281    node_id: WidgetId,
282    ir: &CoreIR,
283    list: &mut Vec<(WidgetId, usize)>,
284    stop_at_barriers: bool,
285    mut order: usize,
286) {
287    if let Some(node) = ir.nodes.get(&node_id) {
288        let mut is_barrier = false;
289        if let Op::Semantics(s) = &node.op {
290            if s.focusable && !s.disabled {
291                list.push((node_id, order));
292                order += 1;
293            }
294            is_barrier = s.is_focus_barrier;
295        }
296
297        if stop_at_barriers && is_barrier {
298            return;
299        }
300
301        let mut children = node.children.clone();
302        // Internal sort within branches still useful for tree-order
303        children.sort_by_key(|cid| {
304            ir.nodes
305                .get(cid)
306                .and_then(|n| {
307                    if let Op::Semantics(s) = &n.op {
308                        s.focus_index
309                    } else {
310                        None
311                    }
312                })
313                .unwrap_or(i32::MAX)
314        });
315
316        for child in children {
317            collect_focusable_nodes(child, ir, list, stop_at_barriers, order);
318            order = list.last().map(|(_, o)| *o + 1).unwrap_or(order);
319        }
320    }
321}
322
323fn find_parent_scope(node_id: WidgetId, ir: &CoreIR) -> Option<WidgetId> {
324    let mut curr = ir.nodes.get(&node_id)?.parent;
325    while let Some(pid) = curr {
326        if let Some(node) = ir.nodes.get(&pid) {
327            if let Op::Semantics(s) = &node.op {
328                if s.is_focus_scope {
329                    return Some(pid);
330                }
331            }
332            curr = node.parent;
333        } else {
334            break;
335        }
336    }
337    None
338}
339
340pub fn find_neighbor_focus_node(
341    ir: &CoreIR,
342    layout: &LayoutSnapshot,
343    current: WidgetId,
344    direction: FocusDirection,
345) -> Option<WidgetId> {
346    let current_rect = layout.get_node_rect(current)?;
347    let focusable_nodes = get_all_focusable_nodes(ir);
348
349    let mut best_candidate = None;
350    let mut best_dist = f32::INFINITY;
351
352    let (cx, cy) = (
353        current_rect.x() + current_rect.width() / 2.0,
354        current_rect.y() + current_rect.height() / 2.0,
355    );
356
357    for node_id in focusable_nodes {
358        if node_id == current {
359            continue;
360        }
361        let rect = match layout.get_node_rect(node_id) {
362            Some(r) => r,
363            None => continue,
364        };
365
366        let (nx, ny) = (
367            rect.x() + rect.width() / 2.0,
368            rect.y() + rect.height() / 2.0,
369        );
370
371        let is_in_dir = match direction {
372            FocusDirection::Up => ny < cy && (nx - cx).abs() < (ny - cy).abs(),
373            FocusDirection::Down => ny > cy && (nx - cx).abs() < (ny - cy).abs(),
374            FocusDirection::Left => nx < cx && (ny - cy).abs() < (nx - cx).abs(),
375            FocusDirection::Right => nx > cx && (ny - cy).abs() < (nx - cx).abs(),
376        };
377
378        if is_in_dir {
379            let dist = (nx - cx).powi(2) + (ny - cy).powi(2);
380            if dist < best_dist {
381                best_dist = dist;
382                best_candidate = Some(node_id);
383            }
384        }
385    }
386
387    best_candidate
388}