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::{BuiltinPrivateStruct, 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};
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    repeater: Vec<ErasedRepeaterWithinComponent<'id>>,
466    /// Map the Element::id of the repeater to the index in the `repeater` vec
467    pub repeater_names: HashMap<SmolStr, usize>,
468    /// Offset to a Option<ComponentPinRef>
469    pub(crate) parent_item_tree_offset:
470        Option<FieldOffset<Instance<'id>, OnceCell<ErasedItemTreeBoxWeak>>>,
471    pub(crate) root_offset: FieldOffset<Instance<'id>, OnceCell<ErasedItemTreeBoxWeak>>,
472    /// Offset of a ComponentExtraData
473    pub(crate) extra_data_offset: FieldOffset<Instance<'id>, ComponentExtraData>,
474    /// Keep the Rc alive
475    pub(crate) original: Rc<object_tree::Component>,
476    /// Maps from an item_id to the original element it came from
477    pub(crate) original_elements: Vec<ElementRc>,
478    /// Copy of original.root_element.property_declarations, without a guarded refcell
479    public_properties: BTreeMap<SmolStr, PropertyDeclaration>,
480    change_trackers: Option<(
481        FieldOffset<Instance<'id>, OnceCell<Vec<ChangeTracker>>>,
482        Vec<(NamedReference, Expression)>,
483    )>,
484    timers: Vec<FieldOffset<Instance<'id>, Timer>>,
485    /// Map of element IDs to their active popup's ID
486    popup_ids: std::cell::RefCell<HashMap<SmolStr, NonZeroU32>>,
487
488    pub(crate) popup_menu_description: PopupMenuDescription,
489
490    /// The collection of compiled globals
491    compiled_globals: Option<Rc<CompiledGlobalCollection>>,
492
493    /// The type loader, which will be available only on the top-most `ItemTreeDescription`.
494    /// All other `ItemTreeDescription`s have `None` here.
495    #[cfg(feature = "internal-highlight")]
496    pub(crate) type_loader:
497        std::cell::OnceCell<std::rc::Rc<i_slint_compiler::typeloader::TypeLoader>>,
498    /// The type loader, which will be available only on the top-most `ItemTreeDescription`.
499    /// All other `ItemTreeDescription`s have `None` here.
500    #[cfg(feature = "internal-highlight")]
501    pub(crate) raw_type_loader:
502        std::cell::OnceCell<Option<std::rc::Rc<i_slint_compiler::typeloader::TypeLoader>>>,
503
504    pub(crate) debug_handler: std::cell::RefCell<
505        Rc<dyn Fn(Option<&i_slint_compiler::diagnostics::SourceLocation>, &str)>,
506    >,
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 sig = x.apply(unsafe { &*(component.as_ptr() as *const dynamic_type::Instance) });
737            sig.set_handler(handler);
738        }
739        Ok(())
740    }
741
742    /// Invoke the specified callback or function
743    ///
744    /// Returns an error if the component is not an instance corresponding to this ItemTreeDescription,
745    /// or if the callback with this name does not exist in this component
746    pub fn invoke(
747        &self,
748        component: ItemTreeRefPin,
749        name: &SmolStr,
750        args: &[Value],
751    ) -> Result<Value, ()> {
752        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
753            return Err(());
754        }
755        generativity::make_guard!(guard);
756        // Safety: we just verified that the component has the right vtable
757        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
758        let borrow = self.original.root_element.borrow();
759        let decl = borrow.property_declarations.get(name).ok_or(())?;
760
761        let (elem, name) = if let Some(alias) = &decl.is_alias {
762            (alias.element(), alias.name())
763        } else {
764            (self.original.root_element.clone(), name)
765        };
766
767        let inst = eval::ComponentInstance::InstanceRef(c);
768
769        if matches!(&decl.property_type, Type::Function { .. }) {
770            eval::call_function(&inst, &elem, name, args.to_vec()).ok_or(())
771        } else {
772            eval::invoke_callback(&inst, &elem, name, args).ok_or(())
773        }
774    }
775
776    // Return the global with the given name
777    pub fn get_global(
778        &self,
779        component: ItemTreeRefPin,
780        global_name: &str,
781    ) -> Result<Pin<Rc<dyn crate::global_component::GlobalComponent>>, ()> {
782        if !core::ptr::eq((&self.ct) as *const _, component.get_vtable() as *const _) {
783            return Err(());
784        }
785        generativity::make_guard!(guard);
786        // Safety: we just verified that the component has the right vtable
787        let c = unsafe { InstanceRef::from_pin_ref(component, guard) };
788        let extra_data = c.description.extra_data_offset.apply(c.instance.get_ref());
789        let g = extra_data.globals.get().unwrap().get(global_name).clone();
790        g.ok_or(())
791    }
792
793    pub fn recursively_set_debug_handler(
794        &self,
795        handler: Rc<dyn Fn(Option<&i_slint_compiler::diagnostics::SourceLocation>, &str)>,
796    ) {
797        *self.debug_handler.borrow_mut() = handler.clone();
798
799        for r in &self.repeater {
800            generativity::make_guard!(guard);
801            r.unerase(guard).item_tree_to_repeat.recursively_set_debug_handler(handler.clone());
802        }
803    }
804}
805
806#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
807extern "C" fn visit_children_item(
808    component: ItemTreeRefPin,
809    index: isize,
810    order: TraversalOrder,
811    v: ItemVisitorRefMut,
812) -> VisitChildrenResult {
813    generativity::make_guard!(guard);
814    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
815    let comp_rc = instance_ref.self_weak().get().unwrap().upgrade().unwrap();
816    i_slint_core::item_tree::visit_item_tree(
817        instance_ref.instance,
818        &vtable::VRc::into_dyn(comp_rc),
819        get_item_tree(component).as_slice(),
820        index,
821        order,
822        v,
823        |_, order, visitor, index| {
824            if index as usize >= instance_ref.description.repeater.len() {
825                // Do nothing: We are ComponentContainer and Our parent already did all the work!
826                VisitChildrenResult::CONTINUE
827            } else {
828                generativity::make_guard!(guard);
829                let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
830                let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
831                repeater.visit(order, visitor)
832            }
833        },
834    )
835}
836
837/// Information attached to a builtin item
838pub(crate) struct ItemRTTI {
839    vtable: &'static ItemVTable,
840    type_info: dynamic_type::StaticTypeInfo,
841    pub(crate) properties: HashMap<&'static str, Box<dyn eval::ErasedPropertyInfo>>,
842    pub(crate) callbacks: HashMap<&'static str, Box<dyn eval::ErasedCallbackInfo>>,
843}
844
845fn rtti_for<T: 'static + Default + rtti::BuiltinItem + vtable::HasStaticVTable<ItemVTable>>()
846-> (&'static str, Rc<ItemRTTI>) {
847    let rtti = ItemRTTI {
848        vtable: T::static_vtable(),
849        type_info: dynamic_type::StaticTypeInfo::new::<T>(),
850        properties: T::properties()
851            .into_iter()
852            .map(|(k, v)| (k, Box::new(v) as Box<dyn eval::ErasedPropertyInfo>))
853            .collect(),
854        callbacks: T::callbacks()
855            .into_iter()
856            .map(|(k, v)| (k, Box::new(v) as Box<dyn eval::ErasedCallbackInfo>))
857            .collect(),
858    };
859    (T::name(), Rc::new(rtti))
860}
861
862/// Create a ItemTreeDescription from a source.
863/// The path corresponding to the source need to be passed as well (path is used for diagnostics
864/// and loading relative assets)
865pub async fn load(
866    source: String,
867    path: std::path::PathBuf,
868    mut compiler_config: CompilerConfiguration,
869) -> CompilationResult {
870    // If the native style should be Qt, resolve it here as we know that we have it
871    let is_native = compiler_config.style.as_deref() == Some("native");
872    if is_native {
873        // On wasm, look at the browser user agent
874        #[cfg(target_arch = "wasm32")]
875        let target = web_sys::window()
876            .and_then(|window| window.navigator().platform().ok())
877            .map_or("wasm", |platform| {
878                let platform = platform.to_ascii_lowercase();
879                if platform.contains("mac")
880                    || platform.contains("iphone")
881                    || platform.contains("ipad")
882                {
883                    "apple"
884                } else if platform.contains("android") {
885                    "android"
886                } else if platform.contains("win") {
887                    "windows"
888                } else if platform.contains("linux") {
889                    "linux"
890                } else {
891                    "wasm"
892                }
893            });
894        #[cfg(not(target_arch = "wasm32"))]
895        let target = "";
896        compiler_config.style = Some(
897            i_slint_common::get_native_style(i_slint_backend_selector::HAS_NATIVE_STYLE, target)
898                .to_string(),
899        );
900    }
901
902    let diag = BuildDiagnostics::default();
903    #[cfg(feature = "internal-highlight")]
904    let (path, mut diag, loader, raw_type_loader) =
905        i_slint_compiler::load_root_file_with_raw_type_loader(
906            &path,
907            &path,
908            source,
909            diag,
910            compiler_config,
911        )
912        .await;
913    #[cfg(not(feature = "internal-highlight"))]
914    let (path, mut diag, loader) =
915        i_slint_compiler::load_root_file(&path, &path, source, diag, compiler_config).await;
916    #[cfg(feature = "internal-file-watcher")]
917    let watch_paths = loader.all_files_to_watch().into_iter().collect();
918    if diag.has_errors() {
919        return CompilationResult {
920            components: HashMap::new(),
921            diagnostics: diag.into_iter().collect(),
922            #[cfg(feature = "internal-file-watcher")]
923            watch_paths,
924            #[cfg(feature = "internal")]
925            structs_and_enums: Vec::new(),
926            #[cfg(feature = "internal")]
927            named_exports: Vec::new(),
928        };
929    }
930
931    #[cfg(feature = "internal-highlight")]
932    let loader = Rc::new(loader);
933    #[cfg(feature = "internal-highlight")]
934    let raw_type_loader = raw_type_loader.map(Rc::new);
935
936    let doc = loader.get_document(&path).unwrap();
937
938    let compiled_globals = Rc::new(CompiledGlobalCollection::compile(doc));
939    let mut components = HashMap::new();
940
941    let popup_menu_description = if let Some(popup_menu_impl) = &doc.popup_menu_impl {
942        PopupMenuDescription::Rc(Rc::new_cyclic(|weak| {
943            generativity::make_guard!(guard);
944            ErasedItemTreeDescription::from(generate_item_tree(
945                popup_menu_impl,
946                Some(compiled_globals.clone()),
947                PopupMenuDescription::Weak(weak.clone()),
948                true,
949                guard,
950            ))
951        }))
952    } else {
953        PopupMenuDescription::Weak(Default::default())
954    };
955
956    for c in doc.exported_roots() {
957        generativity::make_guard!(guard);
958        #[allow(unused_mut)]
959        let mut it = generate_item_tree(
960            &c,
961            Some(compiled_globals.clone()),
962            popup_menu_description.clone(),
963            false,
964            guard,
965        );
966        #[cfg(feature = "internal-highlight")]
967        {
968            let _ = it.type_loader.set(loader.clone());
969            let _ = it.raw_type_loader.set(raw_type_loader.clone());
970        }
971        components.insert(c.id.to_string(), ComponentDefinition { inner: it.into() });
972    }
973
974    if components.is_empty() {
975        diag.push_error_with_span("No component found".into(), Default::default());
976    };
977
978    #[cfg(feature = "internal")]
979    let structs_and_enums = doc.used_types.borrow().structs_and_enums.clone();
980
981    #[cfg(feature = "internal")]
982    let named_exports = doc
983        .exports
984        .iter()
985        .filter_map(|export| match &export.1 {
986            Either::Left(component) if !component.is_global() => {
987                Some((&export.0.name, &component.id))
988            }
989            Either::Right(ty) => match &ty {
990                Type::Struct(s) if s.node().is_some() => {
991                    if let StructName::User { name, .. } = &s.name {
992                        Some((&export.0.name, name))
993                    } else {
994                        None
995                    }
996                }
997                Type::Enumeration(en) => Some((&export.0.name, &en.name)),
998                _ => None,
999            },
1000            _ => None,
1001        })
1002        .filter(|(export_name, type_name)| *export_name != *type_name)
1003        .map(|(export_name, type_name)| (type_name.to_string(), export_name.to_string()))
1004        .collect::<Vec<_>>();
1005
1006    CompilationResult {
1007        diagnostics: diag.into_iter().collect(),
1008        components,
1009        #[cfg(feature = "internal-file-watcher")]
1010        watch_paths,
1011        #[cfg(feature = "internal")]
1012        structs_and_enums,
1013        #[cfg(feature = "internal")]
1014        named_exports,
1015    }
1016}
1017
1018fn generate_rtti() -> HashMap<&'static str, Rc<ItemRTTI>> {
1019    let mut rtti = HashMap::new();
1020    use i_slint_core::items::*;
1021    rtti.extend(
1022        [
1023            rtti_for::<ComponentContainer>(),
1024            rtti_for::<Empty>(),
1025            rtti_for::<ImageItem>(),
1026            rtti_for::<ClippedImage>(),
1027            rtti_for::<ComplexText>(),
1028            rtti_for::<StyledTextItem>(),
1029            rtti_for::<SimpleText>(),
1030            rtti_for::<Rectangle>(),
1031            rtti_for::<BasicBorderRectangle>(),
1032            rtti_for::<BorderRectangle>(),
1033            rtti_for::<TouchArea>(),
1034            rtti_for::<TooltipArea>(),
1035            rtti_for::<FocusScope>(),
1036            rtti_for::<KeyBinding>(),
1037            rtti_for::<SwipeGestureHandler>(),
1038            rtti_for::<ScaleRotateGestureHandler>(),
1039            rtti_for::<Path>(),
1040            rtti_for::<Flickable>(),
1041            rtti_for::<WindowItem>(),
1042            rtti_for::<TextInput>(),
1043            rtti_for::<Clip>(),
1044            rtti_for::<BoxShadow>(),
1045            rtti_for::<Transform>(),
1046            rtti_for::<Opacity>(),
1047            rtti_for::<Layer>(),
1048            rtti_for::<DragArea>(),
1049            rtti_for::<DropArea>(),
1050            rtti_for::<ContextMenu>(),
1051            rtti_for::<MenuItem>(),
1052            rtti_for::<SystemTrayIcon>(),
1053        ]
1054        .iter()
1055        .cloned(),
1056    );
1057
1058    trait NativeHelper {
1059        fn push(rtti: &mut HashMap<&str, Rc<ItemRTTI>>);
1060    }
1061    impl NativeHelper for () {
1062        fn push(_rtti: &mut HashMap<&str, Rc<ItemRTTI>>) {}
1063    }
1064    impl<
1065        T: 'static + Default + rtti::BuiltinItem + vtable::HasStaticVTable<ItemVTable>,
1066        Next: NativeHelper,
1067    > NativeHelper for (T, Next)
1068    {
1069        fn push(rtti: &mut HashMap<&str, Rc<ItemRTTI>>) {
1070            let info = rtti_for::<T>();
1071            rtti.insert(info.0, info.1);
1072            Next::push(rtti);
1073        }
1074    }
1075    i_slint_backend_selector::NativeWidgets::push(&mut rtti);
1076
1077    rtti
1078}
1079
1080pub(crate) fn generate_item_tree<'id>(
1081    component: &Rc<object_tree::Component>,
1082    compiled_globals: Option<Rc<CompiledGlobalCollection>>,
1083    popup_menu_description: PopupMenuDescription,
1084    is_popup_menu_impl: bool,
1085    guard: generativity::Guard<'id>,
1086) -> Rc<ItemTreeDescription<'id>> {
1087    //dbg!(&*component.root_element.borrow());
1088
1089    thread_local! {
1090        static RTTI: Lazy<HashMap<&'static str, Rc<ItemRTTI>>> = Lazy::new(generate_rtti);
1091    }
1092
1093    struct TreeBuilder<'id> {
1094        tree_array: Vec<ItemTreeNode>,
1095        item_array:
1096            Vec<vtable::VOffset<crate::dynamic_type::Instance<'id>, ItemVTable, vtable::AllowPin>>,
1097        original_elements: Vec<ElementRc>,
1098        items_types: HashMap<SmolStr, ItemWithinItemTree>,
1099        type_builder: dynamic_type::TypeBuilder<'id>,
1100        repeater: Vec<ErasedRepeaterWithinComponent<'id>>,
1101        repeater_names: HashMap<SmolStr, usize>,
1102        change_callbacks: Vec<(NamedReference, Expression)>,
1103        popup_menu_description: PopupMenuDescription,
1104    }
1105    impl generator::ItemTreeBuilder for TreeBuilder<'_> {
1106        type SubComponentState = ();
1107
1108        fn push_repeated_item(
1109            &mut self,
1110            item_rc: &ElementRc,
1111            repeater_count: u32,
1112            parent_index: u32,
1113            _component_state: &Self::SubComponentState,
1114        ) {
1115            self.tree_array.push(ItemTreeNode::DynamicTree { index: repeater_count, parent_index });
1116            self.original_elements.push(item_rc.clone());
1117            let item = item_rc.borrow();
1118            let base_component = item.base_type.as_component();
1119            self.repeater_names.insert(item.id.clone(), self.repeater.len());
1120            generativity::make_guard!(guard);
1121            let repeated_element_info = item.repeated.as_ref().unwrap();
1122            self.repeater.push(
1123                RepeaterWithinItemTree {
1124                    item_tree_to_repeat: generate_item_tree(
1125                        base_component,
1126                        None,
1127                        self.popup_menu_description.clone(),
1128                        false,
1129                        guard,
1130                    ),
1131                    offset: self.type_builder.add_field_type::<Repeater<ErasedItemTreeBox>>(),
1132                    model: repeated_element_info.model.clone(),
1133                    is_conditional: repeated_element_info.is_conditional_element,
1134                }
1135                .into(),
1136            );
1137        }
1138
1139        fn push_native_item(
1140            &mut self,
1141            rc_item: &ElementRc,
1142            child_offset: u32,
1143            parent_index: u32,
1144            _component_state: &Self::SubComponentState,
1145        ) {
1146            let item = rc_item.borrow();
1147            let rt = RTTI.with(|rtti| {
1148                rtti.get(&*item.base_type.as_native().class_name)
1149                    .unwrap_or_else(|| {
1150                        panic!(
1151                            "Native type not registered: {}",
1152                            item.base_type.as_native().class_name
1153                        )
1154                    })
1155                    .clone()
1156            });
1157
1158            let offset = self.type_builder.add_field(rt.type_info);
1159
1160            self.tree_array.push(ItemTreeNode::Item {
1161                is_accessible: !item.accessibility_props.0.is_empty(),
1162                children_index: child_offset,
1163                children_count: item.children.len() as u32,
1164                parent_index,
1165                item_array_index: self.item_array.len() as u32,
1166            });
1167            self.item_array.push(unsafe { vtable::VOffset::from_raw(rt.vtable, offset) });
1168            self.original_elements.push(rc_item.clone());
1169            debug_assert_eq!(self.original_elements.len(), self.tree_array.len());
1170            self.items_types.insert(
1171                item.id.clone(),
1172                ItemWithinItemTree { offset, rtti: rt, elem: rc_item.clone() },
1173            );
1174            for (prop, expr) in &item.change_callbacks {
1175                self.change_callbacks.push((
1176                    NamedReference::new(rc_item, prop.clone()),
1177                    Expression::CodeBlock(expr.borrow().clone()),
1178                ));
1179            }
1180        }
1181
1182        fn enter_component(
1183            &mut self,
1184            _item: &ElementRc,
1185            _sub_component: &Rc<object_tree::Component>,
1186            _children_offset: u32,
1187            _component_state: &Self::SubComponentState,
1188        ) -> Self::SubComponentState {
1189            /* nothing to do */
1190        }
1191
1192        fn enter_component_children(
1193            &mut self,
1194            _item: &ElementRc,
1195            _repeater_count: u32,
1196            _component_state: &Self::SubComponentState,
1197            _sub_component_state: &Self::SubComponentState,
1198        ) {
1199            todo!()
1200        }
1201    }
1202
1203    let mut builder = TreeBuilder {
1204        tree_array: Vec::new(),
1205        item_array: Vec::new(),
1206        original_elements: Vec::new(),
1207        items_types: HashMap::new(),
1208        type_builder: dynamic_type::TypeBuilder::new(guard),
1209        repeater: Vec::new(),
1210        repeater_names: HashMap::new(),
1211        change_callbacks: Vec::new(),
1212        popup_menu_description,
1213    };
1214
1215    if !component.is_global() {
1216        generator::build_item_tree(component, &(), &mut builder);
1217    } else {
1218        for (prop, expr) in component.root_element.borrow().change_callbacks.iter() {
1219            builder.change_callbacks.push((
1220                NamedReference::new(&component.root_element, prop.clone()),
1221                Expression::CodeBlock(expr.borrow().clone()),
1222            ));
1223        }
1224    }
1225
1226    let mut custom_properties = HashMap::new();
1227    let mut custom_callbacks = HashMap::new();
1228    fn property_info<T>() -> (Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)
1229    where
1230        T: PartialEq + Clone + Default + std::convert::TryInto<Value> + 'static,
1231        Value: std::convert::TryInto<T>,
1232    {
1233        // Fixme: using u8 in PropertyInfo<> is not sound, we would need to materialize a type for out component
1234        (
1235            Box::new(unsafe {
1236                vtable::FieldOffset::<u8, Property<T>, _>::new_from_offset_pinned(0)
1237            }),
1238            dynamic_type::StaticTypeInfo::new::<Property<T>>(),
1239        )
1240    }
1241    fn animated_property_info<T>()
1242    -> (Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)
1243    where
1244        T: Clone + Default + InterpolatedPropertyValue + std::convert::TryInto<Value> + 'static,
1245        Value: std::convert::TryInto<T>,
1246    {
1247        // Fixme: using u8 in PropertyInfo<> is not sound, we would need to materialize a type for out component
1248        (
1249            Box::new(unsafe {
1250                rtti::MaybeAnimatedPropertyInfoWrapper(
1251                    vtable::FieldOffset::<u8, Property<T>, _>::new_from_offset_pinned(0),
1252                )
1253            }),
1254            dynamic_type::StaticTypeInfo::new::<Property<T>>(),
1255        )
1256    }
1257
1258    fn property_info_for_type(
1259        ty: &Type,
1260        name: &str,
1261    ) -> Option<(Box<dyn PropertyInfo<u8, Value>>, dynamic_type::StaticTypeInfo)> {
1262        Some(match ty {
1263            Type::Float32 => animated_property_info::<f32>(),
1264            Type::Int32 => animated_property_info::<i32>(),
1265            Type::String => property_info::<SharedString>(),
1266            Type::Color => animated_property_info::<Color>(),
1267            Type::Brush => animated_property_info::<Brush>(),
1268            Type::Duration => animated_property_info::<i64>(),
1269            Type::Angle => animated_property_info::<f32>(),
1270            Type::PhysicalLength => animated_property_info::<f32>(),
1271            Type::LogicalLength => animated_property_info::<f32>(),
1272            Type::Rem => animated_property_info::<f32>(),
1273            Type::Image => property_info::<i_slint_core::graphics::Image>(),
1274            Type::Bool => property_info::<bool>(),
1275            Type::ComponentFactory => property_info::<ComponentFactory>(),
1276            Type::Struct(s)
1277                if matches!(
1278                    s.name,
1279                    StructName::BuiltinPrivate(BuiltinPrivateStruct::StateInfo)
1280                ) =>
1281            {
1282                property_info::<i_slint_core::properties::StateInfo>()
1283            }
1284            Type::Struct(_) => property_info::<Value>(),
1285            Type::Array(_) => property_info::<Value>(),
1286            Type::Easing => property_info::<i_slint_core::animations::EasingCurve>(),
1287            Type::Percent => animated_property_info::<f32>(),
1288            Type::Enumeration(e) => {
1289                macro_rules! match_enum_type {
1290                    ($( $(#[$enum_doc:meta])* $vis:vis enum $Name:ident { $($body:tt)* })*) => {
1291                        match e.name.as_str() {
1292                            $(
1293                                stringify!($Name) => property_info::<i_slint_core::items::$Name>(),
1294                            )*
1295                            x => unreachable!("Unknown non-builtin enum {x}"),
1296                        }
1297                    }
1298                }
1299
1300                if e.node.is_some() {
1301                    property_info::<Value>()
1302                } else {
1303                    i_slint_common::for_each_enums!(match_enum_type)
1304                }
1305            }
1306            Type::Keys => property_info::<Keys>(),
1307            Type::DataTransfer => property_info::<DataTransfer>(),
1308            Type::LayoutCache => property_info::<SharedVector<f32>>(),
1309            Type::ArrayOfU16 => property_info::<SharedVector<u16>>(),
1310            Type::Function { .. } | Type::Callback { .. } => return None,
1311            Type::StyledText => property_info::<StyledText>(),
1312            // These can't be used in properties
1313            Type::Invalid
1314            | Type::Void
1315            | Type::InferredProperty
1316            | Type::InferredCallback
1317            | Type::Model
1318            | Type::PathData
1319            | Type::UnitProduct(_)
1320            | Type::ElementReference => panic!("bad type {ty:?} for property {name}"),
1321        })
1322    }
1323
1324    for (name, decl) in &component.root_element.borrow().property_declarations {
1325        if decl.is_alias.is_some() {
1326            continue;
1327        }
1328        if matches!(&decl.property_type, Type::Callback { .. }) {
1329            custom_callbacks
1330                .insert(name.clone(), builder.type_builder.add_field_type::<Callback>());
1331            continue;
1332        }
1333        let Some((prop, type_info)) = property_info_for_type(&decl.property_type, name) else {
1334            continue;
1335        };
1336        custom_properties.insert(
1337            name.clone(),
1338            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1339        );
1340    }
1341    if let Some(parent_element) = component.parent_element()
1342        && let Some(r) = &parent_element.borrow().repeated
1343        && !r.is_conditional_element
1344    {
1345        let (prop, type_info) = property_info::<u32>();
1346        custom_properties.insert(
1347            SPECIAL_PROPERTY_INDEX.into(),
1348            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1349        );
1350
1351        let model_ty = Expression::RepeaterModelReference {
1352            element: component.parent_element.borrow().clone(),
1353        }
1354        .ty();
1355        let (prop, type_info) =
1356            property_info_for_type(&model_ty, SPECIAL_PROPERTY_MODEL_DATA).unwrap();
1357        custom_properties.insert(
1358            SPECIAL_PROPERTY_MODEL_DATA.into(),
1359            PropertiesWithinComponent { offset: builder.type_builder.add_field(type_info), prop },
1360        );
1361    }
1362
1363    let parent_item_tree_offset = if component.parent_element().is_some() || is_popup_menu_impl {
1364        Some(builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>())
1365    } else {
1366        None
1367    };
1368
1369    let root_offset = builder.type_builder.add_field_type::<OnceCell<ErasedItemTreeBoxWeak>>();
1370    let extra_data_offset = builder.type_builder.add_field_type::<ComponentExtraData>();
1371
1372    let change_trackers = (!builder.change_callbacks.is_empty()).then(|| {
1373        (
1374            builder.type_builder.add_field_type::<OnceCell<Vec<ChangeTracker>>>(),
1375            builder.change_callbacks,
1376        )
1377    });
1378    let timers = component
1379        .timers
1380        .borrow()
1381        .iter()
1382        .map(|_| builder.type_builder.add_field_type::<Timer>())
1383        .collect();
1384
1385    // only the public exported component needs the public property list
1386    let public_properties = if component.parent_element().is_none() {
1387        component.root_element.borrow().property_declarations.clone()
1388    } else {
1389        Default::default()
1390    };
1391
1392    let t = ItemTreeVTable {
1393        visit_children_item,
1394        layout_info,
1395        ensure_instantiated,
1396        get_item_ref,
1397        get_item_tree,
1398        get_subtree_range,
1399        get_subtree,
1400        parent_node,
1401        embed_component,
1402        subtree_index,
1403        item_geometry,
1404        accessible_role,
1405        accessible_string_property,
1406        accessibility_action,
1407        supported_accessibility_actions,
1408        item_element_infos,
1409        window_adapter,
1410        drop_in_place,
1411        dealloc,
1412    };
1413    let t = ItemTreeDescription {
1414        ct: t,
1415        dynamic_type: builder.type_builder.build(),
1416        item_tree: builder.tree_array,
1417        item_array: builder.item_array,
1418        items: builder.items_types,
1419        custom_properties,
1420        custom_callbacks,
1421        original: component.clone(),
1422        original_elements: builder.original_elements,
1423        repeater: builder.repeater,
1424        repeater_names: builder.repeater_names,
1425        parent_item_tree_offset,
1426        root_offset,
1427        extra_data_offset,
1428        public_properties,
1429        compiled_globals,
1430        change_trackers,
1431        timers,
1432        popup_ids: std::cell::RefCell::new(HashMap::new()),
1433        popup_menu_description: builder.popup_menu_description,
1434        #[cfg(feature = "internal-highlight")]
1435        type_loader: std::cell::OnceCell::new(),
1436        #[cfg(feature = "internal-highlight")]
1437        raw_type_loader: std::cell::OnceCell::new(),
1438        debug_handler: std::cell::RefCell::new(Rc::new(|_, text| {
1439            i_slint_core::debug_log!("{text}")
1440        })),
1441    };
1442
1443    Rc::new(t)
1444}
1445
1446pub fn animation_for_property(
1447    component: InstanceRef,
1448    animation: &Option<i_slint_compiler::object_tree::PropertyAnimation>,
1449) -> AnimatedBindingKind {
1450    match animation {
1451        Some(i_slint_compiler::object_tree::PropertyAnimation::Static(anim_elem)) => {
1452            AnimatedBindingKind::Animation(Box::new({
1453                let component_ptr = component.as_ptr();
1454                let vtable = NonNull::from(&component.description.ct).cast();
1455                let anim_elem = Rc::clone(anim_elem);
1456                move || -> PropertyAnimation {
1457                    generativity::make_guard!(guard);
1458                    let component = unsafe {
1459                        InstanceRef::from_pin_ref(
1460                            Pin::new_unchecked(vtable::VRef::from_raw(
1461                                vtable,
1462                                NonNull::new_unchecked(component_ptr as *mut u8),
1463                            )),
1464                            guard,
1465                        )
1466                    };
1467
1468                    eval::new_struct_with_bindings(
1469                        &anim_elem.borrow().bindings,
1470                        &mut eval::EvalLocalContext::from_component_instance(component),
1471                    )
1472                }
1473            }))
1474        }
1475        Some(i_slint_compiler::object_tree::PropertyAnimation::Transition {
1476            animations,
1477            state_ref,
1478        }) => {
1479            let component_ptr = component.as_ptr();
1480            let vtable = NonNull::from(&component.description.ct).cast();
1481            let animations = animations.clone();
1482            let state_ref = state_ref.clone();
1483            AnimatedBindingKind::Transition(Box::new(
1484                move || -> (PropertyAnimation, i_slint_core::animations::Instant) {
1485                    generativity::make_guard!(guard);
1486                    let component = unsafe {
1487                        InstanceRef::from_pin_ref(
1488                            Pin::new_unchecked(vtable::VRef::from_raw(
1489                                vtable,
1490                                NonNull::new_unchecked(component_ptr as *mut u8),
1491                            )),
1492                            guard,
1493                        )
1494                    };
1495
1496                    let mut context = eval::EvalLocalContext::from_component_instance(component);
1497                    let state = eval::eval_expression(&state_ref, &mut context);
1498                    let state_info: i_slint_core::properties::StateInfo = state.try_into().unwrap();
1499                    for a in &animations {
1500                        let is_previous_state = a.state_id == state_info.previous_state;
1501                        let is_current_state = a.state_id == state_info.current_state;
1502                        match (a.direction, is_previous_state, is_current_state) {
1503                            (TransitionDirection::In, false, true)
1504                            | (TransitionDirection::Out, true, false)
1505                            | (TransitionDirection::InOut, false, true)
1506                            | (TransitionDirection::InOut, true, false) => {
1507                                return (
1508                                    eval::new_struct_with_bindings(
1509                                        &a.animation.borrow().bindings,
1510                                        &mut context,
1511                                    ),
1512                                    state_info.change_time,
1513                                );
1514                            }
1515                            _ => {}
1516                        }
1517                    }
1518                    Default::default()
1519                },
1520            ))
1521        }
1522        None => AnimatedBindingKind::NotAnimated,
1523    }
1524}
1525
1526fn make_callback_eval_closure(
1527    expr: Expression,
1528    self_weak: ErasedItemTreeBoxWeak,
1529) -> impl Fn(&[Value]) -> Value {
1530    move |args| {
1531        let self_rc = self_weak.upgrade().unwrap();
1532        generativity::make_guard!(guard);
1533        let self_ = self_rc.unerase(guard);
1534        let instance_ref = self_.borrow_instance();
1535        let mut local_context =
1536            eval::EvalLocalContext::from_function_arguments(instance_ref, args.to_vec());
1537        eval::eval_expression(&expr, &mut local_context)
1538    }
1539}
1540
1541fn make_binding_eval_closure(
1542    expr: Expression,
1543    self_weak: ErasedItemTreeBoxWeak,
1544) -> impl Fn() -> Value {
1545    move || {
1546        let self_rc = self_weak.upgrade().unwrap();
1547        generativity::make_guard!(guard);
1548        let self_ = self_rc.unerase(guard);
1549        let instance_ref = self_.borrow_instance();
1550        eval::eval_expression(
1551            &expr,
1552            &mut eval::EvalLocalContext::from_component_instance(instance_ref),
1553        )
1554    }
1555}
1556
1557pub fn instantiate(
1558    description: Rc<ItemTreeDescription>,
1559    parent_ctx: Option<ErasedItemTreeBoxWeak>,
1560    root: Option<ErasedItemTreeBoxWeak>,
1561    window_options: Option<&WindowOptions>,
1562    globals: crate::global_component::GlobalStorage,
1563) -> DynamicComponentVRc {
1564    let instance = description.dynamic_type.clone().create_instance();
1565
1566    let component_box = ItemTreeBox { instance, description: description.clone() };
1567
1568    let self_rc = vtable::VRc::new(ErasedItemTreeBox::from(component_box));
1569    let self_weak = vtable::VRc::downgrade(&self_rc);
1570
1571    generativity::make_guard!(guard);
1572    let comp = self_rc.unerase(guard);
1573    let instance_ref = comp.borrow_instance();
1574    instance_ref.self_weak().set(self_weak.clone()).ok();
1575    let description = comp.description();
1576
1577    if let Some(WindowOptions::UseExistingWindow(existing_adapter)) = &window_options
1578        && let Err((a, b)) = globals.window_adapter().unwrap().try_insert(existing_adapter.clone())
1579    {
1580        assert!(Rc::ptr_eq(a, &b), "window not the same as parent window");
1581    }
1582
1583    if let Some(parent) = parent_ctx {
1584        description
1585            .parent_item_tree_offset
1586            .unwrap()
1587            .apply(instance_ref.as_ref())
1588            .set(parent)
1589            .ok()
1590            .unwrap();
1591    } else if let Some(g) = description.compiled_globals.as_ref() {
1592        for g in g.compiled_globals.iter() {
1593            crate::global_component::instantiate(g, &globals, self_weak.clone());
1594        }
1595    }
1596    let extra_data = description.extra_data_offset.apply(instance_ref.as_ref());
1597    extra_data.globals.set(globals).ok().unwrap();
1598    if let Some(WindowOptions::Embed { parent_item_tree, parent_item_tree_index }) = window_options
1599    {
1600        vtable::VRc::borrow_pin(&self_rc)
1601            .as_ref()
1602            .embed_component(parent_item_tree, *parent_item_tree_index);
1603        description.root_offset.apply(instance_ref.as_ref()).set(self_weak.clone()).ok().unwrap();
1604    } else {
1605        generativity::make_guard!(guard);
1606        let root = root
1607            .or_else(|| {
1608                instance_ref.parent_instance(guard).map(|parent| parent.root_weak().clone())
1609            })
1610            .unwrap_or_else(|| self_weak.clone());
1611        description.root_offset.apply(instance_ref.as_ref()).set(root).ok().unwrap();
1612    }
1613
1614    if !description.original.is_global() {
1615        let maybe_window_adapter =
1616            if let Some(WindowOptions::UseExistingWindow(adapter)) = window_options.as_ref() {
1617                Some(adapter.clone())
1618            } else {
1619                instance_ref.maybe_window_adapter()
1620            };
1621
1622        let component_rc = vtable::VRc::into_dyn(self_rc.clone());
1623        i_slint_core::item_tree::register_item_tree(&component_rc, maybe_window_adapter);
1624    }
1625
1626    // Some properties are generated as Value, but for which the default constructed Value must be initialized
1627    for (prop_name, decl) in &description.original.root_element.borrow().property_declarations {
1628        if !matches!(
1629            decl.property_type,
1630            Type::Struct { .. } | Type::Array(_) | Type::Enumeration(_)
1631        ) || decl.is_alias.is_some()
1632        {
1633            continue;
1634        }
1635        if let Some(b) = description.original.root_element.borrow().bindings.get(prop_name)
1636            && b.borrow().two_way_bindings.is_empty()
1637        {
1638            continue;
1639        }
1640        let p = description.custom_properties.get(prop_name).unwrap();
1641        unsafe {
1642            let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(p.offset));
1643            p.prop.set(item, eval::default_value_for_type(&decl.property_type), None).unwrap();
1644        }
1645    }
1646
1647    #[cfg(slint_debug_property)]
1648    {
1649        let component_id = description.original.id.as_str();
1650
1651        // Set debug names on custom (root element) properties
1652        for (prop_name, prop_info) in &description.custom_properties {
1653            let name = format!("{}.{}", component_id, prop_name);
1654            unsafe {
1655                let item = Pin::new_unchecked(&*instance_ref.as_ptr().add(prop_info.offset));
1656                prop_info.prop.set_debug_name(item, name);
1657            }
1658        }
1659
1660        // Set debug names on built-in item properties
1661        for (item_name, item_within_component) in &description.items {
1662            let item = unsafe { item_within_component.item_from_item_tree(instance_ref.as_ptr()) };
1663            for (prop_name, prop_rtti) in &item_within_component.rtti.properties {
1664                let name = format!("{}::{}.{}", component_id, item_name, prop_name);
1665                prop_rtti.set_debug_name(item, name);
1666            }
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::BuiltinPrivate(BuiltinPrivateStruct::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 self.0.description.original.init_code.borrow().iter() {
2085            eval::eval_expression(
2086                extra_init_code,
2087                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2088            );
2089        }
2090        if let Some(cts) = instance_ref.description.change_trackers.as_ref() {
2091            let self_weak = instance_ref.self_weak().get().unwrap();
2092            let v = cts
2093                .1
2094                .iter()
2095                .enumerate()
2096                .map(|(idx, _)| {
2097                    let ct = ChangeTracker::default();
2098                    ct.init(
2099                        self_weak.clone(),
2100                        move |self_weak| {
2101                            let s = self_weak.upgrade().unwrap();
2102                            generativity::make_guard!(guard);
2103                            let compo_box = s.unerase(guard);
2104                            let instance_ref = compo_box.borrow_instance();
2105                            let nr = &s.0.description.change_trackers.as_ref().unwrap().1[idx].0;
2106                            eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap()
2107                        },
2108                        move |self_weak, _| {
2109                            let s = self_weak.upgrade().unwrap();
2110                            generativity::make_guard!(guard);
2111                            let compo_box = s.unerase(guard);
2112                            let instance_ref = compo_box.borrow_instance();
2113                            let e = &s.0.description.change_trackers.as_ref().unwrap().1[idx].1;
2114                            eval::eval_expression(
2115                                e,
2116                                &mut eval::EvalLocalContext::from_component_instance(instance_ref),
2117                            );
2118                        },
2119                    );
2120                    ct
2121                })
2122                .collect::<Vec<_>>();
2123            cts.0
2124                .apply_pin(instance_ref.instance)
2125                .set(v)
2126                .unwrap_or_else(|_| panic!("run_setup_code called twice?"));
2127        }
2128        update_timers(instance_ref);
2129    }
2130}
2131impl<'id> From<ItemTreeBox<'id>> for ErasedItemTreeBox {
2132    fn from(inner: ItemTreeBox<'id>) -> Self {
2133        // Safety: Nothing access the component directly, we only access it through unerased where
2134        // the lifetime is unique again
2135        unsafe {
2136            ErasedItemTreeBox(core::mem::transmute::<ItemTreeBox<'id>, ItemTreeBox<'static>>(inner))
2137        }
2138    }
2139}
2140
2141pub fn get_repeater_by_name<'a, 'id>(
2142    instance_ref: InstanceRef<'a, '_>,
2143    name: &str,
2144    guard: generativity::Guard<'id>,
2145) -> (std::pin::Pin<&'a Repeater<ErasedItemTreeBox>>, Rc<ItemTreeDescription<'id>>) {
2146    let rep_index = instance_ref.description.repeater_names[name];
2147    let rep_in_comp = instance_ref.description.repeater[rep_index].unerase(guard);
2148    (rep_in_comp.offset.apply_pin(instance_ref.instance), rep_in_comp.item_tree_to_repeat.clone())
2149}
2150
2151#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2152extern "C" fn ensure_instantiated(component: ItemTreeRefPin) -> bool {
2153    generativity::make_guard!(guard);
2154    // Safety: called through the vtable of our own ItemTreeDescription.
2155    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2156
2157    let mut changed = false;
2158    for (tree_index, node) in instance_ref.description.item_tree.iter().enumerate() {
2159        if !matches!(node, ItemTreeNode::Item { .. }) {
2160            continue;
2161        }
2162        let item_ref = component.as_ref().get_item_ref(tree_index as u32);
2163        if let Some(container) = i_slint_core::items::ItemRef::downcast_pin::<
2164            i_slint_core::items::ComponentContainer,
2165        >(item_ref)
2166        {
2167            changed |= container.ensure_updated();
2168        }
2169    }
2170
2171    for rep_in_comp in &instance_ref.description.repeater {
2172        // Safety: we do not mix the repeater with a different component id.
2173        let rep_in_comp = unsafe { rep_in_comp.get_untagged() };
2174        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2175        let init = || {
2176            let extra_data =
2177                instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2178            instantiate(
2179                rep_in_comp.item_tree_to_repeat.clone(),
2180                instance_ref.self_weak().get().cloned(),
2181                None,
2182                None,
2183                extra_data.globals.get().unwrap().clone(),
2184            )
2185        };
2186        if let Some(lv) = &rep_in_comp
2187            .item_tree_to_repeat
2188            .original
2189            .parent_element
2190            .borrow()
2191            .upgrade()
2192            .unwrap()
2193            .borrow()
2194            .repeated
2195            .as_ref()
2196            .unwrap()
2197            .is_listview
2198        {
2199            let assume_property_logical_length =
2200                |prop| unsafe { Pin::new_unchecked(&*(prop as *const Property<LogicalLength>)) };
2201            changed |= repeater.ensure_updated_listview(
2202                init,
2203                assume_property_logical_length(get_property_ptr(&lv.viewport_width, instance_ref)),
2204                assume_property_logical_length(get_property_ptr(&lv.viewport_height, instance_ref)),
2205                assume_property_logical_length(get_property_ptr(&lv.viewport_y, instance_ref)),
2206                eval::load_property(
2207                    instance_ref,
2208                    &lv.listview_width.element(),
2209                    lv.listview_width.name(),
2210                )
2211                .unwrap()
2212                .try_into()
2213                .unwrap(),
2214                assume_property_logical_length(get_property_ptr(&lv.listview_height, instance_ref)),
2215            );
2216        } else {
2217            changed |= repeater.ensure_updated(init);
2218        }
2219    }
2220    changed
2221}
2222
2223#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2224extern "C" fn layout_info(component: ItemTreeRefPin, orientation: Orientation) -> LayoutInfo {
2225    generativity::make_guard!(guard);
2226    // This is fine since we can only be called with a component that with our vtable which is a ItemTreeDescription
2227    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2228    let orientation = crate::eval_layout::from_runtime(orientation);
2229
2230    let mut result = crate::eval_layout::get_layout_info(
2231        &instance_ref.description.original.root_element,
2232        instance_ref,
2233        &instance_ref.window_adapter(),
2234        orientation,
2235    );
2236
2237    let constraints = instance_ref.description.original.root_constraints.borrow();
2238    if constraints.has_explicit_restrictions(orientation) {
2239        crate::eval_layout::fill_layout_info_constraints(
2240            &mut result,
2241            &constraints,
2242            orientation,
2243            &|nr: &NamedReference| {
2244                eval::load_property(instance_ref, &nr.element(), nr.name())
2245                    .unwrap()
2246                    .try_into()
2247                    .unwrap()
2248            },
2249        );
2250    }
2251    result
2252}
2253
2254#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2255unsafe extern "C" fn get_item_ref(component: ItemTreeRefPin, index: u32) -> Pin<ItemRef> {
2256    let tree = get_item_tree(component);
2257    match &tree[index as usize] {
2258        ItemTreeNode::Item { item_array_index, .. } => unsafe {
2259            generativity::make_guard!(guard);
2260            let instance_ref = InstanceRef::from_pin_ref(component, guard);
2261            core::mem::transmute::<Pin<ItemRef>, Pin<ItemRef>>(
2262                instance_ref.description.item_array[*item_array_index as usize]
2263                    .apply_pin(instance_ref.instance),
2264            )
2265        },
2266        ItemTreeNode::DynamicTree { .. } => panic!("get_item_ref called on dynamic tree"),
2267    }
2268}
2269
2270#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2271extern "C" fn get_subtree_range(component: ItemTreeRefPin, index: u32) -> IndexRange {
2272    generativity::make_guard!(guard);
2273    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2274    if index as usize >= instance_ref.description.repeater.len() {
2275        let container_index = {
2276            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2277            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2278                *parent_index
2279            } else {
2280                u32::MAX
2281            }
2282        };
2283        let container = component.as_ref().get_item_ref(container_index);
2284        let container = i_slint_core::items::ItemRef::downcast_pin::<
2285            i_slint_core::items::ComponentContainer,
2286        >(container)
2287        .unwrap();
2288        container.subtree_range()
2289    } else {
2290        generativity::make_guard!(guard);
2291        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2292
2293        let repeater = rep_in_comp.offset.apply_pin(instance_ref.instance);
2294        repeater.track_instance_changes();
2295        repeater.range().into()
2296    }
2297}
2298
2299#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2300extern "C" fn get_subtree(
2301    component: ItemTreeRefPin,
2302    index: u32,
2303    subtree_index: usize,
2304    result: &mut ItemTreeWeak,
2305) {
2306    generativity::make_guard!(guard);
2307    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2308    if index as usize >= instance_ref.description.repeater.len() {
2309        let container_index = {
2310            let tree_node = &component.as_ref().get_item_tree()[index as usize];
2311            if let ItemTreeNode::DynamicTree { parent_index, .. } = tree_node {
2312                *parent_index
2313            } else {
2314                u32::MAX
2315            }
2316        };
2317        let container = component.as_ref().get_item_ref(container_index);
2318        let container = i_slint_core::items::ItemRef::downcast_pin::<
2319            i_slint_core::items::ComponentContainer,
2320        >(container)
2321        .unwrap();
2322        if subtree_index == 0 {
2323            *result = container.subtree_component();
2324        }
2325    } else {
2326        generativity::make_guard!(guard);
2327        let rep_in_comp = instance_ref.description.repeater[index as usize].unerase(guard);
2328
2329        let repeater = rep_in_comp.offset.apply(&instance_ref.instance);
2330        if let Some(instance_at) = repeater.instance_at(subtree_index) {
2331            *result = vtable::VRc::downgrade(&vtable::VRc::into_dyn(instance_at))
2332        }
2333    }
2334}
2335
2336#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2337extern "C" fn get_item_tree(component: ItemTreeRefPin) -> Slice<ItemTreeNode> {
2338    generativity::make_guard!(guard);
2339    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2340    let tree = instance_ref.description.item_tree.as_slice();
2341    unsafe { core::mem::transmute::<&[ItemTreeNode], &[ItemTreeNode]>(tree) }.into()
2342}
2343
2344#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2345extern "C" fn subtree_index(component: ItemTreeRefPin) -> usize {
2346    generativity::make_guard!(guard);
2347    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2348    if let Ok(value) = instance_ref.description.get_property(component, SPECIAL_PROPERTY_INDEX) {
2349        value.try_into().unwrap()
2350    } else {
2351        usize::MAX
2352    }
2353}
2354
2355#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2356unsafe extern "C" fn parent_node(component: ItemTreeRefPin, result: &mut ItemWeak) {
2357    generativity::make_guard!(guard);
2358    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2359
2360    let component_and_index = {
2361        // Normal inner-compilation unit case:
2362        if let Some(parent_offset) = instance_ref.description.parent_item_tree_offset {
2363            let parent_item_index = instance_ref
2364                .description
2365                .original
2366                .parent_element
2367                .borrow()
2368                .upgrade()
2369                .and_then(|e| e.borrow().item_index.get().cloned())
2370                .unwrap_or(u32::MAX);
2371            let parent_component = parent_offset
2372                .apply(instance_ref.as_ref())
2373                .get()
2374                .and_then(|p| p.upgrade())
2375                .map(vtable::VRc::into_dyn);
2376
2377            (parent_component, parent_item_index)
2378        } else if let Some((parent_component, parent_index)) = instance_ref
2379            .description
2380            .extra_data_offset
2381            .apply(instance_ref.as_ref())
2382            .embedding_position
2383            .get()
2384        {
2385            (parent_component.upgrade(), *parent_index)
2386        } else {
2387            (None, u32::MAX)
2388        }
2389    };
2390
2391    if let (Some(component), index) = component_and_index {
2392        *result = ItemRc::new(component, index).downgrade();
2393    }
2394}
2395
2396#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2397unsafe extern "C" fn embed_component(
2398    component: ItemTreeRefPin,
2399    parent_component: &ItemTreeWeak,
2400    parent_item_tree_index: u32,
2401) -> bool {
2402    generativity::make_guard!(guard);
2403    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2404
2405    if instance_ref.description.parent_item_tree_offset.is_some() {
2406        // We are not the root of the compilation unit tree... Can not embed this!
2407        return false;
2408    }
2409
2410    {
2411        // sanity check parent:
2412        let prc = parent_component.upgrade().unwrap();
2413        let pref = vtable::VRc::borrow_pin(&prc);
2414        let it = pref.as_ref().get_item_tree();
2415        if !matches!(
2416            it.get(parent_item_tree_index as usize),
2417            Some(ItemTreeNode::DynamicTree { .. })
2418        ) {
2419            panic!("Trying to embed into a non-dynamic index in the parents item tree")
2420        }
2421    }
2422
2423    let extra_data = instance_ref.description.extra_data_offset.apply(instance_ref.as_ref());
2424    extra_data.embedding_position.set((parent_component.clone(), parent_item_tree_index)).is_ok()
2425}
2426
2427#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2428extern "C" fn item_geometry(component: ItemTreeRefPin, item_index: u32) -> LogicalRect {
2429    generativity::make_guard!(guard);
2430    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2431
2432    let e = instance_ref.description.original_elements[item_index as usize].borrow();
2433    let g = e.geometry_props.as_ref().unwrap();
2434
2435    let load_f32 = |nr: &NamedReference| -> f32 {
2436        crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2437            .unwrap()
2438            .try_into()
2439            .unwrap()
2440    };
2441
2442    LogicalRect {
2443        origin: (load_f32(&g.x), load_f32(&g.y)).into(),
2444        size: (load_f32(&g.width), load_f32(&g.height)).into(),
2445    }
2446}
2447
2448// silence the warning despite `AccessibleRole` is a `#[non_exhaustive]` enum from another crate.
2449#[allow(improper_ctypes_definitions)]
2450#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2451extern "C" fn accessible_role(component: ItemTreeRefPin, item_index: u32) -> AccessibleRole {
2452    generativity::make_guard!(guard);
2453    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2454    let nr = instance_ref.description.original_elements[item_index as usize]
2455        .borrow()
2456        .accessibility_props
2457        .0
2458        .get("accessible-role")
2459        .cloned();
2460    match nr {
2461        Some(nr) => crate::eval::load_property(instance_ref, &nr.element(), nr.name())
2462            .unwrap()
2463            .try_into()
2464            .unwrap(),
2465        None => AccessibleRole::default(),
2466    }
2467}
2468
2469#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2470extern "C" fn accessible_string_property(
2471    component: ItemTreeRefPin,
2472    item_index: u32,
2473    what: AccessibleStringProperty,
2474    result: &mut SharedString,
2475) -> bool {
2476    generativity::make_guard!(guard);
2477    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2478    let prop_name = format!("accessible-{what}");
2479    let nr = instance_ref.description.original_elements[item_index as usize]
2480        .borrow()
2481        .accessibility_props
2482        .0
2483        .get(&prop_name)
2484        .cloned();
2485    if let Some(nr) = nr {
2486        let value = crate::eval::load_property(instance_ref, &nr.element(), nr.name()).unwrap();
2487        match value {
2488            Value::String(s) => *result = s,
2489            Value::Bool(b) => *result = if b { "true" } else { "false" }.into(),
2490            Value::Number(x) => *result = x.to_string().into(),
2491            Value::EnumerationValue(_, v) => *result = v.into(),
2492            _ => unimplemented!("invalid type for accessible_string_property"),
2493        };
2494        true
2495    } else {
2496        false
2497    }
2498}
2499
2500#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2501extern "C" fn accessibility_action(
2502    component: ItemTreeRefPin,
2503    item_index: u32,
2504    action: &AccessibilityAction,
2505) {
2506    let perform = |prop_name, args: &[Value]| {
2507        generativity::make_guard!(guard);
2508        let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2509        let nr = instance_ref.description.original_elements[item_index as usize]
2510            .borrow()
2511            .accessibility_props
2512            .0
2513            .get(prop_name)
2514            .cloned();
2515        if let Some(nr) = nr {
2516            let instance_ref = eval::ComponentInstance::InstanceRef(instance_ref);
2517            crate::eval::invoke_callback(&instance_ref, &nr.element(), nr.name(), args).unwrap();
2518        }
2519    };
2520
2521    match action {
2522        AccessibilityAction::Default => perform("accessible-action-default", &[]),
2523        AccessibilityAction::Decrement => perform("accessible-action-decrement", &[]),
2524        AccessibilityAction::Increment => perform("accessible-action-increment", &[]),
2525        AccessibilityAction::Expand => perform("accessible-action-expand", &[]),
2526        AccessibilityAction::ReplaceSelectedText(_a) => {
2527            //perform("accessible-action-replace-selected-text", &[Value::String(a.clone())])
2528            i_slint_core::debug_log!(
2529                "AccessibilityAction::ReplaceSelectedText not implemented in interpreter's accessibility_action"
2530            );
2531        }
2532        AccessibilityAction::SetValue(a) => {
2533            perform("accessible-action-set-value", &[Value::String(a.clone())])
2534        }
2535    };
2536}
2537
2538#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2539extern "C" fn supported_accessibility_actions(
2540    component: ItemTreeRefPin,
2541    item_index: u32,
2542) -> SupportedAccessibilityAction {
2543    generativity::make_guard!(guard);
2544    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2545    instance_ref.description.original_elements[item_index as usize]
2546        .borrow()
2547        .accessibility_props
2548        .0
2549        .keys()
2550        .filter_map(|x| x.strip_prefix("accessible-action-"))
2551        .fold(SupportedAccessibilityAction::default(), |acc, value| {
2552            SupportedAccessibilityAction::from_name(&i_slint_compiler::generator::to_pascal_case(
2553                value,
2554            ))
2555            .unwrap_or_else(|| panic!("Not an accessible action: {value:?}"))
2556                | acc
2557        })
2558}
2559
2560#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2561extern "C" fn item_element_infos(
2562    component: ItemTreeRefPin,
2563    item_index: u32,
2564    result: &mut SharedString,
2565) -> bool {
2566    generativity::make_guard!(guard);
2567    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2568    *result = instance_ref.description.original_elements[item_index as usize]
2569        .borrow()
2570        .element_infos()
2571        .into();
2572    true
2573}
2574
2575#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2576extern "C" fn window_adapter(
2577    component: ItemTreeRefPin,
2578    do_create: bool,
2579    result: &mut Option<WindowAdapterRc>,
2580) {
2581    generativity::make_guard!(guard);
2582    let instance_ref = unsafe { InstanceRef::from_pin_ref(component, guard) };
2583    if do_create {
2584        *result = Some(instance_ref.window_adapter());
2585    } else {
2586        *result = instance_ref.maybe_window_adapter();
2587    }
2588}
2589
2590#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2591unsafe extern "C" fn drop_in_place(component: vtable::VRefMut<ItemTreeVTable>) -> vtable::Layout {
2592    unsafe {
2593        let instance_ptr = component.as_ptr() as *mut Instance<'static>;
2594        let layout = (*instance_ptr).type_info().layout();
2595        dynamic_type::TypeInfo::drop_in_place(instance_ptr);
2596        layout.into()
2597    }
2598}
2599
2600#[cfg_attr(not(feature = "ffi"), i_slint_core_macros::remove_extern)]
2601unsafe extern "C" fn dealloc(_vtable: &ItemTreeVTable, ptr: *mut u8, layout: vtable::Layout) {
2602    unsafe { std::alloc::dealloc(ptr, layout.try_into().unwrap()) };
2603}
2604
2605#[derive(Copy, Clone)]
2606pub struct InstanceRef<'a, 'id> {
2607    pub instance: Pin<&'a Instance<'id>>,
2608    pub description: &'a ItemTreeDescription<'id>,
2609}
2610
2611impl<'a, 'id> InstanceRef<'a, 'id> {
2612    pub unsafe fn from_pin_ref(
2613        component: ItemTreeRefPin<'a>,
2614        _guard: generativity::Guard<'id>,
2615    ) -> Self {
2616        unsafe {
2617            Self {
2618                instance: Pin::new_unchecked(
2619                    &*(component.as_ref().as_ptr() as *const Instance<'id>),
2620                ),
2621                description: &*(Pin::into_inner_unchecked(component).get_vtable()
2622                    as *const ItemTreeVTable
2623                    as *const ItemTreeDescription<'id>),
2624            }
2625        }
2626    }
2627
2628    pub fn as_ptr(&self) -> *const u8 {
2629        (&*self.instance.as_ref()) as *const Instance as *const u8
2630    }
2631
2632    pub fn as_ref(&self) -> &Instance<'id> {
2633        &self.instance
2634    }
2635
2636    /// Borrow this component as a `Pin<ItemTreeRef>`
2637    pub fn borrow(self) -> ItemTreeRefPin<'a> {
2638        unsafe {
2639            Pin::new_unchecked(vtable::VRef::from_raw(
2640                NonNull::from(&self.description.ct).cast(),
2641                NonNull::from(self.instance.get_ref()).cast(),
2642            ))
2643        }
2644    }
2645
2646    pub fn self_weak(&self) -> &OnceCell<ErasedItemTreeBoxWeak> {
2647        let extra_data = self.description.extra_data_offset.apply(self.as_ref());
2648        &extra_data.self_weak
2649    }
2650
2651    pub fn root_weak(&self) -> &ErasedItemTreeBoxWeak {
2652        self.description.root_offset.apply(self.as_ref()).get().unwrap()
2653    }
2654
2655    pub fn window_adapter(&self) -> WindowAdapterRc {
2656        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2657        let root = self.root_weak().upgrade().unwrap();
2658        generativity::make_guard!(guard);
2659        let comp = root.unerase(guard);
2660        Self::get_or_init_window_adapter_ref(
2661            &comp.description,
2662            root_weak,
2663            true,
2664            comp.instance.as_pin_ref().get_ref(),
2665        )
2666        .unwrap()
2667        .clone()
2668    }
2669
2670    pub fn get_or_init_window_adapter_ref<'b, 'id2>(
2671        description: &'b ItemTreeDescription<'id2>,
2672        root_weak: ItemTreeWeak,
2673        do_create: bool,
2674        instance: &'b Instance<'id2>,
2675    ) -> Result<&'b WindowAdapterRc, PlatformError> {
2676        // We are the actual root: Generate and store a window_adapter if necessary
2677        description
2678            .extra_data_offset
2679            .apply(instance)
2680            .globals
2681            .get()
2682            .unwrap()
2683            .window_adapter()
2684            .unwrap()
2685            .get_or_try_init(|| {
2686                let mut parent_node = ItemWeak::default();
2687                if let Some(rc) = vtable::VWeak::upgrade(&root_weak) {
2688                    vtable::VRc::borrow_pin(&rc).as_ref().parent_node(&mut parent_node);
2689                }
2690
2691                if let Some(parent) = parent_node.upgrade() {
2692                    // We are embedded: Get window adapter from our parent
2693                    let mut result = None;
2694                    vtable::VRc::borrow_pin(parent.item_tree())
2695                        .as_ref()
2696                        .window_adapter(do_create, &mut result);
2697                    result.ok_or(PlatformError::NoPlatform)
2698                } else if do_create {
2699                    let extra_data = description.extra_data_offset.apply(instance);
2700                    let window_adapter = // We are the root: Create a window adapter
2701                    i_slint_backend_selector::with_platform(|_b| {
2702                        _b.create_window_adapter()
2703                    })?;
2704
2705                    let comp_rc = extra_data.self_weak.get().unwrap().upgrade().unwrap();
2706                    WindowInner::from_pub(window_adapter.window())
2707                        .set_component(&vtable::VRc::into_dyn(comp_rc));
2708                    Ok(window_adapter)
2709                } else {
2710                    Err(PlatformError::NoPlatform)
2711                }
2712            })
2713    }
2714
2715    pub fn maybe_window_adapter(&self) -> Option<WindowAdapterRc> {
2716        let root_weak = vtable::VWeak::into_dyn(self.root_weak().clone());
2717        let root = self.root_weak().upgrade()?;
2718        generativity::make_guard!(guard);
2719        let comp = root.unerase(guard);
2720        Self::get_or_init_window_adapter_ref(
2721            &comp.description,
2722            root_weak,
2723            false,
2724            comp.instance.as_pin_ref().get_ref(),
2725        )
2726        .ok()
2727        .cloned()
2728    }
2729
2730    pub fn access_window<R>(
2731        self,
2732        callback: impl FnOnce(&'_ i_slint_core::window::WindowInner) -> R,
2733    ) -> R {
2734        callback(WindowInner::from_pub(self.window_adapter().window()))
2735    }
2736
2737    pub fn parent_instance<'id2>(
2738        &self,
2739        _guard: generativity::Guard<'id2>,
2740    ) -> Option<InstanceRef<'a, 'id2>> {
2741        // we need a 'static guard in order to be able to re-borrow with lifetime 'a.
2742        // Safety: This is the only 'static Id in scope.
2743        if let Some(parent_offset) = self.description.parent_item_tree_offset
2744            && let Some(parent) =
2745                parent_offset.apply(self.as_ref()).get().and_then(vtable::VWeak::upgrade)
2746        {
2747            let parent_instance = parent.unerase(_guard);
2748            // And also assume that the parent lives for at least 'a.  FIXME: this may not be sound
2749            let parent_instance = unsafe {
2750                std::mem::transmute::<InstanceRef<'_, 'id2>, InstanceRef<'a, 'id2>>(
2751                    parent_instance.borrow_instance(),
2752                )
2753            };
2754            return Some(parent_instance);
2755        }
2756        None
2757    }
2758}
2759
2760/// Show the popup with a lazily evaluated location.
2761pub fn show_popup(
2762    element: ElementRc,
2763    instance: InstanceRef,
2764    popup: &object_tree::PopupWindow,
2765    pos_getter: impl Fn(InstanceRef<'_, '_>) -> LogicalPosition + 'static,
2766    close_policy: PopupClosePolicy,
2767    parent_comp: ErasedItemTreeBoxWeak,
2768    parent_window_adapter: WindowAdapterRc,
2769    parent_item: &ItemRc,
2770) {
2771    generativity::make_guard!(guard);
2772    let debug_handler = instance.description.debug_handler.borrow().clone();
2773
2774    // FIXME: we should compile once and keep the cached compiled component
2775    let compiled = generate_item_tree(
2776        &popup.component,
2777        None,
2778        parent_comp.upgrade().unwrap().0.description().popup_menu_description.clone(),
2779        false,
2780        guard,
2781    );
2782    compiled.recursively_set_debug_handler(debug_handler);
2783
2784    let extra_data = instance.description.extra_data_offset.apply(instance.as_ref());
2785    // Use the newly created window adapter if we are able to create one. Otherwise use the parent's one.
2786    // Tooltips skip this to share the parent's adapter, ensuring they use the ChildWindow path
2787    // and renderer caches stay consistent.
2788    let globals = if !popup.is_tooltip
2789        && let Some(window_adapter) =
2790            WindowInner::from_pub(parent_window_adapter.window()).create_popup_window_adapter()
2791    {
2792        extra_data.globals.get().unwrap().clone_with_window_adapter(window_adapter)
2793    } else {
2794        extra_data.globals.get().unwrap().clone()
2795    };
2796
2797    let popup_window_adapter = globals
2798        .window_adapter()
2799        .and_then(|window_adapter| window_adapter.get().cloned())
2800        .unwrap_or_else(|| parent_window_adapter.clone());
2801
2802    let inst = instantiate(
2803        compiled,
2804        Some(parent_comp),
2805        None,
2806        Some(&WindowOptions::UseExistingWindow(popup_window_adapter)),
2807        globals,
2808    );
2809    let inst_for_position = inst.clone();
2810    let access_position = Box::new(move || {
2811        generativity::make_guard!(guard);
2812        let compo_box = inst_for_position.unerase(guard);
2813        let instance_ref = compo_box.borrow_instance();
2814        pos_getter(instance_ref)
2815    });
2816    close_popup(element.clone(), instance, parent_window_adapter.clone());
2817    instance.description.popup_ids.borrow_mut().insert(
2818        element.borrow().id.clone(),
2819        WindowInner::from_pub(parent_window_adapter.window()).show_popup(
2820            &vtable::VRc::into_dyn(inst.clone()),
2821            access_position,
2822            close_policy,
2823            parent_item,
2824            popup.is_tooltip,
2825            false,
2826        ),
2827    );
2828    inst.run_setup_code();
2829}
2830
2831pub fn close_popup(
2832    element: ElementRc,
2833    instance: InstanceRef,
2834    parent_window_adapter: WindowAdapterRc,
2835) {
2836    if let Some(current_id) =
2837        instance.description.popup_ids.borrow_mut().remove(&element.borrow().id)
2838    {
2839        WindowInner::from_pub(parent_window_adapter.window()).close_popup(current_id);
2840    }
2841}
2842
2843pub fn make_menu_item_tree(
2844    menu_item_tree: &Rc<object_tree::Component>,
2845    enclosing_component: &InstanceRef,
2846    condition: Option<&Expression>,
2847    visible: Option<&Expression>,
2848) -> vtable::VRc<i_slint_core::menus::MenuVTable, MenuFromItemTree> {
2849    generativity::make_guard!(guard);
2850    let mit_compiled = generate_item_tree(
2851        menu_item_tree,
2852        None,
2853        enclosing_component.description.popup_menu_description.clone(),
2854        false,
2855        guard,
2856    );
2857    let enclosing_component_weak = enclosing_component.self_weak().get().unwrap();
2858    let extra_data =
2859        enclosing_component.description.extra_data_offset.apply(enclosing_component.as_ref());
2860    let mit_inst = instantiate(
2861        mit_compiled.clone(),
2862        Some(enclosing_component_weak.clone()),
2863        None,
2864        None,
2865        extra_data.globals.get().unwrap().clone(),
2866    );
2867    mit_inst.run_setup_code();
2868    let item_tree = vtable::VRc::into_dyn(mit_inst);
2869    let condition = condition.map(|condition| {
2870        let binding =
2871            make_binding_eval_closure(condition.clone(), enclosing_component_weak.clone());
2872        move || binding().try_into().unwrap()
2873    });
2874    let visible = visible.map(|visible| {
2875        let binding = make_binding_eval_closure(visible.clone(), enclosing_component_weak.clone());
2876        move || binding().try_into().unwrap()
2877    });
2878    let menu = match (condition, visible) {
2879        (None, None) => MenuFromItemTree::new(item_tree),
2880        (None, Some(visible)) => {
2881            MenuFromItemTree::new_with_condition_and_visible(item_tree, || true, visible)
2882        }
2883        (Some(condition), None) => {
2884            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, || true)
2885        }
2886        (Some(condition), Some(visible)) => {
2887            MenuFromItemTree::new_with_condition_and_visible(item_tree, condition, visible)
2888        }
2889    };
2890    vtable::VRc::new(menu)
2891}
2892
2893pub fn update_timers(instance: InstanceRef) {
2894    let ts = instance.description.original.timers.borrow();
2895    for (desc, offset) in ts.iter().zip(&instance.description.timers) {
2896        let timer = offset.apply(instance.as_ref());
2897        let running =
2898            eval::load_property(instance, &desc.running.element(), desc.running.name()).unwrap();
2899        if matches!(running, Value::Bool(true)) {
2900            let millis: i64 =
2901                eval::load_property(instance, &desc.interval.element(), desc.interval.name())
2902                    .unwrap()
2903                    .try_into()
2904                    .expect("interval must be a duration");
2905            if millis < 0 {
2906                timer.stop();
2907                continue;
2908            }
2909            let interval = core::time::Duration::from_millis(millis as _);
2910            if !timer.running() || interval != timer.interval() {
2911                let callback = desc.triggered.clone();
2912                let self_weak = instance.self_weak().get().unwrap().clone();
2913                timer.start(i_slint_core::timers::TimerMode::Repeated, interval, move || {
2914                    if let Some(instance) = self_weak.upgrade() {
2915                        generativity::make_guard!(guard);
2916                        let c = instance.unerase(guard);
2917                        let c = c.borrow_instance();
2918                        let inst = eval::ComponentInstance::InstanceRef(c);
2919                        eval::invoke_callback(&inst, &callback.element(), callback.name(), &[])
2920                            .unwrap();
2921                    }
2922                });
2923            }
2924        } else {
2925            timer.stop();
2926        }
2927    }
2928}
2929
2930pub fn restart_timer(element: ElementWeak, instance: InstanceRef) {
2931    let timers = instance.description.original.timers.borrow();
2932    if let Some((_, offset)) = timers
2933        .iter()
2934        .zip(&instance.description.timers)
2935        .find(|(desc, _)| Weak::ptr_eq(&desc.element, &element))
2936    {
2937        let timer = offset.apply(instance.as_ref());
2938        timer.restart();
2939    }
2940}