Skip to main content

slint_interpreter/
instance.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//! Runtime component tree: a hierarchy of [`SubComponentInstance`]s rooted
5//! in an [`Instance`].
6
7use crate::erased::{ErasedItemRc, SubComponentCallback, SubComponentProperty};
8use crate::globals::GlobalStorage;
9use crate::item_registry::ItemRegistry;
10use i_slint_compiler::llr::{
11    self, CompilationUnit, ItemInstanceIdx, RepeatedElementIdx, SubComponentIdx,
12    SubComponentInstanceIdx,
13};
14use i_slint_core::item_tree::{ItemTreeNode, ItemTreeVTable};
15use i_slint_core::model::{Conditional, Repeater};
16use i_slint_core::properties::ChangeTracker;
17use i_slint_core::window::WindowAdapterRc;
18use i_slint_core::{Callback, Property};
19use std::cell::{OnceCell, RefCell};
20use std::pin::Pin;
21use std::rc::{Rc, Weak};
22use typed_index_collections::TiVec;
23use vtable::{VRc, VWeak};
24
25/// Either a `Repeater<Instance>` (`for` loops) or a `Conditional<Instance>`
26/// (`if expr` elements).
27/// The conditional variant reuses the existing instance while the condition
28/// stays true, avoiding spurious re-init.
29pub enum RepeaterOrConditional {
30    Repeater(Pin<Box<Repeater<Instance>>>),
31    Conditional(Pin<Box<Conditional<Instance>>>),
32}
33
34impl RepeaterOrConditional {
35    pub fn visit(
36        &self,
37        order: i_slint_core::item_tree::TraversalOrder,
38        visitor: i_slint_core::item_tree::ItemVisitorRefMut<'_>,
39    ) -> i_slint_core::item_tree::VisitChildrenResult {
40        match self {
41            Self::Repeater(r) => Pin::as_ref(r).visit(order, visitor),
42            Self::Conditional(c) => Pin::as_ref(c).visit(order, visitor),
43        }
44    }
45
46    pub fn range(&self) -> core::ops::Range<usize> {
47        match self {
48            Self::Repeater(r) => r.range(),
49            Self::Conditional(c) => c.range(),
50        }
51    }
52
53    pub fn instance_at(&self, subindex: usize) -> Option<VRc<ItemTreeVTable, Instance>> {
54        match self {
55            Self::Repeater(r) => r.instance_at(subindex),
56            Self::Conditional(c) => c.instance_at(subindex),
57        }
58    }
59
60    pub fn instances_vec(&self) -> Vec<VRc<ItemTreeVTable, Instance>> {
61        match self {
62            Self::Repeater(r) => r.instances_vec(),
63            Self::Conditional(c) => c.instances_vec(),
64        }
65    }
66
67    /// Register the instance generation as a dependency of the current
68    /// tracking scope. Layout expressions use this instead of instantiating,
69    /// so they re-evaluate after the `ensure_instantiated` pass materializes
70    /// instance changes.
71    pub fn track_instance_changes(&self) {
72        match self {
73            Self::Repeater(r) => Pin::as_ref(r).track_instance_changes(),
74            Self::Conditional(c) => Pin::as_ref(c).track_instance_changes(),
75        }
76    }
77
78    /// Ensure the repeater/conditional has been updated. Must be called
79    /// before accessing instances.
80    /// Returns `true` if instances were created or removed.
81    pub fn ensure_updated(
82        &self,
83        init: impl Fn() -> VRc<ItemTreeVTable, Instance> + 'static,
84    ) -> bool {
85        match self {
86            Self::Repeater(r) => Pin::as_ref(r).ensure_updated(init),
87            Self::Conditional(c) => Pin::as_ref(c).ensure_updated(init),
88        }
89    }
90
91    /// Like `ensure_updated` but for listview repeaters that need
92    /// virtualized row layout. The interpreter's content properties may
93    /// live on a native item (e.g. `Flickable::content-y`), which
94    /// doesn't expose a `Pin<&Property<Value>>` — so we go through the
95    /// closure-based [`i_slint_core::model::ListViewProperties`] variant
96    /// and let `load_property`/`store_property` route to rtti as needed.
97    pub fn ensure_updated_listview_callback(
98        &self,
99        init: impl Fn() -> VRc<ItemTreeVTable, Instance> + 'static,
100        props: &dyn i_slint_core::model::ListViewProperties,
101        listview_width: i_slint_core::lengths::LogicalLength,
102        listview_height: i_slint_core::lengths::LogicalLength,
103    ) -> bool {
104        match self {
105            Self::Repeater(r) => Pin::as_ref(r).ensure_updated_listview_callback(
106                init,
107                props,
108                listview_width,
109                listview_height,
110            ),
111            Self::Conditional(_) => unreachable!("listview on a conditional element"),
112        }
113    }
114
115    /// Set the model binding for `for` repeaters.
116    pub fn set_model_binding(
117        &self,
118        binding: impl Fn() -> i_slint_core::model::ModelRc<crate::Value> + 'static,
119    ) {
120        match self {
121            Self::Repeater(r) => Pin::as_ref(r).set_model_binding(binding),
122            Self::Conditional(_) => unreachable!("set_model_binding on conditional"),
123        }
124    }
125
126    /// Set the condition binding for conditional elements.
127    pub fn set_condition_binding(&self, binding: impl Fn() -> bool + 'static) {
128        match self {
129            Self::Conditional(c) => c.set_model_binding(binding),
130            Self::Repeater(_) => unreachable!("set_condition_binding on repeater"),
131        }
132    }
133
134    /// Write model data back to a for-loop model row.
135    pub fn model_set_row_data(&self, row: usize, data: crate::Value) {
136        match self {
137            Self::Repeater(r) => Pin::as_ref(r).model_set_row_data(row, data),
138            Self::Conditional(_) => {} // conditionals have no model data
139        }
140    }
141
142    pub fn is_conditional(&self) -> bool {
143        matches!(self, Self::Conditional(_))
144    }
145}
146
147/// Runtime instance of a single [`SubComponent`](llr::SubComponent).
148///
149/// Each field is indexed by its corresponding LLR index, so lookups are O(1).
150pub struct SubComponentInstance {
151    pub compilation_unit: Rc<CompilationUnit>,
152    pub sub_component_idx: SubComponentIdx,
153    pub properties: TiVec<llr::PropertyIdx, SubComponentProperty>,
154    pub callbacks: TiVec<llr::CallbackIdx, SubComponentCallback>,
155    /// For each callback with `needs_tracker`, a `Property<()>` that tracks
156    /// handler changes: invoking the callback from a binding reads it to
157    /// register a dependency; setting a new handler marks it dirty so
158    /// dependent bindings re-evaluate.
159    pub callback_trackers: TiVec<llr::CallbackIdx, Option<Pin<Rc<Property<()>>>>>,
160    pub items: TiVec<ItemInstanceIdx, ErasedItemRc>,
161    pub sub_components: TiVec<SubComponentInstanceIdx, Pin<Rc<SubComponentInstance>>>,
162    /// One repeater per LLR `RepeatedElementIdx`.
163    /// Conditional elements (`if expr`) use `Conditional<Instance>` which
164    /// reuses the existing instance when the condition stays true; `for`
165    /// loops use `Repeater<Instance>` which manages a `ModelRc<Value>`.
166    pub repeaters: TiVec<RepeatedElementIdx, RepeaterOrConditional>,
167    /// Resolves `MemberReference::Relative { parent_level: > 0 }`.
168    pub parent: Weak<SubComponentInstance>,
169    /// Back-reference to the owning root, populated right after construction.
170    pub root: OnceCell<VWeak<ItemTreeVTable, Instance>>,
171    /// Change trackers for the timers (two per timer, first) and the
172    /// `change_callbacks` (in declaration order, after).
173    pub change_trackers: Vec<ChangeTracker>,
174    /// Per-sub-component runtime `Timer`s, one per `SubComponent::timers`
175    /// entry. Owned here so they stay alive with the instance; their
176    /// lifecycle (start / stop / interval) is driven by a change tracker
177    /// that re-evaluates the LLR `running` / `interval` expressions.
178    pub timers: Vec<i_slint_core::timers::Timer>,
179    /// One entry per `SubComponent::popup_windows`. Stores the currently
180    /// open popup's id (handed out by `WindowInner::show_popup`) so a
181    /// later `popup.close()` in the same sub-component can resolve which
182    /// popup to tear down.
183    pub popup_ids: Vec<std::cell::Cell<Option<std::num::NonZeroU32>>>,
184    /// Set on the root sub-component of a repeated `Instance`. Points back to
185    /// the parent sub-component holding the `Repeater` this instance belongs to.
186    /// Used by `ModelDataAssignment` to write back into the model.
187    pub repeated_in: OnceCell<(Weak<SubComponentInstance>, RepeatedElementIdx)>,
188    /// Keeps the `MenuFromItemTree` alive so the weak reference stored by
189    /// `setup_menubar_shortcuts` in the window remains valid.
190    pub menubar: RefCell<Option<vtable::VRc<i_slint_core::menus::MenuVTable>>>,
191}
192
193/// Top-level item tree handed to i-slint-core via `VRc<ItemTreeVTable, _>`.
194pub struct Instance {
195    pub root_sub_component: Pin<Rc<SubComponentInstance>>,
196    /// Flat `ItemTreeNode` slice returned by the `get_item_tree` vtable entry.
197    pub tree_nodes: Box<[ItemTreeNode]>,
198    /// Parallel table mapping each `DynamicTree` flat index to the
199    /// `(sub_component_path, RepeatedElementIdx)` that owns the repeater.
200    /// `None` entries correspond to non-dynamic nodes.
201    pub dynamic_table: Box<[Option<(Box<[SubComponentInstanceIdx]>, RepeatedElementIdx)>]>,
202    /// Parallel table mapping each static-item flat index to the
203    /// `(sub_component_path, ItemInstanceIdx)` that owns it. `None`
204    /// entries correspond to dynamic-tree nodes.
205    pub item_table: Box<[Option<(Box<[SubComponentInstanceIdx]>, ItemInstanceIdx)>]>,
206    pub globals: Rc<GlobalStorage>,
207    pub self_weak: OnceCell<VWeak<ItemTreeVTable, Instance>>,
208    /// When this `Instance` is a repeated entry, points back to the parent
209    /// item tree so `parent_node` can return a meaningful weak.
210    pub parent_instance: Weak<SubComponentInstance>,
211    /// Index into `compilation_unit.public_components` for the public
212    /// component this instance was built from. `None` for repeated /
213    /// nested instances that don't correspond to a public component.
214    pub public_component_index: Option<usize>,
215    /// Lazily-created window adapter, used by `ImplicitLayoutInfo` and the
216    /// public window/run helpers.
217    pub window_adapter: OnceCell<WindowAdapterRc>,
218    /// Message of the first failed window adapter creation. Later accesses
219    /// return it instead of asking the platform again, so the first error is
220    /// what `create()` reports.
221    window_adapter_error: OnceCell<String>,
222    /// Set once [`Instance::attach_to_window`] has linked the window adapter
223    /// back to this item tree via `WindowInner::set_component`. Keeps the
224    /// attach idempotent and lets binding-evaluated code paths distinguish
225    /// "adapter exists" from "window is fully wired for display".
226    pub window_attached: OnceCell<()>,
227    /// Set once `bindings::install_bindings_only` has wired up property
228    /// bindings, two-way links and timers. Idempotent on repeated calls.
229    pub bindings_installed: OnceCell<()>,
230    /// Set once the user-facing `init_code` has run on this instance. Kept
231    /// separate from `bindings_installed` so the listview-virtualization
232    /// factory can install bindings eagerly (so the first measurement
233    /// returns the right row height) while still deferring `init_code`
234    /// until the core's `init_instances` step.
235    pub init_code_run: OnceCell<()>,
236    /// When this instance has been embedded into another item tree via
237    /// `embed_component`, stores the weak handle to the outer item tree and
238    /// the flat index of the `ComponentContainer` it substitutes into.
239    /// `parent_node` uses this to let coordinate-mapping helpers walk up
240    /// into the outer tree.
241    pub embedded_in: OnceCell<(VWeak<ItemTreeVTable>, u32)>,
242    /// `TypeLoader` snapshots (post-pass + pre-pass) kept around for the
243    /// highlight module and the LSP live preview's `DocumentCache`
244    /// reconstruction. Both sides are `None` on sub-tree / popup / repeated
245    /// instances — only the top-level definition sets them.
246    pub type_loaders: crate::component::TypeLoaders,
247}
248
249impl Drop for Instance {
250    fn drop(&mut self) {
251        // Free the per-component renderer caches (text shaping, bounding rects, …)
252        // and notify any `WindowAdapterInternal` that the item tree is
253        // going away. Skipping this leaks cache entries across destroyed
254        // conditional/repeated sub-trees; once the allocator hands out a
255        // fresh item at a previously-cached pointer, the renderer serves
256        // the old widget's text / font / color.
257        //
258        // `self_weak` can't be upgraded here — the strong count is already
259        // zero — so build a borrowed `VRef<ItemTreeVTable>` from `&*self`.
260        let Some(adapter) = self.window_adapter.get().cloned().or_else(|| {
261            let mut parent = self.parent_instance.upgrade();
262            while let Some(sub) = parent {
263                let root = sub.root.get().and_then(|w| w.upgrade())?;
264                if let Some(a) = root.window_adapter.get() {
265                    return Some(a.clone());
266                }
267                parent = root.parent_instance.upgrade();
268            }
269            None
270        }) else {
271            return;
272        };
273        vtable::new_vref!(let item_tree_ref : VRef<i_slint_core::item_tree::ItemTreeVTable> for i_slint_core::item_tree::ItemTree = self);
274        let items = collect_item_refs(&self.root_sub_component);
275        // Same order as `i_slint_core::item_tree::unregister_item_tree`:
276        // deinit each item (a focused TextInput resets
277        // `text-input-focused`), free the renderer caches, notify the
278        // adapter, then close popups whose parent item just went away.
279        for item in &items {
280            item.as_ref().deinit(&adapter);
281        }
282        let _ =
283            adapter.renderer().free_graphics_resources(item_tree_ref, &mut items.iter().copied());
284        if let Some(internal) = adapter.internal(i_slint_core::InternalToken) {
285            internal.unregister_item_tree(item_tree_ref, &mut items.iter().copied());
286        }
287        let window_inner = i_slint_core::window::WindowInner::from_pub(adapter.window());
288        let to_close_popups = window_inner
289            .active_popups()
290            .iter()
291            .filter_map(|p| p.parent_item.upgrade().is_none().then_some(p.popup_id))
292            .collect::<Vec<_>>();
293        for popup_id in to_close_popups {
294            window_inner.close_popup(popup_id);
295        }
296    }
297}
298
299/// Collect every native item in `sub` and its nested sub-components as
300/// pinned vtable refs for `free_graphics_resources` / `unregister_item_tree`.
301fn collect_item_refs<'a>(
302    sub: &'a Pin<Rc<SubComponentInstance>>,
303) -> Vec<Pin<vtable::VRef<'a, i_slint_core::items::ItemVTable>>> {
304    let mut out = Vec::new();
305    fn walk<'a>(
306        sub: &'a Pin<Rc<SubComponentInstance>>,
307        out: &mut Vec<Pin<vtable::VRef<'a, i_slint_core::items::ItemVTable>>>,
308    ) {
309        for item in &sub.items {
310            out.push(Pin::as_ref(item).as_item_ref());
311        }
312        for nested in &sub.sub_components {
313            walk(nested, out);
314        }
315    }
316    walk(sub, &mut out);
317    out
318}
319
320impl Instance {
321    /// Like [`Self::try_window_adapter`], but collapse the error case to
322    /// `None` for the many callers that only need best-effort access.
323    pub fn window_adapter_or_default(&self) -> Option<WindowAdapterRc> {
324        self.try_window_adapter().ok()
325    }
326
327    /// Return a window adapter, creating one through the platform selector
328    /// if needed. Failure to create one surfaces as the platform's error so
329    /// callers with an error channel (e.g. `create()`) can report it.
330    ///
331    /// Does **not** call `WindowInner::set_component`: this method is called
332    /// from inside binding evaluation (e.g. `ImplicitLayoutInfo`), and
333    /// `set_component` eagerly reads and writes window-item properties,
334    /// which would recurse into the in-flight binding. Call
335    /// [`Self::attach_to_window`] separately from lifecycle entry points
336    /// (show/run) to link the window back to this item tree.
337    ///
338    /// Sub-instances (popups, repeated/conditional sub-trees) inherit the
339    /// adapter of the root instance instead of creating a fresh one — that
340    /// would otherwise leave dispatched events going to a different window
341    /// than the one the test driver captured.
342    pub fn try_window_adapter(&self) -> Result<WindowAdapterRc, i_slint_core::api::PlatformError> {
343        if let Some(a) = self.window_adapter.get() {
344            return Ok(a.clone());
345        }
346        // An embedded instance reuses the outer tree's adapter. We must
347        // _not_ create a fresh one: any resize event on it would fire
348        // `set_window_item_geometry`, which walks the TwoWayBinding chain
349        // down into `common_1.set(..)` and erases the ComponentContainer
350        // width/height bindings the embedded root is supposed to track.
351        if let Some((outer_weak, _)) = self.embedded_in.get()
352            && let Some(outer) = outer_weak.upgrade()
353        {
354            let mut result = None;
355            vtable::VRc::borrow_pin(&outer).as_ref().window_adapter(true, &mut result);
356            if let Some(a) = result {
357                let _ = self.window_adapter.set(a.clone());
358                return Ok(a);
359            }
360        }
361        // Walk up the parent chain to find an existing adapter on the root
362        // instance, so popup-in-popup etc. share the same window.
363        let mut outermost_root = None;
364        let mut parent_sub = self.parent_instance.upgrade();
365        while let Some(sub) = parent_sub {
366            let Some(root_vrc) = sub.root.get().and_then(|w| w.upgrade()) else { break };
367            if let Some(a) = root_vrc.window_adapter.get() {
368                let cloned = a.clone();
369                // Cache on this instance so future lookups don't have to walk
370                // again, but don't store a *new* adapter on a non-root.
371                let _ = self.window_adapter.set(cloned.clone());
372                return Ok(cloned);
373            }
374            parent_sub = root_vrc.parent_instance.upgrade();
375            outermost_root = Some(root_vrc);
376        }
377        if let Some(e) = self
378            .window_adapter_error
379            .get()
380            .or_else(|| outermost_root.as_ref().and_then(|root| root.window_adapter_error.get()))
381        {
382            return Err(i_slint_core::api::PlatformError::Other(e.clone()));
383        }
384        let adapter = i_slint_backend_selector::with_platform(|p| p.create_window_adapter())
385            .inspect_err(|e| {
386                let msg = e.to_string();
387                if let Some(root) = &outermost_root {
388                    let _ = root.window_adapter_error.set(msg.clone());
389                }
390                let _ = self.window_adapter_error.set(msg);
391            })?;
392        // Point the renderer at its adapter right away: font registration in
393        // `pre_init_code` and image decoding need the renderer's Slint context
394        // before `attach_to_window` runs `set_component` on show.
395        adapter.renderer().set_window_adapter(&adapter);
396        // A freshly created adapter belongs to the outermost root instance;
397        // caching it only on a sub-tree would leave the root creating a
398        // second one later, splitting the tree across two windows.
399        if let Some(root) = outermost_root {
400            let _ = root.window_adapter.set(adapter.clone());
401        }
402        let _ = self.window_adapter.set(adapter.clone());
403        Ok(adapter)
404    }
405
406    /// Link this instance's root item tree into its window adapter via
407    /// `WindowInner::set_component`, if not already attached.
408    ///
409    /// Must be called from a context that is **not** currently evaluating a
410    /// property binding — `set_component` touches geometry and scale-factor
411    /// trackers and would otherwise trip `Recursion detected`. The public
412    /// `show()` / `run()` entry points call this before handing off to the
413    /// backend event loop. Idempotent via the `window_attached` flag.
414    pub fn attach_to_window(&self) {
415        if self.window_attached.get().is_some() {
416            return;
417        }
418        let Some(adapter) = self.window_adapter_or_default() else { return };
419        let Some(self_rc) = self.self_weak.get().and_then(|w| w.upgrade()) else { return };
420        let _ = self.window_attached.set(());
421        i_slint_core::window::WindowInner::from_pub(adapter.window())
422            .set_component(&vtable::VRc::into_dyn(self_rc));
423    }
424}
425
426/// When the LLR `RepeatedElement` at `rep_idx` is actually a
427/// `ComponentContainer` placeholder (created by `lower_component_container`),
428/// return a pinned reference to the `ComponentContainer` item that hosts
429/// the embedded tree. Returns `None` for regular repeaters and conditional
430/// elements.
431pub(crate) fn component_container_item(
432    sub: &Pin<Rc<SubComponentInstance>>,
433    rep_idx: RepeatedElementIdx,
434) -> Option<Pin<&i_slint_core::items::ComponentContainer>> {
435    let sc = &sub.compilation_unit.sub_components[sub.sub_component_idx];
436    let cc_item_idx = sc.repeated.get(rep_idx)?.container_item_index?;
437    let item = sub.items.get(cc_item_idx)?;
438    i_slint_core::items::ItemRef::downcast_pin::<i_slint_core::items::ComponentContainer>(
439        Pin::as_ref(item).as_item_ref(),
440    )
441}
442
443impl Instance {
444    /// Resolve a flat `tree_nodes` index into the owning sub-component and
445    /// its local repeater index by walking the cached
446    /// `dynamic_table` entry's `sub_component_path`.
447    pub fn dynamic_at(
448        &self,
449        tree_index: u32,
450    ) -> Option<(Pin<Rc<SubComponentInstance>>, RepeatedElementIdx)> {
451        let entry = self.dynamic_table.get(tree_index as usize)?.as_ref()?;
452        let mut current = self.root_sub_component.clone();
453        for &idx in entry.0.iter() {
454            let next = current.sub_components[idx].clone();
455            current = next;
456        }
457        Some((current, entry.1))
458    }
459
460    /// Ensure the repeater at `tree_index` is populated from its model.
461    /// Called by `get_subtree_range`, `get_subtree` and
462    /// `visit_dynamic_children` before reading the repeater's instances.
463    ///
464    /// When the LLR `RepeatedElement` is actually a `ComponentContainer`
465    /// placeholder (`container_item_index = Some`), defer to the
466    /// `ComponentContainer` item's own `ensure_updated`, which drives
467    /// the `ComponentFactory` and stores the embedded item tree on the
468    /// container item directly — the repeater slot stays a no-op
469    /// `Conditional` with `model: false`.
470    pub fn ensure_updated(&self, tree_index: u32) -> bool {
471        let Some((sub, rep_idx)) = self.dynamic_at(tree_index) else { return false };
472        if let Some(cc) = component_container_item(&sub, rep_idx) {
473            return cc.ensure_updated();
474        }
475        let cu = sub.compilation_unit.clone();
476        let sc_idx = sub.sub_component_idx;
477        let sub_weak = Rc::downgrade(&Pin::into_inner(sub.clone()));
478        let globals = self.globals.clone();
479        let repeated = &cu.sub_components[sc_idx].repeated[rep_idx];
480        let listview_factory = repeated.listview.is_some();
481        let listview_info = repeated.listview.clone();
482        let factory = move || {
483            let item_tree = &cu.sub_components[sc_idx].repeated[rep_idx].sub_tree;
484            let vrc = Instance::new_repeated(
485                cu.clone(),
486                item_tree,
487                sub_weak.clone(),
488                rep_idx,
489                globals.clone(),
490            );
491            if listview_factory {
492                // The listview measurement reads row heights *before* the
493                // core calls `RepeatedItemTree::init` on each row, so the
494                // height/width/geometry bindings must be in place
495                // immediately; `init_code` stays deferred to `init()`.
496                install_bindings_for_repeated_row(&vrc);
497            }
498            vrc
499        };
500        let repeater = &sub.repeaters[rep_idx];
501        if let Some(lv) = listview_info.as_ref() {
502            let listview_width = read_logical_length(&sub, &lv.listview_width);
503            let listview_height = read_logical_length(&sub, &lv.listview_height);
504            // If layout hasn't propagated a real visible height yet (eager
505            // hit-test before show()), bail out instead of running the
506            // virtualization with `0`, which would create no rows or — with
507            // the loop_count == 3 retry — instantiate the whole model.
508            if listview_height.get() <= 0.0 {
509                return false;
510            }
511            let props = ValueListViewProps {
512                content_y: lv.content_y.clone(),
513                content_width: lv.content_width.clone(),
514                content_height: lv.content_height.clone(),
515                ctx_sub: sub.clone(),
516            };
517            repeater.ensure_updated_listview_callback(
518                factory,
519                &props,
520                listview_width,
521                listview_height,
522            )
523        } else {
524            repeater.ensure_updated(factory)
525        }
526    }
527
528    /// Instantiate every repeater, conditional and `ComponentContainer` in
529    /// this item tree. Runs as a dedicated update pass before rendering and
530    /// event dispatch, so the visit pass only has to register dependencies.
531    /// Returns `true` if any instance was created or removed.
532    pub fn ensure_instantiated(&self) -> bool {
533        let mut changed = false;
534        for idx in 0..self.dynamic_table.len() {
535            if self.dynamic_table[idx].is_some() {
536                changed |= self.ensure_updated(idx as u32);
537            }
538        }
539        changed
540    }
541
542    /// `visit_children_item` entry point for `DynamicTree` nodes.
543    ///
544    /// For `ComponentContainer` placeholders the visit delegates to the
545    /// container item's own `visit_children_item`, which hops into the
546    /// embedded item tree stored on the container. The repeater slot is
547    /// a dummy `Conditional` (see `lower_component_container`) and must
548    /// not be visited directly, or the embedded content never renders.
549    pub fn visit_dynamic_children(
550        self: Pin<&Self>,
551        dyn_index: u32,
552        order: i_slint_core::item_tree::TraversalOrder,
553        visitor: vtable::VRefMut<'_, i_slint_core::item_tree::ItemVisitorVTable>,
554    ) -> i_slint_core::item_tree::VisitChildrenResult {
555        let Some((sub, rep_idx)) = self.get_ref().dynamic_at(dyn_index) else {
556            return i_slint_core::item_tree::VisitChildrenResult::CONTINUE;
557        };
558        if let Some(cc) = component_container_item(&sub, rep_idx) {
559            return cc.visit_children_item(-1, order, visitor);
560        }
561        // Instantiation happens in the `ensure_instantiated` pass; the visit
562        // only registers dependencies so the redraw tracker is notified when
563        // the model or the ListView content geometry changes.
564        let repeater = &sub.repeaters[rep_idx];
565        let sc = &sub.compilation_unit.sub_components[sub.sub_component_idx];
566        if let (Some(lv), RepeaterOrConditional::Repeater(r)) =
567            (sc.repeated[rep_idx].listview.as_ref(), repeater)
568        {
569            let props = ValueListViewProps {
570                content_y: lv.content_y.clone(),
571                content_width: lv.content_width.clone(),
572                content_height: lv.content_height.clone(),
573                ctx_sub: sub.clone(),
574            };
575            let listview_width = read_logical_length(&sub, &lv.listview_width);
576            let _ = read_logical_length(&sub, &lv.listview_height);
577            Pin::as_ref(r).track_changes_listview_callback(&props, listview_width);
578        }
579        repeater.visit(order, visitor)
580    }
581
582    /// Build an instance for a public component.
583    ///
584    /// Properties are default-valued, then `bindings::install_bindings` wires
585    /// up `property_init`, `two_way_bindings` and `init_code`.
586    pub fn new(
587        compilation_unit: Rc<CompilationUnit>,
588        public_component_index: usize,
589    ) -> VRc<ItemTreeVTable, Instance> {
590        Self::new_with_window(compilation_unit, public_component_index, None, Default::default())
591    }
592
593    /// Build an instance for a public component and optionally reuse an
594    /// existing [`WindowAdapterRc`]. Live preview passes in the window from
595    /// the old instance so reloaded components keep the same window frame.
596    pub fn new_with_window(
597        compilation_unit: Rc<CompilationUnit>,
598        public_component_index: usize,
599        window_adapter: Option<i_slint_core::window::WindowAdapterRc>,
600        type_loaders: crate::component::TypeLoaders,
601    ) -> VRc<ItemTreeVTable, Instance> {
602        Self::new_with_options(
603            compilation_unit,
604            public_component_index,
605            window_adapter,
606            type_loaders,
607            None,
608        )
609    }
610
611    /// Build an instance embedded inside an existing item tree via a
612    /// `ComponentFactory`. Records the outer item tree handle and the
613    /// `ComponentContainer` slot index it substitutes into so that
614    /// `parent_node` can walk back into the host tree.
615    pub fn new_embedded(
616        compilation_unit: Rc<CompilationUnit>,
617        public_component_index: usize,
618        type_loaders: crate::component::TypeLoaders,
619        parent: vtable::VWeak<ItemTreeVTable>,
620        parent_item_tree_index: u32,
621    ) -> VRc<ItemTreeVTable, Instance> {
622        Self::new_with_options(
623            compilation_unit,
624            public_component_index,
625            None,
626            type_loaders,
627            Some((parent, parent_item_tree_index)),
628        )
629    }
630
631    fn new_with_options(
632        compilation_unit: Rc<CompilationUnit>,
633        public_component_index: usize,
634        window_adapter: Option<i_slint_core::window::WindowAdapterRc>,
635        type_loaders: crate::component::TypeLoaders,
636        embedded_in: Option<(vtable::VWeak<ItemTreeVTable>, u32)>,
637    ) -> VRc<ItemTreeVTable, Instance> {
638        let public = &compilation_unit.public_components[public_component_index];
639        let globals = Rc::new(GlobalStorage::new(&compilation_unit));
640        let item_tree = &public.item_tree;
641        let vrc = build_instance(
642            &compilation_unit,
643            item_tree,
644            Weak::new(),
645            globals,
646            Some(public_component_index),
647            type_loaders,
648        );
649        if let Some(adapter) = window_adapter {
650            let _ = vrc.window_adapter.set(adapter);
651        }
652        // Set the outer-tree handle before finalizing so bindings that
653        // read absolute coordinates during `install_bindings` /
654        // `init_code` can resolve `parent_node` through the host.
655        if let Some((parent, idx)) = embedded_in {
656            let _ = vrc.embedded_in.set((parent, idx));
657        }
658        finalize_instance(&vrc);
659        vrc
660    }
661
662    /// Build an instance for a repeated sub-tree, sharing `globals` with its
663    /// owning root instance.
664    /// `repeater_idx` lets `ModelDataAssignment` find the owning repeater
665    /// when an event in the repeated sub-tree wants to write back.
666    pub fn new_repeated(
667        compilation_unit: Rc<CompilationUnit>,
668        item_tree: &llr::ItemTree,
669        parent: Weak<SubComponentInstance>,
670        repeater_idx: RepeatedElementIdx,
671        globals: Rc<GlobalStorage>,
672    ) -> VRc<ItemTreeVTable, Instance> {
673        let vrc = build_instance(
674            &compilation_unit,
675            item_tree,
676            parent.clone(),
677            globals,
678            None,
679            Default::default(),
680        );
681        let _ = vrc.root_sub_component.repeated_in.set((parent, repeater_idx));
682        vrc
683    }
684
685    /// Build an instance for a popup sub-tree. The resulting `Instance` is
686    /// parented on the sub-component that owns the popup so that parent-
687    /// relative property references resolve through `parent.upgrade()`.
688    pub fn new_popup(
689        compilation_unit: Rc<CompilationUnit>,
690        item_tree: &llr::ItemTree,
691        parent: Weak<SubComponentInstance>,
692        globals: Rc<GlobalStorage>,
693    ) -> VRc<ItemTreeVTable, Instance> {
694        build_instance(&compilation_unit, item_tree, parent, globals, None, Default::default())
695    }
696}
697
698/// Allocate the `Instance` skeleton (sub-component tree, items, repeaters,
699/// tree nodes, globals) but do **not** install bindings yet.
700///
701/// Bindings install happens via [`finalize_instance`], which the caller
702/// invokes once the parent repeater (if any) has dropped its `RefCell`
703/// borrow. This avoids re-entrant repeater access when an `init` callback
704/// reads a layout property that walks back through the same repeater.
705fn build_instance(
706    compilation_unit: &Rc<CompilationUnit>,
707    item_tree: &llr::ItemTree,
708    parent: Weak<SubComponentInstance>,
709    globals: Rc<GlobalStorage>,
710    public_component_index: Option<usize>,
711    type_loaders: crate::component::TypeLoaders,
712) -> VRc<ItemTreeVTable, Instance> {
713    let parent_for_root = parent.clone();
714    let root_sub_component =
715        build_sub_component_instance(compilation_unit, item_tree.root, parent_for_root);
716    let (tree_nodes, dynamic_table, item_table) = build_tree_nodes(&item_tree.tree);
717
718    let vrc = VRc::new(Instance {
719        root_sub_component,
720        tree_nodes: tree_nodes.into_boxed_slice(),
721        dynamic_table: dynamic_table.into_boxed_slice(),
722        item_table: item_table.into_boxed_slice(),
723        globals,
724        self_weak: OnceCell::new(),
725        parent_instance: parent,
726        public_component_index,
727        window_adapter: OnceCell::new(),
728        window_adapter_error: OnceCell::new(),
729        window_attached: OnceCell::new(),
730        bindings_installed: OnceCell::new(),
731        init_code_run: OnceCell::new(),
732        embedded_in: OnceCell::new(),
733        type_loaders,
734    });
735    let weak = VRc::downgrade(&vrc);
736    let _ = vrc.self_weak.set(weak.clone());
737    // Repeated sub-trees and popups share their owner's storage; keep its root.
738    let _ = vrc.globals.root.set(weak.clone());
739    propagate_root(&vrc.root_sub_component, &weak);
740    vrc
741}
742
743/// Install global, sub-component and init bindings on a freshly built
744/// instance, then run `init_code`.
745///
746/// Idempotent: separate `OnceCell` flags guard the bindings install and
747/// the `init_code` step so each side can be called independently. The
748/// listview virtualization path uses
749/// [`install_bindings_for_repeated_row`] to install bindings before the
750/// first measurement and defers `init_code` to the core's
751/// `init_instances` callback (`<Instance as RepeatedItemTree>::init`).
752pub(crate) fn finalize_instance(vrc: &VRc<ItemTreeVTable, Instance>) {
753    install_bindings_for_repeated_row(vrc);
754    if vrc.init_code_run.get().is_some() {
755        return;
756    }
757    let _ = vrc.init_code_run.set(());
758    // For top-level instances, attach the window to the item tree *before*
759    // running init_code so `set_component` doesn't clear focus set by
760    // `forward-focus`. Embedded instances piggy-back on the host tree's
761    // adapter (see `window_adapter_or_default`) and skip this: the host
762    // has already run `set_component`, and running it again on the
763    // embedded root would reroute the host's window events into the sub-
764    // tree and clobber the ComponentContainer-driven size bindings.
765    if vrc.public_component_index.is_some() && vrc.embedded_in.get().is_none() {
766        vrc.attach_to_window();
767    }
768    // Call Item::init() on every native item and register the item tree
769    // with the window adapter. Registration matters: the rendering backend
770    // keeps per-component caches (text shaping, bounding rects) released
771    // only by the matching `unregister_item_tree` on Drop, and skipping
772    // the pair leaks entries until the renderer serves stale data for
773    // reused item addresses.
774    {
775        let dyn_rc = vtable::VRc::into_dyn(vrc.self_weak.get().unwrap().upgrade().unwrap());
776        let adapter = vrc.window_adapter_or_default();
777        i_slint_core::item_tree::register_item_tree(&dyn_rc, adapter);
778    }
779    crate::bindings::run_init_code_for_instance(vrc);
780}
781
782/// Install bindings, two-way links and timers on `vrc` without running
783/// `init_code`. Used by the listview row factory; safe to call from any
784/// other path that needs bindings in place but doesn't want to fire user
785/// init handlers yet.
786pub(crate) fn install_bindings_for_repeated_row(vrc: &VRc<ItemTreeVTable, Instance>) {
787    if vrc.bindings_installed.get().is_some() {
788        return;
789    }
790    let _ = vrc.bindings_installed.set(());
791    let is_root = vrc.parent_instance.upgrade().is_none();
792    if is_root {
793        crate::globals::install_global_bindings(&vrc.globals);
794    }
795    crate::bindings::install_bindings_only(vrc);
796}
797
798/// Back-fill the root weak reference on every sub-component under `sub`.
799fn propagate_root(sub: &Pin<Rc<SubComponentInstance>>, weak: &VWeak<ItemTreeVTable, Instance>) {
800    let _ = sub.root.set(weak.clone());
801    for nested in &sub.sub_components {
802        propagate_root(nested, weak);
803    }
804}
805
806/// Recursively allocate a [`SubComponentInstance`].
807fn build_sub_component_instance(
808    cu: &Rc<CompilationUnit>,
809    sub_idx: SubComponentIdx,
810    parent: Weak<SubComponentInstance>,
811) -> Pin<Rc<SubComponentInstance>> {
812    let sc = &cu.sub_components[sub_idx];
813    let registry = ItemRegistry::global();
814
815    let properties = sc
816        .properties
817        .iter()
818        .map(|p| Rc::pin(Property::new(crate::eval::default_value_for_type(&p.ty))))
819        .collect();
820    let callbacks = sc.callbacks.iter().map(|_| Rc::pin(Callback::default())).collect();
821    let callback_trackers =
822        sc.callbacks.iter().map(|c| c.needs_tracker.then(|| Rc::pin(Property::new(())))).collect();
823    let items =
824        sc.items
825            .iter()
826            .map(|item| {
827                registry.factory(&item.ty.class_name).unwrap_or_else(|| {
828                    panic!("native item `{}` is not registered", item.ty.class_name)
829                })()
830            })
831            .collect();
832    let repeaters = sc
833        .repeated
834        .iter()
835        .map(|rep| {
836            if rep.data_prop.is_none() {
837                RepeaterOrConditional::Conditional(Box::pin(Conditional::default()))
838            } else {
839                RepeaterOrConditional::Repeater(Box::pin(Repeater::default()))
840            }
841        })
842        .collect();
843
844    // `Rc::new_cyclic` gives nested sub-components a `Weak` to their parent.
845    // `SubComponentInstance` is `Unpin` (every pinned field lives behind its own
846    // `Pin<Rc<_>>`), so `Pin::new` on the resulting `Rc` needs no unsafe.
847    let rc = Rc::new_cyclic(|weak_self: &Weak<SubComponentInstance>| {
848        let sub_components = sc
849            .sub_components
850            .iter()
851            .map(|nested| build_sub_component_instance(cu, nested.ty, weak_self.clone()))
852            .collect();
853        SubComponentInstance {
854            compilation_unit: cu.clone(),
855            sub_component_idx: sub_idx,
856            properties,
857            callbacks,
858            callback_trackers,
859            items,
860            sub_components,
861            repeaters,
862            parent,
863            root: OnceCell::new(),
864            change_trackers: std::iter::repeat_with(ChangeTracker::default)
865                .take(2 * sc.timers.len() + sc.change_callbacks.len())
866                .collect(),
867            timers: std::iter::repeat_with(Default::default).take(sc.timers.len()).collect(),
868            popup_ids: vec![std::cell::Cell::new(None); sc.popup_windows.len()],
869            repeated_in: OnceCell::new(),
870            menubar: RefCell::new(None),
871        }
872    });
873    Pin::new(rc)
874}
875
876/// Read a `MemberReference` (rooted in `sub`) and convert the result to a
877/// `LogicalLength`. Used to seed the listview virtualization with the
878/// listview-width / listview-height values stored as `Value::Number`.
879fn read_logical_length(
880    sub: &Pin<Rc<SubComponentInstance>>,
881    mr: &llr::MemberReference,
882) -> i_slint_core::lengths::LogicalLength {
883    let mut ctx = crate::eval::EvalContext::new(sub.clone());
884    let v = crate::eval::load_property(&ctx, mr);
885    let _ = &mut ctx;
886    let n: f64 = v.try_into().unwrap_or(0.0);
887    i_slint_core::lengths::LogicalLength::new(n as f32)
888}
889
890/// Shim implementing [`i_slint_core::model::ListViewProperties`] over
891/// the interpreter's `Value`-typed content storage. The content
892/// references may be user-declared `Property<Value>` fields *or* native
893/// item properties (e.g. `Flickable::content-y`); routing through
894/// `load_property` / `store_property` handles both uniformly.
895struct ValueListViewProps {
896    content_y: llr::MemberReference,
897    /// `None` when the user set `content-width` explicitly, in which case
898    /// the ListView must not overwrite it (see #12264).
899    content_width: Option<llr::MemberReference>,
900    content_height: Option<llr::MemberReference>,
901    ctx_sub: Pin<Rc<SubComponentInstance>>,
902}
903
904impl i_slint_core::model::ListViewProperties for ValueListViewProps {
905    fn content_y_get(&self) -> i_slint_core::lengths::LogicalLength {
906        read_logical_length(&self.ctx_sub, &self.content_y)
907    }
908    fn content_y_get_internal(&self) -> i_slint_core::lengths::LogicalLength {
909        // The rtti route has no equivalent of `Property::get_internal`;
910        // reading normally only differs while a physics animation drives
911        // `content-y`, where it may re-evaluate the animated binding.
912        read_logical_length(&self.ctx_sub, &self.content_y)
913    }
914    fn content_y_set(&self, value: i_slint_core::lengths::LogicalLength) {
915        let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
916        crate::eval::store_property(
917            &ctx,
918            &self.content_y,
919            crate::Value::Number(value.get() as f64),
920        );
921    }
922    fn content_y_has_binding(&self) -> bool {
923        // Unlike the generated code, the interpreter doesn't track whether
924        // the underlying property has an external binding; `false` lets
925        // `update_visible_instances` clamp the value when scrolling.
926        false
927    }
928    fn computes_content_height(&self) -> bool {
929        self.content_height.is_some()
930    }
931    fn content_width_set(&self, value: i_slint_core::lengths::LogicalLength) {
932        let Some(content_width) = &self.content_width else { return };
933        let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
934        crate::eval::store_property(&ctx, content_width, crate::Value::Number(value.get() as f64));
935    }
936    fn content_height_set(&self, value: i_slint_core::lengths::LogicalLength) {
937        let Some(content_height) = &self.content_height else { return };
938        let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
939        crate::eval::store_property(&ctx, content_height, crate::Value::Number(value.get() as f64));
940    }
941    fn register_as_dependencies(&self) {
942        // Reading through `load_property` registers the dependency with the
943        // current tracking scope, which is all this hook needs.
944        if let Some(content_width) = &self.content_width {
945            let _ = read_logical_length(&self.ctx_sub, content_width);
946        }
947        if let Some(content_height) = &self.content_height {
948            let _ = read_logical_length(&self.ctx_sub, content_height);
949        }
950        let _ = read_logical_length(&self.ctx_sub, &self.content_y);
951    }
952}
953
954type DynamicEntry = Option<(Box<[SubComponentInstanceIdx]>, RepeatedElementIdx)>;
955type ItemEntry = Option<(Box<[SubComponentInstanceIdx]>, ItemInstanceIdx)>;
956
957/// Flatten an LLR [`llr::TreeNode`] into the `ItemTreeNode` slice expected by
958/// the `get_item_tree` vtable entry, plus two parallel tables: one mapping
959/// flat indices to the dynamic repeaters they represent, and one mapping
960/// static flat indices to the sub-component path + items slot that owns them.
961///
962/// Walks in the same order as [`llr::TreeNode::visit_in_array`], so flat
963/// indices match what the rest of the runtime expects.
964fn build_tree_nodes(
965    root: &llr::TreeNode,
966) -> (Vec<ItemTreeNode>, Vec<DynamicEntry>, Vec<ItemEntry>) {
967    use itertools::Either;
968
969    let mut out = Vec::new();
970    let mut dyn_table: Vec<DynamicEntry> = Vec::new();
971    let mut item_table: Vec<ItemEntry> = Vec::new();
972    root.visit_in_array(&mut |node, children_offset, parent_index| {
973        let parent_index = parent_index as u32;
974        let (entry, dyn_entry, item_entry) = match node.item_index {
975            Either::Left(item_idx) => (
976                ItemTreeNode::Item {
977                    is_accessible: node.is_accessible,
978                    children_count: node.children.len() as u32,
979                    children_index: children_offset as u32,
980                    parent_index,
981                    // `item_array_index` is the flat tree index so
982                    // `get_item_ref` can walk the item_table directly.
983                    item_array_index: out.len() as u32,
984                },
985                None,
986                Some((node.sub_component_path.clone().into_boxed_slice(), item_idx)),
987            ),
988            Either::Right(dynamic_index) => (
989                // The `index` field on `DynamicTree` is opaque to the core:
990                // whatever value we store here is echoed back to
991                // `visit_dynamic_children` / `get_subtree_range` /
992                // `get_subtree`. Use the flat tree index of this node so
993                // those hooks can look up `dynamic_table` directly, rather
994                // than the Rust-codegen convention of a global repeater
995                // index that's unique across the sub-component tree.
996                ItemTreeNode::DynamicTree { index: out.len() as u32, parent_index },
997                Some((
998                    node.sub_component_path.clone().into_boxed_slice(),
999                    (dynamic_index as usize).into(),
1000                )),
1001                None,
1002            ),
1003        };
1004        out.push(entry);
1005        dyn_table.push(dyn_entry);
1006        item_table.push(item_entry);
1007    });
1008    (out, dyn_table, item_table)
1009}
1010
1011/// Lets [`Instance`] be used inside a `Repeater<C>`.
1012///
1013/// `update(idx, data)` writes the repeater's `index_prop` and `data_prop` on
1014/// the repeated instance's root sub-component.
1015impl i_slint_core::model::RepeatedItemTree for Instance {
1016    type Data = crate::Value;
1017
1018    fn update(&self, index: usize, data: Self::Data) {
1019        let sc_idx = self.root_sub_component.sub_component_idx;
1020        let cu = self.root_sub_component.compilation_unit.clone();
1021        let sc = &cu.sub_components[sc_idx];
1022        // `lower_sub_component` pushes `model_data` and `model_index` as the
1023        // first two properties of a repeated component's root sub-component.
1024        // Walk the full property list so user-declared `index` / `model-data`
1025        // shadows don't accidentally collide with slot 0/1.
1026        for (idx, prop) in sc.properties.iter_enumerated() {
1027            let target = &self.root_sub_component.properties[idx];
1028            match prop.name.as_str() {
1029                "model_data" => Pin::as_ref(target).set(data.clone()),
1030                "model_index" => Pin::as_ref(target).set(crate::Value::Number(index as f64)),
1031                _ => {}
1032            }
1033        }
1034    }
1035
1036    fn init(&self) {
1037        // Bindings and init code are installed here rather than in
1038        // `Instance::new_repeated`: by the time `init` runs,
1039        // `Repeater::ensure_updated` has released its `RefCell` borrow, so
1040        // a binding evaluated here can walk back through the same repeater
1041        // (e.g. an `init` callback that reads a layout property).
1042        if let Some(weak) = self.self_weak.get()
1043            && let Some(vrc) = weak.upgrade()
1044        {
1045            finalize_instance(&vrc);
1046        }
1047    }
1048
1049    fn listview_layout(
1050        self: Pin<&Self>,
1051        offset_y: &mut i_slint_core::lengths::LogicalLength,
1052    ) -> i_slint_core::lengths::LogicalLength {
1053        use i_slint_core::item_tree::ItemTree as _;
1054        use i_slint_core::lengths::LogicalLength;
1055        // Write `prop_y` on the repeated row's root sub-component, advance
1056        // `offset_y` by `prop_height`, and return the row's preferred
1057        // horizontal layout info width as the new content width estimate.
1058        let this = self.get_ref();
1059        let Some((parent_weak, rep_idx)) = this.root_sub_component.repeated_in.get() else {
1060            return LogicalLength::default();
1061        };
1062        let Some(parent_sub) = parent_weak.upgrade() else { return LogicalLength::default() };
1063        let parent_sub = Pin::new(parent_sub);
1064        let parent_cu = parent_sub.compilation_unit.clone();
1065        let parent_sc = &parent_cu.sub_components[parent_sub.sub_component_idx];
1066        let Some(lv) = parent_sc.repeated[*rep_idx].listview.as_ref() else {
1067            return LogicalLength::default();
1068        };
1069
1070        // `prop_y` and `prop_height` are member references in the repeated
1071        // sub-component's own context, so evaluate them against
1072        // `this.root_sub_component`.
1073        let row_sub = this.root_sub_component.clone();
1074        let ctx = crate::eval::EvalContext::new(row_sub.clone());
1075        crate::eval::store_property(&ctx, &lv.prop_y, crate::Value::Number(offset_y.get() as f64));
1076        let height_v = crate::eval::load_property(&ctx, &lv.prop_height);
1077        let height: f64 = height_v.try_into().unwrap_or(0.0);
1078        *offset_y += LogicalLength::new(height as f32);
1079        let info = self.layout_info(i_slint_core::items::Orientation::Horizontal);
1080        LogicalLength::new(info.min)
1081    }
1082
1083    fn layout_item_info(
1084        self: Pin<&Self>,
1085        orientation: i_slint_core::items::Orientation,
1086        child_index: Option<usize>,
1087    ) -> i_slint_core::layout::LayoutItemInfo {
1088        // Evaluate the repeated component's `layout_info_h` / `layout_info_v`
1089        // and wrap the result in a LayoutItemInfo.
1090        //
1091        // When the sub-component is a repeated Row with `row_child_templates`,
1092        // each `child_index` points at one concrete child position. Walk the
1093        // templates in declaration order and return per-child layout info —
1094        // static children read `grid_layout_children[idx]`, repeated children
1095        // forward to the inner repeater instance's own `layout_info`.
1096        let this = self.get_ref();
1097        let cu = this.root_sub_component.compilation_unit.clone();
1098        let sc_idx = this.root_sub_component.sub_component_idx;
1099        let sc = &cu.sub_components[sc_idx];
1100
1101        if let (Some(index), true, Some(templates)) =
1102            (child_index, sc.is_repeated_row, sc.row_child_templates.as_ref())
1103        {
1104            return row_child_layout_item_info(this, sc, templates, orientation, index);
1105        }
1106
1107        let expr = match orientation {
1108            i_slint_core::items::Orientation::Horizontal => sc.layout_info_h.borrow(),
1109            i_slint_core::items::Orientation::Vertical => sc.layout_info_v.borrow(),
1110        };
1111        let mut ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1112        let constraint =
1113            crate::eval::eval_expression(&mut ctx, &expr).try_into().unwrap_or_default();
1114        // The cell's `cross-axis-self-alignment` in a box layout, returned for
1115        // the cross axis only, so the main-axis cache stays independent of it.
1116        let cross_axis_self_alignment = match &sc.cross_axis_self_alignment_for_repeated {
1117            Some((cross_o, align_expr))
1118                if crate::eval::llr_to_core_orientation(*cross_o) == orientation =>
1119            {
1120                crate::eval::eval_expression(&mut ctx, &align_expr.borrow())
1121                    .try_into()
1122                    .unwrap_or_default()
1123            }
1124            _ => Default::default(),
1125        };
1126        i_slint_core::layout::LayoutItemInfo { constraint, cross_axis_self_alignment }
1127    }
1128
1129    fn flexbox_layout_item_info(
1130        self: Pin<&Self>,
1131        orientation: i_slint_core::items::Orientation,
1132        child_index: Option<usize>,
1133    ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1134        // For flexbox, the SubComponent stores `flexbox_layout_item_info_for_repeated`
1135        // - an expression that evaluates to a `FlexboxLayoutItemInfo` struct.
1136        // Fall back to wrapping `layout_item_info` if it's not set.
1137        let cu = self.root_sub_component.compilation_unit.clone();
1138        let sc_idx = self.root_sub_component.sub_component_idx;
1139        let sc = &cu.sub_components[sc_idx];
1140        if let Some(expr) = &sc.flexbox_layout_item_info_for_repeated {
1141            let expr = expr.borrow();
1142            let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1143            let value = crate::eval::eval_expression(&mut ctx, &expr);
1144            let mut info = value_to_flexbox_layout_item_info(value, orientation, self);
1145            // Break the height-for-width recursion for a repeated instance in
1146            // a column FlexboxLayout: its vertical info must not read
1147            // self.width (set by the parent flex cache it is feeding). Use the
1148            // constrained vertical info (computed at the instance's own
1149            // preferred width) instead.
1150            if matches!(orientation, i_slint_core::items::Orientation::Vertical)
1151                && child_index.is_none()
1152                && let Some(v_expr) = &sc.layout_info_v_constrained_for_repeated
1153            {
1154                let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1155                info.constraint = crate::eval::eval_expression(&mut ctx, &v_expr.borrow())
1156                    .try_into()
1157                    .unwrap_or_default();
1158                return info;
1159            }
1160            // Mirror for the other axis: a width-for-height instance (e.g. a
1161            // wrapping column FlexboxLayout) must not read self.height. Use the
1162            // constrained horizontal info (computed at an unbounded height).
1163            if matches!(orientation, i_slint_core::items::Orientation::Horizontal)
1164                && child_index.is_none()
1165                && let Some(h_expr) = &sc.layout_info_h_constrained_for_repeated
1166            {
1167                let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1168                info.constraint = crate::eval::eval_expression(&mut ctx, &h_expr.borrow())
1169                    .try_into()
1170                    .unwrap_or_default();
1171                return info;
1172            }
1173            // The expression leaves the constraint unset; fill it with the
1174            // layout item's real constraint.
1175            info.constraint = self.layout_item_info(orientation, child_index).constraint;
1176            return info;
1177        }
1178        let info = self.layout_item_info(orientation, None);
1179        info.into()
1180    }
1181}
1182
1183impl Instance {
1184    /// Vertical flexbox info for a repeated instance measured at the container
1185    /// cross width instead of its own preferred width, so a height-for-width
1186    /// cell wraps to the same height as an equivalent static cell.
1187    pub fn flexbox_layout_item_info_at_cross_width(
1188        self: Pin<&Self>,
1189        flex_cross_width: f32,
1190    ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1191        use i_slint_core::items::Orientation;
1192        use i_slint_core::model::RepeatedItemTree;
1193        let mut info =
1194            RepeatedItemTree::flexbox_layout_item_info(self, Orientation::Vertical, None);
1195        let cu = self.root_sub_component.compilation_unit.clone();
1196        let sc = &cu.sub_components[self.root_sub_component.sub_component_idx];
1197        if let Some(v_expr) = &sc.layout_info_v_at_cross_width_for_repeated {
1198            let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1199            ctx.locals.insert(
1200                i_slint_compiler::llr::lower_layout_expression::FLEX_CROSS_WIDTH_LOCAL.into(),
1201                crate::Value::Number(flex_cross_width as f64),
1202            );
1203            info.constraint = crate::eval::eval_expression(&mut ctx, &v_expr.borrow())
1204                .try_into()
1205                .unwrap_or_default();
1206        }
1207        info
1208    }
1209
1210    /// Horizontal flexbox info for a repeated instance measured at the assigned
1211    /// cross height, so a width-for-height cell resolves to the same width as
1212    /// an equivalent static cell.
1213    pub fn flexbox_layout_item_info_at_cross_height(
1214        self: Pin<&Self>,
1215        flex_cross_height: f32,
1216    ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1217        use i_slint_core::items::Orientation;
1218        use i_slint_core::model::RepeatedItemTree;
1219        let mut info =
1220            RepeatedItemTree::flexbox_layout_item_info(self, Orientation::Horizontal, None);
1221        let cu = self.root_sub_component.compilation_unit.clone();
1222        let sc = &cu.sub_components[self.root_sub_component.sub_component_idx];
1223        if let Some(h_expr) = &sc.layout_info_h_at_cross_height_for_repeated {
1224            let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1225            ctx.locals.insert(
1226                i_slint_compiler::llr::lower_layout_expression::FLEX_CROSS_HEIGHT_LOCAL.into(),
1227                crate::Value::Number(flex_cross_height as f64),
1228            );
1229            info.constraint = crate::eval::eval_expression(&mut ctx, &h_expr.borrow())
1230                .try_into()
1231                .unwrap_or_default();
1232        }
1233        info
1234    }
1235}
1236
1237/// Walk the row_child_templates in declaration order, counting cells, until
1238/// the target `index` is reached. Static cells read from `grid_layout_children`;
1239/// a repeated cell forwards to the inner repeater instance's `layout_info`.
1240fn row_child_layout_item_info(
1241    this: &Instance,
1242    sc: &i_slint_compiler::llr::SubComponent,
1243    templates: &[i_slint_compiler::llr::RowChildTemplateInfo],
1244    orientation: i_slint_core::items::Orientation,
1245    mut index: usize,
1246) -> i_slint_core::layout::LayoutItemInfo {
1247    use i_slint_compiler::llr::RowChildTemplateInfo;
1248    use i_slint_core::model::RepeatedItemTree;
1249    for entry in templates {
1250        match entry {
1251            RowChildTemplateInfo::Static { child_index } => {
1252                if index == 0 {
1253                    let child = &sc.grid_layout_children[*child_index];
1254                    let expr = match orientation {
1255                        i_slint_core::items::Orientation::Horizontal => {
1256                            child.layout_info_h.borrow()
1257                        }
1258                        i_slint_core::items::Orientation::Vertical => child.layout_info_v.borrow(),
1259                    };
1260                    let mut ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1261                    let constraint = crate::eval::eval_expression(&mut ctx, &expr)
1262                        .try_into()
1263                        .unwrap_or_default();
1264                    return i_slint_core::layout::LayoutItemInfo {
1265                        constraint,
1266                        ..Default::default()
1267                    };
1268                }
1269                index -= 1;
1270            }
1271            RowChildTemplateInfo::Repeated { repeater_index } => {
1272                let repeater = &this.root_sub_component.repeaters[*repeater_index];
1273                repeater.track_instance_changes();
1274                let count = repeater.range().len();
1275                if index < count {
1276                    if let Some(inner) = repeater.instance_at(index) {
1277                        return RepeatedItemTree::layout_item_info(
1278                            inner.as_pin_ref(),
1279                            orientation,
1280                            None,
1281                        );
1282                    }
1283                    return i_slint_core::layout::LayoutItemInfo::default();
1284                }
1285                index -= count;
1286            }
1287        }
1288    }
1289    i_slint_core::layout::LayoutItemInfo::default()
1290}
1291
1292fn value_to_flexbox_layout_item_info(
1293    v: crate::Value,
1294    orientation: i_slint_core::items::Orientation,
1295    instance: Pin<&Instance>,
1296) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1297    use i_slint_core::model::RepeatedItemTree;
1298    let crate::Value::Struct(s) = v else {
1299        let info = RepeatedItemTree::layout_item_info(instance, orientation, None);
1300        return info.into();
1301    };
1302    crate::eval_layout::flexbox_item_info_from_struct(&s)
1303}