Skip to main content

slint_interpreter/
dynamic_item_tree.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
4use crate::api::{CompilationResult, ComponentDefinition, Value};
5use crate::global_component::CompiledGlobalCollection;
6use crate::{dynamic_type, eval};
7use core::ffi::c_void;
8use core::ptr::NonNull;
9use dynamic_type::{Instance, InstanceBox};
10use i_slint_compiler::expression_tree::{Expression, NamedReference, TwoWayBinding};
11use i_slint_compiler::langtype::{BuiltinStruct, StructName, Type};
12use i_slint_compiler::object_tree::{ElementRc, ElementWeak, TransitionDirection};
13use i_slint_compiler::{CompilerConfiguration, generator, object_tree, parser};
14use i_slint_compiler::{diagnostics::BuildDiagnostics, object_tree::PropertyDeclaration};
15use i_slint_core::accessibility::{
16    AccessibilityAction, AccessibleStringProperty, SupportedAccessibilityAction,
17};
18use i_slint_core::api::LogicalPosition;
19use i_slint_core::component_factory::ComponentFactory;
20use i_slint_core::input::Keys;
21use i_slint_core::item_tree::{
22    IndexRange, ItemRc, ItemTree, ItemTreeNode, ItemTreeRef, ItemTreeRefPin, ItemTreeVTable,
23    ItemTreeWeak, ItemVisitorRefMut, ItemVisitorVTable, ItemWeak, TraversalOrder,
24    VisitChildrenResult,
25};
26use i_slint_core::items::{
27    AccessibleRole, ItemRef, ItemVTable, PopupClosePolicy, PropertyAnimation,
28};
29use i_slint_core::layout::{LayoutInfo, LayoutItemInfo, Orientation};
30use i_slint_core::lengths::{LogicalLength, LogicalRect};
31use i_slint_core::menus::MenuFromItemTree;
32use i_slint_core::model::{ModelRc, RepeatedItemTree, Repeater};
33use i_slint_core::platform::PlatformError;
34use i_slint_core::properties::{ChangeTracker, InterpolatedPropertyValue};
35use i_slint_core::rtti::{self, AnimatedBindingKind, FieldOffset, PropertyInfo};
36use i_slint_core::slice::Slice;
37use i_slint_core::styled_text::StyledText;
38use i_slint_core::timers::Timer;
39use i_slint_core::window::{WindowAdapterRc, WindowInner, WindowKind};
40use i_slint_core::{Brush, Color, DataTransfer, Property, SharedString, SharedVector};
41#[cfg(feature = "internal")]
42use itertools::Either;
43use once_cell::unsync::{Lazy, OnceCell};
44use smol_str::{SmolStr, ToSmolStr};
45use std::collections::BTreeMap;
46use std::collections::HashMap;
47use std::num::NonZeroU32;
48use std::rc::Weak;
49use std::{pin::Pin, rc::Rc};
50
51pub const SPECIAL_PROPERTY_INDEX: &str = "$index";
52pub const SPECIAL_PROPERTY_MODEL_DATA: &str = "$model_data";
53
54pub(crate) type CallbackHandler = Box<dyn Fn(&[Value]) -> Value>;
55
56pub struct ItemTreeBox<'id> {
57    instance: InstanceBox<'id>,
58    description: Rc<ItemTreeDescription<'id>>,
59}
60
61impl<'id> ItemTreeBox<'id> {
62    /// Borrow this instance as a `Pin<ItemTreeRef>`
63    pub fn borrow(&self) -> ItemTreeRefPin<'_> {
64        self.borrow_instance().borrow()
65    }
66
67    /// Safety: the lifetime is not unique
68    pub fn description(&self) -> Rc<ItemTreeDescription<'id>> {
69        self.description.clone()
70    }
71
72    pub fn borrow_instance<'a>(&'a self) -> InstanceRef<'a, 'id> {
73        InstanceRef { instance: self.instance.as_pin_ref(), description: &self.description }
74    }
75
76    pub fn window_adapter_ref(&self) -> Result<&WindowAdapterRc, PlatformError> {
77        let root_weak = vtable::VWeak::into_dyn(self.borrow_instance().root_weak().clone());
78        InstanceRef::get_or_init_window_adapter_ref(
79            &self.description,
80            root_weak,
81            true,
82            self.instance.as_pin_ref().get_ref(),
83        )
84    }
85}
86
87pub(crate) type ErasedItemTreeBoxWeak = vtable::VWeak<ItemTreeVTable, ErasedItemTreeBox>;
88
89pub(crate) struct ItemWithinItemTree {
90    offset: usize,
91    pub(crate) rtti: Rc<ItemRTTI>,
92    elem: ElementRc,
93}
94
95impl ItemWithinItemTree {
96    /// Safety: the pointer must be a dynamic item tree which is coming from the same description as Self
97    pub(crate) unsafe fn item_from_item_tree(
98        &self,
99        mem: *const u8,
100    ) -> Pin<vtable::VRef<'_, ItemVTable>> {
101        unsafe {
102            Pin::new_unchecked(vtable::VRef::from_raw(
103                NonNull::from(self.rtti.vtable),
104                NonNull::new(mem.add(self.offset) as _).unwrap(),
105            ))
106        }
107    }
108
109    pub(crate) fn item_index(&self) -> u32 {
110        *self.elem.borrow().item_index.get().unwrap()
111    }
112}
113
114pub(crate) struct PropertiesWithinComponent {
115    pub(crate) offset: usize,
116    pub(crate) prop: Box<dyn PropertyInfo<u8, Value>>,
117}
118
119pub(crate) struct RepeaterWithinItemTree<'par_id, 'sub_id> {
120    /// The description of the items to repeat
121    pub(crate) item_tree_to_repeat: Rc<ItemTreeDescription<'sub_id>>,
122    /// The model
123    pub(crate) model: Expression,
124    /// Offset of the `Repeater`
125    offset: FieldOffset<Instance<'par_id>, Repeater<ErasedItemTreeBox>>,
126    /// When true, it is representing a `if`, instead of a `for`.
127    /// Based on [`i_slint_compiler::object_tree::RepeatedElementInfo::is_conditional_element`]
128    is_conditional: bool,
129}
130
131impl RepeatedItemTree for ErasedItemTreeBox {
132    type Data = Value;
133
134    fn update(&self, index: usize, data: Self::Data) {
135        generativity::make_guard!(guard);
136        let s = self.unerase(guard);
137        let is_repeated = s.description.original.parent_element().is_some_and(|p| {
138            p.borrow().repeated.as_ref().is_some_and(|r| !r.is_conditional_element)
139        });
140        if is_repeated {
141            s.description.set_property(s.borrow(), SPECIAL_PROPERTY_INDEX, index.into()).unwrap();
142            s.description.set_property(s.borrow(), SPECIAL_PROPERTY_MODEL_DATA, data).unwrap();
143        }
144    }
145
146    fn init(&self) {
147        self.run_setup_code();
148    }
149
150    fn listview_layout(self: Pin<&Self>, offset_y: &mut LogicalLength) -> LogicalLength {
151        generativity::make_guard!(guard);
152        let s = self.unerase(guard);
153
154        let geom = s.description.original.root_element.borrow().geometry_props.clone().unwrap();
155
156        crate::eval::store_property(
157            s.borrow_instance(),
158            &geom.y.element(),
159            geom.y.name(),
160            Value::Number(offset_y.get() as f64),
161        )
162        .expect("cannot set y");
163
164        let h: LogicalLength = crate::eval::load_property(
165            s.borrow_instance(),
166            &geom.height.element(),
167            geom.height.name(),
168        )
169        .expect("missing height")
170        .try_into()
171        .expect("height not the right type");
172
173        *offset_y += h;
174        LogicalLength::new(self.borrow().as_ref().layout_info(Orientation::Horizontal).min)
175    }
176
177    fn layout_item_info(
178        self: Pin<&Self>,
179        o: Orientation,
180        child_index: Option<usize>,
181    ) -> LayoutItemInfo {
182        generativity::make_guard!(guard);
183        let s = self.unerase(guard);
184
185        if let Some(index) = child_index {
186            let instance_ref = s.borrow_instance();
187            let root_element = &s.description.original.root_element;
188
189            let children = root_element.borrow().children.clone();
190            if let Some(child_elem) = children.get(index) {
191                // Get the layout info for this child element
192                let layout_info = crate::eval_layout::get_layout_info(
193                    child_elem,
194                    instance_ref,
195                    &instance_ref.window_adapter(),
196                    crate::eval_layout::from_runtime(o),
197                );
198                return LayoutItemInfo { constraint: layout_info };
199            } else {
200                panic!(
201                    "child_index {} out of bounds for repeated item {}",
202                    index,
203                    s.description().id()
204                );
205            }
206        }
207
208        LayoutItemInfo { constraint: self.borrow().as_ref().layout_info(o) }
209    }
210
211    fn flexbox_layout_item_info(
212        self: Pin<&Self>,
213        o: Orientation,
214        child_index: Option<usize>,
215    ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
216        generativity::make_guard!(guard);
217        let s = self.unerase(guard);
218        let instance_ref = s.borrow_instance();
219        let root_element = &s.description.original.root_element;
220
221        let load_f32 = |name: &str| -> f32 {
222            eval::load_property(instance_ref, root_element, name)
223                .ok()
224                .and_then(|v| v.try_into().ok())
225                .unwrap_or(0.0)
226        };
227
228        let flex_grow = load_f32("flex-grow");
229        let flex_shrink = load_f32("flex-shrink");
230        let flex_basis = if root_element.borrow().bindings.contains_key("flex-basis") {
231            load_f32("flex-basis")
232        } else {
233            -1.0
234        };
235        let flex_align_self = eval::load_property(instance_ref, root_element, "flex-align-self")
236            .ok()
237            .and_then(|v| v.try_into().ok())
238            .unwrap_or(i_slint_core::items::FlexboxLayoutAlignSelf::Auto);
239        let flex_order = load_f32("flex-order") as i32;
240
241        i_slint_core::layout::FlexboxLayoutItemInfo {
242            constraint: self.layout_item_info(o, child_index).constraint,
243            flex_grow,
244            flex_shrink,
245            flex_basis,
246            flex_align_self,
247            flex_order,
248        }
249    }
250}
251
252impl ItemTree for ErasedItemTreeBox {
253    fn visit_children_item(
254        self: Pin<&Self>,
255        index: isize,
256        order: TraversalOrder,
257        visitor: ItemVisitorRefMut,
258    ) -> VisitChildrenResult {
259        self.borrow().as_ref().visit_children_item(index, order, visitor)
260    }
261
262    fn layout_info(self: Pin<&Self>, orientation: Orientation) -> i_slint_core::layout::LayoutInfo {
263        self.borrow().as_ref().layout_info(orientation)
264    }
265
266    fn ensure_instantiated(self: Pin<&Self>) -> bool {
267        self.borrow().as_ref().ensure_instantiated()
268    }
269
270    fn get_item_tree(self: Pin<&Self>) -> Slice<'_, ItemTreeNode> {
271        get_item_tree(self.get_ref().borrow())
272    }
273
274    fn get_item_ref(self: Pin<&Self>, index: u32) -> Pin<ItemRef<'_>> {
275        // We're having difficulties transferring the lifetime to a pinned reference
276        // to the other ItemTreeVTable with the same life time. So skip the vtable
277        // indirection and call our implementation directly.
278        unsafe { get_item_ref(self.get_ref().borrow(), index) }
279    }
280
281    fn get_subtree_range(self: Pin<&Self>, index: u32) -> IndexRange {
282        self.borrow().as_ref().get_subtree_range(index)
283    }
284
285    fn get_subtree(self: Pin<&Self>, index: u32, subindex: usize, result: &mut ItemTreeWeak) {
286        self.borrow().as_ref().get_subtree(index, subindex, result);
287    }
288
289    fn parent_node(self: Pin<&Self>, result: &mut ItemWeak) {
290        self.borrow().as_ref().parent_node(result)
291    }
292
293    fn embed_component(
294        self: core::pin::Pin<&Self>,
295        parent_component: &ItemTreeWeak,
296        item_tree_index: u32,
297    ) -> bool {
298        self.borrow().as_ref().embed_component(parent_component, item_tree_index)
299    }
300
301    fn subtree_index(self: Pin<&Self>) -> usize {
302        self.borrow().as_ref().subtree_index()
303    }
304
305    fn item_geometry(self: Pin<&Self>, item_index: u32) -> i_slint_core::lengths::LogicalRect {
306        self.borrow().as_ref().item_geometry(item_index)
307    }
308
309    fn accessible_role(self: Pin<&Self>, index: u32) -> AccessibleRole {
310        self.borrow().as_ref().accessible_role(index)
311    }
312
313    fn accessible_string_property(
314        self: Pin<&Self>,
315        index: u32,
316        what: AccessibleStringProperty,
317        result: &mut SharedString,
318    ) -> bool {
319        self.borrow().as_ref().accessible_string_property(index, what, result)
320    }
321
322    fn window_adapter(self: Pin<&Self>, do_create: bool, result: &mut Option<WindowAdapterRc>) {
323        self.borrow().as_ref().window_adapter(do_create, result);
324    }
325
326    fn accessibility_action(self: core::pin::Pin<&Self>, index: u32, action: &AccessibilityAction) {
327        self.borrow().as_ref().accessibility_action(index, action)
328    }
329
330    fn supported_accessibility_actions(
331        self: core::pin::Pin<&Self>,
332        index: u32,
333    ) -> SupportedAccessibilityAction {
334        self.borrow().as_ref().supported_accessibility_actions(index)
335    }
336
337    fn item_element_infos(
338        self: core::pin::Pin<&Self>,
339        index: u32,
340        result: &mut SharedString,
341    ) -> bool {
342        self.borrow().as_ref().item_element_infos(index, result)
343    }
344}
345
346i_slint_core::ItemTreeVTable_static!(static COMPONENT_BOX_VT for ErasedItemTreeBox);
347
348impl Drop for ErasedItemTreeBox {
349    fn drop(&mut self) {
350        generativity::make_guard!(guard);
351        let unerase = self.unerase(guard);
352        let instance_ref = unerase.borrow_instance();
353
354        let maybe_window_adapter = instance_ref
355            .description
356            .extra_data_offset
357            .apply(instance_ref.as_ref())
358            .globals
359            .get()
360            .and_then(|globals| globals.window_adapter())
361            .and_then(|wa| wa.get());
362        if let Some(window_adapter) = maybe_window_adapter {
363            i_slint_core::item_tree::unregister_item_tree(
364                instance_ref.instance,
365                vtable::VRef::new(self),
366                instance_ref.description.item_array.as_slice(),
367                window_adapter,
368            );
369        }
370    }
371}
372
373pub type DynamicComponentVRc = vtable::VRc<ItemTreeVTable, ErasedItemTreeBox>;
374
375#[derive(Default)]
376pub(crate) struct ComponentExtraData {
377    pub(crate) globals: OnceCell<crate::global_component::GlobalStorage>,
378    pub(crate) self_weak: OnceCell<ErasedItemTreeBoxWeak>,
379    pub(crate) embedding_position: OnceCell<(ItemTreeWeak, u32)>,
380}
381
382struct ErasedRepeaterWithinComponent<'id>(RepeaterWithinItemTree<'id, 'static>);
383impl<'id, 'sub_id> From<RepeaterWithinItemTree<'id, 'sub_id>>
384    for ErasedRepeaterWithinComponent<'id>
385{
386    fn from(from: RepeaterWithinItemTree<'id, 'sub_id>) -> Self {
387        // Safety: this is safe as we erase the sub_id lifetime.
388        // As long as when we get it back we get an unique lifetime with ErasedRepeaterWithinComponent::unerase
389        Self(unsafe {
390            core::mem::transmute::<
391                RepeaterWithinItemTree<'id, 'sub_id>,
392                RepeaterWithinItemTree<'id, 'static>,
393            >(from)
394        })
395    }
396}
397impl<'id> ErasedRepeaterWithinComponent<'id> {
398    pub fn unerase<'a, 'sub_id>(
399        &'a self,
400        _guard: generativity::Guard<'sub_id>,
401    ) -> &'a RepeaterWithinItemTree<'id, 'sub_id> {
402        // Safety: we just go from 'static to an unique lifetime
403        unsafe {
404            core::mem::transmute::<
405                &'a RepeaterWithinItemTree<'id, 'static>,
406                &'a RepeaterWithinItemTree<'id, 'sub_id>,
407            >(&self.0)
408        }
409    }
410
411    /// Return a repeater with a ItemTree with a 'static lifetime
412    ///
413    /// Safety: one should ensure that the inner ItemTree is not mixed with other inner ItemTree
414    unsafe fn get_untagged(&self) -> &RepeaterWithinItemTree<'id, 'static> {
415        &self.0
416    }
417}
418
419type Callback = i_slint_core::Callback<[Value], Value>;
420
421#[derive(Clone)]
422pub struct ErasedItemTreeDescription(Rc<ItemTreeDescription<'static>>);
423impl ErasedItemTreeDescription {
424    pub fn unerase<'a, 'id>(
425        &'a self,
426        _guard: generativity::Guard<'id>,
427    ) -> &'a Rc<ItemTreeDescription<'id>> {
428        // Safety: we just go from 'static to an unique lifetime
429        unsafe {
430            core::mem::transmute::<
431                &'a Rc<ItemTreeDescription<'static>>,
432                &'a Rc<ItemTreeDescription<'id>>,
433            >(&self.0)
434        }
435    }
436}
437impl<'id> From<Rc<ItemTreeDescription<'id>>> for ErasedItemTreeDescription {
438    fn from(from: Rc<ItemTreeDescription<'id>>) -> Self {
439        // Safety: We never access the ItemTreeDescription with the static lifetime, only after we unerase it
440        Self(unsafe {
441            core::mem::transmute::<Rc<ItemTreeDescription<'id>>, Rc<ItemTreeDescription<'static>>>(
442                from,
443            )
444        })
445    }
446}
447
448/// ItemTreeDescription is a representation of a ItemTree suitable for interpretation
449///
450/// It contains information about how to create and destroy the Component.
451/// Its first member is the ItemTreeVTable for generated instance, since it is a `#[repr(C)]`
452/// structure, it is valid to cast a pointer to the ItemTreeVTable back to a
453/// ItemTreeDescription to access the extra field that are needed at runtime
454#[repr(C)]
455pub struct ItemTreeDescription<'id> {
456    pub(crate) ct: ItemTreeVTable,
457    /// INVARIANT: both dynamic_type and item_tree have the same lifetime id. Here it is erased to 'static
458    dynamic_type: Rc<dynamic_type::TypeInfo<'id>>,
459    item_tree: Vec<ItemTreeNode>,
460    item_array:
461        Vec<vtable::VOffset<crate::dynamic_type::Instance<'id>, ItemVTable, vtable::AllowPin>>,
462    pub(crate) items: HashMap<SmolStr, ItemWithinItemTree>,
463    pub(crate) custom_properties: HashMap<SmolStr, PropertiesWithinComponent>,
464    pub(crate) custom_callbacks: HashMap<SmolStr, FieldOffset<Instance<'id>, Callback>>,
465    /// For each exported callback, a `Property<()>` that tracks when the handler changes.
466    /// Calling `get()` before invoking a callback registers a dependency; calling `mark_dirty()`
467    /// after setting a handler triggers re-evaluation of dependent bindings.
468    pub(crate) callback_trackers: HashMap<SmolStr, FieldOffset<Instance<'id>, Property<()>>>,
469    repeater: Vec<ErasedRepeaterWithinComponent<'id>>,
470    /// Map the Element::id of the repeater to the index in the `repeater` vec
471    pub repeater_names: HashMap<SmolStr, usize>,
472    /// Offset to a Option<ComponentPinRef>
473    pub(crate) parent_item_tree_offset:
474        Option<FieldOffset<Instance<'id>, OnceCell<ErasedItemTreeBoxWeak>>>,
475    pub(crate) root_offset: FieldOffset<Instance<'id>, OnceCell<ErasedItemTreeBoxWeak>>,
476    /// Offset of a ComponentExtraData
477    pub(crate) extra_data_offset: FieldOffset<Instance<'id>, ComponentExtraData>,
478    /// Keep the Rc alive
479    pub(crate) original: Rc<object_tree::Component>,
480    /// Maps from an item_id to the original element it came from
481    pub(crate) original_elements: Vec<ElementRc>,
482    /// Copy of original.root_element.property_declarations, without a guarded refcell
483    public_properties: BTreeMap<SmolStr, PropertyDeclaration>,
484    change_trackers: Option<(
485        FieldOffset<Instance<'id>, OnceCell<Vec<ChangeTracker>>>,
486        Vec<(NamedReference, Expression)>,
487    )>,
488    timers: Vec<FieldOffset<Instance<'id>, Timer>>,
489    /// Map of element IDs to their active popup's ID
490    popup_ids: std::cell::RefCell<HashMap<SmolStr, NonZeroU32>>,
491
492    pub(crate) popup_menu_description: PopupMenuDescription,
493
494    /// The collection of compiled globals
495    compiled_globals: Option<Rc<CompiledGlobalCollection>>,
496
497    /// The type loader, which will be available only on the top-most `ItemTreeDescription`.
498    /// All other `ItemTreeDescription`s have `None` here.
499    #[cfg(feature = "internal-highlight")]
500    pub(crate) type_loader:
501        std::cell::OnceCell<std::rc::Rc<i_slint_compiler::typeloader::TypeLoader>>,
502    /// The type loader, which will be available only on the top-most `ItemTreeDescription`.
503    /// All other `ItemTreeDescription`s have `None` here.
504    #[cfg(feature = "internal-highlight")]
505    pub(crate) raw_type_loader:
506        std::cell::OnceCell<Option<std::rc::Rc<i_slint_compiler::typeloader::TypeLoader>>>,
507}
508
509#[derive(Clone, derive_more::From)]
510pub(crate) enum PopupMenuDescription {
511    Rc(Rc<ErasedItemTreeDescription>),
512    Weak(Weak<ErasedItemTreeDescription>),
513}
514impl PopupMenuDescription {
515    pub fn unerase<'id>(&self, guard: generativity::Guard<'id>) -> Rc<ItemTreeDescription<'id>> {
516        match self {
517            PopupMenuDescription::Rc(rc) => rc.unerase(guard).clone(),
518            PopupMenuDescription::Weak(weak) => weak.upgrade().unwrap().unerase(guard).clone(),
519        }
520    }
521}
522
523fn internal_properties_to_public<'a>(
524    prop_iter: impl Iterator<Item = (&'a SmolStr, &'a PropertyDeclaration)> + 'a,
525) -> impl Iterator<
526    Item = (
527        SmolStr,
528        i_slint_compiler::langtype::Type,
529        i_slint_compiler::object_tree::PropertyVisibility,
530    ),
531> + 'a {
532    prop_iter.filter(|(_, v)| v.expose_in_public_api).map(|(s, v)| {
533        let name = v
534            .node
535            .as_ref()
536            .and_then(|n| {
537                n.child_node(parser::SyntaxKind::DeclaredIdentifier)
538                    .and_then(|n| n.child_token(parser::SyntaxKind::Identifier))
539            })
540            .map(|n| n.to_smolstr())
541            .unwrap_or_else(|| s.to_smolstr());
542        (name, v.property_type.clone(), v.visibility)
543    })
544}
545
546#[derive(Default)]
547pub enum WindowOptions {
548    #[default]
549    CreateNewWindow,
550    UseExistingWindow(WindowAdapterRc),
551    Embed {
552        parent_item_tree: ItemTreeWeak,
553        parent_item_tree_index: u32,
554    },
555}
556
557impl ItemTreeDescription<'_> {
558    /// The name of this Component as written in the .slint file
559    pub fn id(&self) -> &str {
560        self.original.id.as_str()
561    }
562
563    /// List of publicly declared properties or callbacks
564    ///
565    /// We try to preserve the dashes and underscore as written in the property declaration
566    pub fn properties(
567        &self,
568    ) -> impl Iterator<
569        Item = (
570            SmolStr,
571            i_slint_compiler::langtype::Type,
572            i_slint_compiler::object_tree::PropertyVisibility,
573        ),
574    > + '_ {
575        internal_properties_to_public(self.public_properties.iter())
576    }
577
578    /// List names of exported global singletons
579    pub fn global_names(&self) -> impl Iterator<Item = SmolStr> + '_ {
580        self.compiled_globals
581            .as_ref()
582            .expect("Root component should have globals")
583            .compiled_globals
584            .iter()
585            .filter(|g| g.visible_in_public_api())
586            .flat_map(|g| g.names().into_iter())
587    }
588
589    pub fn global_properties(
590        &self,
591        name: &str,
592    ) -> Option<
593        impl Iterator<
594            Item = (
595                SmolStr,
596                i_slint_compiler::langtype::Type,
597                i_slint_compiler::object_tree::PropertyVisibility,
598            ),
599        > + '_,
600    > {
601        let g = self.compiled_globals.as_ref().expect("Root component should have globals");
602        g.exported_globals_by_name
603            .get(&crate::normalize_identifier(name))
604            .and_then(|global_idx| g.compiled_globals.get(*global_idx))
605            .map(|global| internal_properties_to_public(global.public_properties()))
606    }
607
608    /// Instantiate a runtime ItemTree from this ItemTreeDescription
609    pub fn create(
610        self: Rc<Self>,
611        options: WindowOptions,
612    ) -> Result<DynamicComponentVRc, PlatformError> {
613        i_slint_backend_selector::with_platform(|_b| {
614            // Nothing to do, just make sure a backend was created
615            Ok(())
616        })?;
617
618        let instance = instantiate(self, None, None, Some(&options), Default::default());
619        if let WindowOptions::UseExistingWindow(existing_adapter) = options {
620            WindowInner::from_pub(existing_adapter.window())
621                .set_component(&vtable::VRc::into_dyn(instance.clone()));
622        }
623        instance.run_setup_code();
624        Ok(instance)
625    }
626
627    /// Set a value to property.
628    ///
629    /// Return an error if the property with this name does not exist,
630    /// or if the value is the wrong type.
631    /// Panics if the component is not an instance corresponding to this ItemTreeDescription,
632    pub fn set_property(
633        &self,
634        component: ItemTreeRefPin,
635        name: &str,
636        value: Value,
637    ) -> Result<(), crate::api::SetPropertyError> {
638        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
639            panic!("mismatch instance and vtable");
640        }
641        generativity::make_guard!(guard);
642        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
643        if let Some(alias) = self
644            .original
645            .root_element
646            .borrow()
647            .property_declarations
648            .get(name)
649            .and_then(|d| d.is_alias.as_ref())
650        {
651            eval::store_property(c, &alias.element(), alias.name(), value)
652        } else {
653            eval::store_property(c, &self.original.root_element, name, value)
654        }
655    }
656
657    /// Set a binding to a property
658    ///
659    /// Returns an error if the instance does not corresponds to this ItemTreeDescription,
660    /// or if the property with this name does not exist in this component
661    pub fn set_binding(
662        &self,
663        component: ItemTreeRefPin,
664        name: &str,
665        binding: Box<dyn Fn() -> Value>,
666    ) -> Result<(), ()> {
667        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
668            return Err(());
669        }
670        let x = self.custom_properties.get(name).ok_or(())?;
671        unsafe {
672            x.prop
673                .set_binding(
674                    Pin::new_unchecked(&*component.as_ptr().add(x.offset)),
675                    binding,
676                    i_slint_core::rtti::AnimatedBindingKind::NotAnimated,
677                )
678                .unwrap()
679        };
680        Ok(())
681    }
682
683    /// Return the value of a property
684    ///
685    /// Returns an error if the component is not an instance corresponding to this ItemTreeDescription,
686    /// or if a callback with this name does not exist
687    pub fn get_property(&self, component: ItemTreeRefPin, name: &str) -> Result<Value, ()> {
688        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
689            return Err(());
690        }
691        generativity::make_guard!(guard);
692        // Safety: we just verified that the component has the right vtable
693        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
694        if let Some(alias) = self
695            .original
696            .root_element
697            .borrow()
698            .property_declarations
699            .get(name)
700            .and_then(|d| d.is_alias.as_ref())
701        {
702            eval::load_property(c, &alias.element(), alias.name())
703        } else {
704            eval::load_property(c, &self.original.root_element, name)
705        }
706    }
707
708    /// Sets an handler for a callback
709    ///
710    /// Returns an error if the component is not an instance corresponding to this ItemTreeDescription,
711    /// or if the property with this name does not exist
712    pub fn set_callback_handler(
713        &self,
714        component: Pin<ItemTreeRef>,
715        name: &str,
716        handler: CallbackHandler,
717    ) -> Result<(), ()> {
718        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
719            return Err(());
720        }
721        if let Some(alias) = self
722            .original
723            .root_element
724            .borrow()
725            .property_declarations
726            .get(name)
727            .and_then(|d| d.is_alias.as_ref())
728        {
729            generativity::make_guard!(guard);
730            // Safety: we just verified that the component has the right vtable
731            let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
732            let inst = eval::ComponentInstance::InstanceRef(c);
733            eval::set_callback_handler(&inst, &alias.element(), alias.name(), handler)?
734        } else {
735            let x = self.custom_callbacks.get(name).ok_or(())?;
736            let inst = unsafe { &*(component.as_ptr() as *const dynamic_type::Instance) };
737            let sig = x.apply(inst);
738            sig.set_handler(handler);
739            if let Some(tracker_offset) = self.callback_trackers.get(name) {
740                tracker_offset.apply_pin(unsafe { Pin::new_unchecked(inst) }).mark_dirty();
741            }
742        }
743        Ok(())
744    }
745
746    /// Invoke the specified callback or function
747    ///
748    /// Returns an error if the component is not an instance corresponding to this ItemTreeDescription,
749    /// or if the callback with this name does not exist in this component
750    pub fn invoke(
751        &self,
752        component: ItemTreeRefPin,
753        name: &SmolStr,
754        args: &[Value],
755    ) -> Result<Value, ()> {
756        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
757            return Err(());
758        }
759        generativity::make_guard!(guard);
760        // Safety: we just verified that the component has the right vtable
761        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
762        let borrow = self.original.root_element.borrow();
763        let decl = borrow.property_declarations.get(name).ok_or(())?;
764
765        let (elem, name) = if let Some(alias) = &decl.is_alias {
766            (alias.element(), alias.name())
767        } else {
768            (self.original.root_element.clone(), name)
769        };
770
771        let inst = eval::ComponentInstance::InstanceRef(c);
772
773        if matches!(&decl.property_type, Type::Function { .. }) {
774            eval::call_function(&inst, &elem, name, args.to_vec()).ok_or(())
775        } else {
776            eval::invoke_callback(&inst, &elem, name, args).ok_or(())
777        }
778    }
779
780    // Return the global with the given name
781    pub fn get_global(
782        &self,
783        component: ItemTreeRefPin,
784        global_name: &str,
785    ) -> Result<Pin<Rc<dyn crate::global_component::GlobalComponent>>, ()> {
786        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
787            return Err(());
788        }
789        generativity::make_guard!(guard);
790        // Safety: we just verified that the component has the right vtable
791        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
792        let extra_data = c.description.extra_data_offset.apply(c.instance.get_ref());
793        let g = extra_data.globals.get().unwrap().get(global_name).clone();
794        g.ok_or(())
795    }
796}
797
798#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
799extern "C" fn visit_children_item(
800    component: ItemTreeRefPin,
801    index: isize,
802    order: TraversalOrder,
803    v: ItemVisitorRefMut,
804) -> VisitChildrenResult {
805    generativity::make_guard!(guard);
806    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
807    let comp_rc = instance_ref.self_weak().get().unwrap().upgrade().unwrap();
808    i_slint_core::item_tree::visit_item_tree(
809        instance_ref.instance,
810        &vtable::VRc::into_dyn(comp_rc),
811        get_item_tree(component).as_slice(),
812        index,
813        order,
814        v,
815        |_, order, visitor, index| {
816            if index as usize >= instance_ref.description.repeater.len() {
817                // Do nothing: We are ComponentContainer and Our parent already did all the work!
818                VisitChildrenResult::CONTINUE
819            } else {
820                generativity::make_guard!(guard);
821                let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
822                let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
823                repeater.visit(order, visitor)
824            }
825        },
826    )
827}
828
829/// Information attached to a builtin item
830pub(crate) struct ItemRTTI {
831    vtable: &'static ItemVTable,
832    type_info: dynamic_type::StaticTypeInfo,
833    pub(crate) properties: HashMap<&'static str, Box<dyn eval::ErasedPropertyInfo>>,
834    pub(crate) callbacks: HashMap<&'static str, Box<dyn eval::ErasedCallbackInfo>>,
835}
836
837fn rtti_for<T: 'static + Default + rtti::BuiltinItem + vtable::HasStaticVTable<ItemVTable>>()
838-> (&'static str, Rc<ItemRTTI>) {
839    let rtti = ItemRTTI {
840        vtable: T::static_vtable(),
841        type_info: dynamic_type::StaticTypeInfo::new::<T>(),
842        properties: T::properties()
843            .into_iter()
844            .map(|(k, v)| (k, Box::new(v) as Box<dyn eval::ErasedPropertyInfo>))
845            .collect(),
846        callbacks: T::callbacks()
847            .into_iter()
848            .map(|(k, v)| (k, Box::new(v) as Box<dyn eval::ErasedCallbackInfo>))
849            .collect(),
850    };
851    (T::name(), Rc::new(rtti))
852}
853
854/// Create a ItemTreeDescription from a source.
855/// The path corresponding to the source need to be passed as well (path is used for diagnostics
856/// and loading relative assets)
857pub async fn load(
858    source: String,
859    path: std::path::PathBuf,
860    mut compiler_config: CompilerConfiguration,
861) -> CompilationResult {
862    // If the native style should be Qt, resolve it here as we know that we have it
863    let is_native = compiler_config.style.as_deref() == Some("native");
864    if is_native {
865        // On wasm, look at the browser user agent
866        #[cfg(target_arch = "wasm32")]
867        let target = web_sys::window()
868            .and_then(|window| window.navigator().platform().ok())
869            .map_or("wasm", |platform| {
870                let platform = platform.to_ascii_lowercase();
871                if platform.contains("mac")
872                    || platform.contains("iphone")
873                    || platform.contains("ipad")
874                {
875                    "apple"
876                } else if platform.contains("android") {
877                    "android"
878                } else if platform.contains("win") {
879                    "windows"
880                } else if platform.contains("linux") {
881                    "linux"
882                } else {
883                    "wasm"
884                }
885            });
886        #[cfg(not(target_arch = "wasm32"))]
887        let target = "";
888        compiler_config.style = Some(
889            i_slint_common::get_native_style(i_slint_backend_selector::HAS_NATIVE_STYLE, target)
890                .to_string(),
891        );
892    }
893
894    let diag = BuildDiagnostics::default();
895    #[cfg(feature = "internal-highlight")]
896    let (path, mut diag, loader, raw_type_loader) =
897        i_slint_compiler::load_root_file_with_raw_type_loader(
898            &path,
899            &path,
900            source,
901            diag,
902            compiler_config,
903        )
904        .await;
905    #[cfg(not(feature = "internal-highlight"))]
906    let (path, mut diag, loader) =
907        i_slint_compiler::load_root_file(&path, &path, source, diag, compiler_config).await;
908    #[cfg(feature = "internal")]
909    let watch_paths = loader.all_files_to_watch().into_iter().collect();
910    if diag.has_errors() {
911        return CompilationResult {
912            components: HashMap::new(),
913            diagnostics: diag.into_iter().collect(),
914            #[cfg(feature = "internal")]
915            watch_paths,
916            #[cfg(feature = "internal")]
917            structs_and_enums: Vec::new(),
918            #[cfg(feature = "internal")]
919            named_exports: Vec::new(),
920        };
921    }
922
923    #[cfg(feature = "internal-highlight")]
924    let loader = Rc::new(loader);
925    #[cfg(feature = "internal-highlight")]
926    let raw_type_loader = raw_type_loader.map(Rc::new);
927
928    let doc = loader.get_document(&path).unwrap();
929
930    let compiled_globals = Rc::new(CompiledGlobalCollection::compile(doc));
931    let mut components = HashMap::new();
932
933    let popup_menu_description = if let Some(popup_menu_impl) = &doc.popup_menu_impl {
934        PopupMenuDescription::Rc(Rc::new_cyclic(|weak| {
935            generativity::make_guard!(guard);
936            ErasedItemTreeDescription::from(generate_item_tree(
937                popup_menu_impl,
938                Some(compiled_globals.clone()),
939                PopupMenuDescription::Weak(weak.clone()),
940                true,
941                guard,
942            ))
943        }))
944    } else {
945        PopupMenuDescription::Weak(Default::default())
946    };
947
948    for c in doc.exported_roots() {
949        generativity::make_guard!(guard);
950        #[allow(unused_mut)]
951        let mut it = generate_item_tree(
952            &c,
953            Some(compiled_globals.clone()),
954            popup_menu_description.clone(),
955            false,
956            guard,
957        );
958        #[cfg(feature = "internal-highlight")]
959        {
960            let _ = it.type_loader.set(loader.clone());
961            let _ = it.raw_type_loader.set(raw_type_loader.clone());
962        }
963        components.insert(c.id.to_string(), ComponentDefinition { inner: it.into() });
964    }
965
966    if components.is_empty() {
967        diag.push_error_with_span("No component found".into(), Default::default());
968    };
969
970    #[cfg(feature = "internal")]
971    let structs_and_enums = doc.used_types.borrow().structs_and_enums.clone();
972
973    #[cfg(feature = "internal")]
974    let named_exports = doc
975        .exports
976        .iter()
977        .filter_map(|export| match &export.1 {
978            Either::Left(component) if !component.is_global() => {
979                Some((&export.0.name, &component.id))
980            }
981            Either::Right(ty) => match &ty {
982                Type::Struct(s) if s.node().is_some() => {
983                    if let StructName::User { name, .. } = &s.name {
984                        Some((&export.0.name, name))
985                    } else {
986                        None
987                    }
988                }
989                Type::Enumeration(en) => Some((&export.0.name, &en.name)),
990                _ => None,
991            },
992            _ => None,
993        })
994        .filter(|(export_name, type_name)| *export_name != *type_name)
995        .map(|(export_name, type_name)| (type_name.to_string(), export_name.to_string()))
996        .collect::<Vec<_>>();
997
998    CompilationResult {
999        diagnostics: diag.into_iter().collect(),
1000        components,
1001        #[cfg(feature = "internal")]
1002        watch_paths,
1003        #[cfg(feature = "internal")]
1004        structs_and_enums,
1005        #[cfg(feature = "internal")]
1006        named_exports,
1007    }
1008}
1009
1010fn generate_rtti() -> HashMap<&'static str, Rc<ItemRTTI>> {
1011    let mut rtti = HashMap::new();
1012    use i_slint_core::items::*;
1013    rtti.extend(
1014        [
1015            rtti_for::<ComponentContainer>(),
1016            rtti_for::<Empty>(),
1017            rtti_for::<ImageItem>(),
1018            rtti_for::<ClippedImage>(),
1019            rtti_for::<ComplexText>(),
1020            rtti_for::<StyledTextItem>(),
1021            rtti_for::<SimpleText>(),
1022            rtti_for::<Rectangle>(),
1023            rtti_for::<BasicBorderRectangle>(),
1024            rtti_for::<BorderRectangle>(),
1025            rtti_for::<TouchArea>(),
1026            rtti_for::<TooltipArea>(),
1027            rtti_for::<FocusScope>(),
1028            rtti_for::<KeyBinding>(),
1029            rtti_for::<SwipeGestureHandler>(),
1030            rtti_for::<ScaleRotateGestureHandler>(),
1031            rtti_for::<Path>(),
1032            rtti_for::<Flickable>(),
1033            rtti_for::<WindowItem>(),
1034            rtti_for::<TextInput>(),
1035            rtti_for::<Clip>(),
1036            rtti_for::<BoxShadow>(),
1037            rtti_for::<Transform>(),
1038            rtti_for::<Opacity>(),
1039            rtti_for::<Layer>(),
1040            rtti_for::<DragArea>(),
1041            rtti_for::<DropArea>(),
1042            rtti_for::<ContextMenu>(),
1043            rtti_for::<MenuItem>(),
1044            rtti_for::<SystemTrayIcon>(),
1045        ]
1046        .iter()
1047        .cloned(),
1048    );
1049
1050    trait NativeHelper {
1051        fn push(rtti: &mut HashMap<&str, Rc<ItemRTTI>>);
1052    }
1053    impl NativeHelper for () {
1054        fn push(_rtti: &mut HashMap<&str, Rc<ItemRTTI>>) {}
1055    }
1056    impl<
1057        T: 'static + Default + rtti::BuiltinItem + vtable::HasStaticVTable<ItemVTable>,
1058        Next: NativeHelper,
1059    > NativeHelper for (T, Next)
1060    {
1061        fn push(rtti: &mut HashMap<&str, Rc<ItemRTTI>>) {
1062            let info = rtti_for::<T>();
1063            rtti.insert(info.0, info.1);
1064            Next::push(rtti);
1065        }
1066    }
1067    i_slint_backend_selector::NativeWidgets::push(&mut rtti);
1068
1069    rtti
1070}
1071
1072pub(crate) fn generate_item_tree<'id>(
1073    component: &Rc<object_tree::Component>,
1074    compiled_globals: Option<Rc<CompiledGlobalCollection>>,
1075    popup_menu_description: PopupMenuDescription,
1076    is_popup_menu_impl: bool,
1077    guard: generativity::Guard<'id>,
1078) -> Rc<ItemTreeDescription<'id>> {
1079    //dbg!(&*component.root_element.borrow());
1080
1081    thread_local! {
1082        static RTTI: Lazy<HashMap<&'static str, Rc<ItemRTTI>>> = Lazy::new(generate_rtti);
1083    }
1084
1085    struct TreeBuilder<'id> {
1086        tree_array: Vec<ItemTreeNode>,
1087        item_array:
1088            Vec<vtable::VOffset<crate::dynamic_type::Instance<'id>, ItemVTable, vtable::AllowPin>>,
1089        original_elements: Vec<ElementRc>,
1090        items_types: HashMap<SmolStr, ItemWithinItemTree>,
1091        type_builder: dynamic_type::TypeBuilder<'id>,
1092        repeater: Vec<ErasedRepeaterWithinComponent<'id>>,
1093        repeater_names: HashMap<SmolStr, usize>,
1094        change_callbacks: Vec<(NamedReference, Expression)>,
1095        popup_menu_description: PopupMenuDescription,
1096    }
1097    impl generator::ItemTreeBuilder for TreeBuilder<'_> {
1098        type SubComponentState = ();
1099
1100        fn push_repeated_item(
1101            &mut self,
1102            item_rc: &ElementRc,
1103            repeater_count: u32,
1104            parent_index: u32,
1105            _component_state: &Self::SubComponentState,
1106        ) {
1107            self.tree_array.push(ItemTreeNode::DynamicTree { index: repeater_count, parent_index });
1108            self.original_elements.push(item_rc.clone());
1109            let item = item_rc.borrow();
1110            let base_component = item.base_type.as_component();
1111            self.repeater_names.insert(item.id.clone(), self.repeater.len());
1112            generativity::make_guard!(guard);
1113            let repeated_element_info = item.repeated.as_ref().unwrap();
1114            self.repeater.push(
1115                RepeaterWithinItemTree {
1116                    item_tree_to_repeat: generate_item_tree(
1117                        base_component,
1118                        None,
1119                        self.popup_menu_description.clone(),
1120                        false,
1121                        guard,
1122                    ),
1123                    offset: self.type_builder.add_field_type::<Repeater<ErasedItemTreeBox>>(),
1124                    model: repeated_element_info.model.clone(),
1125                    is_conditional: repeated_element_info.is_conditional_element,
1126                }
1127                .into(),
1128            );
1129        }
1130
1131        fn push_native_item(
1132            &mut self,
1133            rc_item: &ElementRc,
1134            child_offset: u32,
1135            parent_index: u32,
1136            _component_state: &Self::SubComponentState,
1137        ) {
1138            let item = rc_item.borrow();
1139            let rt = RTTI.with(|rtti| {
1140                rtti.get(&*item.base_type.as_native().class_name)
1141                    .unwrap_or_else(|| {
1142                        panic!(
1143                            "Native type not registered: {}",
1144                            item.base_type.as_native().class_name
1145                        )
1146                    })
1147                    .clone()
1148            });
1149
1150            let offset = self.type_builder.add_field(rt.type_info);
1151
1152            self.tree_array.push(ItemTreeNode::Item {
1153                is_accessible: !item.accessibility_props.0.is_empty(),
1154                children_index: child_offset,
1155                children_count: item.children.len() as u32,
1156                parent_index,
1157                item_array_index: self.item_array.len() as u32,
1158            });
1159            self.item_array.push(unsafe { vtable::VOffset::from_raw(rt.vtable, offset) });
1160            self.original_elements.push(rc_item.clone());
1161            debug_assert_eq!(self.original_elements.len(), self.tree_array.len());
1162            self.items_types.insert(
1163                item.id.clone(),
1164                ItemWithinItemTree { offset, rtti: rt, elem: rc_item.clone() },
1165            );
1166            for (prop, expr) in &item.change_callbacks {
1167                self.change_callbacks.push((
1168                    NamedReference::new(rc_item, prop.clone()),
1169                    Expression::CodeBlock(expr.borrow().clone()),
1170                ));
1171            }
1172        }
1173
1174        fn enter_component(
1175            &mut self,
1176            _item: &ElementRc,
1177            _sub_component: &Rc<object_tree::Component>,
1178            _children_offset: u32,
1179            _component_state: &Self::SubComponentState,
1180        ) -> Self::SubComponentState {
1181            /* nothing to do */
1182        }
1183
1184        fn enter_component_children(
1185            &mut self,
1186            _item: &ElementRc,
1187            _repeater_count: u32,
1188            _component_state: &Self::SubComponentState,
1189            _sub_component_state: &Self::SubComponentState,
1190        ) {
1191            todo!()
1192        }
1193    }
1194
1195    let mut builder = TreeBuilder {
1196        tree_array: Vec::new(),
1197        item_array: Vec::new(),
1198        original_elements: Vec::new(),
1199        items_types: HashMap::new(),
1200        type_builder: dynamic_type::TypeBuilder::new(guard),
1201        repeater: Vec::new(),
1202        repeater_names: HashMap::new(),
1203        change_callbacks: Vec::new(),
1204        popup_menu_description,
1205    };
1206
1207    if !component.is_global() {
1208        generator::build_item_tree(component, &(), &mut builder);
1209    } else {
1210        for (prop, expr) in component.root_element.borrow().change_callbacks.iter() {
1211            builder.change_callbacks.push((
1212                NamedReference::new(&component.root_element, prop.clone()),
1213                Expression::CodeBlock(expr.borrow().clone()),
1214            ));
1215        }
1216    }
1217
1218    let mut custom_properties = HashMap::new();
1219    let mut custom_callbacks = HashMap::new();
1220    let mut callback_trackers = HashMap::new();
1221    fn property_info<T>() -> (Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)
1222    where
1223        T: PartialEq + Clone + Default + std::convert::TryInto<Value> + 'static,
1224        Value: std::convert::TryInto<T>,
1225    {
1226        // Fixme: using u8 in PropertyInfo<> is not sound, we would need to materialize a type for out component
1227        (
1228            Box::new(unsafe {
1229                vtable::FieldOffset::<u8, Property<T>, _>::new_from_offset_pinned(0)
1230            }),
1231            dynamic_type::StaticTypeInfo::new::<Property<T>>(),
1232        )
1233    }
1234    fn animated_property_info<T>()
1235    -> (Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)
1236    where
1237        T: Clone + Default + InterpolatedPropertyValue + std::convert::TryInto<Value> + 'static,
1238        Value: std::convert::TryInto<T>,
1239    {
1240        // Fixme: using u8 in PropertyInfo<> is not sound, we would need to materialize a type for out component
1241        (
1242            Box::new(unsafe {
1243                rtti::MaybeAnimatedPropertyInfoWrapper(
1244                    vtable::FieldOffset::<u8, Property<T>, _>::new_from_offset_pinned(0),
1245                )
1246            }),
1247            dynamic_type::StaticTypeInfo::new::<Property<T>>(),
1248        )
1249    }
1250
1251    fn property_info_for_type(
1252        ty: &Type,
1253        name: &str,
1254    ) -> Option<(Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)> {
1255        Some(match ty {
1256            Type::Float32 => animated_property_info::<f32>(),
1257            Type::Int32 => animated_property_info::<i32>(),
1258            Type::String => property_info::<SharedString>(),
1259            Type::Color => animated_property_info::<Color>(),
1260            Type::Brush => animated_property_info::<Brush>(),
1261            Type::Duration => animated_property_info::<i64>(),
1262            Type::Angle => animated_property_info::<f32>(),
1263            Type::PhysicalLength => animated_property_info::<f32>(),
1264            Type::LogicalLength => animated_property_info::<f32>(),
1265            Type::Rem => animated_property_info::<f32>(),
1266            Type::Image => property_info::<i_slint_core::graphics::Image>(),
1267            Type::Bool => property_info::<bool>(),
1268            Type::ComponentFactory => property_info::<ComponentFactory>(),
1269            Type::Struct(s) if matches!(s.name, StructName::Builtin(BuiltinStruct::StateInfo)) => {
1270                property_info::<i_slint_core::properties::StateInfo>()
1271            }
1272            Type::Struct(_) => property_info::<Value>(),
1273            Type::Array(_) => property_info::<Value>(),
1274            Type::Easing => property_info::<i_slint_core::animations::EasingCurve>(),
1275            Type::Percent => animated_property_info::<f32>(),
1276            Type::Enumeration(e) => {
1277                macro_rules! match_enum_type {
1278                    ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => {
1279                        match e.name.as_str() {
1280                            $(
1281                                stringify!($Name) => property_info::<i_slint_core::items::$Name>(),
1282                            )*
1283                            x => unreachable!("Unknown non-builtin enum {x}"),
1284                        }
1285                    }
1286                }
1287
1288                if e.node.is_some() {
1289                    property_info::<Value>()
1290                } else {
1291                    i_slint_common::for_each_enums!(match_enum_type)
1292                }
1293            }
1294            Type::Keys => property_info::<Keys>(),
1295            Type::DataTransfer => property_info::<DataTransfer>(),
1296            Type::LayoutCache => property_info::<SharedVector<f32>>(),
1297            Type::ArrayOfU16 => property_info::<SharedVector<u16>>(),
1298            Type::Function { .. } | Type::Callback { .. } => return None,
1299            Type::StyledText => property_info::<StyledText>(),
1300            // These can't be used in properties
1301            Type::Invalid
1302            | Type::Void
1303            | Type::InferredProperty
1304            | Type::InferredCallback
1305            | Type::Model
1306            | Type::PathData
1307            | Type::UnitProduct(_)
1308            | Type::ElementReference
1309            | Type::Closure => panic!("bad type {ty:?} for property {name}"),
1310        })
1311    }
1312
1313    for (name, decl) in &component.root_element.borrow().property_declarations {
1314        if decl.is_alias.is_some() {
1315            continue;
1316        }
1317        if matches!(&decl.property_type, Type::Callback { .. }) {
1318            custom_callbacks
1319                .insert(name.clone(), builder.type_builder.add_field_type::<Callback>());
1320            if decl.expose_in_public_api {
1321                callback_trackers
1322                    .insert(name.clone(), builder.type_builder.add_field_type::<Property<()>>());
1323            }
1324            continue;
1325        }
1326        let Some((prop, type_info)) = property_info_for_type(&decl.property_type, name) else {
1327            continue;
1328        };
1329        custom_properties.insert(
1330            name.clone(),
1331            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1332        );
1333    }
1334    if let Some(parent_element) = component.parent_element()
1335        && let Some(r) = &parent_element.borrow().repeated
1336        && !r.is_conditional_element
1337    {
1338        let (prop, type_info) = property_info::<u32>();
1339        custom_properties.insert(
1340            SPECIAL_PROPERTY_INDEX.into(),
1341            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1342        );
1343
1344        let model_ty = Expression::RepeaterModelReference {
1345            element: component.parent_element.borrow().clone(),
1346        }
1347        .ty();
1348        let (prop, type_info) =
1349            property_info_for_type(&model_ty, SPECIAL_PROPERTY_MODEL_DATA).unwrap();
1350        custom_properties.insert(
1351            SPECIAL_PROPERTY_MODEL_DATA.into(),
1352            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1353        );
1354    }
1355
1356    let parent_item_tree_offset = if component.parent_element().is_some() || is_popup_menu_impl {
1357        Some(builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>())
1358    } else {
1359        None
1360    };
1361
1362    let root_offset = builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>();
1363    let extra_data_offset = builder.type_builder.add_field_type::<ComponentExtraData>();
1364
1365    let change_trackers = (!builder.change_callbacks.is_empty()).then(|| {
1366        (
1367            builder.type_builder.add_field_type::<OnceCell<Vec<ChangeTracker>>>(),
1368            builder.change_callbacks,
1369        )
1370    });
1371    let timers = component
1372        .timers
1373        .borrow()
1374        .iter()
1375        .map(|_| builder.type_builder.add_field_type::<Timer>())
1376        .collect();
1377
1378    // only the public exported component needs the public property list
1379    let public_properties = if component.parent_element().is_none() {
1380        component.root_element.borrow().property_declarations.clone()
1381    } else {
1382        Default::default()
1383    };
1384
1385    let t = ItemTreeVTable {
1386        visit_children_item,
1387        layout_info,
1388        ensure_instantiated,
1389        get_item_ref,
1390        get_item_tree,
1391        get_subtree_range,
1392        get_subtree,
1393        parent_node,
1394        embed_component,
1395        subtree_index,
1396        item_geometry,
1397        accessible_role,
1398        accessible_string_property,
1399        accessibility_action,
1400        supported_accessibility_actions,
1401        item_element_infos,
1402        window_adapter,
1403        drop_in_place,
1404        dealloc,
1405    };
1406    let t = ItemTreeDescription {
1407        ct: t,
1408        dynamic_type: builder.type_builder.build(),
1409        item_tree: builder.tree_array,
1410        item_array: builder.item_array,
1411        items: builder.items_types,
1412        custom_properties,
1413        custom_callbacks,
1414        callback_trackers,
1415        original: component.clone(),
1416        original_elements: builder.original_elements,
1417        repeater: builder.repeater,
1418        repeater_names: builder.repeater_names,
1419        parent_item_tree_offset,
1420        root_offset,
1421        extra_data_offset,
1422        public_properties,
1423        compiled_globals,
1424        change_trackers,
1425        timers,
1426        popup_ids: std::cell::RefCell::new(HashMap::new()),
1427        popup_menu_description: builder.popup_menu_description,
1428        #[cfg(feature = "internal-highlight")]
1429        type_loader: std::cell::OnceCell::new(),
1430        #[cfg(feature = "internal-highlight")]
1431        raw_type_loader: std::cell::OnceCell::new(),
1432    };
1433
1434    Rc::new(t)
1435}
1436
1437pub fn animation_for_property(
1438    component: InstanceRef,
1439    animation: &Option<i_slint_compiler::object_tree::PropertyAnimation>,
1440) -> AnimatedBindingKind {
1441    match animation {
1442        Some(i_slint_compiler::object_tree::PropertyAnimation::Static(anim_elem)) => {
1443            AnimatedBindingKind::Animation(Box::new({
1444                let component_ptr = component.as_ptr();
1445                let vtable = NonNull::from(&component.description.ct).cast();
1446                let anim_elem = Rc::clone(anim_elem);
1447                move || -> PropertyAnimation {
1448                    generativity::make_guard!(guard);
1449                    let component = unsafe {
1450                        InstanceRef::from_pin_ref(
1451                            Pin::new_unchecked(vtable::VRef::from_raw(
1452                                vtable,
1453                                NonNull::new_unchecked(component_ptr as *mut u8),
1454                            )),
1455                            guard,
1456                        )
1457                    };
1458
1459                    eval::new_struct_with_bindings(
1460                        &anim_elem.borrow().bindings,
1461                        &mut eval::EvalLocalContext::from_component_instance(component),
1462                    )
1463                }
1464            }))
1465        }
1466        Some(i_slint_compiler::object_tree::PropertyAnimation::Transition {
1467            animations,
1468            state_ref,
1469        }) => {
1470            let component_ptr = component.as_ptr();
1471            let vtable = NonNull::from(&component.description.ct).cast();
1472            let animations = animations.clone();
1473            let state_ref = state_ref.clone();
1474            AnimatedBindingKind::Transition(Box::new(
1475                move || -> (PropertyAnimation, i_slint_core::animations::Instant) {
1476                    generativity::make_guard!(guard);
1477                    let component = unsafe {
1478                        InstanceRef::from_pin_ref(
1479                            Pin::new_unchecked(vtable::VRef::from_raw(
1480                                vtable,
1481                                NonNull::new_unchecked(component_ptr as *mut u8),
1482                            )),
1483                            guard,
1484                        )
1485                    };
1486
1487                    let mut context = eval::EvalLocalContext::from_component_instance(component);
1488                    let state = eval::eval_expression(&state_ref, &mut context);
1489                    let state_info: i_slint_core::properties::StateInfo = state.try_into().unwrap();
1490                    for a in &animations {
1491                        let is_previous_state = a.state_id == state_info.previous_state;
1492                        let is_current_state = a.state_id == state_info.current_state;
1493                        match (a.direction, is_previous_state, is_current_state) {
1494                            (TransitionDirection::In, false, true)
1495                            | (TransitionDirection::Out, true, false)
1496                            | (TransitionDirection::InOut, false, true)
1497                            | (TransitionDirection::InOut, true, false) => {
1498                                return (
1499                                    eval::new_struct_with_bindings(
1500                                        &a.animation.borrow().bindings,
1501                                        &mut context,
1502                                    ),
1503                                    state_info.change_time,
1504                                );
1505                            }
1506                            _ => {}
1507                        }
1508                    }
1509                    Default::default()
1510                },
1511            ))
1512        }
1513        None => AnimatedBindingKind::NotAnimated,
1514    }
1515}
1516
1517fn make_callback_eval_closure(
1518    expr: Expression,
1519    self_weak: ErasedItemTreeBoxWeak,
1520) -> impl Fn(&[Value]) -> Value {
1521    move |args| {
1522        let self_rc = self_weak.upgrade().unwrap();
1523        generativity::make_guard!(guard);
1524        let self_ = self_rc.unerase(guard);
1525        let instance_ref = self_.borrow_instance();
1526        let mut local_context =
1527            eval::EvalLocalContext::from_function_arguments(instance_ref, args.to_vec());
1528        eval::eval_expression(&expr, &mut local_context)
1529    }
1530}
1531
1532fn make_binding_eval_closure(
1533    expr: Expression,
1534    self_weak: ErasedItemTreeBoxWeak,
1535) -> impl Fn() -> Value {
1536    move || {
1537        let self_rc = self_weak.upgrade().unwrap();
1538        generativity::make_guard!(guard);
1539        let self_ = self_rc.unerase(guard);
1540        let instance_ref = self_.borrow_instance();
1541        eval::eval_expression(
1542            &expr,
1543            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1544        )
1545    }
1546}
1547
1548pub fn instantiate(
1549    description: Rc<ItemTreeDescription>,
1550    parent_ctx: Option<ErasedItemTreeBoxWeak>,
1551    root: Option<ErasedItemTreeBoxWeak>,
1552    window_options: Option<&WindowOptions>,
1553    globals: crate::global_component::GlobalStorage,
1554) -> DynamicComponentVRc {
1555    let instance = description.dynamic_type.clone().create_instance();
1556
1557    let component_box = ItemTreeBox { instance, description: description.clone() };
1558
1559    let self_rc = vtable::VRc::new(ErasedItemTreeBox::from(component_box));
1560    let self_weak = vtable::VRc::downgrade(&self_rc);
1561
1562    generativity::make_guard!(guard);
1563    let comp = self_rc.unerase(guard);
1564    let instance_ref = comp.borrow_instance();
1565    instance_ref.self_weak().set(self_weak.clone()).ok();
1566    let description = comp.description();
1567
1568    if let Some(WindowOptions::UseExistingWindow(existing_adapter)) = &window_options
1569        && let Err((a, b)) = globals.window_adapter().unwrap().try_insert(existing_adapter.clone())
1570    {
1571        assert!(Rc::ptr_eq(a, &b), "window not the same as parent window");
1572    }
1573
1574    let has_parent = parent_ctx.is_some();
1575    if let Some(parent) = parent_ctx {
1576        description
1577            .parent_item_tree_offset
1578            .unwrap()
1579            .apply(instance_ref.as_ref())
1580            .set(parent)
1581            .ok()
1582            .unwrap();
1583    }
1584    let extra_data = description.extra_data_offset.apply(instance_ref.as_ref());
1585    extra_data.globals.set(globals.clone()).ok().unwrap();
1586
1587    let resolved_root = if let Some(WindowOptions::Embed { .. }) = window_options {
1588        self_weak.clone()
1589    } else {
1590        generativity::make_guard!(guard);
1591        root.or_else(|| {
1592            instance_ref.parent_instance(guard).map(|parent| parent.root_weak().clone())
1593        })
1594        .unwrap_or_else(|| self_weak.clone())
1595    };
1596    description.root_offset.apply(instance_ref.as_ref()).set(resolved_root).ok().unwrap();
1597
1598    if !has_parent && let Some(g) = description.compiled_globals.as_ref() {
1599        for g in g.compiled_globals.iter() {
1600            crate::global_component::instantiate(g, &globals, self_weak.clone());
1601        }
1602    }
1603
1604    if let Some(WindowOptions::Embed { parent_item_tree, parent_item_tree_index }) = window_options
1605    {
1606        vtable::VRc::borrow_pin(&self_rc)
1607            .as_ref()
1608            .embed_component(parent_item_tree, *parent_item_tree_index);
1609    }
1610
1611    if !description.original.is_global() {
1612        let maybe_window_adapter =
1613            if let Some(WindowOptions::UseExistingWindow(adapter)) = window_options.as_ref() {
1614                Some(adapter.clone())
1615            } else {
1616                extra_data.globals.get().unwrap().window_adapter().and_then(|wa| wa.get().cloned())
1617            };
1618
1619        let component_rc = vtable::VRc::into_dyn(self_rc.clone());
1620        i_slint_core::item_tree::register_item_tree(&component_rc, maybe_window_adapter);
1621    }
1622
1623    // Some properties are generated as Value, but for which the default constructed Value must be initialized
1624    for (prop_name, decl) in &description.original.root_element.borrow().property_declarations {
1625        if !matches!(
1626            decl.property_type,
1627            Type::Struct { .. } | Type::Array(_) | Type::Enumeration(_)
1628        ) || decl.is_alias.is_some()
1629        {
1630            continue;
1631        }
1632        if let Some(b) = description.original.root_element.borrow().bindings.get(prop_name)
1633            && b.borrow().two_way_bindings.is_empty()
1634        {
1635            continue;
1636        }
1637        let p = description.custom_properties.get(prop_name).unwrap();
1638        unsafe {
1639            let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(p.offset));
1640            p.prop.set(item, eval::default_value_for_type(&decl.property_type), None).unwrap();
1641        }
1642    }
1643
1644    #[cfg(slint_debug_property)]
1645    {
1646        let component_id = description.original.id.as_str();
1647
1648        // Set debug names on custom (root element) properties
1649        for (prop_name, prop_info) in &description.custom_properties {
1650            let name = format!("{}.{}", component_id, prop_name);
1651            unsafe {
1652                let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(prop_info.offset));
1653                prop_info.prop.set_debug_name(item, name);
1654            }
1655        }
1656
1657        // Set debug names on built-in item properties
1658        for (item_name, item_within_component) in &description.items {
1659            let item = unsafe { item_within_component.item_from_item_tree(instance_ref.as_ptr()) };
1660            for (prop_name, prop_rtti) in &item_within_component.rtti.properties {
1661                let name = format!("{}::{}.{}", component_id, item_name, prop_name);
1662                prop_rtti.set_debug_name(item, name);
1663            }
1664        }
1665    }
1666
1667    generator::handle_property_bindings_init(
1668        &description.original,
1669        |elem, prop_name, binding| unsafe {
1670            let is_root = Rc::ptr_eq(
1671                elem,
1672                &elem.borrow().enclosing_component.upgrade().unwrap().root_element,
1673            );
1674            let elem = elem.borrow();
1675            let is_const = binding.analysis.as_ref().is_some_and(|a| a.is_const);
1676
1677            let property_type = elem.lookup_property(prop_name).property_type;
1678            if let Type::Function { .. } = property_type {
1679                // function don't need initialization
1680            } else if let Type::Callback { .. } = property_type {
1681                if !matches!(binding.expression, Expression::Invalid) {
1682                    let expr = binding.expression.clone();
1683                    let description = description.clone();
1684                    if let Some(callback_offset) =
1685                        description.custom_callbacks.get(prop_name).filter(|_| is_root)
1686                    {
1687                        let callback = callback_offset.apply(instance_ref.as_ref());
1688                        callback.set_handler(make_callback_eval_closure(expr, self_weak.clone()));
1689                    } else {
1690                        let item_within_component = &description.items[&elem.id];
1691                        let item = item_within_component.item_from_item_tree(instance_ref.as_ptr());
1692                        if let Some(callback) =
1693                            item_within_component.rtti.callbacks.get(prop_name.as_str())
1694                        {
1695                            callback.set_handler(
1696                                item,
1697                                Box::new(make_callback_eval_closure(expr, self_weak.clone())),
1698                            );
1699                        } else {
1700                            panic!("unknown callback {prop_name}")
1701                        }
1702                    }
1703                }
1704            } else if let Some(PropertiesWithinComponent { offset, prop: prop_info, .. }) =
1705                description.custom_properties.get(prop_name).filter(|_| is_root)
1706            {
1707                let is_state_info = matches!(&property_type, Type::Struct (s) if matches!(s.name, StructName::Builtin(BuiltinStruct::StateInfo)));
1708                if is_state_info {
1709                    let prop = Pin::new_unchecked(
1710                        &*(instance_ref.as_ptr().add(*offset)
1711                            as *const Property<i_slint_core::properties::StateInfo>),
1712                    );
1713                    let e = binding.expression.clone();
1714                    let state_binding = make_binding_eval_closure(e, self_weak.clone());
1715                    i_slint_core::properties::set_state_binding(prop, move || {
1716                        state_binding().try_into().unwrap()
1717                    });
1718                    return;
1719                }
1720
1721                let maybe_animation = animation_for_property(instance_ref, &binding.animation);
1722                let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(*offset));
1723
1724                if !matches!(binding.expression, Expression::Invalid) {
1725                    if is_const {
1726                        let v = eval::eval_expression(
1727                            &binding.expression,
1728                            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1729                        );
1730                        prop_info.set(item, v, None).unwrap();
1731                    } else {
1732                        let e = binding.expression.clone();
1733                        prop_info
1734                            .set_binding(
1735                                item,
1736                                Box::new(make_binding_eval_closure(e, self_weak.clone())),
1737                                maybe_animation,
1738                            )
1739                            .unwrap();
1740                    }
1741                }
1742                for twb in &binding.two_way_bindings {
1743                    match twb {
1744                        TwoWayBinding::Property { property, field_access }
1745                            if field_access.is_empty()
1746                                && !matches!(
1747                                    &property_type,
1748                                    Type::Struct(..) | Type::Array(..)
1749                                ) =>
1750                        {
1751                            // Safety: The compiler ensured that the properties exist and have
1752                            // the same type (except for struct/array, which may map to a Value).
1753                            prop_info.link_two_ways(item, get_property_ptr(property, instance_ref));
1754                        }
1755                        TwoWayBinding::Property { property, field_access } => {
1756                            let (common, map) =
1757                                prepare_for_two_way_binding(instance_ref, property, field_access);
1758                            prop_info.link_two_way_with_map(item, common, map);
1759                        }
1760                        TwoWayBinding::ModelData { repeated_element, field_access } => {
1761                            let (getter, setter) = prepare_model_two_way_binding(
1762                                instance_ref,
1763                                repeated_element,
1764                                field_access,
1765                            );
1766                            prop_info.link_two_way_to_model_data(item, getter, setter);
1767                        }
1768                    }
1769                }
1770            } else {
1771                let item_within_component = &description.items[&elem.id];
1772                let item = item_within_component.item_from_item_tree(instance_ref.as_ptr());
1773                if let Some(prop_rtti) =
1774                    item_within_component.rtti.properties.get(prop_name.as_str())
1775                {
1776                    let maybe_animation = animation_for_property(instance_ref, &binding.animation);
1777
1778                    for twb in &binding.two_way_bindings {
1779                        match twb {
1780                            TwoWayBinding::Property { property, field_access }
1781                                if field_access.is_empty()
1782                                    && !matches!(
1783                                        &property_type,
1784                                        Type::Struct(..) | Type::Array(..)
1785                                    ) =>
1786                            {
1787                                // Safety: The compiler ensured that the properties exist and
1788                                // have the same type.
1789                                prop_rtti
1790                                    .link_two_ways(item, get_property_ptr(property, instance_ref));
1791                            }
1792                            TwoWayBinding::Property { property, field_access } => {
1793                                let (common, map) = prepare_for_two_way_binding(
1794                                    instance_ref,
1795                                    property,
1796                                    field_access,
1797                                );
1798                                prop_rtti.link_two_way_with_map(item, common, map);
1799                            }
1800                            TwoWayBinding::ModelData { repeated_element, field_access } => {
1801                                let (getter, setter) = prepare_model_two_way_binding(
1802                                    instance_ref,
1803                                    repeated_element,
1804                                    field_access,
1805                                );
1806                                prop_rtti.link_two_way_to_model_data(item, getter, setter);
1807                            }
1808                        }
1809                    }
1810                    if !matches!(binding.expression, Expression::Invalid) {
1811                        if is_const {
1812                            prop_rtti
1813                                .set(
1814                                    item,
1815                                    eval::eval_expression(
1816                                        &binding.expression,
1817                                        &mut eval::EvalLocalContext::from_component_instance(
1818                                            instance_ref,
1819                                        ),
1820                                    ),
1821                                    maybe_animation.as_animation(),
1822                                )
1823                                .unwrap();
1824                        } else {
1825                            let e = binding.expression.clone();
1826                            prop_rtti.set_binding(
1827                                item,
1828                                Box::new(make_binding_eval_closure(e, self_weak.clone())),
1829                                maybe_animation,
1830                            );
1831                        }
1832                    }
1833                } else {
1834                    panic!("unknown property {} in {}", prop_name, elem.id);
1835                }
1836            }
1837        },
1838    );
1839
1840    for rep_in_comp in &description.repeater {
1841        generativity::make_guard!(guard);
1842        let rep_in_comp = rep_in_comp.unerase(guard);
1843
1844        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
1845        let expr = rep_in_comp.model.clone();
1846        let model_binding_closure = make_binding_eval_closure(expr, self_weak.clone());
1847        if rep_in_comp.is_conditional {
1848            let bool_model = Rc::new(crate::value_model::BoolModel::default());
1849            repeater.set_model_binding(move || {
1850                let v = model_binding_closure();
1851                bool_model.set_value(v.try_into().expect("condition model is bool"));
1852                ModelRc::from(bool_model.clone())
1853            });
1854        } else {
1855            repeater.set_model_binding(move || {
1856                let m = model_binding_closure();
1857                if let Value::Model(m) = m {
1858                    m
1859                } else {
1860                    ModelRc::new(crate::value_model::ValueModel::new(m))
1861                }
1862            });
1863        }
1864    }
1865    self_rc
1866}
1867
1868fn prepare_for_two_way_binding(
1869    instance_ref: InstanceRef,
1870    property: &NamedReference,
1871    field_access: &[SmolStr],
1872) -> (Pin<Rc<Property<Value>>>, Option<Rc<dyn rtti::TwoWayBindingMapping<Value>>>) {
1873    let element = property.element();
1874    let name = property.name().as_str();
1875
1876    generativity::make_guard!(guard);
1877    let enclosing_component = eval::enclosing_component_instance_for_element(
1878        &element,
1879        &eval::ComponentInstance::InstanceRef(instance_ref),
1880        guard,
1881    );
1882    let map: Option<Rc<dyn rtti::TwoWayBindingMapping<Value>>> = if field_access.is_empty() {
1883        None
1884    } else {
1885        struct FieldAccess(Vec<SmolStr>);
1886        impl rtti::TwoWayBindingMapping<Value> for FieldAccess {
1887            fn map_to(&self, value: &Value) -> Value {
1888                walk_struct_field_path(value.clone(), &self.0).unwrap_or_default()
1889            }
1890            fn map_from(&self, root: &mut Value, from: &Value) {
1891                if let Some(leaf) = walk_struct_field_path_mut(root, &self.0) {
1892                    *leaf = from.clone();
1893                }
1894            }
1895        }
1896        Some(Rc::new(FieldAccess(field_access.to_vec())))
1897    };
1898    let common = match enclosing_component {
1899        eval::ComponentInstance::InstanceRef(enclosing_component) => {
1900            let element = element.borrow();
1901            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
1902                && let Some(x) = enclosing_component.description.custom_properties.get(name)
1903            {
1904                let item =
1905                    unsafe { Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset)) };
1906                let common = x.prop.prepare_for_two_way_binding(item);
1907                return (common, map);
1908            }
1909            let item_info = enclosing_component
1910                .description
1911                .items
1912                .get(element.id.as_str())
1913                .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, name));
1914            let prop_info = item_info
1915                .rtti
1916                .properties
1917                .get(name)
1918                .unwrap_or_else(|| panic!("Property {} not in {}", name, element.id));
1919            core::mem::drop(element);
1920            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1921            prop_info.prepare_for_two_way_binding(item)
1922        }
1923        eval::ComponentInstance::GlobalComponent(glob) => {
1924            glob.as_ref().prepare_for_two_way_binding(name).unwrap()
1925        }
1926    };
1927    (common, map)
1928}
1929
1930/// Build a (getter, setter) pair for a `TwoWayBinding::ModelData`. The
1931/// setter writes the whole row back through the field-access path, and
1932/// skips the write if the leaf value is unchanged.
1933fn prepare_model_two_way_binding(
1934    instance_ref: InstanceRef,
1935    repeated_element: &i_slint_compiler::object_tree::ElementWeak,
1936    field_access: &[SmolStr],
1937) -> (Box<dyn Fn() -> Option<Value>>, Box<dyn Fn(&Value)>) {
1938    let self_weak = instance_ref.self_weak().get().unwrap().clone();
1939    let repeated_element = repeated_element.clone();
1940    let field_access: Vec<SmolStr> = field_access.to_vec();
1941
1942    let getter = {
1943        let self_weak = self_weak.clone();
1944        let repeated_element = repeated_element.clone();
1945        let field_access = field_access.clone();
1946        Box::new(move || -> Option<Value> {
1947            with_repeater_row(&self_weak, &repeated_element, |repeater, row| {
1948                walk_struct_field_path(repeater.model_row_data(row)?, &field_access)
1949            })
1950        })
1951    };
1952
1953    let setter = Box::new(move |new_value: &Value| {
1954        with_repeater_row(&self_weak, &repeated_element, |repeater, row| {
1955            let mut data = repeater.model_row_data(row)?;
1956            // Short-circuit identical writes to avoid spurious change notifications.
1957            let leaf = walk_struct_field_path_mut(&mut data, &field_access)?;
1958            if &*leaf == new_value {
1959                return Some(());
1960            }
1961            *leaf = new_value.clone();
1962            repeater.model_set_row_data(row, data);
1963            Some(())
1964        });
1965    });
1966
1967    (getter, setter)
1968}
1969
1970/// Resolve the repeater that backs `repeated_element` and its current row
1971/// index, then run `f`. Returns `None` if any link is unavailable.
1972fn with_repeater_row<R>(
1973    self_weak: &ErasedItemTreeBoxWeak,
1974    repeated_element: &i_slint_compiler::object_tree::ElementWeak,
1975    f: impl FnOnce(Pin<&Repeater<ErasedItemTreeBox>>, usize) -> Option<R>,
1976) -> Option<R> {
1977    let self_rc = self_weak.upgrade()?;
1978    generativity::make_guard!(guard);
1979    let s = self_rc.unerase(guard);
1980    let instance = s.borrow_instance();
1981    let element = repeated_element.upgrade()?;
1982    let index = crate::eval::load_property(
1983        instance,
1984        &element.borrow().base_type.as_component().root_element,
1985        crate::dynamic_item_tree::SPECIAL_PROPERTY_INDEX,
1986    )
1987    .ok()?;
1988    let row = usize::try_from(i32::try_from(index).ok()?).ok()?;
1989    generativity::make_guard!(guard);
1990    let enclosing = crate::eval::enclosing_component_for_element(&element, instance, guard);
1991    generativity::make_guard!(guard);
1992    let (repeater, _) = get_repeater_by_name(enclosing, element.borrow().id.as_str(), guard);
1993    f(repeater, row)
1994}
1995
1996/// Follow a chain of struct field accesses on `value`.
1997fn walk_struct_field_path(mut value: Value, fields: &[SmolStr]) -> Option<Value> {
1998    for f in fields {
1999        match value {
2000            Value::Struct(o) => value = o.get_field(f).cloned().unwrap_or_default(),
2001            Value::Void => return None,
2002            _ => return None,
2003        }
2004    }
2005    Some(value)
2006}
2007
2008/// Mutable counterpart of [`walk_struct_field_path`].
2009fn walk_struct_field_path_mut<'a>(
2010    mut value: &'a mut Value,
2011    fields: &[SmolStr],
2012) -> Option<&'a mut Value> {
2013    for f in fields {
2014        match value {
2015            Value::Struct(o) => value = o.0.get_mut(f)?,
2016            _ => return None,
2017        }
2018    }
2019    Some(value)
2020}
2021
2022pub(crate) fn get_property_ptr(nr: &NamedReference, instance: InstanceRef) -> *const c_void {
2023    let element = nr.element();
2024    generativity::make_guard!(guard);
2025    let enclosing_component = eval::enclosing_component_instance_for_element(
2026        &element,
2027        &eval::ComponentInstance::InstanceRef(instance),
2028        guard,
2029    );
2030    match enclosing_component {
2031        eval::ComponentInstance::InstanceRef(enclosing_component) => {
2032            let element = element.borrow();
2033            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2034                && let Some(x) = enclosing_component.description.custom_properties.get(nr.name())
2035            {
2036                return unsafe { enclosing_component.as_ptr().add(x.offset).cast() };
2037            };
2038            let item_info = enclosing_component
2039                .description
2040                .items
2041                .get(element.id.as_str())
2042                .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, nr.name()));
2043            let prop_info = item_info
2044                .rtti
2045                .properties
2046                .get(nr.name().as_str())
2047                .unwrap_or_else(|| panic!("Property {} not in {}", nr.name(), element.id));
2048            core::mem::drop(element);
2049            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2050            unsafe { item.as_ptr().add(prop_info.offset()).cast() }
2051        }
2052        eval::ComponentInstance::GlobalComponent(glob) => glob.as_ref().get_property_ptr(nr.name()),
2053    }
2054}
2055
2056pub struct ErasedItemTreeBox(ItemTreeBox<'static>);
2057impl ErasedItemTreeBox {
2058    pub fn unerase<'a, 'id>(
2059        &'a self,
2060        _guard: generativity::Guard<'id>,
2061    ) -> Pin<&'a ItemTreeBox<'id>> {
2062        Pin::new(
2063            //Safety: 'id is unique because of `_guard`
2064            unsafe { core::mem::transmute::<&ItemTreeBox<'static>, &ItemTreeBox<'id>>(&self.0) },
2065        )
2066    }
2067
2068    pub fn borrow(&self) -> ItemTreeRefPin<'_> {
2069        // Safety: it is safe to access self.0 here because the 'id lifetime does not leak
2070        self.0.borrow()
2071    }
2072
2073    pub fn window_adapter_ref(&self) -> Result<&WindowAdapterRc, PlatformError> {
2074        self.0.window_adapter_ref()
2075    }
2076
2077    pub fn run_setup_code(&self) {
2078        generativity::make_guard!(guard);
2079        let compo_box = self.unerase(guard);
2080        let instance_ref = compo_box.borrow_instance();
2081        for extra_init_code in self.0.description.original.init_code.borrow().iter() {
2082            eval::eval_expression(
2083                extra_init_code,
2084                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2085            );
2086        }
2087        if let Some(cts) = instance_ref.description.change_trackers.as_ref() {
2088            let self_weak = instance_ref.self_weak().get().unwrap();
2089            let v = cts
2090                .1
2091                .iter()
2092                .enumerate()
2093                .map(|(idx, _)| {
2094                    let ct = ChangeTracker::default();
2095                    ct.init(
2096                        self_weak.clone(),
2097                        move |self_weak| {
2098                            let s = self_weak.upgrade().unwrap();
2099                            generativity::make_guard!(guard);
2100                            let compo_box = s.unerase(guard);
2101                            let instance_ref = compo_box.borrow_instance();
2102                            let nr = &s.0.description.change_trackers.as_ref().unwrap().1[idx].0;
2103                            eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap()
2104                        },
2105                        move |self_weak, _| {
2106                            let s = self_weak.upgrade().unwrap();
2107                            generativity::make_guard!(guard);
2108                            let compo_box = s.unerase(guard);
2109                            let instance_ref = compo_box.borrow_instance();
2110                            let e = &s.0.description.change_trackers.as_ref().unwrap().1[idx].1;
2111                            eval::eval_expression(
2112                                e,
2113                                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2114                            );
2115                        },
2116                    );
2117                    ct
2118                })
2119                .collect::<Vec<_>>();
2120            cts.0
2121                .apply_pin(instance_ref.instance)
2122                .set(v)
2123                .unwrap_or_else(|_| panic!("run_setup_code called twice?"));
2124        }
2125        update_timers(instance_ref);
2126    }
2127}
2128impl<'id> From<ItemTreeBox<'id>> for ErasedItemTreeBox {
2129    fn from(inner: ItemTreeBox<'id>) -> Self {
2130        // Safety: Nothing access the component directly, we only access it through unerased where
2131        // the lifetime is unique again
2132        unsafe {
2133            ErasedItemTreeBox(core::mem::transmute::<ItemTreeBox<'id>, ItemTreeBox<'static>>(inner))
2134        }
2135    }
2136}
2137
2138pub fn get_repeater_by_name<'a, 'id>(
2139    instance_ref: InstanceRef<'a, '_>,
2140    name: &str,
2141    guard: generativity::Guard<'id>,
2142) -> (std::pin::Pin<&'a Repeater<ErasedItemTreeBox>>, Rc<ItemTreeDescription<'id>>) {
2143    let rep_index = instance_ref.description.repeater_names[name];
2144    let rep_in_comp = instance_ref.description.repeater[rep_index].unerase(guard);
2145    (rep_in_comp.offset.apply_pin(instance_ref.instance), rep_in_comp.item_tree_to_repeat.clone())
2146}
2147
2148#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2149extern "C" fn ensure_instantiated(component: ItemTreeRefPin) -> bool {
2150    generativity::make_guard!(guard);
2151    // Safety: called through the vtable of our own ItemTreeDescription.
2152    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2153
2154    let mut changed = false;
2155    for (tree_index, node) in instance_ref.description.item_tree.iter().enumerate() {
2156        if !matches!(node, ItemTreeNode::Item { .. }) {
2157            continue;
2158        }
2159        let item_ref = component.as_ref().get_item_ref(tree_index as u32);
2160        if let Some(container) = i_slint_core::items::ItemRef::downcast_pin::<
2161            i_slint_core::items::ComponentContainer,
2162        >(item_ref)
2163        {
2164            changed |= container.ensure_updated();
2165        }
2166    }
2167
2168    for rep_in_comp in &instance_ref.description.repeater {
2169        // Safety: we do not mix the repeater with a different component id.
2170        let rep_in_comp = unsafe { rep_in_comp.get_untagged() };
2171        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2172        let init = || {
2173            let extra_data =
2174                instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2175            instantiate(
2176                rep_in_comp.item_tree_to_repeat.clone(),
2177                instance_ref.self_weak().get().cloned(),
2178                None,
2179                None,
2180                extra_data.globals.get().unwrap().clone(),
2181            )
2182        };
2183        if let Some(lv) = &rep_in_comp
2184            .item_tree_to_repeat
2185            .original
2186            .parent_element
2187            .borrow()
2188            .upgrade()
2189            .unwrap()
2190            .borrow()
2191            .repeated
2192            .as_ref()
2193            .unwrap()
2194            .is_listview
2195        {
2196            let assume_property_logical_length =
2197                |prop| unsafe { Pin::new_unchecked(&*(prop as *const Property<LogicalLength>)) };
2198            changed |= repeater.ensure_updated_listview(
2199                init,
2200                assume_property_logical_length(get_property_ptr(&lv.viewport_width, instance_ref)),
2201                assume_property_logical_length(get_property_ptr(&lv.viewport_height, instance_ref)),
2202                assume_property_logical_length(get_property_ptr(&lv.viewport_y, instance_ref)),
2203                eval::load_property(
2204                    instance_ref,
2205                    &lv.listview_width.element(),
2206                    lv.listview_width.name(),
2207                )
2208                .unwrap()
2209                .try_into()
2210                .unwrap(),
2211                assume_property_logical_length(get_property_ptr(&lv.listview_height, instance_ref)),
2212            );
2213        } else {
2214            changed |= repeater.ensure_updated(init);
2215        }
2216    }
2217    changed
2218}
2219
2220#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2221extern "C" fn layout_info(component: ItemTreeRefPin, orientation: Orientation) -> LayoutInfo {
2222    generativity::make_guard!(guard);
2223    // This is fine since we can only be called with a component that with our vtable which is a ItemTreeDescription
2224    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2225    let orientation = crate::eval_layout::from_runtime(orientation);
2226
2227    // The vtable layout_info path is taken e.g. for repeater cells. When
2228    // the component root has a parameterized layout-info function, route
2229    // through it: reading the bare `layoutinfo-{h,v}` would cycle on
2230    // `self.{w,h}` for the cross-axis case, and we have no explicit
2231    // constraint at this entry point. `f32::MAX` (i.e. "unconstrained")
2232    // tells the runtime's flex algorithm to behave as if items don't
2233    // need to wrap, which gives the natural max-cell-cross-axis result
2234    // — much closer to correct than the `sqrt(item-areas)` heuristic
2235    // that a `-1` sentinel would trigger.
2236    let root = &instance_ref.description.original.root_element;
2237    let cross_axis_constraint = match orientation {
2238        i_slint_compiler::layout::Orientation::Vertical => {
2239            root.borrow().layout_info_v_with_constraint.is_some().then_some(f32::MAX)
2240        }
2241        i_slint_compiler::layout::Orientation::Horizontal => {
2242            root.borrow().layout_info_h_with_constraint.is_some().then_some(f32::MAX)
2243        }
2244    };
2245    let mut result = crate::eval_layout::get_layout_info_with_constraint(
2246        root,
2247        instance_ref,
2248        &instance_ref.window_adapter(),
2249        orientation,
2250        cross_axis_constraint,
2251    );
2252
2253    let constraints = instance_ref.description.original.root_constraints.borrow();
2254    if constraints.has_explicit_restrictions(orientation) {
2255        crate::eval_layout::fill_layout_info_constraints(
2256            &mut result,
2257            &constraints,
2258            orientation,
2259            &|nr: &NamedReference| {
2260                eval::load_property(instance_ref, &nr.element(), nr.name())
2261                    .unwrap()
2262                    .try_into()
2263                    .unwrap()
2264            },
2265        );
2266    }
2267    result
2268}
2269
2270#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2271unsafe extern "C" fn get_item_ref(component: ItemTreeRefPin, index: u32) -> Pin<ItemRef> {
2272    let tree = get_item_tree(component);
2273    match &tree[index as usize] {
2274        ItemTreeNode::Item { item_array_index, .. } => unsafe {
2275            generativity::make_guard!(guard);
2276            let instance_ref = InstanceRef::from_pin_ref(component, guard);
2277            core::mem::transmute::<Pin<ItemRef>, Pin<ItemRef>>(
2278                instance_ref.description.item_array[*item_array_index as usize]
2279                    .apply_pin(instance_ref.instance),
2280            )
2281        },
2282        ItemTreeNode::DynamicTree { .. } => panic!("get_item_ref called on dynamic tree"),
2283    }
2284}
2285
2286#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2287extern "C" fn get_subtree_range(component: ItemTreeRefPin, index: u32) -> IndexRange {
2288    generativity::make_guard!(guard);
2289    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2290    if index as usize >= instance_ref.description.repeater.len() {
2291        let container_index = {
2292            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2293            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2294                *parent_index
2295            } else {
2296                u32::MAX
2297            }
2298        };
2299        let container = component.as_ref().get_item_ref(container_index);
2300        let container = i_slint_core::items::ItemRef::downcast_pin::<
2301            i_slint_core::items::ComponentContainer,
2302        >(container)
2303        .unwrap();
2304        container.subtree_range()
2305    } else {
2306        generativity::make_guard!(guard);
2307        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2308
2309        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2310        repeater.track_instance_changes();
2311        repeater.range().into()
2312    }
2313}
2314
2315#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2316extern "C" fn get_subtree(
2317    component: ItemTreeRefPin,
2318    index: u32,
2319    subtree_index: usize,
2320    result: &mut ItemTreeWeak,
2321) {
2322    generativity::make_guard!(guard);
2323    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2324    if index as usize >= instance_ref.description.repeater.len() {
2325        let container_index = {
2326            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2327            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2328                *parent_index
2329            } else {
2330                u32::MAX
2331            }
2332        };
2333        let container = component.as_ref().get_item_ref(container_index);
2334        let container = i_slint_core::items::ItemRef::downcast_pin::<
2335            i_slint_core::items::ComponentContainer,
2336        >(container)
2337        .unwrap();
2338        if subtree_index == 0 {
2339            *result = container.subtree_component();
2340        }
2341    } else {
2342        generativity::make_guard!(guard);
2343        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2344
2345        let repeater = rep_in_comp.offset.apply(&instance_ref.instance);
2346        if let Some(instance_at) = repeater.instance_at(subtree_index) {
2347            *result = vtable::VRc::downgrade(&vtable::VRc::into_dyn(instance_at))
2348        }
2349    }
2350}
2351
2352#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2353extern "C" fn get_item_tree(component: ItemTreeRefPin) -> Slice<ItemTreeNode> {
2354    generativity::make_guard!(guard);
2355    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2356    let tree = instance_ref.description.item_tree.as_slice();
2357    unsafe { core::mem::transmute::<&[ItemTreeNode], &[ItemTreeNode]>(tree) }.into()
2358}
2359
2360#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2361extern "C" fn subtree_index(component: ItemTreeRefPin) -> usize {
2362    generativity::make_guard!(guard);
2363    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2364    if let Ok(value) = instance_ref.description.get_property(component, SPECIAL_PROPERTY_INDEX) {
2365        value.try_into().unwrap()
2366    } else {
2367        usize::MAX
2368    }
2369}
2370
2371#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2372unsafe extern "C" fn parent_node(component: ItemTreeRefPin, result: &mut ItemWeak) {
2373    generativity::make_guard!(guard);
2374    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2375
2376    let component_and_index = {
2377        // Normal inner-compilation unit case:
2378        if let Some(parent_offset) = instance_ref.description.parent_item_tree_offset {
2379            let parent_item_index = instance_ref
2380                .description
2381                .original
2382                .parent_element
2383                .borrow()
2384                .upgrade()
2385                .and_then(|e| e.borrow().item_index.get().cloned())
2386                .unwrap_or(u32::MAX);
2387            let parent_component = parent_offset
2388                .apply(instance_ref.as_ref())
2389                .get()
2390                .and_then(|p| p.upgrade())
2391                .map(vtable::VRc::into_dyn);
2392
2393            (parent_component, parent_item_index)
2394        } else if let Some((parent_component, parent_index)) = instance_ref
2395            .description
2396            .extra_data_offset
2397            .apply(instance_ref.as_ref())
2398            .embedding_position
2399            .get()
2400        {
2401            (parent_component.upgrade(), *parent_index)
2402        } else {
2403            (None, u32::MAX)
2404        }
2405    };
2406
2407    if let (Some(component), index) = component_and_index {
2408        *result = ItemRc::new(component, index).downgrade();
2409    }
2410}
2411
2412#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2413unsafe extern "C" fn embed_component(
2414    component: ItemTreeRefPin,
2415    parent_component: &ItemTreeWeak,
2416    parent_item_tree_index: u32,
2417) -> bool {
2418    generativity::make_guard!(guard);
2419    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2420
2421    if instance_ref.description.parent_item_tree_offset.is_some() {
2422        // We are not the root of the compilation unit tree... Can not embed this!
2423        return false;
2424    }
2425
2426    {
2427        // sanity check parent:
2428        let prc = parent_component.upgrade().unwrap();
2429        let pref = vtable::VRc::borrow_pin(&prc);
2430        let it = pref.as_ref().get_item_tree();
2431        if !matches!(
2432            it.get(parent_item_tree_index as usize),
2433            Some(ItemTreeNode::DynamicTree { .. })
2434        ) {
2435            panic!("Trying to embed into a non-dynamic index in the parents item tree")
2436        }
2437    }
2438
2439    let extra_data = instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2440    extra_data.embedding_position.set((parent_component.clone(), parent_item_tree_index)).is_ok()
2441}
2442
2443#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2444extern "C" fn item_geometry(component: ItemTreeRefPin, item_index: u32) -> LogicalRect {
2445    generativity::make_guard!(guard);
2446    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2447
2448    let e = instance_ref.description.original_elements[item_index as usize].borrow();
2449    let g = e.geometry_props.as_ref().unwrap();
2450
2451    let load_f32 = |nr: &NamedReference| -> f32 {
2452        crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2453            .unwrap()
2454            .try_into()
2455            .unwrap()
2456    };
2457
2458    LogicalRect {
2459        origin: (load_f32(&g.x), load_f32(&g.y)).into(),
2460        size: (load_f32(&g.width), load_f32(&g.height)).into(),
2461    }
2462}
2463
2464// silence the warning despite `AccessibleRole` is a `#[non_exhaustive]` enum from another crate.
2465#[allow(improper_ctypes_definitions)]
2466#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2467extern "C" fn accessible_role(component: ItemTreeRefPin, item_index: u32) -> AccessibleRole {
2468    generativity::make_guard!(guard);
2469    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2470    let nr = instance_ref.description.original_elements[item_index as usize]
2471        .borrow()
2472        .accessibility_props
2473        .0
2474        .get("accessible-role")
2475        .cloned();
2476    match nr {
2477        Some(nr) => crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2478            .unwrap()
2479            .try_into()
2480            .unwrap(),
2481        None => AccessibleRole::default(),
2482    }
2483}
2484
2485#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2486extern "C" fn accessible_string_property(
2487    component: ItemTreeRefPin,
2488    item_index: u32,
2489    what: AccessibleStringProperty,
2490    result: &mut SharedString,
2491) -> bool {
2492    generativity::make_guard!(guard);
2493    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2494    let prop_name = format!("accessible-{what}");
2495    let nr = instance_ref.description.original_elements[item_index as usize]
2496        .borrow()
2497        .accessibility_props
2498        .0
2499        .get(&prop_name)
2500        .cloned();
2501    if let Some(nr) = nr {
2502        let value = crate::eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap();
2503        match value {
2504            Value::String(s) => *result = s,
2505            Value::Bool(b) => *result = if b { "true" } else { "false" }.into(),
2506            Value::Number(x) => *result = x.to_string().into(),
2507            Value::EnumerationValue(_, v) => *result = v.into(),
2508            _ => unimplemented!("invalid type for accessible_string_property"),
2509        };
2510        true
2511    } else {
2512        false
2513    }
2514}
2515
2516#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2517extern "C" fn accessibility_action(
2518    component: ItemTreeRefPin,
2519    item_index: u32,
2520    action: &AccessibilityAction,
2521) {
2522    let perform = |prop_name, args: &[Value]| {
2523        generativity::make_guard!(guard);
2524        let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2525        let nr = instance_ref.description.original_elements[item_index as usize]
2526            .borrow()
2527            .accessibility_props
2528            .0
2529            .get(prop_name)
2530            .cloned();
2531        if let Some(nr) = nr {
2532            let instance_ref = eval::ComponentInstance::InstanceRef(instance_ref);
2533            crate::eval::invoke_callback(&instance_ref, &nr.element(), nr.name(), args).unwrap();
2534        }
2535    };
2536
2537    match action {
2538        AccessibilityAction::Default => perform("accessible-action-default", &[]),
2539        AccessibilityAction::Decrement => perform("accessible-action-decrement", &[]),
2540        AccessibilityAction::Increment => perform("accessible-action-increment", &[]),
2541        AccessibilityAction::Expand => perform("accessible-action-expand", &[]),
2542        AccessibilityAction::ReplaceSelectedText(_a) => {
2543            //perform("accessible-action-replace-selected-text", &[Value::String(a.clone())])
2544            i_slint_core::debug_log!(
2545                "AccessibilityAction::ReplaceSelectedText not implemented in interpreter's accessibility_action"
2546            );
2547        }
2548        AccessibilityAction::SetValue(a) => {
2549            perform("accessible-action-set-value", &[Value::String(a.clone())])
2550        }
2551    };
2552}
2553
2554#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2555extern "C" fn supported_accessibility_actions(
2556    component: ItemTreeRefPin,
2557    item_index: u32,
2558) -> SupportedAccessibilityAction {
2559    generativity::make_guard!(guard);
2560    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2561    instance_ref.description.original_elements[item_index as usize]
2562        .borrow()
2563        .accessibility_props
2564        .0
2565        .keys()
2566        .filter_map(|x| x.strip_prefix("accessible-action-"))
2567        .fold(SupportedAccessibilityAction::default(), |acc, value| {
2568            SupportedAccessibilityAction::from_name(&i_slint_compiler::generator::to_pascal_case(
2569                value,
2570            ))
2571            .unwrap_or_else(|| panic!("Not an accessible action: {value:?}"))
2572                | acc
2573        })
2574}
2575
2576#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2577extern "C" fn item_element_infos(
2578    component: ItemTreeRefPin,
2579    item_index: u32,
2580    result: &mut SharedString,
2581) -> bool {
2582    generativity::make_guard!(guard);
2583    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2584    *result = instance_ref.description.original_elements[item_index as usize]
2585        .borrow()
2586        .element_infos()
2587        .into();
2588    true
2589}
2590
2591#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2592extern "C" fn window_adapter(
2593    component: ItemTreeRefPin,
2594    do_create: bool,
2595    result: &mut Option<WindowAdapterRc>,
2596) {
2597    generativity::make_guard!(guard);
2598    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2599    if do_create {
2600        *result = Some(instance_ref.window_adapter());
2601    } else {
2602        *result = instance_ref.maybe_window_adapter();
2603    }
2604}
2605
2606#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2607unsafe extern "C" fn drop_in_place(component: vtable::VRefMut<ItemTreeVTable>) -> vtable::Layout {
2608    unsafe {
2609        let instance_ptr = component.as_ptr() as *mut Instance<'static>;
2610        let layout = (*instance_ptr).type_info().layout();
2611        dynamic_type::TypeInfo::drop_in_place(instance_ptr);
2612        layout.into()
2613    }
2614}
2615
2616#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2617unsafe extern "C" fn dealloc(_vtable: &ItemTreeVTable, ptr: *mut u8, layout: vtable::Layout) {
2618    unsafe { std::alloc::dealloc(ptr, layout.try_into().unwrap()) };
2619}
2620
2621#[derive(Copy, Clone)]
2622pub struct InstanceRef<'a, 'id> {
2623    pub instance: Pin<&'a Instance<'id>>,
2624    pub description: &'a ItemTreeDescription<'id>,
2625}
2626
2627impl<'a, 'id> InstanceRef<'a, 'id> {
2628    pub unsafe fn from_pin_ref(
2629        component: ItemTreeRefPin<'a>,
2630        _guard: generativity::Guard<'id>,
2631    ) -> Self {
2632        unsafe {
2633            Self {
2634                instance: Pin::new_unchecked(
2635                    &*(component.as_ref().as_ptr() as *const Instance<'id>),
2636                ),
2637                description: &*(Pin::into_inner_unchecked(component).get_vtable()
2638                    as *const ItemTreeVTable
2639                    as *const ItemTreeDescription<'id>),
2640            }
2641        }
2642    }
2643
2644    pub fn as_ptr(&self) -> *const u8 {
2645        (&*self.instance.as_ref()) as *const Instance as *const u8
2646    }
2647
2648    pub fn as_ref(&self) -> &Instance<'id> {
2649        &self.instance
2650    }
2651
2652    /// Borrow this component as a `Pin<ItemTreeRef>`
2653    pub fn borrow(self) -> ItemTreeRefPin<'a> {
2654        unsafe {
2655            Pin::new_unchecked(vtable::VRef::from_raw(
2656                NonNull::from(&self.description.ct).cast(),
2657                NonNull::from(self.instance.get_ref()).cast(),
2658            ))
2659        }
2660    }
2661
2662    pub fn self_weak(&self) -> &OnceCell<ErasedItemTreeBoxWeak> {
2663        let extra_data = self.description.extra_data_offset.apply(self.as_ref());
2664        &extra_data.self_weak
2665    }
2666
2667    pub fn root_weak(&self) -> &ErasedItemTreeBoxWeak {
2668        self.description.root_offset.apply(self.as_ref()).get().unwrap()
2669    }
2670
2671    pub fn window_adapter(&self) -> WindowAdapterRc {
2672        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2673        let root = self.root_weak().upgrade().unwrap();
2674        generativity::make_guard!(guard);
2675        let comp = root.unerase(guard);
2676        Self::get_or_init_window_adapter_ref(
2677            &comp.description,
2678            root_weak,
2679            true,
2680            comp.instance.as_pin_ref().get_ref(),
2681        )
2682        .unwrap()
2683        .clone()
2684    }
2685
2686    pub fn get_or_init_window_adapter_ref<'b, 'id2>(
2687        description: &'b ItemTreeDescription<'id2>,
2688        root_weak: ItemTreeWeak,
2689        do_create: bool,
2690        instance: &'b Instance<'id2>,
2691    ) -> Result<&'b WindowAdapterRc, PlatformError> {
2692        // We are the actual root: Generate and store a window_adapter if necessary
2693        description
2694            .extra_data_offset
2695            .apply(instance)
2696            .globals
2697            .get()
2698            .unwrap()
2699            .window_adapter()
2700            .unwrap()
2701            .get_or_try_init(|| {
2702                let mut parent_node = ItemWeak::default();
2703                if let Some(rc) = vtable::VWeak::upgrade(&root_weak) {
2704                    vtable::VRc::borrow_pin(&rc).as_ref().parent_node(&mut parent_node);
2705                }
2706
2707                if let Some(parent) = parent_node.upgrade() {
2708                    // We are embedded: Get window adapter from our parent
2709                    let mut result = None;
2710                    vtable::VRc::borrow_pin(parent.item_tree())
2711                        .as_ref()
2712                        .window_adapter(do_create, &mut result);
2713                    result.ok_or(PlatformError::NoPlatform)
2714                } else if do_create {
2715                    let extra_data = description.extra_data_offset.apply(instance);
2716                    let window_adapter = // We are the root: Create a window adapter
2717                    i_slint_backend_selector::with_platform(|_b| {
2718                        _b.create_window_adapter()
2719                    })?;
2720
2721                    let comp_rc = extra_data.self_weak.get().unwrap().upgrade().unwrap();
2722                    WindowInner::from_pub(window_adapter.window())
2723                        .set_component(&vtable::VRc::into_dyn(comp_rc));
2724                    Ok(window_adapter)
2725                } else {
2726                    Err(PlatformError::NoPlatform)
2727                }
2728            })
2729    }
2730
2731    pub fn maybe_window_adapter(&self) -> Option<WindowAdapterRc> {
2732        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2733        let root = self.root_weak().upgrade()?;
2734        generativity::make_guard!(guard);
2735        let comp = root.unerase(guard);
2736        Self::get_or_init_window_adapter_ref(
2737            &comp.description,
2738            root_weak,
2739            false,
2740            comp.instance.as_pin_ref().get_ref(),
2741        )
2742        .ok()
2743        .cloned()
2744    }
2745
2746    pub fn access_window<R>(
2747        self,
2748        callback: impl FnOnce(&'_ i_slint_core::window::WindowInner) -> R,
2749    ) -> R {
2750        callback(WindowInner::from_pub(self.window_adapter().window()))
2751    }
2752
2753    pub fn parent_instance<'id2>(
2754        &self,
2755        _guard: generativity::Guard<'id2>,
2756    ) -> Option<InstanceRef<'a, 'id2>> {
2757        // we need a 'static guard in order to be able to re-borrow with lifetime 'a.
2758        // Safety: This is the only 'static Id in scope.
2759        if let Some(parent_offset) = self.description.parent_item_tree_offset
2760            && let Some(parent) =
2761                parent_offset.apply(self.as_ref()).get().and_then(vtable::VWeak::upgrade)
2762        {
2763            let parent_instance = parent.unerase(_guard);
2764            // And also assume that the parent lives for at least 'a.  FIXME: this may not be sound
2765            let parent_instance = unsafe {
2766                std::mem::transmute::<InstanceRef<'_, 'id2>, InstanceRef<'a, 'id2>>(
2767                    parent_instance.borrow_instance(),
2768                )
2769            };
2770            return Some(parent_instance);
2771        }
2772        None
2773    }
2774}
2775
2776/// Show the popup with a lazily evaluated location.
2777pub fn show_popup(
2778    element: ElementRc,
2779    instance: InstanceRef,
2780    popup: &object_tree::PopupWindow,
2781    pos_getter: impl Fn(InstanceRef<'_, '_>) -> LogicalPosition + 'static,
2782    close_policy: PopupClosePolicy,
2783    parent_comp: ErasedItemTreeBoxWeak,
2784    parent_window_adapter: WindowAdapterRc,
2785    parent_item: &ItemRc,
2786) {
2787    generativity::make_guard!(guard);
2788
2789    // FIXME: we should compile once and keep the cached compiled component
2790    let compiled = generate_item_tree(
2791        &popup.component,
2792        None,
2793        parent_comp.upgrade().unwrap().0.description().popup_menu_description.clone(),
2794        false,
2795        guard,
2796    );
2797
2798    let extra_data = instance.description.extra_data_offset.apply(instance.as_ref());
2799    // Use the newly created window adapter if we are able to create one. Otherwise use the parent's one.
2800    // Tooltips skip this to share the parent's adapter, ensuring they use the ChildWindow path
2801    // and renderer caches stay consistent.
2802    let window_kind = if popup.is_tooltip { WindowKind::ToolTip } else { WindowKind::Popup };
2803    let globals = if let Some(window_adapter) =
2804        WindowInner::from_pub(parent_window_adapter.window())
2805            .create_child_window_adapter(window_kind)
2806    {
2807        extra_data.globals.get().unwrap().clone_with_window_adapter(window_adapter)
2808    } else {
2809        extra_data.globals.get().unwrap().clone()
2810    };
2811
2812    let popup_window_adapter = globals
2813        .window_adapter()
2814        .and_then(|window_adapter| window_adapter.get().cloned())
2815        .unwrap_or_else(|| parent_window_adapter.clone());
2816
2817    let inst = instantiate(
2818        compiled,
2819        Some(parent_comp),
2820        None,
2821        Some(&WindowOptions::UseExistingWindow(popup_window_adapter)),
2822        globals,
2823    );
2824    let inst_for_position = inst.clone();
2825    let access_position = Box::new(move || {
2826        generativity::make_guard!(guard);
2827        let compo_box = inst_for_position.unerase(guard);
2828        let instance_ref = compo_box.borrow_instance();
2829        pos_getter(instance_ref)
2830    });
2831    close_popup(element.clone(), instance, parent_window_adapter.clone());
2832    let window_kind = if popup.is_tooltip { WindowKind::ToolTip } else { WindowKind::Popup };
2833    instance.description.popup_ids.borrow_mut().insert(
2834        element.borrow().id.clone(),
2835        WindowInner::from_pub(parent_window_adapter.window()).show_popup(
2836            &vtable::VRc::into_dyn(inst.clone()),
2837            access_position,
2838            close_policy,
2839            parent_item,
2840            window_kind,
2841        ),
2842    );
2843    inst.run_setup_code();
2844}
2845
2846pub fn close_popup(
2847    element: ElementRc,
2848    instance: InstanceRef,
2849    parent_window_adapter: WindowAdapterRc,
2850) {
2851    if let Some(current_id) =
2852        instance.description.popup_ids.borrow_mut().remove(&element.borrow().id)
2853    {
2854        WindowInner::from_pub(parent_window_adapter.window()).close_popup(current_id);
2855    }
2856}
2857
2858pub fn make_menu_item_tree(
2859    menu_item_tree: &Rc<object_tree::Component>,
2860    enclosing_component: &InstanceRef,
2861    condition: Option<&Expression>,
2862    visible: Option<&Expression>,
2863) -> vtable::VRc<i_slint_core::menus::MenuVTable, MenuFromItemTree> {
2864    generativity::make_guard!(guard);
2865    let mit_compiled = generate_item_tree(
2866        menu_item_tree,
2867        None,
2868        enclosing_component.description.popup_menu_description.clone(),
2869        false,
2870        guard,
2871    );
2872    let enclosing_component_weak = enclosing_component.self_weak().get().unwrap();
2873    let extra_data =
2874        enclosing_component.description.extra_data_offset.apply(enclosing_component.as_ref());
2875    let mit_inst = instantiate(
2876        mit_compiled.clone(),
2877        Some(enclosing_component_weak.clone()),
2878        None,
2879        None,
2880        extra_data.globals.get().unwrap().clone(),
2881    );
2882    mit_inst.run_setup_code();
2883    let item_tree = vtable::VRc::into_dyn(mit_inst);
2884    let condition = condition.map(|condition| {
2885        let binding =
2886            make_binding_eval_closure(condition.clone(), enclosing_component_weak.clone());
2887        move || binding().try_into().unwrap()
2888    });
2889    let visible = visible.map(|visible| {
2890        let binding = make_binding_eval_closure(visible.clone(), enclosing_component_weak.clone());
2891        move || binding().try_into().unwrap()
2892    });
2893    let menu = match (condition, visible) {
2894        (None, None) => MenuFromItemTree::new(item_tree),
2895        (None, Some(visible)) => {
2896            MenuFromItemTree::new_with_condition_and_visible(item_tree, || true, visible)
2897        }
2898        (Some(condition), None) => {
2899            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, || true)
2900        }
2901        (Some(condition), Some(visible)) => {
2902            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, visible)
2903        }
2904    };
2905    vtable::VRc::new(menu)
2906}
2907
2908pub fn update_timers(instance: InstanceRef) {
2909    let ts = instance.description.original.timers.borrow();
2910    for (desc, offset) in ts.iter().zip(&instance.description.timers) {
2911        let timer = offset.apply(instance.as_ref());
2912        let running =
2913            eval::load_property(instance, &desc.running.element(), desc.running.name()).unwrap();
2914        if matches!(running, Value::Bool(true)) {
2915            let millis: i64 =
2916                eval::load_property(instance, &desc.interval.element(), desc.interval.name())
2917                    .unwrap()
2918                    .try_into()
2919                    .expect("interval must be a duration");
2920            if millis < 0 {
2921                timer.stop();
2922                continue;
2923            }
2924            let interval = core::time::Duration::from_millis(millis as _);
2925            if !timer.running() || interval != timer.interval() {
2926                let callback = desc.triggered.clone();
2927                let self_weak = instance.self_weak().get().unwrap().clone();
2928                timer.start(i_slint_core::timers::TimerMode::Repeated, interval, move || {
2929                    if let Some(instance) = self_weak.upgrade() {
2930                        generativity::make_guard!(guard);
2931                        let c = instance.unerase(guard);
2932                        let c = c.borrow_instance();
2933                        let inst = eval::ComponentInstance::InstanceRef(c);
2934                        eval::invoke_callback(&inst, &callback.element(), callback.name(), &[])
2935                            .unwrap();
2936                    }
2937                });
2938            }
2939        } else {
2940            timer.stop();
2941        }
2942    }
2943}
2944
2945pub fn restart_timer(element: ElementWeak, instance: InstanceRef) {
2946    let timers = instance.description.original.timers.borrow();
2947    if let Some((_, offset)) = timers
2948        .iter()
2949        .zip(&instance.description.timers)
2950        .find(|(desc, _)| Weak::ptr_eq(&desc.element, &element))
2951    {
2952        let timer = offset.apply(instance.as_ref());
2953        timer.restart();
2954    }
2955}