1use crate::erased::{ErasedItemRc, SubComponentCallback, SubComponentProperty};
8use crate::globals::GlobalStorage;
9use crate::item_registry::ItemRegistry;
10use crate::prelude::*;
11use alloc::rc::Weak;
12use i_slint_compiler::llr::{
13 self, CompilationUnit, ItemInstanceIdx, PublicComponentIdx, RepeatedElementIdx,
14 SubComponentIdx, SubComponentInstanceIdx,
15};
16use i_slint_core::item_tree::ItemTreeNode;
17use i_slint_core::model::{Conditional, Repeater};
18use i_slint_core::properties::ChangeTracker;
19use i_slint_core::window::WindowAdapterRc;
20use typed_index_collections::TiVec;
21use vtable::VWeak;
22
23pub enum RepeaterOrConditional {
28 Repeater(Pin<Box<Repeater<Instance>>>),
29 Conditional(Pin<Box<Conditional<Instance>>>),
30}
31
32impl RepeaterOrConditional {
33 pub fn visit(
34 &self,
35 order: i_slint_core::item_tree::TraversalOrder,
36 visitor: i_slint_core::item_tree::ItemVisitorRefMut<'_>,
37 ) -> i_slint_core::item_tree::VisitChildrenResult {
38 match self {
39 Self::Repeater(r) => Pin::as_ref(r).visit(order, visitor),
40 Self::Conditional(c) => Pin::as_ref(c).visit(order, visitor),
41 }
42 }
43
44 pub fn for_each_instance_z(&self, cb: &mut dyn FnMut(u32, f32)) {
47 match self {
48 Self::Repeater(r) => Pin::as_ref(r).for_each_instance_z(cb),
49 Self::Conditional(c) => Pin::as_ref(c).for_each_instance_z(cb),
50 }
51 }
52
53 pub fn range(&self) -> core::ops::Range<usize> {
54 match self {
55 Self::Repeater(r) => r.range(),
56 Self::Conditional(c) => c.range(),
57 }
58 }
59
60 pub fn instance_at(&self, subindex: usize) -> Option<VRc<ItemTreeVTable, Instance>> {
61 match self {
62 Self::Repeater(r) => r.instance_at(subindex),
63 Self::Conditional(c) => c.instance_at(subindex),
64 }
65 }
66
67 pub fn instances_vec(&self) -> Vec<VRc<ItemTreeVTable, Instance>> {
68 match self {
69 Self::Repeater(r) => r.instances_vec(),
70 Self::Conditional(c) => c.instances_vec(),
71 }
72 }
73
74 pub fn track_instance_changes(&self) {
79 match self {
80 Self::Repeater(r) => Pin::as_ref(r).track_instance_changes(),
81 Self::Conditional(c) => Pin::as_ref(c).track_instance_changes(),
82 }
83 }
84
85 pub fn ensure_updated(
89 &self,
90 init: impl Fn() -> VRc<ItemTreeVTable, Instance> + 'static,
91 ) -> bool {
92 match self {
93 Self::Repeater(r) => Pin::as_ref(r).ensure_updated(init),
94 Self::Conditional(c) => Pin::as_ref(c).ensure_updated(init),
95 }
96 }
97
98 pub fn ensure_updated_listview_callback(
105 &self,
106 init: impl Fn() -> VRc<ItemTreeVTable, Instance> + 'static,
107 props: &dyn i_slint_core::model::ListViewProperties,
108 listview_width: i_slint_core::lengths::LogicalLength,
109 listview_height: i_slint_core::lengths::LogicalLength,
110 ) -> bool {
111 match self {
112 Self::Repeater(r) => Pin::as_ref(r).ensure_updated_listview_callback(
113 init,
114 props,
115 listview_width,
116 listview_height,
117 ),
118 Self::Conditional(_) => unreachable!("listview on a conditional element"),
119 }
120 }
121
122 pub fn set_model_binding(
124 &self,
125 binding: impl Fn() -> i_slint_core::model::ModelRc<Value> + 'static,
126 ) {
127 match self {
128 Self::Repeater(r) => Pin::as_ref(r).set_model_binding(binding),
129 Self::Conditional(_) => unreachable!("set_model_binding on conditional"),
130 }
131 }
132
133 pub fn set_condition_binding(&self, binding: impl Fn() -> bool + 'static) {
135 match self {
136 Self::Conditional(c) => c.set_model_binding(binding),
137 Self::Repeater(_) => unreachable!("set_condition_binding on repeater"),
138 }
139 }
140
141 pub fn model_set_row_data(&self, row: usize, data: Value) {
143 match self {
144 Self::Repeater(r) => Pin::as_ref(r).model_set_row_data(row, data),
145 Self::Conditional(_) => {} }
147 }
148
149 pub fn is_conditional(&self) -> bool {
150 matches!(self, Self::Conditional(_))
151 }
152}
153
154pub struct SubComponentInstance {
158 pub compilation_unit: Rc<CompilationUnit>,
159 pub sub_component_idx: SubComponentIdx,
160 pub properties: TiVec<llr::PropertyIdx, SubComponentProperty>,
161 pub callbacks: TiVec<llr::CallbackIdx, SubComponentCallback>,
162 pub callback_trackers: TiVec<llr::CallbackIdx, Option<Pin<Rc<Property<()>>>>>,
167 pub items: TiVec<ItemInstanceIdx, ErasedItemRc>,
168 pub sub_components: TiVec<SubComponentInstanceIdx, Pin<Rc<SubComponentInstance>>>,
169 pub repeaters: TiVec<RepeatedElementIdx, RepeaterOrConditional>,
174 pub parent: Weak<SubComponentInstance>,
176 pub root: OnceCell<VWeak<ItemTreeVTable, Instance>>,
178 pub change_trackers: Vec<ChangeTracker>,
181 pub timers: Vec<i_slint_core::timers::Timer>,
186 pub popup_ids: Vec<Cell<Option<core::num::NonZeroU32>>>,
191 pub repeated_in: OnceCell<(Weak<SubComponentInstance>, RepeatedElementIdx)>,
195 pub menubar: RefCell<Option<VRc<i_slint_core::menus::MenuVTable>>>,
198}
199
200pub struct Instance {
202 pub root_sub_component: Pin<Rc<SubComponentInstance>>,
203 pub tree_nodes: Box<[ItemTreeNode]>,
205 pub dynamic_table: Box<[Option<(Box<[SubComponentInstanceIdx]>, RepeatedElementIdx)>]>,
209 pub item_table: Box<[Option<(Box<[SubComponentInstanceIdx]>, ItemInstanceIdx)>]>,
213 pub z_sort_table: Box<[Option<Vec<llr::ZSource>>]>,
216 pub globals: Rc<GlobalStorage>,
217 pub self_weak: OnceCell<VWeak<ItemTreeVTable, Instance>>,
218 pub parent_instance: Weak<SubComponentInstance>,
221 pub public_component_index: Option<PublicComponentIdx>,
225 pub window_adapter: OnceCell<WindowAdapterRc>,
228 window_adapter_error: OnceCell<String>,
232 pub window_attached: OnceCell<()>,
237 window_attachment_disabled: bool,
238 pub bindings_installed: OnceCell<()>,
241 pub init_code_run: OnceCell<()>,
247 pub embedded_in: OnceCell<(VWeak<ItemTreeVTable>, u32)>,
253 pub type_loaders: crate::component::TypeLoaders,
258}
259
260impl Drop for Instance {
261 fn drop(&mut self) {
262 let Some(adapter) = self.window_adapter.get().cloned().or_else(|| {
272 let mut parent = self.parent_instance.upgrade();
273 while let Some(sub) = parent {
274 let root = sub.root.get().and_then(|w| w.upgrade())?;
275 if let Some(a) = root.window_adapter.get() {
276 return Some(a.clone());
277 }
278 parent = root.parent_instance.upgrade();
279 }
280 None
281 }) else {
282 return;
283 };
284 vtable::new_vref!(let item_tree_ref : VRef<ItemTreeVTable> for i_slint_core::item_tree::ItemTree = self);
285 let items = collect_item_refs(&self.root_sub_component);
286 for item in &items {
291 item.as_ref().deinit(&adapter);
292 }
293 let _ =
294 adapter.renderer().free_graphics_resources(item_tree_ref, &mut items.iter().copied());
295 if let Some(internal) = adapter.internal(i_slint_core::InternalToken) {
296 internal.unregister_item_tree(item_tree_ref, &mut items.iter().copied());
297 }
298 let window_inner = i_slint_core::window::WindowInner::from_pub(adapter.window());
299 let to_close_popups = window_inner
300 .active_popups()
301 .iter()
302 .filter_map(|p| p.parent_item.upgrade().is_none().then_some(p.popup_id))
303 .collect::<Vec<_>>();
304 for popup_id in to_close_popups {
305 window_inner.close_popup(popup_id);
306 }
307 }
308}
309
310fn collect_item_refs<'a>(
313 sub: &'a Pin<Rc<SubComponentInstance>>,
314) -> Vec<Pin<vtable::VRef<'a, i_slint_core::items::ItemVTable>>> {
315 let mut out = Vec::new();
316 fn walk<'a>(
317 sub: &'a Pin<Rc<SubComponentInstance>>,
318 out: &mut Vec<Pin<vtable::VRef<'a, i_slint_core::items::ItemVTable>>>,
319 ) {
320 for item in &sub.items {
321 out.push(Pin::as_ref(item).as_item_ref());
322 }
323 for nested in &sub.sub_components {
324 walk(nested, out);
325 }
326 }
327 walk(sub, &mut out);
328 out
329}
330
331impl Instance {
332 pub fn window_adapter_or_default(&self) -> Option<WindowAdapterRc> {
335 self.try_window_adapter().ok()
336 }
337
338 pub fn try_window_adapter(&self) -> Result<WindowAdapterRc, i_slint_core::api::PlatformError> {
354 if let Some(a) = self.window_adapter.get() {
355 return Ok(a.clone());
356 }
357 if let Some((outer_weak, _)) = self.embedded_in.get()
363 && let Some(outer) = outer_weak.upgrade()
364 {
365 let mut result = None;
366 VRc::borrow_pin(&outer).as_ref().window_adapter(true, &mut result);
367 if let Some(a) = result {
368 let _ = self.window_adapter.set(a.clone());
369 return Ok(a);
370 }
371 }
372 let mut outermost_root = None;
375 let mut parent_sub = self.parent_instance.upgrade();
376 while let Some(sub) = parent_sub {
377 let Some(root_vrc) = sub.root.get().and_then(|w| w.upgrade()) else { break };
378 if let Some(a) = root_vrc.window_adapter.get() {
379 let cloned = a.clone();
380 let _ = self.window_adapter.set(cloned.clone());
383 return Ok(cloned);
384 }
385 parent_sub = root_vrc.parent_instance.upgrade();
386 outermost_root = Some(root_vrc);
387 }
388 if let Some(e) = self
389 .window_adapter_error
390 .get()
391 .or_else(|| outermost_root.as_ref().and_then(|root| root.window_adapter_error.get()))
392 {
393 return Err(i_slint_core::api::PlatformError::Other(e.clone()));
394 }
395 let context = &self.globals.context;
396 let adapter = context.create_window_adapter().inspect_err(|e| {
397 let msg = e.to_string();
398 if let Some(root) = &outermost_root {
399 let _ = root.window_adapter_error.set(msg.clone());
400 }
401 let _ = self.window_adapter_error.set(msg);
402 })?;
403 adapter.renderer().set_window_adapter(&adapter);
407 if let Some(root) = outermost_root {
411 let _ = root.window_adapter.set(adapter.clone());
412 }
413 let _ = self.window_adapter.set(adapter.clone());
414 Ok(adapter)
415 }
416
417 pub fn attach_to_window(&self) {
426 if self.window_attached.get().is_some()
429 || self.window_attachment_disabled
430 || self.embedded_in.get().is_some()
431 {
432 return;
433 }
434 let Some(adapter) = self.window_adapter_or_default() else { return };
435 let Some(self_rc) = self.self_weak.get().and_then(|w| w.upgrade()) else { return };
436 let _ = self.window_attached.set(());
437 i_slint_core::window::WindowInner::from_pub(adapter.window())
438 .set_component(&VRc::into_dyn(self_rc));
439 }
440}
441
442pub(crate) fn component_container_item(
448 sub: &Pin<Rc<SubComponentInstance>>,
449 rep_idx: RepeatedElementIdx,
450) -> Option<Pin<&i_slint_core::items::ComponentContainer>> {
451 let sc = &sub.compilation_unit.sub_components[sub.sub_component_idx];
452 let cc_item_idx = sc.repeated.get(rep_idx)?.container_item_index?;
453 let item = sub.items.get(cc_item_idx)?;
454 i_slint_core::items::ItemRef::downcast_pin::<i_slint_core::items::ComponentContainer>(
455 Pin::as_ref(item).as_item_ref(),
456 )
457}
458
459impl Instance {
460 pub fn dynamic_at(
464 &self,
465 tree_index: u32,
466 ) -> Option<(Pin<Rc<SubComponentInstance>>, RepeatedElementIdx)> {
467 let entry = self.dynamic_table.get(tree_index as usize)?.as_ref()?;
468 let mut current = self.root_sub_component.clone();
469 for &idx in entry.0.iter() {
470 let next = current.sub_components[idx].clone();
471 current = next;
472 }
473 Some((current, entry.1))
474 }
475
476 pub fn ensure_updated(&self, tree_index: u32) -> bool {
485 let Some((sub, rep_idx)) = self.dynamic_at(tree_index) else { return false };
486 if let Some(cc) = component_container_item(&sub, rep_idx) {
487 return cc.ensure_updated();
488 }
489 let cu = sub.compilation_unit.clone();
490 let sc_idx = sub.sub_component_idx;
491 let sub_weak = Rc::downgrade(&Pin::into_inner(sub.clone()));
492 let globals = self.globals.clone();
493 let repeated = &cu.sub_components[sc_idx].repeated[rep_idx];
494 let listview_factory = repeated.listview.is_some();
495 let listview_info = repeated.listview.clone();
496 let factory = move || {
497 let item_tree = &cu.sub_components[sc_idx].repeated[rep_idx].sub_tree;
498 let vrc = Instance::new_repeated(
499 cu.clone(),
500 item_tree,
501 sub_weak.clone(),
502 rep_idx,
503 globals.clone(),
504 );
505 if listview_factory {
506 init_items_and_bindings(&vrc);
511 }
512 vrc
513 };
514 let repeater = &sub.repeaters[rep_idx];
515 if let Some(lv) = listview_info.as_ref() {
516 let listview_width = read_logical_length(&sub, &lv.listview_width);
517 let listview_height = read_logical_length(&sub, &lv.listview_height);
518 let props = ValueListViewProps {
519 content_y: lv.content_y.clone(),
520 content_width: lv.content_width.clone(),
521 content_height: lv.content_height.clone(),
522 ctx_sub: sub.clone(),
523 };
524 repeater.ensure_updated_listview_callback(
525 factory,
526 &props,
527 listview_width,
528 listview_height,
529 )
530 } else {
531 repeater.ensure_updated(factory)
532 }
533 }
534
535 pub fn ensure_instantiated(&self) -> bool {
540 let mut changed = false;
541 for idx in 0..self.dynamic_table.len() {
542 if self.dynamic_table[idx].is_some() {
543 changed |= self.ensure_updated(idx as u32);
544 }
545 }
546 changed
547 }
548
549 pub fn visit_dynamic_children(
557 self: Pin<&Self>,
558 dyn_index: u32,
559 order: i_slint_core::item_tree::TraversalOrder,
560 visitor: vtable::VRefMut<'_, i_slint_core::item_tree::ItemVisitorVTable>,
561 ) -> i_slint_core::item_tree::VisitChildrenResult {
562 let Some((sub, rep_idx)) = self.get_ref().dynamic_at(dyn_index) else {
563 return i_slint_core::item_tree::VisitChildrenResult::CONTINUE;
564 };
565 if let Some(cc) = component_container_item(&sub, rep_idx) {
566 return cc.visit_children_item(-1, order, visitor);
567 }
568 let repeater = &sub.repeaters[rep_idx];
572 let sc = &sub.compilation_unit.sub_components[sub.sub_component_idx];
573 if let (Some(lv), RepeaterOrConditional::Repeater(r)) =
574 (sc.repeated[rep_idx].listview.as_ref(), repeater)
575 {
576 let props = ValueListViewProps {
577 content_y: lv.content_y.clone(),
578 content_width: lv.content_width.clone(),
579 content_height: lv.content_height.clone(),
580 ctx_sub: sub.clone(),
581 };
582 let listview_width = read_logical_length(&sub, &lv.listview_width);
583 let _ = read_logical_length(&sub, &lv.listview_height);
584 Pin::as_ref(r).track_changes_listview_callback(&props, listview_width);
585 }
586 repeater.visit(order, visitor)
587 }
588
589 pub fn collect_z_sorted_children(
594 self: Pin<&Self>,
595 index: isize,
596 push: &mut dyn FnMut(u32, Option<u32>, f32),
597 ) {
598 let Some(Some(sources)) = self.z_sort_table.get(index as usize) else { return };
599 let ItemTreeNode::Item { children_index, .. } = self.tree_nodes[index as usize] else {
600 return;
601 };
602 let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
603 for (k, source) in sources.iter().enumerate() {
604 let child_offset = k as u32;
605 match source {
606 llr::ZSource::Expression(e) => {
607 let z: f64 = crate::eval::eval_expression(&mut ctx, &e.borrow())
608 .try_into()
609 .unwrap_or(0.0);
610 push(child_offset, None, z as f32);
611 }
612 llr::ZSource::RepeaterInstances => {
613 if let Some((sub, rep_idx)) =
615 self.get_ref().dynamic_at(children_index + child_offset)
616 {
617 sub.repeaters[rep_idx].for_each_instance_z(&mut |instance, z| {
618 push(child_offset, Some(instance), z)
619 });
620 }
621 }
622 }
623 }
624 }
625
626 pub fn new_with_window(
630 compilation_unit: Rc<CompilationUnit>,
631 public_component_index: PublicComponentIdx,
632 window_adapter: i_slint_core::window::WindowAdapterRc,
633 type_loaders: crate::component::TypeLoaders,
634 resources: Rc<crate::component::Resources>,
635 ) -> VRc<ItemTreeVTable, Instance> {
636 let context =
637 i_slint_core::window::WindowInner::from_pub(window_adapter.window()).context().clone();
638 Self::new_with_options(
639 compilation_unit,
640 public_component_index,
641 Some(window_adapter),
642 type_loaders,
643 resources,
644 None,
645 context,
646 false,
647 )
648 }
649
650 pub fn new_with_context(
653 compilation_unit: Rc<CompilationUnit>,
654 public_component_index: PublicComponentIdx,
655 type_loaders: crate::component::TypeLoaders,
656 resources: Rc<crate::component::Resources>,
657 context: SlintContext,
658 ) -> VRc<ItemTreeVTable, Instance> {
659 Self::new_with_options(
660 compilation_unit,
661 public_component_index,
662 None,
663 type_loaders,
664 resources,
665 None,
666 context,
667 false,
668 )
669 }
670
671 #[cfg(feature = "internal")]
672 pub fn new_detached_with_window(
673 compilation_unit: Rc<CompilationUnit>,
674 public_component_index: PublicComponentIdx,
675 window_adapter: i_slint_core::window::WindowAdapterRc,
676 type_loaders: crate::component::TypeLoaders,
677 resources: Rc<crate::component::Resources>,
678 ) -> VRc<ItemTreeVTable, Instance> {
679 let context =
680 i_slint_core::window::WindowInner::from_pub(window_adapter.window()).context().clone();
681 Self::new_with_options(
682 compilation_unit,
683 public_component_index,
684 Some(window_adapter),
685 type_loaders,
686 resources,
687 None,
688 context,
689 true,
690 )
691 }
692
693 pub fn new_embedded(
698 compilation_unit: Rc<CompilationUnit>,
699 public_component_index: PublicComponentIdx,
700 type_loaders: crate::component::TypeLoaders,
701 resources: Rc<crate::component::Resources>,
702 parent: vtable::VWeak<ItemTreeVTable>,
703 parent_item_tree_index: u32,
704 ) -> VRc<ItemTreeVTable, Instance> {
705 let host = parent
706 .upgrade()
707 .expect("the host item tree is alive while it builds its embedded component");
708 let context = i_slint_core::window::context_for_root(&host);
709 Self::new_with_options(
710 compilation_unit,
711 public_component_index,
712 None,
713 type_loaders,
714 resources,
715 Some((parent, parent_item_tree_index)),
716 context,
717 false,
718 )
719 }
720
721 fn new_with_options(
724 compilation_unit: Rc<CompilationUnit>,
725 public_component_index: PublicComponentIdx,
726 window_adapter: Option<i_slint_core::window::WindowAdapterRc>,
727 type_loaders: crate::component::TypeLoaders,
728 resources: Rc<crate::component::Resources>,
729 embedded_in: Option<(vtable::VWeak<ItemTreeVTable>, u32)>,
730 context: SlintContext,
731 disable_window_attachment: bool,
732 ) -> VRc<ItemTreeVTable, Instance> {
733 let public = &compilation_unit.public_components[public_component_index];
734 let globals = Rc::new(GlobalStorage::new(&compilation_unit, context, resources));
735 let item_tree = &public.item_tree;
736 let vrc = build_instance(
737 &compilation_unit,
738 item_tree,
739 Weak::new(),
740 globals,
741 Some(public_component_index),
742 type_loaders,
743 disable_window_attachment,
744 );
745 if let Some(adapter) = window_adapter {
746 let _ = vrc.window_adapter.set(adapter);
747 }
748 if let Some((parent, idx)) = embedded_in {
752 let _ = vrc.embedded_in.set((parent, idx));
753 }
754 #[cfg(feature = "bundle-translations")]
756 if let Some(translations) = &compilation_unit.translations {
757 vrc.globals.context.set_bundled_languages(
758 translations.languages.iter().map(|(l, s)| (l.to_string(), *s)),
759 );
760 }
761 finalize_instance(&vrc);
762 vrc
763 }
764
765 pub fn new_repeated(
770 compilation_unit: Rc<CompilationUnit>,
771 item_tree: &llr::ItemTree,
772 parent: Weak<SubComponentInstance>,
773 repeater_idx: RepeatedElementIdx,
774 globals: Rc<GlobalStorage>,
775 ) -> VRc<ItemTreeVTable, Instance> {
776 let vrc = build_instance(
777 &compilation_unit,
778 item_tree,
779 parent.clone(),
780 globals,
781 None,
782 Default::default(),
783 false,
784 );
785 let _ = vrc.root_sub_component.repeated_in.set((parent, repeater_idx));
786 vrc
787 }
788
789 pub fn new_popup(
793 compilation_unit: Rc<CompilationUnit>,
794 item_tree: &llr::ItemTree,
795 parent: Weak<SubComponentInstance>,
796 globals: Rc<GlobalStorage>,
797 ) -> VRc<ItemTreeVTable, Instance> {
798 build_instance(
799 &compilation_unit,
800 item_tree,
801 parent,
802 globals,
803 None,
804 Default::default(),
805 false,
806 )
807 }
808}
809
810fn build_instance(
818 compilation_unit: &Rc<CompilationUnit>,
819 item_tree: &llr::ItemTree,
820 parent: Weak<SubComponentInstance>,
821 globals: Rc<GlobalStorage>,
822 public_component_index: Option<PublicComponentIdx>,
823 type_loaders: crate::component::TypeLoaders,
824 disable_window_attachment: bool,
825) -> VRc<ItemTreeVTable, Instance> {
826 let parent_for_root = parent.clone();
827 let root_sub_component =
828 build_sub_component_instance(compilation_unit, item_tree.root, parent_for_root);
829 let (tree_nodes, dynamic_table, item_table, z_sort_table) = build_tree_nodes(&item_tree.tree);
830
831 let vrc = VRc::new(Instance {
832 root_sub_component,
833 tree_nodes: tree_nodes.into_boxed_slice(),
834 dynamic_table: dynamic_table.into_boxed_slice(),
835 item_table: item_table.into_boxed_slice(),
836 z_sort_table: z_sort_table.into_boxed_slice(),
837 globals,
838 self_weak: OnceCell::new(),
839 parent_instance: parent,
840 public_component_index,
841 window_adapter: OnceCell::new(),
842 window_adapter_error: OnceCell::new(),
843 window_attached: OnceCell::new(),
844 window_attachment_disabled: disable_window_attachment,
845 bindings_installed: OnceCell::new(),
846 init_code_run: OnceCell::new(),
847 embedded_in: OnceCell::new(),
848 type_loaders,
849 });
850 let weak = VRc::downgrade(&vrc);
851 let _ = vrc.self_weak.set(weak.clone());
852 let _ = vrc.globals.root.set(weak.clone());
854 propagate_root(&vrc.root_sub_component, &weak);
855 vrc
856}
857
858pub(crate) fn finalize_instance(vrc: &VRc<ItemTreeVTable, Instance>) {
864 init_items_and_bindings(vrc);
865 if vrc.init_code_run.get().is_some() {
866 return;
867 }
868 let _ = vrc.init_code_run.set(());
869 if vrc.public_component_index.is_some() && vrc.embedded_in.get().is_none() {
877 vrc.attach_to_window();
878 }
879 crate::bindings::run_init_code_for_instance(vrc);
880}
881
882pub(crate) fn init_items_and_bindings(vrc: &VRc<ItemTreeVTable, Instance>) {
885 if vrc.bindings_installed.get().is_some() {
886 return;
887 }
888 let _ = vrc.bindings_installed.set(());
889 i_slint_core::item_tree::register_item_tree(
892 &VRc::into_dyn(vrc.clone()),
893 vrc.window_adapter_or_default(),
894 );
895 let is_root = vrc.parent_instance.upgrade().is_none();
896 if is_root {
897 crate::globals::install_global_bindings(&vrc.globals);
898 }
899 crate::bindings::install_bindings_only(vrc);
900}
901
902fn propagate_root(sub: &Pin<Rc<SubComponentInstance>>, weak: &VWeak<ItemTreeVTable, Instance>) {
904 let _ = sub.root.set(weak.clone());
905 for nested in &sub.sub_components {
906 propagate_root(nested, weak);
907 }
908}
909
910fn build_sub_component_instance(
912 cu: &Rc<CompilationUnit>,
913 sub_idx: SubComponentIdx,
914 parent: Weak<SubComponentInstance>,
915) -> Pin<Rc<SubComponentInstance>> {
916 let sc = &cu.sub_components[sub_idx];
917 let registry = ItemRegistry::global();
918
919 let properties = sc
920 .properties
921 .iter()
922 .map(|p| Rc::pin(Property::new(crate::eval::default_value_for_type(&p.ty))))
923 .collect();
924 let callbacks = sc.callbacks.iter().map(|_| Rc::pin(Callback::default())).collect();
925 let callback_trackers =
926 sc.callbacks.iter().map(|c| c.needs_tracker.then(|| Rc::pin(Property::new(())))).collect();
927 let items =
928 sc.items
929 .iter()
930 .map(|item| {
931 registry.factory(&item.ty.class_name).unwrap_or_else(|| {
932 panic!("native item `{}` is not registered", item.ty.class_name)
933 })()
934 })
935 .collect();
936 let repeaters = sc
937 .repeated
938 .iter()
939 .map(|rep| {
940 if rep.data_prop.is_none() {
941 RepeaterOrConditional::Conditional(Box::pin(Conditional::default()))
942 } else {
943 RepeaterOrConditional::Repeater(Box::pin(Repeater::default()))
944 }
945 })
946 .collect();
947
948 let rc = Rc::new_cyclic(|weak_self: &Weak<SubComponentInstance>| {
952 let sub_components = sc
953 .sub_components
954 .iter()
955 .map(|nested| build_sub_component_instance(cu, nested.ty, weak_self.clone()))
956 .collect();
957 SubComponentInstance {
958 compilation_unit: cu.clone(),
959 sub_component_idx: sub_idx,
960 properties,
961 callbacks,
962 callback_trackers,
963 items,
964 sub_components,
965 repeaters,
966 parent,
967 root: OnceCell::new(),
968 change_trackers: core::iter::repeat_with(ChangeTracker::default)
969 .take(2 * sc.timers.len() + sc.change_callbacks.len())
970 .collect(),
971 timers: core::iter::repeat_with(Default::default).take(sc.timers.len()).collect(),
972 popup_ids: vec![Cell::new(None); sc.popup_windows.len()],
973 repeated_in: OnceCell::new(),
974 menubar: RefCell::new(None),
975 }
976 });
977 Pin::new(rc)
978}
979
980fn read_logical_length(
984 sub: &Pin<Rc<SubComponentInstance>>,
985 mr: &llr::MemberReference,
986) -> i_slint_core::lengths::LogicalLength {
987 let mut ctx = crate::eval::EvalContext::new(sub.clone());
988 let v = crate::eval::load_property(&ctx, mr);
989 let _ = &mut ctx;
990 let n: f64 = v.try_into().unwrap_or(0.0);
991 i_slint_core::lengths::LogicalLength::new(n as f32)
992}
993
994struct ValueListViewProps {
1000 content_y: llr::MemberReference,
1001 content_width: Option<llr::MemberReference>,
1004 content_height: Option<llr::MemberReference>,
1005 ctx_sub: Pin<Rc<SubComponentInstance>>,
1006}
1007
1008impl i_slint_core::model::ListViewProperties for ValueListViewProps {
1009 fn content_y_get(&self) -> i_slint_core::lengths::LogicalLength {
1010 read_logical_length(&self.ctx_sub, &self.content_y)
1011 }
1012 fn content_y_get_internal(&self) -> i_slint_core::lengths::LogicalLength {
1013 read_logical_length(&self.ctx_sub, &self.content_y)
1017 }
1018 fn content_y_set(&self, value: i_slint_core::lengths::LogicalLength) {
1019 let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
1020 crate::eval::store_property(&ctx, &self.content_y, Value::Number(value.get() as f64));
1021 }
1022 fn content_y_has_binding(&self) -> bool {
1023 false
1027 }
1028 fn computes_content_height(&self) -> bool {
1029 self.content_height.is_some()
1030 }
1031 fn content_width_set(&self, value: i_slint_core::lengths::LogicalLength) {
1032 let Some(content_width) = &self.content_width else { return };
1033 let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
1034 crate::eval::store_property(&ctx, content_width, Value::Number(value.get() as f64));
1035 }
1036 fn content_height_set(&self, value: i_slint_core::lengths::LogicalLength) {
1037 let Some(content_height) = &self.content_height else { return };
1038 let ctx = crate::eval::EvalContext::new(self.ctx_sub.clone());
1039 crate::eval::store_property(&ctx, content_height, Value::Number(value.get() as f64));
1040 }
1041 fn register_as_dependencies(&self) {
1042 if let Some(content_width) = &self.content_width {
1045 let _ = read_logical_length(&self.ctx_sub, content_width);
1046 }
1047 if let Some(content_height) = &self.content_height {
1048 let _ = read_logical_length(&self.ctx_sub, content_height);
1049 }
1050 let _ = read_logical_length(&self.ctx_sub, &self.content_y);
1051 }
1052}
1053
1054type DynamicEntry = Option<(Box<[SubComponentInstanceIdx]>, RepeatedElementIdx)>;
1055type ItemEntry = Option<(Box<[SubComponentInstanceIdx]>, ItemInstanceIdx)>;
1056type ZSortEntry = Option<Vec<llr::ZSource>>;
1057
1058fn build_tree_nodes(
1068 root: &llr::TreeNode,
1069) -> (Vec<ItemTreeNode>, Vec<DynamicEntry>, Vec<ItemEntry>, Vec<ZSortEntry>) {
1070 use either::Either;
1071
1072 let mut out = Vec::new();
1073 let mut dyn_table: Vec<DynamicEntry> = Vec::new();
1074 let mut item_table: Vec<ItemEntry> = Vec::new();
1075 let mut z_sort_table: Vec<ZSortEntry> = Vec::new();
1076 root.visit_in_array(&mut |node, children_offset, parent_index| {
1077 let parent_index = parent_index as u32;
1078 let (entry, dyn_entry, item_entry) = match node.item_index {
1079 Either::Left(item_idx) => (
1080 ItemTreeNode::Item {
1081 is_accessible: node.is_accessible,
1082 children_count: node.children.len() as u32,
1083 children_index: children_offset as u32,
1084 parent_index,
1085 item_array_index: out.len() as u32,
1088 },
1089 None,
1090 Some((node.sub_component_path.clone().into_boxed_slice(), item_idx)),
1091 ),
1092 Either::Right(dynamic_index) => (
1093 ItemTreeNode::DynamicTree { index: out.len() as u32, parent_index },
1101 Some((
1102 node.sub_component_path.clone().into_boxed_slice(),
1103 (dynamic_index as usize).into(),
1104 )),
1105 None,
1106 ),
1107 };
1108 out.push(entry);
1109 dyn_table.push(dyn_entry);
1110 item_table.push(item_entry);
1111 z_sort_table.push(node.z_sort_order_property.clone());
1112 });
1113 (out, dyn_table, item_table, z_sort_table)
1114}
1115
1116fn repeated_align_self(
1119 sc: &i_slint_compiler::llr::SubComponent,
1120 ctx: &mut crate::eval::EvalContext,
1121 orientation: i_slint_core::items::Orientation,
1122) -> i_slint_core::items::CrossAxisAlignment {
1123 match &sc.cross_axis_self_alignment_for_repeated {
1124 Some((cross_o, expr)) if crate::eval::llr_to_core_orientation(*cross_o) == orientation => {
1125 crate::eval::eval_expression(ctx, &expr.borrow()).try_into().unwrap_or_default()
1126 }
1127 _ => Default::default(),
1128 }
1129}
1130
1131fn repeated_layout_order(
1134 sc: &i_slint_compiler::llr::SubComponent,
1135 ctx: &mut crate::eval::EvalContext,
1136 orientation: i_slint_core::items::Orientation,
1137) -> i32 {
1138 match &sc.layout_order_for_repeated {
1139 Some((main_o, expr)) if crate::eval::llr_to_core_orientation(*main_o) == orientation => {
1140 match crate::eval::eval_expression(ctx, &expr.borrow()) {
1141 Value::Number(n) => n as i32,
1142 _ => 0,
1143 }
1144 }
1145 _ => 0,
1146 }
1147}
1148
1149impl i_slint_core::model::RepeatedItemTree for Instance {
1154 type Data = Value;
1155
1156 fn update(&self, index: usize, data: Self::Data) {
1157 let sc_idx = self.root_sub_component.sub_component_idx;
1158 let cu = self.root_sub_component.compilation_unit.clone();
1159 let sc = &cu.sub_components[sc_idx];
1160 for (idx, prop) in sc.properties.iter_enumerated() {
1165 let target = &self.root_sub_component.properties[idx];
1166 match prop.name.as_str() {
1167 "model_data" => Pin::as_ref(target).set(data.clone()),
1168 "model_index" => Pin::as_ref(target).set(Value::Number(index as f64)),
1169 _ => {}
1170 }
1171 }
1172 }
1173
1174 fn init(&self) {
1175 if let Some(weak) = self.self_weak.get()
1181 && let Some(vrc) = weak.upgrade()
1182 {
1183 finalize_instance(&vrc);
1184 }
1185 }
1186
1187 fn z_order(self: Pin<&Self>) -> Option<f32> {
1188 let this = self.get_ref();
1191 let (parent_weak, rep_idx) = this.root_sub_component.repeated_in.get()?;
1192 let parent_sub = parent_weak.upgrade()?;
1193 let parent_sc = &parent_sub.compilation_unit.sub_components[parent_sub.sub_component_idx];
1194 let z_ref = parent_sc.repeated[*rep_idx].dynamic_z.as_ref()?;
1195 let ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1196 let z: f64 = crate::eval::load_property(&ctx, z_ref).try_into().unwrap_or(0.0);
1197 Some(z as f32)
1198 }
1199
1200 fn listview_layout(
1201 self: Pin<&Self>,
1202 offset_y: &mut i_slint_core::lengths::LogicalLength,
1203 ) -> i_slint_core::lengths::LogicalLength {
1204 use i_slint_core::item_tree::ItemTree as _;
1205 use i_slint_core::lengths::LogicalLength;
1206 let this = self.get_ref();
1210 let Some((parent_weak, rep_idx)) = this.root_sub_component.repeated_in.get() else {
1211 return LogicalLength::default();
1212 };
1213 let Some(parent_sub) = parent_weak.upgrade() else { return LogicalLength::default() };
1214 let parent_sub = Pin::new(parent_sub);
1215 let parent_cu = parent_sub.compilation_unit.clone();
1216 let parent_sc = &parent_cu.sub_components[parent_sub.sub_component_idx];
1217 let Some(lv) = parent_sc.repeated[*rep_idx].listview.as_ref() else {
1218 return LogicalLength::default();
1219 };
1220
1221 let row_sub = this.root_sub_component.clone();
1225 let ctx = crate::eval::EvalContext::new(row_sub.clone());
1226 crate::eval::store_property(&ctx, &lv.prop_y, Value::Number(offset_y.get() as f64));
1227 let height_v = crate::eval::load_property(&ctx, &lv.prop_height);
1228 let height: f64 = height_v.try_into().unwrap_or(0.0);
1229 *offset_y += LogicalLength::new(height as f32);
1230 let info = self.layout_info(i_slint_core::items::Orientation::Horizontal);
1231 LogicalLength::new(info.min)
1232 }
1233
1234 fn layout_item_info(
1235 self: Pin<&Self>,
1236 orientation: i_slint_core::items::Orientation,
1237 child_index: Option<usize>,
1238 ) -> i_slint_core::layout::LayoutItemInfo {
1239 let this = self.get_ref();
1248 let cu = this.root_sub_component.compilation_unit.clone();
1249 let sc_idx = this.root_sub_component.sub_component_idx;
1250 let sc = &cu.sub_components[sc_idx];
1251
1252 if let (Some(index), true, Some(templates)) =
1253 (child_index, sc.is_repeated_row, sc.row_child_templates.as_ref())
1254 {
1255 return row_child_layout_item_info(this, sc, templates, orientation, index);
1256 }
1257
1258 let expr = match orientation {
1259 i_slint_core::items::Orientation::Horizontal => sc.layout_info_h.borrow(),
1260 i_slint_core::items::Orientation::Vertical => sc.layout_info_v.borrow(),
1261 };
1262 let mut ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1263 let constraint =
1264 crate::eval::eval_expression(&mut ctx, &expr).try_into().unwrap_or_default();
1265 i_slint_core::layout::LayoutItemInfo {
1266 constraint,
1267 cross_axis_self_alignment: repeated_align_self(sc, &mut ctx, orientation),
1268 layout_order: repeated_layout_order(sc, &mut ctx, orientation),
1269 }
1270 }
1271
1272 fn layout_item_info_at_cross_width(
1278 self: Pin<&Self>,
1279 cross_width: f32,
1280 ) -> i_slint_core::layout::LayoutItemInfo {
1281 use i_slint_compiler::llr::CROSS_WIDTH_LOCAL;
1282 let orientation = i_slint_core::items::Orientation::Vertical;
1283 let cu = self.root_sub_component.compilation_unit.clone();
1284 let sc = &cu.sub_components[self.root_sub_component.sub_component_idx];
1285 let Some(expr) = sc
1286 .layout_info_v_at_cross_width_for_repeated
1287 .as_ref()
1288 .filter(|_| sc.flexbox_layout_item_info_for_repeated.is_none())
1289 else {
1290 return self.layout_item_info(orientation, None);
1291 };
1292 let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1293 ctx.locals.insert(CROSS_WIDTH_LOCAL.into(), Value::Number(cross_width as f64));
1294 let constraint =
1295 crate::eval::eval_expression(&mut ctx, &expr.borrow()).try_into().unwrap_or_default();
1296 i_slint_core::layout::LayoutItemInfo {
1300 constraint,
1301 cross_axis_self_alignment: repeated_align_self(sc, &mut ctx, orientation),
1302 layout_order: repeated_layout_order(sc, &mut ctx, orientation),
1303 }
1304 }
1305
1306 fn flexbox_layout_item_info(
1307 self: Pin<&Self>,
1308 orientation: i_slint_core::items::Orientation,
1309 child_index: Option<usize>,
1310 ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1311 let cu = self.root_sub_component.compilation_unit.clone();
1315 let sc_idx = self.root_sub_component.sub_component_idx;
1316 let sc = &cu.sub_components[sc_idx];
1317 if let Some(expr) = &sc.flexbox_layout_item_info_for_repeated {
1318 let expr = expr.borrow();
1319 let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1320 let value = crate::eval::eval_expression(&mut ctx, &expr);
1321 let mut info = value_to_flexbox_layout_item_info(value, orientation, self);
1322 if matches!(orientation, i_slint_core::items::Orientation::Vertical)
1328 && child_index.is_none()
1329 && let Some(v_expr) = &sc.layout_info_v_constrained_for_repeated
1330 {
1331 let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1332 info.constraint = crate::eval::eval_expression(&mut ctx, &v_expr.borrow())
1333 .try_into()
1334 .unwrap_or_default();
1335 return info;
1336 }
1337 info.constraint = self.layout_item_info(orientation, child_index).constraint;
1340 return info;
1341 }
1342 let info = self.layout_item_info(orientation, None);
1343 info.into()
1344 }
1345}
1346
1347impl Instance {
1348 pub fn flexbox_layout_item_info_at_cross_width(
1352 self: Pin<&Self>,
1353 cross_width: f32,
1354 ) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1355 use i_slint_core::items::Orientation;
1356 use i_slint_core::model::RepeatedItemTree;
1357 let mut info =
1358 RepeatedItemTree::flexbox_layout_item_info(self, Orientation::Vertical, None);
1359 let cu = self.root_sub_component.compilation_unit.clone();
1360 let sc = &cu.sub_components[self.root_sub_component.sub_component_idx];
1361 if let Some(v_expr) = &sc.layout_info_v_at_cross_width_for_repeated {
1362 let mut ctx = crate::eval::EvalContext::new(self.root_sub_component.clone());
1363 ctx.locals.insert(
1364 i_slint_compiler::llr::CROSS_WIDTH_LOCAL.into(),
1365 Value::Number(cross_width as f64),
1366 );
1367 info.constraint = crate::eval::eval_expression(&mut ctx, &v_expr.borrow())
1368 .try_into()
1369 .unwrap_or_default();
1370 }
1371 info
1372 }
1373}
1374
1375fn row_child_layout_item_info(
1379 this: &Instance,
1380 sc: &i_slint_compiler::llr::SubComponent,
1381 templates: &[i_slint_compiler::llr::RowChildTemplateInfo],
1382 orientation: i_slint_core::items::Orientation,
1383 mut index: usize,
1384) -> i_slint_core::layout::LayoutItemInfo {
1385 use i_slint_compiler::llr::RowChildTemplateInfo;
1386 use i_slint_core::model::RepeatedItemTree;
1387 let flat_index = index;
1390 for entry in templates {
1391 match entry {
1392 RowChildTemplateInfo::Static { child_index } => {
1393 if index == 0 {
1394 let child = &sc.grid_layout_children[*child_index];
1395 let expr = match orientation {
1396 i_slint_core::items::Orientation::Horizontal => {
1397 child.layout_info_h.borrow()
1398 }
1399 i_slint_core::items::Orientation::Vertical => child.layout_info_v.borrow(),
1400 };
1401 let mut ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1402 let constraint = crate::eval::eval_expression(&mut ctx, &expr)
1403 .try_into()
1404 .unwrap_or_default();
1405 return i_slint_core::layout::LayoutItemInfo {
1406 constraint,
1407 ..Default::default()
1408 };
1409 }
1410 index -= 1;
1411 }
1412 RowChildTemplateInfo::Repeated { repeater_index, measure_at_cross_width } => {
1413 let repeater = &this.root_sub_component.repeaters[*repeater_index];
1414 repeater.track_instance_changes();
1415 let count = repeater.range().len();
1416 if index < count {
1417 if let Some(inner) = repeater.instance_at(index) {
1418 if *measure_at_cross_width
1422 && orientation == i_slint_core::items::Orientation::Vertical
1423 && let Some(w) = row_child_cross_width(this, sc, flat_index)
1424 {
1425 return RepeatedItemTree::layout_item_info_at_cross_width(
1426 inner.as_pin_ref(),
1427 w,
1428 );
1429 }
1430 return RepeatedItemTree::layout_item_info(
1431 inner.as_pin_ref(),
1432 orientation,
1433 None,
1434 );
1435 }
1436 return i_slint_core::layout::LayoutItemInfo::default();
1437 }
1438 index -= count;
1439 }
1440 }
1441 }
1442 i_slint_core::layout::LayoutItemInfo::default()
1443}
1444
1445fn row_child_cross_width(
1450 this: &Instance,
1451 sc: &i_slint_compiler::llr::SubComponent,
1452 flat_index: usize,
1453) -> Option<f32> {
1454 use i_slint_compiler::llr::GRID_MEASURE_CHILD_INDEX_LOCAL;
1455 let expr = sc.grid_row_child_cross_width.as_ref()?;
1456 let mut ctx = crate::eval::EvalContext::new(this.root_sub_component.clone());
1457 ctx.locals.insert(GRID_MEASURE_CHILD_INDEX_LOCAL.into(), Value::Number(flat_index as f64));
1458 crate::eval::eval_expression(&mut ctx, &expr.borrow()).try_into().ok()
1459}
1460
1461fn value_to_flexbox_layout_item_info(
1462 v: Value,
1463 orientation: i_slint_core::items::Orientation,
1464 instance: Pin<&Instance>,
1465) -> i_slint_core::layout::FlexboxLayoutItemInfo {
1466 use i_slint_core::model::RepeatedItemTree;
1467 let Value::Struct(s) = v else {
1468 let info = RepeatedItemTree::layout_item_info(instance, orientation, None);
1469 return info.into();
1470 };
1471 crate::eval_layout::flexbox_item_info_from_struct(&s)
1472}