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