Skip to main content

slint_interpreter/
highlight.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! Highlight support for running component instances.
5//!
6use crate::instance::SubComponentInstance;
7use crate::prelude::*;
8use i_slint_compiler::diagnostics::SourceLocation;
9use i_slint_compiler::llr::ItemInstanceIdx;
10use i_slint_compiler::object_tree::ElementRc;
11use i_slint_compiler::source_path::SourcePath;
12use i_slint_core::graphics::euclid;
13use i_slint_core::item_tree::{ItemTreeRc, TraversalOrder, VisitChildrenResult};
14use i_slint_core::items::ItemRc;
15use i_slint_core::lengths::{ItemTransform, LogicalPoint, LogicalRect, LogicalVector};
16use std::collections::{BTreeMap, HashSet};
17
18/// The rectangle of an element, which may be rotated around its center.
19#[derive(Clone, Copy, Debug, Default)]
20pub struct HighlightedRect {
21    /// The element's geometry.
22    pub rect: LogicalRect,
23    /// In degrees, around the center of the element.
24    pub angle: f32,
25    /// Whether `rect` and `angle` describe the element's rendered shape.
26    ///
27    /// The two of them describe a rotated rectangle.
28    /// An element renders as one while its own and its ancestors' transforms keep its two axes
29    /// at a right angle.
30    /// A non-uniform scale combined with a rotation shears it into a parallelogram instead,
31    /// which only `local_rect` still describes.
32    pub renders_as_rectangle: bool,
33    /// The element's rectangle in its parent's coordinate system.
34    ///
35    /// This is what the source `x`, `y`, `width` and `height` describe.
36    /// Unlike `rect`, no transform of the element or of any of its ancestors applies to it.
37    pub local_rect: LogicalRect,
38    /// Maps this instance's parent coordinate system to root coordinates.
39    ///
40    /// Invert it to turn a position picked in root coordinates into one that can be written to
41    /// the source.
42    /// It is composed from the instance's own ancestors,
43    /// so it stays correct even if the element is positioned outside of
44    /// (or with a negative offset relative to) its parent.
45    pub parent_transform: ItemTransform,
46    /// Evaluated parent-relative rotation in degrees, including complete turns.
47    pub transform_rotation: f32,
48    /// Evaluated corner radii in logical pixels.
49    pub corner_radii: CornerRadii,
50}
51/// Evaluated rectangle corner radii in logical pixels.
52#[derive(Clone, Copy, Debug, Default)]
53pub struct CornerRadii {
54    /// Top-left radius.
55    pub top_left: f32,
56    /// Top-right radius.
57    pub top_right: f32,
58    /// Bottom-left radius.
59    pub bottom_left: f32,
60    /// Bottom-right radius.
61    pub bottom_right: f32,
62}
63
64impl HighlightedRect {
65    /// Absolute origin of this instance's parent coordinate system, in root coordinates.
66    pub fn parent_origin(&self) -> LogicalPoint {
67        self.parent_transform.transform_point(LogicalPoint::default().cast()).cast()
68    }
69
70    /// Absolute rotation (in degrees) of this instance's parent coordinate system.
71    ///
72    /// `angle - parent_rotation()` yields the element's own rotation relative to its parent,
73    /// which matches `transform-rotation` modulo complete turns.
74    /// Use `transform_rotation` to retain those turns.
75    pub fn parent_rotation(&self) -> f32 {
76        self.parent_transform.m12.atan2(self.parent_transform.m11).to_degrees()
77    }
78
79    /// Returns true if `position` lies inside the (potentially rotated) rectangle.
80    pub fn contains(&self, position: LogicalPoint) -> bool {
81        let center = self.rect.center();
82        let rotation = euclid::Rotation2D::radians((-self.angle).to_radians());
83        let transformed = center + rotation.transform_vector(position - center);
84        self.rect.contains(transformed)
85    }
86}
87
88/// A rendered item under a point and one source element that represents it.
89#[derive(Clone, Debug)]
90pub struct ElementCandidate {
91    /// Source element represented by the runtime item.
92    pub source_location: i_slint_compiler::diagnostics::SourceLocation,
93    /// Runtime geometry of the source element.
94    pub geometry: HighlightedRect,
95    /// Position of this runtime item among the instances of the source element.
96    pub instance_index: usize,
97}
98
99/// Return the geometry of every runtime item whose source location covers
100/// the given `(path, offset)` pair.
101pub(crate) fn component_positions(
102    root: &VRc<ItemTreeVTable, Instance>,
103    path: &SourcePath,
104    offset: u32,
105) -> Vec<HighlightedRect> {
106    let sources = SourceOccurrences::new(root);
107    sources.matching_occurrences(path, offset).map(|(_, geometry)| geometry).collect()
108}
109
110#[cfg(feature = "internal")]
111pub(crate) fn component_item(
112    root: &VRc<ItemTreeVTable, Instance>,
113    path: &SourcePath,
114    offset: u32,
115    instance_index: usize,
116) -> Option<ItemRc> {
117    let sources = SourceOccurrences::new(root);
118    sources
119        .matching_occurrences(path, offset)
120        .nth(instance_index)
121        .map(|(item_index, _)| sources.items[item_index].as_item_rc())
122}
123
124pub(crate) fn element_candidates_at(
125    root: &VRc<ItemTreeVTable, Instance>,
126    position: LogicalPoint,
127) -> Vec<ElementCandidate> {
128    let sources = SourceOccurrences::new(root);
129    let root_item_tree = VRc::into_dyn(root.clone());
130    let mut runtime_items = Vec::new();
131    collect_runtime_items_front_to_back(&root_item_tree, 0, Some(root), &mut runtime_items);
132
133    let mut candidates = Vec::new();
134    let mut seen = HashSet::new();
135    let mut seen_enclosing_elements = HashSet::new();
136    for (instance, flat_index) in runtime_items {
137        let Some(&item_index) =
138            sources.item_indices.get(&(core::ptr::from_ref(&*instance), flat_index))
139        else {
140            continue;
141        };
142        let item = &sources.items[item_index];
143        let Some(geometry) = item.geometry(root) else { continue };
144        if !geometry.contains(position) || !item.as_item_rc().is_visible() {
145            continue;
146        }
147
148        let mut add_candidates = |source_location: &SourceLocation, item_indices: &[usize]| {
149            for &item_index in item_indices {
150                let Some(candidate) = sources.candidate_at(source_location, item_index, position)
151                else {
152                    continue;
153                };
154                if let Some(key) = source_key(source_location)
155                    && seen.insert((key, candidate.instance_index))
156                {
157                    candidates.push(candidate);
158                }
159            }
160        };
161        let definition = &item.owner.compilation_unit.sub_components[item.owner.sub_component_idx];
162        if let Some(debug_info) = &definition.debug_info
163            && let Some(debug_entries) = debug_info.items.get(item.local_item_index)
164        {
165            for debug_entry in debug_entries.iter().rev() {
166                add_candidates(&debug_entry.source_location, &[item_index]);
167            }
168        }
169
170        let mut owner = Some(item.owner.clone());
171        while let Some(component) = owner {
172            let component_pointer = core::ptr::from_ref(&*component);
173            if seen_enclosing_elements.insert(component_pointer)
174                && let Some((source_location, item_indices)) =
175                    sources.enclosing_elements.get(&component_pointer)
176            {
177                add_candidates(source_location, item_indices);
178            }
179            owner = component.parent.upgrade().map(Pin::new);
180        }
181    }
182    candidates
183}
184
185// The same element can have source ranges of different lengths.
186// Use only its file path and starting byte offset to group those entries.
187type SourceKey = (SourcePath, usize);
188type SourceElements = BTreeMap<SourceKey, SourceElement>;
189
190struct RuntimeItem {
191    instance: VRc<ItemTreeVTable, Instance>,
192    flat_index: usize,
193    owner: Pin<Rc<SubComponentInstance>>,
194    local_item_index: ItemInstanceIdx,
195    geometry: OnceCell<Option<HighlightedRect>>,
196}
197
198impl RuntimeItem {
199    fn as_item_rc(&self) -> ItemRc {
200        ItemRc::new(VRc::into_dyn(self.instance.clone()), self.flat_index as u32)
201    }
202
203    fn geometry(&self, root: &VRc<ItemTreeVTable, Instance>) -> Option<HighlightedRect> {
204        *self.geometry.get_or_init(|| item_geometry(&self.instance, root, self.flat_index))
205    }
206}
207
208#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
209enum SourcePriority {
210    Item,
211    ComponentUse,
212    RepeatedElement,
213}
214
215struct SourceElement {
216    source_location: SourceLocation,
217    // Indices into `SourceOccurrences.items` for the runtime items representing this source element.
218    item_indices: Vec<usize>,
219    priority: SourcePriority,
220    // Maps an index in `SourceOccurrences.items` to its position in `component_positions()`, skipping empty geometry.
221    instance_indices: OnceCell<HashMap<usize, usize>>,
222}
223
224impl SourceElement {
225    fn new(
226        source_location: &SourceLocation,
227        item_indices: Vec<usize>,
228        priority: SourcePriority,
229    ) -> Self {
230        Self {
231            source_location: source_location.clone(),
232            item_indices,
233            priority,
234            instance_indices: OnceCell::new(),
235        }
236    }
237
238    fn occurrences<'a>(
239        &'a self,
240        items: &'a [RuntimeItem],
241        root: &'a VRc<ItemTreeVTable, Instance>,
242    ) -> impl Iterator<Item = (usize, HighlightedRect)> + 'a {
243        self.item_indices.iter().filter_map(move |&item_index| {
244            items[item_index].geometry(root).map(|geometry| (item_index, geometry))
245        })
246    }
247}
248
249struct SourceOccurrences<'a> {
250    root: &'a VRc<ItemTreeVTable, Instance>,
251    items: Vec<RuntimeItem>,
252    // Maps an owning `Instance` and its flat item index to an index in `items`.
253    item_indices: HashMap<(*const Instance, usize), usize>,
254    elements: SourceElements,
255    // Indices into `items` for the items whose geometry represents this component use or repeated row.
256    enclosing_elements: HashMap<*const SubComponentInstance, (SourceLocation, Vec<usize>)>,
257}
258
259impl<'a> SourceOccurrences<'a> {
260    fn new(root: &'a VRc<ItemTreeVTable, Instance>) -> Self {
261        i_slint_core::item_tree::ensure_item_tree_instantiated(&VRc::into_dyn(root.clone()));
262        let mut sources = Self {
263            root,
264            items: Vec::new(),
265            item_indices: HashMap::new(),
266            elements: BTreeMap::new(),
267            enclosing_elements: HashMap::new(),
268        };
269        let mut local_item_indices = HashMap::new();
270        for instance in all_instances(root) {
271            for (flat_index, entry) in instance.item_table.iter().enumerate() {
272                let Some((path, local_item_index)) = entry else { continue };
273                let mut owner = instance.root_sub_component.clone();
274                for &component_index in path {
275                    owner = owner.sub_components[component_index].clone();
276                }
277                let item_index = sources.items.len();
278                local_item_indices
279                    .insert((core::ptr::from_ref(&*owner), *local_item_index), item_index);
280                sources
281                    .item_indices
282                    .insert((core::ptr::from_ref(&*instance), flat_index), item_index);
283                sources.items.push(RuntimeItem {
284                    instance: instance.clone(),
285                    flat_index,
286                    owner,
287                    local_item_index: *local_item_index,
288                    geometry: OnceCell::new(),
289                });
290            }
291        }
292        sources.elements = sources.collect_sources(&root.root_sub_component, &local_item_indices);
293        for element in sources.elements.values_mut() {
294            element.item_indices.sort_unstable();
295            element.item_indices.dedup();
296        }
297        for (_, item_indices) in sources.enclosing_elements.values_mut() {
298            item_indices.sort_unstable();
299            item_indices.dedup();
300        }
301        sources
302    }
303
304    fn collect_sources(
305        &mut self,
306        component: &Pin<Rc<SubComponentInstance>>,
307        // Maps a sub-component instance and an index in its `items` array to an index in `SourceOccurrences.items`.
308        local_item_indices: &HashMap<(*const SubComponentInstance, ItemInstanceIdx), usize>,
309    ) -> SourceElements {
310        let definition = &component.compilation_unit.sub_components[component.sub_component_idx];
311        let mut elements = BTreeMap::new();
312        if let Some(debug_info) = &definition.debug_info {
313            for (local_item_index, debug_entries) in debug_info.items.iter_enumerated() {
314                let Some(&item_index) =
315                    local_item_indices.get(&(core::ptr::from_ref(&**component), local_item_index))
316                else {
317                    continue;
318                };
319                for debug_entry in debug_entries {
320                    merge_sources(
321                        &mut elements,
322                        [SourceElement::new(
323                            &debug_entry.source_location,
324                            vec![item_index],
325                            SourcePriority::Item,
326                        )],
327                    );
328                }
329            }
330        }
331
332        for (component_index, child) in component.sub_components.iter_enumerated() {
333            let child_elements = self.collect_sources(child, local_item_indices);
334            if let Some(source_location) = definition
335                .debug_info
336                .as_ref()
337                .and_then(|debug_info| debug_info.sub_component_use_sites.get(component_index))
338            {
339                let root_items = component_root_items(child, &child_elements, source_location);
340                self.enclosing_elements.insert(
341                    core::ptr::from_ref(&**child),
342                    (source_location.clone(), root_items.clone()),
343                );
344                merge_sources(
345                    &mut elements,
346                    [SourceElement::new(source_location, root_items, SourcePriority::ComponentUse)],
347                );
348            }
349            merge_sources(&mut elements, child_elements.into_values());
350        }
351
352        for (repeated_index, repeater) in component.repeaters.iter_enumerated() {
353            let source_location = definition
354                .debug_info
355                .as_ref()
356                .and_then(|debug_info| debug_info.repeated_elements.get(repeated_index));
357            let mut root_items = Vec::new();
358            for row in repeater.instances_vec() {
359                let row_elements =
360                    self.collect_sources(&row.root_sub_component, local_item_indices);
361                if let Some(source_location) = source_location {
362                    let row_root_items = component_root_items(
363                        &row.root_sub_component,
364                        &row_elements,
365                        source_location,
366                    );
367                    self.enclosing_elements.insert(
368                        core::ptr::from_ref(&*row.root_sub_component),
369                        (source_location.clone(), row_root_items.clone()),
370                    );
371                    root_items.extend(row_root_items);
372                }
373                merge_sources(&mut elements, row_elements.into_values());
374            }
375            if let Some(source_location) = source_location {
376                merge_sources(
377                    &mut elements,
378                    [SourceElement::new(
379                        source_location,
380                        root_items,
381                        SourcePriority::RepeatedElement,
382                    )],
383                );
384            }
385        }
386        elements
387    }
388
389    fn matching_occurrences(
390        &self,
391        path: &SourcePath,
392        offset: u32,
393    ) -> impl Iterator<Item = (usize, HighlightedRect)> {
394        self.elements
395            .values()
396            .filter(|element| source_location_contains(&element.source_location, path, offset))
397            .flat_map(|element| element.occurrences(&self.items, self.root))
398            .collect::<BTreeMap<_, _>>()
399            .into_iter()
400    }
401
402    fn candidate_at(
403        &self,
404        source_location: &SourceLocation,
405        item_index: usize,
406        position: LogicalPoint,
407    ) -> Option<ElementCandidate> {
408        let element = self.elements.get(&source_key(source_location)?)?;
409        let instance_indices = element.instance_indices.get_or_init(|| {
410            element
411                .occurrences(&self.items, self.root)
412                .enumerate()
413                .map(|(instance_index, (item_index, _))| (item_index, instance_index))
414                .collect()
415        });
416        let &instance_index = instance_indices.get(&item_index)?;
417        let item = &self.items[item_index];
418        let geometry = item.geometry(self.root)?;
419        if !geometry.contains(position) || !item.as_item_rc().is_visible() {
420            return None;
421        }
422        Some(ElementCandidate {
423            source_location: element.source_location.clone(),
424            geometry,
425            instance_index,
426        })
427    }
428}
429
430fn source_key(source_location: &SourceLocation) -> Option<SourceKey> {
431    Some((source_location.source_file.as_ref()?.path().clone(), source_location.span.offset))
432}
433
434fn merge_sources(elements: &mut SourceElements, sources: impl IntoIterator<Item = SourceElement>) {
435    for source in sources {
436        let Some(key) = source_key(&source.source_location) else { continue };
437        let element = elements.entry(key).or_insert_with(|| {
438            SourceElement::new(&source.source_location, Vec::new(), source.priority)
439        });
440        if source.priority > element.priority {
441            *element = source;
442        } else if source.priority == element.priority {
443            element.item_indices.extend(source.item_indices);
444        }
445    }
446}
447
448fn component_root_items(
449    component: &SubComponentInstance,
450    elements: &SourceElements,
451    source_location: &SourceLocation,
452) -> Vec<usize> {
453    component.compilation_unit.sub_components[component.sub_component_idx]
454        .debug_info
455        .as_ref()
456        .and_then(|debug_info| source_key(&debug_info.source_location))
457        .or_else(|| source_key(source_location))
458        .and_then(|key| elements.get(&key))
459        .map(|element| element.item_indices.clone())
460        .unwrap_or_default()
461}
462
463/// Look up the `(ElementRc, index)` tuples whose `debug` entries cover
464/// the given source offset. Uses the `TypeLoader` stored on the instance
465/// (if available) to walk the original object-tree `Document`.
466pub(crate) fn element_node_at_source_code_position(
467    instance: &VRc<ItemTreeVTable, Instance>,
468    path: &SourcePath,
469    offset: u32,
470) -> Vec<(ElementRc, usize)> {
471    let Some(type_loader) = instance.type_loaders.type_loader.as_ref() else {
472        return Vec::new();
473    };
474    let Some(doc) = type_loader.get_document(path) else {
475        return Vec::new();
476    };
477    let mut result = Vec::new();
478    // `inner_components` lists every component defined in the file,
479    // exported or not.
480    for component in &doc.inner_components {
481        visit_element_for_position(&component.root_element, path, offset, &mut result);
482    }
483    result
484}
485
486fn visit_element_for_position(
487    element: &ElementRc,
488    path: &SourcePath,
489    offset: u32,
490    result: &mut Vec<(ElementRc, usize)>,
491) {
492    if element.borrow().repeated.is_some() {
493        // The children of a repeated element live in the component the
494        // repeater pass wrapped around it, which is not part of
495        // `inner_components` — descend explicitly. The wrapper's root
496        // element carries the same source node as the repeated element.
497        let base = match &element.borrow().base_type {
498            i_slint_compiler::element_type::ElementType::Component(c) => {
499                Some(c.root_element.clone())
500            }
501            _ => None,
502        };
503        if let Some(root) = base {
504            visit_element_for_position(&root, path, offset, result);
505        }
506        return;
507    }
508    for (index, node_path, node_range) in
509        element.borrow().debug.iter().enumerate().map(|(index, debug_info)| {
510            let text_range = debug_info
511                .node
512                .QualifiedName()
513                .map(|qualified_name| qualified_name.text_range())
514                .or_else(|| {
515                    debug_info
516                        .node
517                        .child_token(i_slint_compiler::parser::SyntaxKind::LBrace)
518                        .map(|left_brace| left_brace.text_range())
519                })
520                .expect("An Element must contain a LBrace somewhere");
521            (index, debug_info.node.source_file.path(), text_range)
522        })
523    {
524        if node_path == path && node_range.contains(offset.into()) {
525            result.push((element.clone(), index));
526        }
527    }
528    let children = element.borrow().children.clone();
529    for child in &children {
530        visit_element_for_position(child, path, offset, result);
531    }
532}
533
534/// `root` plus every instantiated repeated / conditional row instance
535/// below it, recursively.
536fn all_instances(root: &VRc<ItemTreeVTable, Instance>) -> Vec<VRc<ItemTreeVTable, Instance>> {
537    let mut instances = Vec::new();
538    collect_instances(root, &mut instances);
539    instances
540}
541
542fn collect_instances(
543    instance: &VRc<ItemTreeVTable, Instance>,
544    instances: &mut Vec<VRc<ItemTreeVTable, Instance>>,
545) {
546    instances.push(instance.clone());
547    collect_row_instances(&instance.root_sub_component, instances);
548}
549
550fn collect_row_instances(
551    sub_component: &Pin<Rc<SubComponentInstance>>,
552    instances: &mut Vec<VRc<ItemTreeVTable, Instance>>,
553) {
554    for repeater in sub_component.repeaters.iter() {
555        repeater.track_instance_changes();
556        for row in repeater.instances_vec() {
557            collect_instances(&row, instances);
558        }
559    }
560    for nested_sub_component in sub_component.sub_components.iter() {
561        collect_row_instances(nested_sub_component, instances);
562    }
563}
564
565fn collect_runtime_items_front_to_back(
566    item_tree: &ItemTreeRc,
567    index: u32,
568    instance: Option<&VRc<ItemTreeVTable, Instance>>,
569    runtime_items: &mut Vec<(VRc<ItemTreeVTable, Instance>, usize)>,
570) {
571    let mut visit_child = |child_item_tree: &ItemTreeRc,
572                           child_index: u32,
573                           _: Pin<i_slint_core::items::ItemRef<'_>>|
574     -> VisitChildrenResult {
575        let resolved_instance;
576        let child_instance = if VRc::ptr_eq(child_item_tree, item_tree) {
577            instance
578        } else {
579            resolved_instance = VRc::borrow(child_item_tree)
580                .downcast::<Instance>()
581                .and_then(|instance| instance.self_weak.get())
582                .and_then(|instance| instance.upgrade());
583            resolved_instance.as_ref()
584        };
585        collect_runtime_items_front_to_back(
586            child_item_tree,
587            child_index,
588            child_instance,
589            runtime_items,
590        );
591        VisitChildrenResult::CONTINUE
592    };
593    vtable::new_vref!(
594        let mut visit_child: VRefMut<i_slint_core::item_tree::ItemVisitorVTable>
595            for i_slint_core::item_tree::ItemVisitor = &mut visit_child
596    );
597    VRc::borrow_pin(item_tree).as_ref().visit_children_item(
598        index as isize,
599        TraversalOrder::FrontToBack,
600        visit_child,
601    );
602    if let Some(instance) = instance {
603        runtime_items.push((instance.clone(), index as usize));
604    }
605}
606
607fn item_geometry(
608    instance: &VRc<ItemTreeVTable, Instance>,
609    root: &VRc<ItemTreeVTable, Instance>,
610    flat_idx: usize,
611) -> Option<HighlightedRect> {
612    let vrc = VRc::into_dyn(instance.clone());
613    let root_vrc = VRc::into_dyn(root.clone());
614    let item_rc = ItemRc::new(vrc.clone(), flat_idx as u32);
615    let geometry = item_rc.geometry();
616    if geometry.size.is_empty() {
617        return None;
618    }
619    // Injected geometry wrappers (opacity/transform/clip/... created by
620    // `lower_property_to_element`) take over the element's geometry and lay the element
621    // out at (0,0) inside themselves, so measuring the parent frame from the element
622    // directly would collapse `rect.origin - parent_origin` to ~0.
623    let mut transform_rotation = 0.;
624    let mut anchor = item_rc.clone();
625    while let Some(parent) =
626        anchor.parent_item(i_slint_core::item_tree::ParentItemTraversalMode::StopAtPopups)
627    {
628        if !VRc::ptr_eq(parent.item_tree(), &vrc) {
629            break; // crossed into another component instance's item tree
630        }
631        if !parent.is_geometry_wrapper() {
632            break;
633        }
634        if let Some(transform) = i_slint_core::items::ItemRef::downcast_pin::<
635            i_slint_core::items::Transform,
636        >(parent.borrow())
637        {
638            transform_rotation += transform.transform_rotation();
639        }
640        anchor = parent;
641    }
642
643    // Neither transform adds its item's own x/y, so `parent_transform` maps the element's
644    // source-parent coordinate system, and `to_root` the coordinate system the injected
645    // wrappers place the element in — the element's own transform included.
646    let to_root = item_rc.transform_to_item_tree(&root_vrc);
647    let parent_transform = anchor.transform_to_item_tree(&root_vrc);
648    let map_axis = |axis: euclid::Vector2D<f32, _>| to_root.transform_vector(axis).cast();
649
650    let origin: LogicalPoint = to_root.transform_point(geometry.origin.cast()).cast();
651    // Both edges are measured, so a scale along one axis is not assumed to match the other.
652    let size = geometry.size.cast::<f32>();
653    let x_axis = map_axis(euclid::vec2(size.width, 0.));
654    let y_axis = map_axis(euclid::vec2(0., size.height));
655    let width = x_axis.length();
656    let height = y_axis.length();
657    let center = origin + (x_axis + y_axis) / 2.0;
658    Some(HighlightedRect {
659        rect: LogicalRect {
660            origin: center - euclid::vec2(width / 2.0, height / 2.0),
661            size: euclid::size2(width, height),
662        },
663        angle: x_axis.y.atan2(x_axis.x).to_degrees(),
664        renders_as_rectangle: are_perpendicular(x_axis, y_axis),
665        local_rect: if anchor == item_rc { geometry } else { anchor.geometry() },
666        parent_transform,
667        transform_rotation,
668        corner_radii: item_corner_radii(item_rc.borrow()),
669    })
670}
671
672/// Whether two axes still meet at a right angle.
673/// The cosine between them is compared, so the tolerance does not depend on how long they are.
674fn are_perpendicular(x: LogicalVector, y: LogicalVector) -> bool {
675    let squared_lengths = x.square_length() * y.square_length();
676    let dot = x.dot(y);
677    squared_lengths == 0. || dot * dot < 1.0e-6 * squared_lengths
678}
679
680fn item_corner_radii(item: Pin<i_slint_core::items::ItemRef<'_>>) -> CornerRadii {
681    use i_slint_core::items::{BasicBorderRectangle, BorderRectangle, ItemRef};
682    if let Some(rect) = ItemRef::downcast_pin::<BorderRectangle>(item) {
683        CornerRadii {
684            top_left: rect.border_top_left_radius().get(),
685            top_right: rect.border_top_right_radius().get(),
686            bottom_left: rect.border_bottom_left_radius().get(),
687            bottom_right: rect.border_bottom_right_radius().get(),
688        }
689    } else if let Some(rect) = ItemRef::downcast_pin::<BasicBorderRectangle>(item) {
690        let radius = rect.border_radius().get();
691        CornerRadii {
692            top_left: radius,
693            top_right: radius,
694            bottom_left: radius,
695            bottom_right: radius,
696        }
697    } else {
698        CornerRadii::default()
699    }
700}
701
702#[cfg(all(test, feature = "internal"))]
703fn items_by_source(
704    root: &VRc<ItemTreeVTable, Instance>,
705    target_path: &SourcePath,
706    target_offset: u32,
707    _source_match: SourceMatch,
708) -> Vec<(VRc<ItemTreeVTable, Instance>, usize)> {
709    let sources = SourceOccurrences::new(root);
710    sources
711        .elements
712        .get(&(target_path.clone(), target_offset as usize))
713        .into_iter()
714        .flat_map(|element| &element.item_indices)
715        .map(|&item_index| {
716            let item = &sources.items[item_index];
717            (item.instance.clone(), item.flat_index)
718        })
719        .collect()
720}
721
722#[cfg(all(test, feature = "internal"))]
723enum SourceMatch {
724    Start,
725}
726
727fn source_location_contains(
728    source_location: &SourceLocation,
729    target_path: &SourcePath,
730    target_offset: u32,
731) -> bool {
732    let Some(source_file) = source_location.source_file.as_ref() else { return false };
733    if source_file.path() != target_path {
734        return false;
735    }
736    let target_offset = target_offset as usize;
737    source_location.span.offset <= target_offset
738        && target_offset < source_location.span.offset.saturating_add(source_location.span.length)
739}
740
741#[cfg(all(test, feature = "internal"))]
742mod tests {
743    use crate::prelude::*;
744    use crate::{
745        ComponentInstance,
746        debug_hook::tests::{compile_with_debug_hooks, test_path},
747    };
748    use VRc;
749    use i_slint_core::item_tree::ParentItemTraversalMode;
750    use i_slint_core::items::{BoxShadow, Clip, ItemRc, Layer, Opacity, Transform};
751
752    fn geometry_of(
753        instance: &ComponentInstance,
754        code: &str,
755        id: &str,
756    ) -> crate::highlight::HighlightedRect {
757        let id_position = code.find(id).unwrap_or_else(|| panic!("{id} not found"));
758        let offset = id_position + code[id_position..].find("Rectangle").unwrap();
759        *instance.component_positions(&test_path(), offset as u32).first().expect("geometry")
760    }
761
762    fn runtime_item_of(instance: &ComponentInstance, source: &str, element_id: &str) -> ItemRc {
763        let element_id_position =
764            source.find(element_id).unwrap_or_else(|| panic!("{element_id} not found"));
765        let offset = element_id_position + source[element_id_position..].find("Rectangle").unwrap();
766        let (runtime_instance, flat_index) = super::items_by_source(
767            instance.inner.vrc(),
768            &test_path(),
769            offset as u32,
770            super::SourceMatch::Start,
771        )
772        .into_iter()
773        .next()
774        .unwrap_or_else(|| panic!("runtime item for {element_id}"));
775        ItemRc::new(VRc::into_dyn(runtime_instance), flat_index as u32)
776    }
777
778    #[test]
779    fn geometry_wrapper_classification() {
780        let code = r#"
781export component Win inherits Window {
782    wrapped := Rectangle {
783        opacity: 0.5;
784        visible: true;
785        transform-rotation: 45deg;
786        cache-rendering-hint: true;
787        drop-shadow-blur: 2px;
788        drop-shadow-color: black;
789    }
790    ordinary-clip := Rectangle { clip: true; }
791}
792"#;
793        let instance = compile_with_debug_hooks(code);
794        let mut ancestors = Vec::new();
795        let mut current = Some(runtime_item_of(&instance, code, "wrapped"));
796        while let Some(item) = current {
797            current = item.parent_item(ParentItemTraversalMode::StopAtPopups);
798            ancestors.push(item);
799        }
800
801        for wrapper_classification in [
802            ancestors
803                .iter()
804                .find(|item| item.downcast::<Transform>().is_some())
805                .map(ItemRc::is_geometry_wrapper),
806            ancestors
807                .iter()
808                .find(|item| item.downcast::<Opacity>().is_some())
809                .map(ItemRc::is_geometry_wrapper),
810            ancestors
811                .iter()
812                .find(|item| item.downcast::<Layer>().is_some())
813                .map(ItemRc::is_geometry_wrapper),
814            ancestors
815                .iter()
816                .find(|item| {
817                    item.downcast::<Clip>()
818                        .is_some_and(|clip| clip.as_pin_ref().is_visibility_clip())
819                })
820                .map(ItemRc::is_geometry_wrapper),
821        ] {
822            assert_eq!(wrapper_classification, Some(true));
823        }
824
825        let root_item_tree = VRc::into_dyn(instance.inner.vrc().clone());
826        let box_shadow = (0..instance.inner.vrc().item_table.len())
827            .map(|flat_index| ItemRc::new(root_item_tree.clone(), flat_index as u32))
828            .find(|item| item.downcast::<BoxShadow>().is_some())
829            .expect("box shadow");
830        assert!(!box_shadow.is_geometry_wrapper());
831
832        let ordinary_clip = (0..instance.inner.vrc().item_table.len())
833            .map(|flat_index| ItemRc::new(root_item_tree.clone(), flat_index as u32))
834            .find(|item| {
835                item.downcast::<Clip>().is_some_and(|clip| !clip.as_pin_ref().is_visibility_clip())
836            })
837            .expect("ordinary clip");
838        assert!(!ordinary_clip.is_geometry_wrapper());
839    }
840
841    // With debug_hooks enabled every element is wrapped in injected geometry wrappers
842    // (`Transform`, plus `Opacity` etc. when those props are set), which take over the element's
843    // geometry. `element_positions` must still report a `parent_origin` from which the element's
844    // own `x`/`y` can be recovered (`rect.origin - parent_origin == x/y`), otherwise the editor
845    // commits wrong coordinates when repositioning. This must hold through stacked wrappers and
846    // for elements nested below a non-root parent.
847    #[test]
848    fn debug_hooks_parent_origin() {
849        let code = r#"
850export component Win inherits Window {
851    width: 300px;
852    height: 200px;
853    plain := Rectangle {
854        x: 30px;
855        y: 40px;
856        width: 50px;
857        height: 60px;
858    }
859    faded := Rectangle {
860        // extra Opacity and visibility-Clip wrappers stacked around the Transform wrapper
861        opacity: 0.5;
862        visible: true;
863        x: 70px;
864        y: 80px;
865        width: 40px;
866        height: 30px;
867    }
868    clipped := Rectangle {
869        clip: true;
870        x: 90px;
871        y: 15px;
872        width: 30px;
873        height: 25px;
874        clipped-child := Rectangle {
875            x: 3px;
876            y: 4px;
877            width: 10px;
878            height: 12px;
879        }
880    }
881    outer := Rectangle {
882        x: 10px;
883        y: 20px;
884        width: 120px;
885        height: 100px;
886        nested := Rectangle {
887            x: 5px;
888            y: 7px;
889            width: 20px;
890            height: 20px;
891        }
892    }
893}"#;
894        let instance = compile_with_debug_hooks(code);
895
896        for (element_id, expected_position) in [
897            ("plain", (30.0, 40.0)),
898            ("faded", (70.0, 80.0)),
899            ("clipped", (90.0, 15.0)),
900            ("clipped-child", (3.0, 4.0)),
901            ("nested", (5.0, 7.0)),
902        ] {
903            let geometry = geometry_of(&instance, code, element_id);
904            let horizontal_position = geometry.rect.origin.x - geometry.parent_origin().x;
905            let vertical_position = geometry.rect.origin.y - geometry.parent_origin().y;
906            assert!(
907                (horizontal_position - expected_position.0).abs() < 0.5
908                    && (vertical_position - expected_position.1).abs() < 0.5,
909                "{element_id}: source-relative position ({horizontal_position}, {vertical_position}) should be {expected_position:?}"
910            );
911        }
912    }
913
914    #[test]
915    fn debug_hooks_local_rect() {
916        let code = r#"
917export component Win inherits Window {
918    width: 300px;
919    height: 300px;
920    outer := Rectangle {
921        x: 50px;
922        y: 60px;
923        width: 160px;
924        height: 140px;
925        transform-rotation: 30deg;
926        inner := Rectangle {
927            x: 20px;
928            y: 25px;
929            width: 40px;
930            height: 30px;
931            transform-rotation: 15deg;
932            transform-origin: { x: 0px, y: 0px };
933        }
934    }
935}"#;
936        let instance = compile_with_debug_hooks(code);
937
938        let check = |id: &str, expected: (f32, f32, f32, f32)| {
939            let rect = geometry_of(&instance, code, id).local_rect;
940            let actual = (rect.origin.x, rect.origin.y, rect.width(), rect.height());
941            assert!(
942                (actual.0 - expected.0).abs() < 0.5
943                    && (actual.1 - expected.1).abs() < 0.5
944                    && (actual.2 - expected.2).abs() < 0.5
945                    && (actual.3 - expected.3).abs() < 0.5,
946                "{id}: parent-relative rectangle {actual:?} should be {expected:?}"
947            );
948        };
949
950        check("outer", (50.0, 60.0, 160.0, 140.0));
951        check("inner", (20.0, 25.0, 40.0, 30.0));
952    }
953
954    #[test]
955    fn scaled_geometry_is_measured_per_axis() {
956        let code = r#"
957export component Win inherits Window {
958    width: 400px;
959    height: 400px;
960    stretched := Rectangle {
961        x: 20px;
962        y: 20px;
963        width: 80px;
964        height: 40px;
965        transform-scale-x: 3;
966    }
967    wide := Rectangle {
968        x: 20px;
969        y: 200px;
970        width: 200px;
971        height: 100px;
972        transform-scale-x: 3;
973        sheared := Rectangle {
974            width: 80px;
975            height: 40px;
976            transform-rotation: 30deg;
977        }
978    }
979}"#;
980        let instance = compile_with_debug_hooks(code);
981
982        // Both axes are measured, so a scale along one of them doesn't stretch the other.
983        let stretched = geometry_of(&instance, code, "stretched");
984        assert!(
985            (stretched.rect.width() - 240.).abs() < 0.5
986                && (stretched.rect.height() - 40.).abs() < 0.5,
987            "stretched: {:?}",
988            stretched.rect
989        );
990        assert!(stretched.renders_as_rectangle);
991
992        // A rotation below a non-uniform scale is a parallelogram, which `rect` can't express.
993        let sheared = geometry_of(&instance, code, "sheared");
994        assert!(!sheared.renders_as_rectangle);
995        assert!((sheared.angle - 30.).abs() > 1., "sheared angle: {}", sheared.angle);
996    }
997
998    #[test]
999    fn debug_hooks_parent_rotation() {
1000        let code = r#"
1001export component Win inherits Window {
1002    width: 300px;
1003    height: 300px;
1004    outer := Rectangle {
1005        x: 50px;
1006        y: 50px;
1007        width: 160px;
1008        height: 160px;
1009        transform-rotation: 30deg;
1010        inner := Rectangle {
1011            x: 20px;
1012            y: 20px;
1013            width: 40px;
1014            height: 40px;
1015            transform-rotation: 15deg;
1016        }
1017    }
1018}"#;
1019        let instance = compile_with_debug_hooks(code);
1020
1021        let check = |id: &str, expected: f32| {
1022            let geometry = geometry_of(&instance, code, id);
1023            let rotation = geometry.angle - geometry.parent_rotation();
1024            assert!(
1025                (rotation - expected).abs() < 0.5,
1026                "{id}: source-relative rotation {rotation} should be {expected}"
1027            );
1028        };
1029
1030        check("outer", 30.0);
1031        check("inner", 15.0);
1032    }
1033    #[test]
1034    fn evaluated_rotation_and_radii_share_geometry_instances() {
1035        let code = r#"
1036export component Win inherits Window {
1037    width: 300px;
1038    height: 300px;
1039    outer := Rectangle {
1040        width: 200px;
1041        height: 200px;
1042        transform-rotation: 30deg;
1043        for angle in [382.25deg, -397.5deg]: Rectangle {
1044            width: 40px;
1045            height: 40px;
1046            transform-rotation: angle;
1047            border-top-left-radius: 1.5px;
1048            border-top-right-radius: 2.5px;
1049            border-bottom-left-radius: 3.5px;
1050            border-bottom-right-radius: 4.5px;
1051        }
1052    }
1053}"#;
1054        let instance = compile_with_debug_hooks(code);
1055        let offset = code
1056            .find(
1057                "Rectangle {
1058            width",
1059            )
1060            .unwrap();
1061        let geometries = instance.component_positions(&test_path(), offset as u32);
1062        assert_eq!(geometries.len(), 2);
1063        for (geometry, expected) in geometries.iter().zip([382.25, -397.5]) {
1064            assert_eq!(geometry.transform_rotation, expected);
1065            assert!((geometry.parent_rotation() - 30.).abs() < 0.001);
1066            let radii = geometry.corner_radii;
1067            assert_eq!(
1068                [radii.top_left, radii.top_right, radii.bottom_left, radii.bottom_right],
1069                [1.5, 2.5, 3.5, 4.5]
1070            );
1071        }
1072    }
1073}