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