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 => panic!("bad type {ty:?} for property {name}"),
1309        })
1310    }
1311
1312    for (name, decl) in &component.root_element.borrow().property_declarations {
1313        if decl.is_alias.is_some() {
1314            continue;
1315        }
1316        if matches!(&decl.property_type, Type::Callback { .. }) {
1317            custom_callbacks
1318                .insert(name.clone(), builder.type_builder.add_field_type::<Callback>());
1319            if decl.expose_in_public_api {
1320                callback_trackers
1321                    .insert(name.clone(), builder.type_builder.add_field_type::<Property<()>>());
1322            }
1323            continue;
1324        }
1325        let Some((prop, type_info)) = property_info_for_type(&decl.property_type, name) else {
1326            continue;
1327        };
1328        custom_properties.insert(
1329            name.clone(),
1330            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1331        );
1332    }
1333    if let Some(parent_element) = component.parent_element()
1334        && let Some(r) = &parent_element.borrow().repeated
1335        && !r.is_conditional_element
1336    {
1337        let (prop, type_info) = property_info::<u32>();
1338        custom_properties.insert(
1339            SPECIAL_PROPERTY_INDEX.into(),
1340            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1341        );
1342
1343        let model_ty = Expression::RepeaterModelReference {
1344            element: component.parent_element.borrow().clone(),
1345        }
1346        .ty();
1347        let (prop, type_info) =
1348            property_info_for_type(&model_ty, SPECIAL_PROPERTY_MODEL_DATA).unwrap();
1349        custom_properties.insert(
1350            SPECIAL_PROPERTY_MODEL_DATA.into(),
1351            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1352        );
1353    }
1354
1355    let parent_item_tree_offset = if component.parent_element().is_some() || is_popup_menu_impl {
1356        Some(builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>())
1357    } else {
1358        None
1359    };
1360
1361    let root_offset = builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>();
1362    let extra_data_offset = builder.type_builder.add_field_type::<ComponentExtraData>();
1363
1364    let change_trackers = (!builder.change_callbacks.is_empty()).then(|| {
1365        (
1366            builder.type_builder.add_field_type::<OnceCell<Vec<ChangeTracker>>>(),
1367            builder.change_callbacks,
1368        )
1369    });
1370    let timers = component
1371        .timers
1372        .borrow()
1373        .iter()
1374        .map(|_| builder.type_builder.add_field_type::<Timer>())
1375        .collect();
1376
1377    // only the public exported component needs the public property list
1378    let public_properties = if component.parent_element().is_none() {
1379        component.root_element.borrow().property_declarations.clone()
1380    } else {
1381        Default::default()
1382    };
1383
1384    let t = ItemTreeVTable {
1385        visit_children_item,
1386        layout_info,
1387        ensure_instantiated,
1388        get_item_ref,
1389        get_item_tree,
1390        get_subtree_range,
1391        get_subtree,
1392        parent_node,
1393        embed_component,
1394        subtree_index,
1395        item_geometry,
1396        accessible_role,
1397        accessible_string_property,
1398        accessibility_action,
1399        supported_accessibility_actions,
1400        item_element_infos,
1401        window_adapter,
1402        drop_in_place,
1403        dealloc,
1404    };
1405    let t = ItemTreeDescription {
1406        ct: t,
1407        dynamic_type: builder.type_builder.build(),
1408        item_tree: builder.tree_array,
1409        item_array: builder.item_array,
1410        items: builder.items_types,
1411        custom_properties,
1412        custom_callbacks,
1413        callback_trackers,
1414        original: component.clone(),
1415        original_elements: builder.original_elements,
1416        repeater: builder.repeater,
1417        repeater_names: builder.repeater_names,
1418        parent_item_tree_offset,
1419        root_offset,
1420        extra_data_offset,
1421        public_properties,
1422        compiled_globals,
1423        change_trackers,
1424        timers,
1425        popup_ids: std::cell::RefCell::new(HashMap::new()),
1426        popup_menu_description: builder.popup_menu_description,
1427        #[cfg(feature = "internal-highlight")]
1428        type_loader: std::cell::OnceCell::new(),
1429        #[cfg(feature = "internal-highlight")]
1430        raw_type_loader: std::cell::OnceCell::new(),
1431    };
1432
1433    Rc::new(t)
1434}
1435
1436pub fn animation_for_property(
1437    component: InstanceRef,
1438    animation: &Option<i_slint_compiler::object_tree::PropertyAnimation>,
1439) -> AnimatedBindingKind {
1440    match animation {
1441        Some(i_slint_compiler::object_tree::PropertyAnimation::Static(anim_elem)) => {
1442            AnimatedBindingKind::Animation(Box::new({
1443                let component_ptr = component.as_ptr();
1444                let vtable = NonNull::from(&component.description.ct).cast();
1445                let anim_elem = Rc::clone(anim_elem);
1446                move || -> PropertyAnimation {
1447                    generativity::make_guard!(guard);
1448                    let component = unsafe {
1449                        InstanceRef::from_pin_ref(
1450                            Pin::new_unchecked(vtable::VRef::from_raw(
1451                                vtable,
1452                                NonNull::new_unchecked(component_ptr as *mut u8),
1453                            )),
1454                            guard,
1455                        )
1456                    };
1457
1458                    eval::new_struct_with_bindings(
1459                        &anim_elem.borrow().bindings,
1460                        &mut eval::EvalLocalContext::from_component_instance(component),
1461                    )
1462                }
1463            }))
1464        }
1465        Some(i_slint_compiler::object_tree::PropertyAnimation::Transition {
1466            animations,
1467            state_ref,
1468        }) => {
1469            let component_ptr = component.as_ptr();
1470            let vtable = NonNull::from(&component.description.ct).cast();
1471            let animations = animations.clone();
1472            let state_ref = state_ref.clone();
1473            AnimatedBindingKind::Transition(Box::new(
1474                move || -> (PropertyAnimation, i_slint_core::animations::Instant) {
1475                    generativity::make_guard!(guard);
1476                    let component = unsafe {
1477                        InstanceRef::from_pin_ref(
1478                            Pin::new_unchecked(vtable::VRef::from_raw(
1479                                vtable,
1480                                NonNull::new_unchecked(component_ptr as *mut u8),
1481                            )),
1482                            guard,
1483                        )
1484                    };
1485
1486                    let mut context = eval::EvalLocalContext::from_component_instance(component);
1487                    let state = eval::eval_expression(&state_ref, &mut context);
1488                    let state_info: i_slint_core::properties::StateInfo = state.try_into().unwrap();
1489                    for a in &animations {
1490                        let is_previous_state = a.state_id == state_info.previous_state;
1491                        let is_current_state = a.state_id == state_info.current_state;
1492                        match (a.direction, is_previous_state, is_current_state) {
1493                            (TransitionDirection::In, false, true)
1494                            | (TransitionDirection::Out, true, false)
1495                            | (TransitionDirection::InOut, false, true)
1496                            | (TransitionDirection::InOut, true, false) => {
1497                                return (
1498                                    eval::new_struct_with_bindings(
1499                                        &a.animation.borrow().bindings,
1500                                        &mut context,
1501                                    ),
1502                                    state_info.change_time,
1503                                );
1504                            }
1505                            _ => {}
1506                        }
1507                    }
1508                    Default::default()
1509                },
1510            ))
1511        }
1512        None => AnimatedBindingKind::NotAnimated,
1513    }
1514}
1515
1516fn make_callback_eval_closure(
1517    expr: Expression,
1518    self_weak: ErasedItemTreeBoxWeak,
1519) -> impl Fn(&[Value]) -> Value {
1520    move |args| {
1521        let self_rc = self_weak.upgrade().unwrap();
1522        generativity::make_guard!(guard);
1523        let self_ = self_rc.unerase(guard);
1524        let instance_ref = self_.borrow_instance();
1525        let mut local_context =
1526            eval::EvalLocalContext::from_function_arguments(instance_ref, args.to_vec());
1527        eval::eval_expression(&expr, &mut local_context)
1528    }
1529}
1530
1531fn make_binding_eval_closure(
1532    expr: Expression,
1533    self_weak: ErasedItemTreeBoxWeak,
1534) -> impl Fn() -> Value {
1535    move || {
1536        let self_rc = self_weak.upgrade().unwrap();
1537        generativity::make_guard!(guard);
1538        let self_ = self_rc.unerase(guard);
1539        let instance_ref = self_.borrow_instance();
1540        eval::eval_expression(
1541            &expr,
1542            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1543        )
1544    }
1545}
1546
1547pub fn instantiate(
1548    description: Rc<ItemTreeDescription>,
1549    parent_ctx: Option<ErasedItemTreeBoxWeak>,
1550    root: Option<ErasedItemTreeBoxWeak>,
1551    window_options: Option<&WindowOptions>,
1552    globals: crate::global_component::GlobalStorage,
1553) -> DynamicComponentVRc {
1554    let instance = description.dynamic_type.clone().create_instance();
1555
1556    let component_box = ItemTreeBox { instance, description: description.clone() };
1557
1558    let self_rc = vtable::VRc::new(ErasedItemTreeBox::from(component_box));
1559    let self_weak = vtable::VRc::downgrade(&self_rc);
1560
1561    generativity::make_guard!(guard);
1562    let comp = self_rc.unerase(guard);
1563    let instance_ref = comp.borrow_instance();
1564    instance_ref.self_weak().set(self_weak.clone()).ok();
1565    let description = comp.description();
1566
1567    if let Some(WindowOptions::UseExistingWindow(existing_adapter)) = &window_options
1568        && let Err((a, b)) = globals.window_adapter().unwrap().try_insert(existing_adapter.clone())
1569    {
1570        assert!(Rc::ptr_eq(a, &b), "window not the same as parent window");
1571    }
1572
1573    let has_parent = parent_ctx.is_some();
1574    if let Some(parent) = parent_ctx {
1575        description
1576            .parent_item_tree_offset
1577            .unwrap()
1578            .apply(instance_ref.as_ref())
1579            .set(parent)
1580            .ok()
1581            .unwrap();
1582    }
1583    let extra_data = description.extra_data_offset.apply(instance_ref.as_ref());
1584    extra_data.globals.set(globals.clone()).ok().unwrap();
1585
1586    let resolved_root = if let Some(WindowOptions::Embed { .. }) = window_options {
1587        self_weak.clone()
1588    } else {
1589        generativity::make_guard!(guard);
1590        root.or_else(|| {
1591            instance_ref.parent_instance(guard).map(|parent| parent.root_weak().clone())
1592        })
1593        .unwrap_or_else(|| self_weak.clone())
1594    };
1595    description.root_offset.apply(instance_ref.as_ref()).set(resolved_root).ok().unwrap();
1596
1597    if !has_parent && let Some(g) = description.compiled_globals.as_ref() {
1598        for g in g.compiled_globals.iter() {
1599            crate::global_component::instantiate(g, &globals, self_weak.clone());
1600        }
1601    }
1602
1603    if let Some(WindowOptions::Embed { parent_item_tree, parent_item_tree_index }) = window_options
1604    {
1605        vtable::VRc::borrow_pin(&self_rc)
1606            .as_ref()
1607            .embed_component(parent_item_tree, *parent_item_tree_index);
1608    }
1609
1610    if !description.original.is_global() {
1611        let maybe_window_adapter =
1612            if let Some(WindowOptions::UseExistingWindow(adapter)) = window_options.as_ref() {
1613                Some(adapter.clone())
1614            } else {
1615                extra_data.globals.get().unwrap().window_adapter().and_then(|wa| wa.get().cloned())
1616            };
1617
1618        let component_rc = vtable::VRc::into_dyn(self_rc.clone());
1619        i_slint_core::item_tree::register_item_tree(&component_rc, maybe_window_adapter);
1620    }
1621
1622    // Some properties are generated as Value, but for which the default constructed Value must be initialized
1623    for (prop_name, decl) in &description.original.root_element.borrow().property_declarations {
1624        if !matches!(
1625            decl.property_type,
1626            Type::Struct { .. } | Type::Array(_) | Type::Enumeration(_)
1627        ) || decl.is_alias.is_some()
1628        {
1629            continue;
1630        }
1631        let p = description.custom_properties.get(prop_name).unwrap();
1632        unsafe {
1633            let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(p.offset));
1634            p.prop.set(item, eval::default_value_for_type(&decl.property_type), None).unwrap();
1635        }
1636    }
1637
1638    #[cfg(slint_debug_property)]
1639    {
1640        let component_id = description.original.id.as_str();
1641
1642        // Set debug names on custom (root element) properties
1643        for (prop_name, prop_info) in &description.custom_properties {
1644            let name = format!("{}.{}", component_id, prop_name);
1645            unsafe {
1646                let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(prop_info.offset));
1647                prop_info.prop.set_debug_name(item, name);
1648            }
1649        }
1650
1651        // Set debug names on built-in item properties
1652        for (item_name, item_within_component) in &description.items {
1653            let item = unsafe { item_within_component.item_from_item_tree(instance_ref.as_ptr()) };
1654            for (prop_name, prop_rtti) in &item_within_component.rtti.properties {
1655                let name = format!("{}::{}.{}", component_id, item_name, prop_name);
1656                prop_rtti.set_debug_name(item, name);
1657            }
1658        }
1659    }
1660
1661    // Register the fonts before the property bindings, so a property that needs them
1662    // (image decoding, text sizing) finds them.
1663    for code in description.original.init_code.borrow().font_registration_code.iter() {
1664        eval::eval_expression(
1665            code,
1666            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1667        );
1668    }
1669
1670    generator::handle_property_bindings_init(
1671        &description.original,
1672        |elem, prop_name, binding| unsafe {
1673            let is_root = Rc::ptr_eq(
1674                elem,
1675                &elem.borrow().enclosing_component.upgrade().unwrap().root_element,
1676            );
1677            let elem = elem.borrow();
1678            let is_const = binding.analysis.as_ref().is_some_and(|a| a.is_const);
1679
1680            let property_type = elem.lookup_property(prop_name).property_type;
1681            if let Type::Function { .. } = property_type {
1682                // function don't need initialization
1683            } else if let Type::Callback { .. } = property_type {
1684                if !matches!(binding.expression, Expression::Invalid) {
1685                    let expr = binding.expression.clone();
1686                    let description = description.clone();
1687                    if let Some(callback_offset) =
1688                        description.custom_callbacks.get(prop_name).filter(|_| is_root)
1689                    {
1690                        let callback = callback_offset.apply(instance_ref.as_ref());
1691                        callback.set_handler(make_callback_eval_closure(expr, self_weak.clone()));
1692                    } else {
1693                        let item_within_component = &description.items[&elem.id];
1694                        let item = item_within_component.item_from_item_tree(instance_ref.as_ptr());
1695                        if let Some(callback) =
1696                            item_within_component.rtti.callbacks.get(prop_name.as_str())
1697                        {
1698                            callback.set_handler(
1699                                item,
1700                                Box::new(make_callback_eval_closure(expr, self_weak.clone())),
1701                            );
1702                        } else {
1703                            panic!("unknown callback {prop_name}")
1704                        }
1705                    }
1706                }
1707            } else if let Some(PropertiesWithinComponent { offset, prop: prop_info, .. }) =
1708                description.custom_properties.get(prop_name).filter(|_| is_root)
1709            {
1710                let is_state_info = matches!(&property_type, Type::Struct (s) if matches!(s.name, StructName::Builtin(BuiltinStruct::StateInfo)));
1711                if is_state_info {
1712                    let prop = Pin::new_unchecked(
1713                        &*(instance_ref.as_ptr().add(*offset)
1714                            as *const Property<i_slint_core::properties::StateInfo>),
1715                    );
1716                    let e = binding.expression.clone();
1717                    let state_binding = make_binding_eval_closure(e, self_weak.clone());
1718                    i_slint_core::properties::set_state_binding(prop, move || {
1719                        state_binding().try_into().unwrap()
1720                    });
1721                    return;
1722                }
1723
1724                let maybe_animation = animation_for_property(instance_ref, &binding.animation);
1725                let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(*offset));
1726
1727                if !matches!(binding.expression, Expression::Invalid) {
1728                    if is_const {
1729                        let v = eval::eval_expression(
1730                            &binding.expression,
1731                            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1732                        );
1733                        prop_info.set(item, v, None).unwrap();
1734                    } else {
1735                        let e = binding.expression.clone();
1736                        prop_info
1737                            .set_binding(
1738                                item,
1739                                Box::new(make_binding_eval_closure(e, self_weak.clone())),
1740                                maybe_animation,
1741                            )
1742                            .unwrap();
1743                    }
1744                }
1745                for twb in &binding.two_way_bindings {
1746                    match twb {
1747                        TwoWayBinding::Property { property, field_access }
1748                            if field_access.is_empty()
1749                                && !matches!(
1750                                    &property_type,
1751                                    Type::Struct(..) | Type::Array(..)
1752                                ) =>
1753                        {
1754                            // Safety: The compiler ensured that the properties exist and have
1755                            // the same type (except for struct/array, which may map to a Value).
1756                            prop_info.link_two_ways(item, get_property_ptr(property, instance_ref));
1757                        }
1758                        TwoWayBinding::Property { property, field_access } => {
1759                            let (common, map) =
1760                                prepare_for_two_way_binding(instance_ref, property, field_access);
1761                            prop_info.link_two_way_with_map(item, common, map);
1762                        }
1763                        TwoWayBinding::ModelData { repeated_element, field_access } => {
1764                            let (getter, setter) = prepare_model_two_way_binding(
1765                                instance_ref,
1766                                repeated_element,
1767                                field_access,
1768                            );
1769                            prop_info.link_two_way_to_model_data(item, getter, setter);
1770                        }
1771                    }
1772                }
1773            } else {
1774                let item_within_component = &description.items[&elem.id];
1775                let item = item_within_component.item_from_item_tree(instance_ref.as_ptr());
1776                if let Some(prop_rtti) =
1777                    item_within_component.rtti.properties.get(prop_name.as_str())
1778                {
1779                    let maybe_animation = animation_for_property(instance_ref, &binding.animation);
1780
1781                    for twb in &binding.two_way_bindings {
1782                        match twb {
1783                            TwoWayBinding::Property { property, field_access }
1784                                if field_access.is_empty()
1785                                    && !matches!(
1786                                        &property_type,
1787                                        Type::Struct(..) | Type::Array(..)
1788                                    ) =>
1789                            {
1790                                // Safety: The compiler ensured that the properties exist and
1791                                // have the same type.
1792                                prop_rtti
1793                                    .link_two_ways(item, get_property_ptr(property, instance_ref));
1794                            }
1795                            TwoWayBinding::Property { property, field_access } => {
1796                                let (common, map) = prepare_for_two_way_binding(
1797                                    instance_ref,
1798                                    property,
1799                                    field_access,
1800                                );
1801                                prop_rtti.link_two_way_with_map(item, common, map);
1802                            }
1803                            TwoWayBinding::ModelData { repeated_element, field_access } => {
1804                                let (getter, setter) = prepare_model_two_way_binding(
1805                                    instance_ref,
1806                                    repeated_element,
1807                                    field_access,
1808                                );
1809                                prop_rtti.link_two_way_to_model_data(item, getter, setter);
1810                            }
1811                        }
1812                    }
1813                    if !matches!(binding.expression, Expression::Invalid) {
1814                        if is_const {
1815                            prop_rtti
1816                                .set(
1817                                    item,
1818                                    eval::eval_expression(
1819                                        &binding.expression,
1820                                        &mut eval::EvalLocalContext::from_component_instance(
1821                                            instance_ref,
1822                                        ),
1823                                    ),
1824                                    maybe_animation.as_animation(),
1825                                )
1826                                .unwrap();
1827                        } else {
1828                            let e = binding.expression.clone();
1829                            prop_rtti.set_binding(
1830                                item,
1831                                Box::new(make_binding_eval_closure(e, self_weak.clone())),
1832                                maybe_animation,
1833                            );
1834                        }
1835                    }
1836                } else {
1837                    panic!("unknown property {} in {}", prop_name, elem.id);
1838                }
1839            }
1840        },
1841    );
1842
1843    for rep_in_comp in &description.repeater {
1844        generativity::make_guard!(guard);
1845        let rep_in_comp = rep_in_comp.unerase(guard);
1846
1847        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
1848        let expr = rep_in_comp.model.clone();
1849        let model_binding_closure = make_binding_eval_closure(expr, self_weak.clone());
1850        if rep_in_comp.is_conditional {
1851            let bool_model = Rc::new(crate::value_model::BoolModel::default());
1852            repeater.set_model_binding(move || {
1853                let v = model_binding_closure();
1854                bool_model.set_value(v.try_into().expect("condition model is bool"));
1855                ModelRc::from(bool_model.clone())
1856            });
1857        } else {
1858            repeater.set_model_binding(move || {
1859                let m = model_binding_closure();
1860                if let Value::Model(m) = m {
1861                    m
1862                } else {
1863                    ModelRc::new(crate::value_model::ValueModel::new(m))
1864                }
1865            });
1866        }
1867    }
1868    self_rc
1869}
1870
1871fn prepare_for_two_way_binding(
1872    instance_ref: InstanceRef,
1873    property: &NamedReference,
1874    field_access: &[SmolStr],
1875) -> (Pin<Rc<Property<Value>>>, Option<Rc<dyn rtti::TwoWayBindingMapping<Value>>>) {
1876    let element = property.element();
1877    let name = property.name().as_str();
1878
1879    generativity::make_guard!(guard);
1880    let enclosing_component = eval::enclosing_component_instance_for_element(
1881        &element,
1882        &eval::ComponentInstance::InstanceRef(instance_ref),
1883        guard,
1884    );
1885    let map: Option<Rc<dyn rtti::TwoWayBindingMapping<Value>>> = if field_access.is_empty() {
1886        None
1887    } else {
1888        struct FieldAccess(Vec<SmolStr>);
1889        impl rtti::TwoWayBindingMapping<Value> for FieldAccess {
1890            fn map_to(&self, value: &Value) -> Value {
1891                walk_struct_field_path(value.clone(), &self.0).unwrap_or_default()
1892            }
1893            fn map_from(&self, root: &mut Value, from: &Value) {
1894                if let Some(leaf) = walk_struct_field_path_mut(root, &self.0) {
1895                    *leaf = from.clone();
1896                }
1897            }
1898        }
1899        Some(Rc::new(FieldAccess(field_access.to_vec())))
1900    };
1901    let common = match enclosing_component {
1902        eval::ComponentInstance::InstanceRef(enclosing_component) => {
1903            let element = element.borrow();
1904            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
1905                && let Some(x) = enclosing_component.description.custom_properties.get(name)
1906            {
1907                let item =
1908                    unsafe { Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset)) };
1909                let common = x.prop.prepare_for_two_way_binding(item);
1910                return (common, map);
1911            }
1912            let item_info = enclosing_component
1913                .description
1914                .items
1915                .get(element.id.as_str())
1916                .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, name));
1917            let prop_info = item_info
1918                .rtti
1919                .properties
1920                .get(name)
1921                .unwrap_or_else(|| panic!("Property {} not in {}", name, element.id));
1922            core::mem::drop(element);
1923            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1924            prop_info.prepare_for_two_way_binding(item)
1925        }
1926        eval::ComponentInstance::GlobalComponent(glob) => {
1927            glob.as_ref().prepare_for_two_way_binding(name).unwrap()
1928        }
1929    };
1930    (common, map)
1931}
1932
1933/// Build a (getter, setter) pair for a `TwoWayBinding::ModelData`. The
1934/// setter writes the whole row back through the field-access path, and
1935/// skips the write if the leaf value is unchanged.
1936fn prepare_model_two_way_binding(
1937    instance_ref: InstanceRef,
1938    repeated_element: &i_slint_compiler::object_tree::ElementWeak,
1939    field_access: &[SmolStr],
1940) -> (Box<dyn Fn() -> Option<Value>>, Box<dyn Fn(&Value)>) {
1941    let self_weak = instance_ref.self_weak().get().unwrap().clone();
1942    let repeated_element = repeated_element.clone();
1943    let field_access: Vec<SmolStr> = field_access.to_vec();
1944
1945    let getter = {
1946        let self_weak = self_weak.clone();
1947        let repeated_element = repeated_element.clone();
1948        let field_access = field_access.clone();
1949        Box::new(move || -> Option<Value> {
1950            with_repeater_row(&self_weak, &repeated_element, |repeater, row| {
1951                walk_struct_field_path(repeater.model_row_data(row)?, &field_access)
1952            })
1953        })
1954    };
1955
1956    let setter = Box::new(move |new_value: &Value| {
1957        with_repeater_row(&self_weak, &repeated_element, |repeater, row| {
1958            let mut data = repeater.model_row_data(row)?;
1959            // Short-circuit identical writes to avoid spurious change notifications.
1960            let leaf = walk_struct_field_path_mut(&mut data, &field_access)?;
1961            if &*leaf == new_value {
1962                return Some(());
1963            }
1964            *leaf = new_value.clone();
1965            repeater.model_set_row_data(row, data);
1966            Some(())
1967        });
1968    });
1969
1970    (getter, setter)
1971}
1972
1973/// Resolve the repeater that backs `repeated_element` and its current row
1974/// index, then run `f`. Returns `None` if any link is unavailable.
1975fn with_repeater_row<R>(
1976    self_weak: &ErasedItemTreeBoxWeak,
1977    repeated_element: &i_slint_compiler::object_tree::ElementWeak,
1978    f: impl FnOnce(Pin<&Repeater<ErasedItemTreeBox>>, usize) -> Option<R>,
1979) -> Option<R> {
1980    let self_rc = self_weak.upgrade()?;
1981    generativity::make_guard!(guard);
1982    let s = self_rc.unerase(guard);
1983    let instance = s.borrow_instance();
1984    let element = repeated_element.upgrade()?;
1985    let index = crate::eval::load_property(
1986        instance,
1987        &element.borrow().base_type.as_component().root_element,
1988        crate::dynamic_item_tree::SPECIAL_PROPERTY_INDEX,
1989    )
1990    .ok()?;
1991    let row = usize::try_from(i32::try_from(index).ok()?).ok()?;
1992    generativity::make_guard!(guard);
1993    let enclosing = crate::eval::enclosing_component_for_element(&element, instance, guard);
1994    generativity::make_guard!(guard);
1995    let (repeater, _) = get_repeater_by_name(enclosing, element.borrow().id.as_str(), guard);
1996    f(repeater, row)
1997}
1998
1999/// Follow a chain of struct field accesses on `value`.
2000fn walk_struct_field_path(mut value: Value, fields: &[SmolStr]) -> Option<Value> {
2001    for f in fields {
2002        match value {
2003            Value::Struct(o) => value = o.get_field(f).cloned().unwrap_or_default(),
2004            Value::Void => return None,
2005            _ => return None,
2006        }
2007    }
2008    Some(value)
2009}
2010
2011/// Mutable counterpart of [`walk_struct_field_path`].
2012fn walk_struct_field_path_mut<'a>(
2013    mut value: &'a mut Value,
2014    fields: &[SmolStr],
2015) -> Option<&'a mut Value> {
2016    for f in fields {
2017        match value {
2018            Value::Struct(o) => value = o.0.get_mut(f)?,
2019            _ => return None,
2020        }
2021    }
2022    Some(value)
2023}
2024
2025pub(crate) fn get_property_ptr(nr: &NamedReference, instance: InstanceRef) -> *const c_void {
2026    let element = nr.element();
2027    generativity::make_guard!(guard);
2028    let enclosing_component = eval::enclosing_component_instance_for_element(
2029        &element,
2030        &eval::ComponentInstance::InstanceRef(instance),
2031        guard,
2032    );
2033    match enclosing_component {
2034        eval::ComponentInstance::InstanceRef(enclosing_component) => {
2035            let element = element.borrow();
2036            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2037                && let Some(x) = enclosing_component.description.custom_properties.get(nr.name())
2038            {
2039                return unsafe { enclosing_component.as_ptr().add(x.offset).cast() };
2040            };
2041            let item_info = enclosing_component
2042                .description
2043                .items
2044                .get(element.id.as_str())
2045                .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, nr.name()));
2046            let prop_info = item_info
2047                .rtti
2048                .properties
2049                .get(nr.name().as_str())
2050                .unwrap_or_else(|| panic!("Property {} not in {}", nr.name(), element.id));
2051            core::mem::drop(element);
2052            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2053            unsafe { item.as_ptr().add(prop_info.offset()).cast() }
2054        }
2055        eval::ComponentInstance::GlobalComponent(glob) => glob.as_ref().get_property_ptr(nr.name()),
2056    }
2057}
2058
2059pub struct ErasedItemTreeBox(ItemTreeBox<'static>);
2060impl ErasedItemTreeBox {
2061    pub fn unerase<'a, 'id>(
2062        &'a self,
2063        _guard: generativity::Guard<'id>,
2064    ) -> Pin<&'a ItemTreeBox<'id>> {
2065        Pin::new(
2066            //Safety: 'id is unique because of `_guard`
2067            unsafe { core::mem::transmute::<&ItemTreeBox<'static>, &ItemTreeBox<'id>>(&self.0) },
2068        )
2069    }
2070
2071    pub fn borrow(&self) -> ItemTreeRefPin<'_> {
2072        // Safety: it is safe to access self.0 here because the 'id lifetime does not leak
2073        self.0.borrow()
2074    }
2075
2076    pub fn window_adapter_ref(&self) -> Result<&WindowAdapterRc, PlatformError> {
2077        self.0.window_adapter_ref()
2078    }
2079
2080    pub fn run_setup_code(&self) {
2081        generativity::make_guard!(guard);
2082        let compo_box = self.unerase(guard);
2083        let instance_ref = compo_box.borrow_instance();
2084        for extra_init_code in
2085            self.0.description.original.init_code.borrow().iter_without_font_registration()
2086        {
2087            eval::eval_expression(
2088                extra_init_code,
2089                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2090            );
2091        }
2092        if let Some(cts) = instance_ref.description.change_trackers.as_ref() {
2093            let self_weak = instance_ref.self_weak().get().unwrap();
2094            let v = cts
2095                .1
2096                .iter()
2097                .enumerate()
2098                .map(|(idx, _)| {
2099                    let ct = ChangeTracker::default();
2100                    ct.init(
2101                        self_weak.clone(),
2102                        move |self_weak| {
2103                            let s = self_weak.upgrade().unwrap();
2104                            generativity::make_guard!(guard);
2105                            let compo_box = s.unerase(guard);
2106                            let instance_ref = compo_box.borrow_instance();
2107                            let nr = &s.0.description.change_trackers.as_ref().unwrap().1[idx].0;
2108                            eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap()
2109                        },
2110                        move |self_weak, _| {
2111                            let s = self_weak.upgrade().unwrap();
2112                            generativity::make_guard!(guard);
2113                            let compo_box = s.unerase(guard);
2114                            let instance_ref = compo_box.borrow_instance();
2115                            let e = &s.0.description.change_trackers.as_ref().unwrap().1[idx].1;
2116                            eval::eval_expression(
2117                                e,
2118                                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2119                            );
2120                        },
2121                    );
2122                    ct
2123                })
2124                .collect::<Vec<_>>();
2125            cts.0
2126                .apply_pin(instance_ref.instance)
2127                .set(v)
2128                .unwrap_or_else(|_| panic!("run_setup_code called twice?"));
2129        }
2130        update_timers(instance_ref);
2131    }
2132}
2133impl<'id> From<ItemTreeBox<'id>> for ErasedItemTreeBox {
2134    fn from(inner: ItemTreeBox<'id>) -> Self {
2135        // Safety: Nothing access the component directly, we only access it through unerased where
2136        // the lifetime is unique again
2137        unsafe {
2138            ErasedItemTreeBox(core::mem::transmute::<ItemTreeBox<'id>, ItemTreeBox<'static>>(inner))
2139        }
2140    }
2141}
2142
2143pub fn get_repeater_by_name<'a, 'id>(
2144    instance_ref: InstanceRef<'a, '_>,
2145    name: &str,
2146    guard: generativity::Guard<'id>,
2147) -> (std::pin::Pin<&'a Repeater<ErasedItemTreeBox>>, Rc<ItemTreeDescription<'id>>) {
2148    let rep_index = instance_ref.description.repeater_names[name];
2149    let rep_in_comp = instance_ref.description.repeater[rep_index].unerase(guard);
2150    (rep_in_comp.offset.apply_pin(instance_ref.instance), rep_in_comp.item_tree_to_repeat.clone())
2151}
2152
2153#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2154extern "C" fn ensure_instantiated(component: ItemTreeRefPin) -> bool {
2155    generativity::make_guard!(guard);
2156    // Safety: called through the vtable of our own ItemTreeDescription.
2157    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2158
2159    let mut changed = false;
2160    for (tree_index, node) in instance_ref.description.item_tree.iter().enumerate() {
2161        if !matches!(node, ItemTreeNode::Item { .. }) {
2162            continue;
2163        }
2164        let item_ref = component.as_ref().get_item_ref(tree_index as u32);
2165        if let Some(container) = i_slint_core::items::ItemRef::downcast_pin::<
2166            i_slint_core::items::ComponentContainer,
2167        >(item_ref)
2168        {
2169            changed |= container.ensure_updated();
2170        }
2171    }
2172
2173    for rep_in_comp in &instance_ref.description.repeater {
2174        // Safety: we do not mix the repeater with a different component id.
2175        let rep_in_comp = unsafe { rep_in_comp.get_untagged() };
2176        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2177        let init = || {
2178            let extra_data =
2179                instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2180            instantiate(
2181                rep_in_comp.item_tree_to_repeat.clone(),
2182                instance_ref.self_weak().get().cloned(),
2183                None,
2184                None,
2185                extra_data.globals.get().unwrap().clone(),
2186            )
2187        };
2188        if let Some(lv) = &rep_in_comp
2189            .item_tree_to_repeat
2190            .original
2191            .parent_element
2192            .borrow()
2193            .upgrade()
2194            .unwrap()
2195            .borrow()
2196            .repeated
2197            .as_ref()
2198            .unwrap()
2199            .is_listview
2200        {
2201            let assume_property_logical_length =
2202                |prop| unsafe { Pin::new_unchecked(&*(prop as *const Property<LogicalLength>)) };
2203            changed |= repeater.ensure_updated_listview(
2204                init,
2205                assume_property_logical_length(get_property_ptr(&lv.viewport_width, instance_ref)),
2206                lv.viewport_width_is_const,
2207                assume_property_logical_length(get_property_ptr(&lv.viewport_height, instance_ref)),
2208                lv.viewport_height_is_const,
2209                assume_property_logical_length(get_property_ptr(&lv.viewport_y, instance_ref)),
2210                eval::load_property(
2211                    instance_ref,
2212                    &lv.listview_width.element(),
2213                    lv.listview_width.name(),
2214                )
2215                .unwrap()
2216                .try_into()
2217                .unwrap(),
2218                assume_property_logical_length(get_property_ptr(&lv.listview_height, instance_ref)),
2219            );
2220        } else {
2221            changed |= repeater.ensure_updated(init);
2222        }
2223    }
2224    changed
2225}
2226
2227#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2228extern "C" fn layout_info(component: ItemTreeRefPin, orientation: Orientation) -> LayoutInfo {
2229    generativity::make_guard!(guard);
2230    // This is fine since we can only be called with a component that with our vtable which is a ItemTreeDescription
2231    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2232    let orientation = crate::eval_layout::from_runtime(orientation);
2233
2234    // Vtable entry (repeater cells, window auto-size). Pass the cross-axis size
2235    // to the root's parameterized layout-info function explicitly, avoiding a
2236    // cycle on `self.{w,h}`: for the vertical query the preferred width, so a
2237    // height-for-width Image sizes its height to that and not to infinity; for
2238    // the horizontal query `f32::MAX`, i.e. "don't wrap".
2239    let root = &instance_ref.description.original.root_element;
2240    let window_adapter = instance_ref.window_adapter();
2241    let cross_axis_constraint = match orientation {
2242        i_slint_compiler::layout::Orientation::Vertical => {
2243            root.borrow().layout_info_v_with_constraint.is_some().then(|| {
2244                crate::eval_layout::get_layout_info(
2245                    root,
2246                    instance_ref,
2247                    &window_adapter,
2248                    i_slint_compiler::layout::Orientation::Horizontal,
2249                )
2250                .preferred_bounded()
2251            })
2252        }
2253        i_slint_compiler::layout::Orientation::Horizontal => {
2254            root.borrow().layout_info_h_with_constraint.is_some().then_some(f32::MAX)
2255        }
2256    };
2257    let mut result = crate::eval_layout::get_layout_info_with_constraint(
2258        root,
2259        instance_ref,
2260        &window_adapter,
2261        orientation,
2262        cross_axis_constraint,
2263    );
2264
2265    let constraints = instance_ref.description.original.root_constraints.borrow();
2266    if constraints.has_explicit_restrictions(orientation) {
2267        crate::eval_layout::fill_layout_info_constraints(
2268            &mut result,
2269            &constraints,
2270            orientation,
2271            &|nr: &NamedReference| {
2272                eval::load_property(instance_ref, &nr.element(), nr.name())
2273                    .unwrap()
2274                    .try_into()
2275                    .unwrap()
2276            },
2277        );
2278    }
2279    result
2280}
2281
2282#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2283unsafe extern "C" fn get_item_ref(component: ItemTreeRefPin, index: u32) -> Pin<ItemRef> {
2284    let tree = get_item_tree(component);
2285    match &tree[index as usize] {
2286        ItemTreeNode::Item { item_array_index, .. } => unsafe {
2287            generativity::make_guard!(guard);
2288            let instance_ref = InstanceRef::from_pin_ref(component, guard);
2289            core::mem::transmute::<Pin<ItemRef>, Pin<ItemRef>>(
2290                instance_ref.description.item_array[*item_array_index as usize]
2291                    .apply_pin(instance_ref.instance),
2292            )
2293        },
2294        ItemTreeNode::DynamicTree { .. } => panic!("get_item_ref called on dynamic tree"),
2295    }
2296}
2297
2298#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2299extern "C" fn get_subtree_range(component: ItemTreeRefPin, index: u32) -> IndexRange {
2300    generativity::make_guard!(guard);
2301    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2302    if index as usize >= instance_ref.description.repeater.len() {
2303        let container_index = {
2304            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2305            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2306                *parent_index
2307            } else {
2308                u32::MAX
2309            }
2310        };
2311        let container = component.as_ref().get_item_ref(container_index);
2312        let container = i_slint_core::items::ItemRef::downcast_pin::<
2313            i_slint_core::items::ComponentContainer,
2314        >(container)
2315        .unwrap();
2316        container.subtree_range()
2317    } else {
2318        generativity::make_guard!(guard);
2319        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2320
2321        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2322        repeater.track_instance_changes();
2323        repeater.range().into()
2324    }
2325}
2326
2327#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2328extern "C" fn get_subtree(
2329    component: ItemTreeRefPin,
2330    index: u32,
2331    subtree_index: usize,
2332    result: &mut ItemTreeWeak,
2333) {
2334    generativity::make_guard!(guard);
2335    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2336    if index as usize >= instance_ref.description.repeater.len() {
2337        let container_index = {
2338            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2339            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2340                *parent_index
2341            } else {
2342                u32::MAX
2343            }
2344        };
2345        let container = component.as_ref().get_item_ref(container_index);
2346        let container = i_slint_core::items::ItemRef::downcast_pin::<
2347            i_slint_core::items::ComponentContainer,
2348        >(container)
2349        .unwrap();
2350        if subtree_index == 0 {
2351            *result = container.subtree_component();
2352        }
2353    } else {
2354        generativity::make_guard!(guard);
2355        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2356
2357        let repeater = rep_in_comp.offset.apply(&instance_ref.instance);
2358        if let Some(instance_at) = repeater.instance_at(subtree_index) {
2359            *result = vtable::VRc::downgrade(&vtable::VRc::into_dyn(instance_at))
2360        }
2361    }
2362}
2363
2364#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2365extern "C" fn get_item_tree(component: ItemTreeRefPin) -> Slice<ItemTreeNode> {
2366    generativity::make_guard!(guard);
2367    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2368    let tree = instance_ref.description.item_tree.as_slice();
2369    unsafe { core::mem::transmute::<&[ItemTreeNode], &[ItemTreeNode]>(tree) }.into()
2370}
2371
2372#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2373extern "C" fn subtree_index(component: ItemTreeRefPin) -> usize {
2374    generativity::make_guard!(guard);
2375    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2376    if let Ok(value) = instance_ref.description.get_property(component, SPECIAL_PROPERTY_INDEX) {
2377        value.try_into().unwrap()
2378    } else {
2379        usize::MAX
2380    }
2381}
2382
2383#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2384unsafe extern "C" fn parent_node(component: ItemTreeRefPin, result: &mut ItemWeak) {
2385    generativity::make_guard!(guard);
2386    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2387
2388    let component_and_index = {
2389        // Normal inner-compilation unit case:
2390        if let Some(parent_offset) = instance_ref.description.parent_item_tree_offset {
2391            let parent_item_index = instance_ref
2392                .description
2393                .original
2394                .parent_element
2395                .borrow()
2396                .upgrade()
2397                .and_then(|e| e.borrow().item_index.get().cloned())
2398                .unwrap_or(u32::MAX);
2399            let parent_component = parent_offset
2400                .apply(instance_ref.as_ref())
2401                .get()
2402                .and_then(|p| p.upgrade())
2403                .map(vtable::VRc::into_dyn);
2404
2405            (parent_component, parent_item_index)
2406        } else if let Some((parent_component, parent_index)) = instance_ref
2407            .description
2408            .extra_data_offset
2409            .apply(instance_ref.as_ref())
2410            .embedding_position
2411            .get()
2412        {
2413            (parent_component.upgrade(), *parent_index)
2414        } else {
2415            (None, u32::MAX)
2416        }
2417    };
2418
2419    if let (Some(component), index) = component_and_index {
2420        *result = ItemRc::new(component, index).downgrade();
2421    }
2422}
2423
2424#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2425unsafe extern "C" fn embed_component(
2426    component: ItemTreeRefPin,
2427    parent_component: &ItemTreeWeak,
2428    parent_item_tree_index: u32,
2429) -> bool {
2430    generativity::make_guard!(guard);
2431    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2432
2433    if instance_ref.description.parent_item_tree_offset.is_some() {
2434        // We are not the root of the compilation unit tree... Can not embed this!
2435        return false;
2436    }
2437
2438    {
2439        // sanity check parent:
2440        let prc = parent_component.upgrade().unwrap();
2441        let pref = vtable::VRc::borrow_pin(&prc);
2442        let it = pref.as_ref().get_item_tree();
2443        if !matches!(
2444            it.get(parent_item_tree_index as usize),
2445            Some(ItemTreeNode::DynamicTree { .. })
2446        ) {
2447            panic!("Trying to embed into a non-dynamic index in the parents item tree")
2448        }
2449    }
2450
2451    let extra_data = instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2452    extra_data.embedding_position.set((parent_component.clone(), parent_item_tree_index)).is_ok()
2453}
2454
2455#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2456extern "C" fn item_geometry(component: ItemTreeRefPin, item_index: u32) -> LogicalRect {
2457    generativity::make_guard!(guard);
2458    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2459
2460    let e = instance_ref.description.original_elements[item_index as usize].borrow();
2461    let g = e.geometry_props.as_ref().unwrap();
2462
2463    let load_f32 = |nr: &NamedReference| -> f32 {
2464        crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2465            .unwrap()
2466            .try_into()
2467            .unwrap()
2468    };
2469
2470    LogicalRect {
2471        origin: (load_f32(&g.x), load_f32(&g.y)).into(),
2472        size: (load_f32(&g.width), load_f32(&g.height)).into(),
2473    }
2474}
2475
2476// silence the warning despite `AccessibleRole` is a `#[non_exhaustive]` enum from another crate.
2477#[allow(improper_ctypes_definitions)]
2478#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2479extern "C" fn accessible_role(component: ItemTreeRefPin, item_index: u32) -> AccessibleRole {
2480    generativity::make_guard!(guard);
2481    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2482    let nr = instance_ref.description.original_elements[item_index as usize]
2483        .borrow()
2484        .accessibility_props
2485        .0
2486        .get("accessible-role")
2487        .cloned();
2488    match nr {
2489        Some(nr) => crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2490            .unwrap()
2491            .try_into()
2492            .unwrap(),
2493        None => AccessibleRole::default(),
2494    }
2495}
2496
2497#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2498extern "C" fn accessible_string_property(
2499    component: ItemTreeRefPin,
2500    item_index: u32,
2501    what: AccessibleStringProperty,
2502    result: &mut SharedString,
2503) -> bool {
2504    generativity::make_guard!(guard);
2505    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2506    let prop_name = format!("accessible-{what}");
2507    let nr = instance_ref.description.original_elements[item_index as usize]
2508        .borrow()
2509        .accessibility_props
2510        .0
2511        .get(&prop_name)
2512        .cloned();
2513    if let Some(nr) = nr {
2514        let value = crate::eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap();
2515        match value {
2516            Value::String(s) => *result = s,
2517            Value::Bool(b) => *result = if b { "true" } else { "false" }.into(),
2518            Value::Number(x) => *result = x.to_string().into(),
2519            Value::EnumerationValue(_, v) => *result = v.into(),
2520            _ => unimplemented!("invalid type for accessible_string_property"),
2521        };
2522        true
2523    } else {
2524        false
2525    }
2526}
2527
2528#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2529extern "C" fn accessibility_action(
2530    component: ItemTreeRefPin,
2531    item_index: u32,
2532    action: &AccessibilityAction,
2533) {
2534    let perform = |prop_name, args: &[Value]| {
2535        generativity::make_guard!(guard);
2536        let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2537        let nr = instance_ref.description.original_elements[item_index as usize]
2538            .borrow()
2539            .accessibility_props
2540            .0
2541            .get(prop_name)
2542            .cloned();
2543        if let Some(nr) = nr {
2544            let instance_ref = eval::ComponentInstance::InstanceRef(instance_ref);
2545            crate::eval::invoke_callback(&instance_ref, &nr.element(), nr.name(), args).unwrap();
2546        }
2547    };
2548
2549    match action {
2550        AccessibilityAction::Default => perform("accessible-action-default", &[]),
2551        AccessibilityAction::Decrement => perform("accessible-action-decrement", &[]),
2552        AccessibilityAction::Increment => perform("accessible-action-increment", &[]),
2553        AccessibilityAction::Expand => perform("accessible-action-expand", &[]),
2554        AccessibilityAction::ReplaceSelectedText(_a) => {
2555            //perform("accessible-action-replace-selected-text", &[Value::String(a.clone())])
2556            i_slint_core::debug_log!(
2557                "AccessibilityAction::ReplaceSelectedText not implemented in interpreter's accessibility_action"
2558            );
2559        }
2560        AccessibilityAction::SetValue(a) => {
2561            perform("accessible-action-set-value", &[Value::String(a.clone())])
2562        }
2563    };
2564}
2565
2566#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2567extern "C" fn supported_accessibility_actions(
2568    component: ItemTreeRefPin,
2569    item_index: u32,
2570) -> SupportedAccessibilityAction {
2571    generativity::make_guard!(guard);
2572    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2573    instance_ref.description.original_elements[item_index as usize]
2574        .borrow()
2575        .accessibility_props
2576        .0
2577        .keys()
2578        .filter_map(|x| x.strip_prefix("accessible-action-"))
2579        .fold(SupportedAccessibilityAction::default(), |acc, value| {
2580            SupportedAccessibilityAction::from_name(&i_slint_compiler::generator::to_pascal_case(
2581                value,
2582            ))
2583            .unwrap_or_else(|| panic!("Not an accessible action: {value:?}"))
2584                | acc
2585        })
2586}
2587
2588#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2589extern "C" fn item_element_infos(
2590    component: ItemTreeRefPin,
2591    item_index: u32,
2592    result: &mut SharedString,
2593) -> bool {
2594    generativity::make_guard!(guard);
2595    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2596    *result = instance_ref.description.original_elements[item_index as usize]
2597        .borrow()
2598        .element_infos()
2599        .into();
2600    true
2601}
2602
2603#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2604extern "C" fn window_adapter(
2605    component: ItemTreeRefPin,
2606    do_create: bool,
2607    result: &mut Option<WindowAdapterRc>,
2608) {
2609    generativity::make_guard!(guard);
2610    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2611    if do_create {
2612        *result = Some(instance_ref.window_adapter());
2613    } else {
2614        *result = instance_ref.maybe_window_adapter();
2615    }
2616}
2617
2618#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2619unsafe extern "C" fn drop_in_place(component: vtable::VRefMut<ItemTreeVTable>) -> vtable::Layout {
2620    unsafe {
2621        let instance_ptr = component.as_ptr() as *mut Instance<'static>;
2622        let layout = (*instance_ptr).type_info().layout();
2623        dynamic_type::TypeInfo::drop_in_place(instance_ptr);
2624        layout.into()
2625    }
2626}
2627
2628#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2629unsafe extern "C" fn dealloc(_vtable: &ItemTreeVTable, ptr: *mut u8, layout: vtable::Layout) {
2630    unsafe { std::alloc::dealloc(ptr, layout.try_into().unwrap()) };
2631}
2632
2633#[derive(Copy, Clone)]
2634pub struct InstanceRef<'a, 'id> {
2635    pub instance: Pin<&'a Instance<'id>>,
2636    pub description: &'a ItemTreeDescription<'id>,
2637}
2638
2639impl<'a, 'id> InstanceRef<'a, 'id> {
2640    pub unsafe fn from_pin_ref(
2641        component: ItemTreeRefPin<'a>,
2642        _guard: generativity::Guard<'id>,
2643    ) -> Self {
2644        unsafe {
2645            Self {
2646                instance: Pin::new_unchecked(
2647                    &*(component.as_ref().as_ptr() as *const Instance<'id>),
2648                ),
2649                description: &*(Pin::into_inner_unchecked(component).get_vtable()
2650                    as *const ItemTreeVTable
2651                    as *const ItemTreeDescription<'id>),
2652            }
2653        }
2654    }
2655
2656    pub fn as_ptr(&self) -> *const u8 {
2657        (&*self.instance.as_ref()) as *const Instance as *const u8
2658    }
2659
2660    pub fn as_ref(&self) -> &Instance<'id> {
2661        &self.instance
2662    }
2663
2664    /// Borrow this component as a `Pin<ItemTreeRef>`
2665    pub fn borrow(self) -> ItemTreeRefPin<'a> {
2666        unsafe {
2667            Pin::new_unchecked(vtable::VRef::from_raw(
2668                NonNull::from(&self.description.ct).cast(),
2669                NonNull::from(self.instance.get_ref()).cast(),
2670            ))
2671        }
2672    }
2673
2674    pub fn self_weak(&self) -> &OnceCell<ErasedItemTreeBoxWeak> {
2675        let extra_data = self.description.extra_data_offset.apply(self.as_ref());
2676        &extra_data.self_weak
2677    }
2678
2679    pub fn root_weak(&self) -> &ErasedItemTreeBoxWeak {
2680        self.description.root_offset.apply(self.as_ref()).get().unwrap()
2681    }
2682
2683    pub fn window_adapter(&self) -> WindowAdapterRc {
2684        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2685        let root = self.root_weak().upgrade().unwrap();
2686        generativity::make_guard!(guard);
2687        let comp = root.unerase(guard);
2688        Self::get_or_init_window_adapter_ref(
2689            &comp.description,
2690            root_weak,
2691            true,
2692            comp.instance.as_pin_ref().get_ref(),
2693        )
2694        .unwrap()
2695        .clone()
2696    }
2697
2698    pub fn get_or_init_window_adapter_ref<'b, 'id2>(
2699        description: &'b ItemTreeDescription<'id2>,
2700        root_weak: ItemTreeWeak,
2701        do_create: bool,
2702        instance: &'b Instance<'id2>,
2703    ) -> Result<&'b WindowAdapterRc, PlatformError> {
2704        // We are the actual root: Generate and store a window_adapter if necessary
2705        description
2706            .extra_data_offset
2707            .apply(instance)
2708            .globals
2709            .get()
2710            .unwrap()
2711            .window_adapter()
2712            .unwrap()
2713            .get_or_try_init(|| {
2714                let mut parent_node = ItemWeak::default();
2715                if let Some(rc) = vtable::VWeak::upgrade(&root_weak) {
2716                    vtable::VRc::borrow_pin(&rc).as_ref().parent_node(&mut parent_node);
2717                }
2718
2719                if let Some(parent) = parent_node.upgrade() {
2720                    // We are embedded: Get window adapter from our parent
2721                    let mut result = None;
2722                    vtable::VRc::borrow_pin(parent.item_tree())
2723                        .as_ref()
2724                        .window_adapter(do_create, &mut result);
2725                    result.ok_or(PlatformError::NoPlatform)
2726                } else if do_create {
2727                    let extra_data = description.extra_data_offset.apply(instance);
2728                    let window_adapter = // We are the root: Create a window adapter
2729                    i_slint_backend_selector::with_platform(|_b| {
2730                        _b.create_window_adapter()
2731                    })?;
2732
2733                    let comp_rc = extra_data.self_weak.get().unwrap().upgrade().unwrap();
2734                    WindowInner::from_pub(window_adapter.window())
2735                        .set_component(&vtable::VRc::into_dyn(comp_rc));
2736                    Ok(window_adapter)
2737                } else {
2738                    Err(PlatformError::NoPlatform)
2739                }
2740            })
2741    }
2742
2743    pub fn maybe_window_adapter(&self) -> Option<WindowAdapterRc> {
2744        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2745        let root = self.root_weak().upgrade()?;
2746        generativity::make_guard!(guard);
2747        let comp = root.unerase(guard);
2748        Self::get_or_init_window_adapter_ref(
2749            &comp.description,
2750            root_weak,
2751            false,
2752            comp.instance.as_pin_ref().get_ref(),
2753        )
2754        .ok()
2755        .cloned()
2756    }
2757
2758    pub fn access_window<R>(
2759        self,
2760        callback: impl FnOnce(&'_ i_slint_core::window::WindowInner) -> R,
2761    ) -> R {
2762        callback(WindowInner::from_pub(self.window_adapter().window()))
2763    }
2764
2765    pub fn parent_instance<'id2>(
2766        &self,
2767        _guard: generativity::Guard<'id2>,
2768    ) -> Option<InstanceRef<'a, 'id2>> {
2769        // we need a 'static guard in order to be able to re-borrow with lifetime 'a.
2770        // Safety: This is the only 'static Id in scope.
2771        if let Some(parent_offset) = self.description.parent_item_tree_offset
2772            && let Some(parent) =
2773                parent_offset.apply(self.as_ref()).get().and_then(vtable::VWeak::upgrade)
2774        {
2775            let parent_instance = parent.unerase(_guard);
2776            // And also assume that the parent lives for at least 'a.  FIXME: this may not be sound
2777            let parent_instance = unsafe {
2778                std::mem::transmute::<InstanceRef<'_, 'id2>, InstanceRef<'a, 'id2>>(
2779                    parent_instance.borrow_instance(),
2780                )
2781            };
2782            return Some(parent_instance);
2783        }
2784        None
2785    }
2786}
2787
2788/// Show the popup with a lazily evaluated location.
2789pub fn show_popup(
2790    element: ElementRc,
2791    instance: InstanceRef,
2792    popup: &object_tree::PopupWindow,
2793    pos_getter: impl Fn(InstanceRef<'_, '_>) -> LogicalPosition + 'static,
2794    close_policy: PopupClosePolicy,
2795    parent_comp: ErasedItemTreeBoxWeak,
2796    parent_window_adapter: WindowAdapterRc,
2797    parent_item: &ItemRc,
2798) {
2799    generativity::make_guard!(guard);
2800
2801    // FIXME: we should compile once and keep the cached compiled component
2802    let compiled = generate_item_tree(
2803        &popup.component,
2804        None,
2805        parent_comp.upgrade().unwrap().0.description().popup_menu_description.clone(),
2806        false,
2807        guard,
2808    );
2809
2810    let extra_data = instance.description.extra_data_offset.apply(instance.as_ref());
2811    // Use the newly created window adapter if we are able to create one. Otherwise use the parent's one.
2812    // Tooltips skip this to share the parent's adapter, ensuring they use the ChildWindow path
2813    // and renderer caches stay consistent.
2814    let window_kind = if popup.is_tooltip { WindowKind::ToolTip } else { WindowKind::Popup };
2815    let globals = if let Some(window_adapter) =
2816        WindowInner::from_pub(parent_window_adapter.window())
2817            .create_child_window_adapter(window_kind)
2818    {
2819        extra_data.globals.get().unwrap().clone_with_window_adapter(window_adapter)
2820    } else {
2821        extra_data.globals.get().unwrap().clone()
2822    };
2823
2824    let popup_window_adapter = globals
2825        .window_adapter()
2826        .and_then(|window_adapter| window_adapter.get().cloned())
2827        .unwrap_or_else(|| parent_window_adapter.clone());
2828
2829    // Keep a weak handle to the parent before `parent_comp` is moved into `instantiate`, so the
2830    // is-open setter (built below) can re-derive the parent instance when the popup closes.
2831    let parent_comp_weak = popup.is_open.is_some().then(|| parent_comp.clone());
2832    let inst = instantiate(
2833        compiled,
2834        Some(parent_comp),
2835        None,
2836        Some(&WindowOptions::UseExistingWindow(popup_window_adapter)),
2837        globals,
2838    );
2839    let inst_for_position = inst.clone();
2840    let access_position = Box::new(move || {
2841        generativity::make_guard!(guard);
2842        let compo_box = inst_for_position.unerase(guard);
2843        let instance_ref = compo_box.borrow_instance();
2844        pos_getter(instance_ref)
2845    });
2846    close_popup(element.clone(), instance, parent_window_adapter.clone());
2847    let window_kind = if popup.is_tooltip { WindowKind::ToolTip } else { WindowKind::Popup };
2848    // Keep the parent's `is-open` property in sync: `show_popup` invokes this with `true` now and with
2849    // `false` from every close path. Passing it directly into `show_popup` avoids an extra registration
2850    // call and a second popup lookup. Popups without `is-open` get a no-op setter.
2851    let is_open_setter: Box<dyn Fn(bool)> =
2852        if let (Some(is_open), Some(parent_comp_weak)) = (&popup.is_open, parent_comp_weak) {
2853            let is_open_element = is_open.element();
2854            let is_open_name = is_open.name().to_string();
2855            Box::new(move |value: bool| {
2856                if let Some(parent) = parent_comp_weak.upgrade() {
2857                    generativity::make_guard!(guard);
2858                    let compo_box = parent.unerase(guard);
2859                    let instance_ref = compo_box.borrow_instance();
2860                    let _ = crate::eval::store_property(
2861                        instance_ref,
2862                        &is_open_element,
2863                        &is_open_name,
2864                        Value::Bool(value),
2865                    );
2866                }
2867            })
2868        } else {
2869            Box::new(|_| {})
2870        };
2871    let popup_id = WindowInner::from_pub(parent_window_adapter.window()).show_popup(
2872        &vtable::VRc::into_dyn(inst.clone()),
2873        access_position,
2874        close_policy,
2875        parent_item,
2876        window_kind,
2877        is_open_setter,
2878    );
2879    instance.description.popup_ids.borrow_mut().insert(element.borrow().id.clone(), popup_id);
2880    inst.run_setup_code();
2881}
2882
2883pub fn close_popup(
2884    element: ElementRc,
2885    instance: InstanceRef,
2886    parent_window_adapter: WindowAdapterRc,
2887) {
2888    if let Some(current_id) =
2889        instance.description.popup_ids.borrow_mut().remove(&element.borrow().id)
2890    {
2891        WindowInner::from_pub(parent_window_adapter.window()).close_popup(current_id);
2892    }
2893}
2894
2895pub fn make_menu_item_tree(
2896    menu_item_tree: &Rc<object_tree::Component>,
2897    enclosing_component: &InstanceRef,
2898    condition: Option<&Expression>,
2899    visible: Option<&Expression>,
2900) -> vtable::VRc<i_slint_core::menus::MenuVTable, MenuFromItemTree> {
2901    generativity::make_guard!(guard);
2902    let mit_compiled = generate_item_tree(
2903        menu_item_tree,
2904        None,
2905        enclosing_component.description.popup_menu_description.clone(),
2906        false,
2907        guard,
2908    );
2909    let enclosing_component_weak = enclosing_component.self_weak().get().unwrap();
2910    let extra_data =
2911        enclosing_component.description.extra_data_offset.apply(enclosing_component.as_ref());
2912    let mit_inst = instantiate(
2913        mit_compiled.clone(),
2914        Some(enclosing_component_weak.clone()),
2915        None,
2916        None,
2917        extra_data.globals.get().unwrap().clone(),
2918    );
2919    mit_inst.run_setup_code();
2920    let item_tree = vtable::VRc::into_dyn(mit_inst);
2921    let condition = condition.map(|condition| {
2922        let binding =
2923            make_binding_eval_closure(condition.clone(), enclosing_component_weak.clone());
2924        move || binding().try_into().unwrap()
2925    });
2926    let visible = visible.map(|visible| {
2927        let binding = make_binding_eval_closure(visible.clone(), enclosing_component_weak.clone());
2928        move || binding().try_into().unwrap()
2929    });
2930    let menu = match (condition, visible) {
2931        (None, None) => MenuFromItemTree::new(item_tree),
2932        (None, Some(visible)) => {
2933            MenuFromItemTree::new_with_condition_and_visible(item_tree, || true, visible)
2934        }
2935        (Some(condition), None) => {
2936            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, || true)
2937        }
2938        (Some(condition), Some(visible)) => {
2939            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, visible)
2940        }
2941    };
2942    vtable::VRc::new(menu)
2943}
2944
2945pub fn update_timers(instance: InstanceRef) {
2946    let ts = instance.description.original.timers.borrow();
2947    for (desc, offset) in ts.iter().zip(&instance.description.timers) {
2948        let timer = offset.apply(instance.as_ref());
2949        let running =
2950            eval::load_property(instance, &desc.running.element(), desc.running.name()).unwrap();
2951        if matches!(running, Value::Bool(true)) {
2952            let millis: i64 =
2953                eval::load_property(instance, &desc.interval.element(), desc.interval.name())
2954                    .unwrap()
2955                    .try_into()
2956                    .expect("interval must be a duration");
2957            if millis < 0 {
2958                timer.stop();
2959                continue;
2960            }
2961            let interval = core::time::Duration::from_millis(millis as _);
2962            if !timer.running() || interval != timer.interval() {
2963                let callback = desc.triggered.clone();
2964                let self_weak = instance.self_weak().get().unwrap().clone();
2965                timer.start(i_slint_core::timers::TimerMode::Repeated, interval, move || {
2966                    if let Some(instance) = self_weak.upgrade() {
2967                        generativity::make_guard!(guard);
2968                        let c = instance.unerase(guard);
2969                        let c = c.borrow_instance();
2970                        let inst = eval::ComponentInstance::InstanceRef(c);
2971                        eval::invoke_callback(&inst, &callback.element(), callback.name(), &[])
2972                            .unwrap();
2973                    }
2974                });
2975            }
2976        } else {
2977            timer.stop();
2978        }
2979    }
2980}
2981
2982pub fn restart_timer(element: ElementWeak, instance: InstanceRef) {
2983    let timers = instance.description.original.timers.borrow();
2984    if let Some((_, offset)) = timers
2985        .iter()
2986        .zip(&instance.description.timers)
2987        .find(|(desc, _)| Weak::ptr_eq(&desc.element, &element))
2988    {
2989        let timer = offset.apply(instance.as_ref());
2990        timer.restart();
2991    }
2992}