1use std::collections::{HashMap, HashSet};
4
5use waft_foundation::{App, Handle, Listener, ValueChanged};
6
7use super::element::{AnyElement, ElementLifecycle};
8use super::widget::GlobalKey;
9use crate::widgets::focus_manager::FocusManager;
10use waft_foundation::Ref;
11
12pub struct BuildScope {
23 build_scheduled: bool,
24 building: bool,
25 schedule_rebuild: Option<Listener>,
34 dirty_elements_needs_resorting: Option<bool>,
42 dirty_elements: Vec<AnyElement>,
43}
44
45impl BuildScope {
46 pub fn new(app: &mut App, schedule_rebuild: Option<Listener>) -> Ref<BuildScope> {
48 app.create(BuildScope {
49 build_scheduled: false,
50 building: false,
51 schedule_rebuild,
52 dirty_elements_needs_resorting: None,
53 dirty_elements: Vec::new(),
54 })
55 }
56
57 pub fn dirty_elements(self: Handle<Self>, app: &App) -> &[AnyElement] {
59 &app.get(self).dirty_elements
60 }
61
62 pub(crate) fn schedule_build_for(self: Handle<Self>, app: &mut App, element: AnyElement) {
63 debug_assert!(element.build_scope(app) == self);
64 if !element.in_dirty_list(app) {
65 app.get_mut(self).dirty_elements.push(element);
66 element.data_mut(app).in_dirty_list = true;
67 }
68 let scope = app.get(self);
69 if !scope.build_scheduled && !scope.building {
70 app.get_mut(self).build_scheduled = true;
71 if let Some(schedule_rebuild) = app.get(self).schedule_rebuild.clone() {
72 schedule_rebuild.call(app);
73 }
74 }
75 if app.get(self).dirty_elements_needs_resorting.is_some() {
76 app.get_mut(self).dirty_elements_needs_resorting = Some(true);
77 }
78 }
79
80 fn try_rebuild(self: Handle<Self>, app: &mut App, element: AnyElement) {
81 debug_assert!(element.in_dirty_list(app));
82 debug_assert!(element.build_scope(app) == self);
83 element.rebuild(app, false);
84 }
85
86 fn debug_assert_element_in_scope(
87 app: &App,
88 element: AnyElement,
89 debug_build_root: AnyElement,
90 ) -> bool {
91 let is_in_scope =
92 element.debug_is_descendant_of(app, debug_build_root) || !element.debug_is_active(app);
93 assert!(
94 is_in_scope,
95 "Tried to build dirty widget in the wrong build scope. A widget which was marked \
96 as dirty and is still active was scheduled to be built, but the current build \
97 scope unexpectedly does not contain that widget."
98 );
99 true
100 }
101
102 pub(crate) fn flush_dirty_elements(
105 self: Handle<Self>,
106 app: &mut App,
107 debug_build_root: AnyElement,
108 ) {
109 debug_assert!(
110 app.get(self).dirty_elements_needs_resorting.is_none(),
111 "_flushDirtyElements must be non-reentrant"
112 );
113 sort_dirty_elements(app, self);
114 app.get_mut(self).dirty_elements_needs_resorting = Some(false);
115 let mut index = 0;
116 while index < app.get(self).dirty_elements.len() {
117 let element = app.get(self).dirty_elements[index];
118 if element.build_scope(app) == self {
119 debug_assert!(BuildScope::debug_assert_element_in_scope(
120 app,
121 element,
122 debug_build_root
123 ));
124 self.try_rebuild(app, element);
125 }
126 index = self.dirty_element_index_after(app, index);
127 }
128 if cfg!(debug_assertions) {
129 let missed: Vec<AnyElement> = app
130 .get(self)
131 .dirty_elements
132 .iter()
133 .copied()
134 .filter(|element| {
135 element.debug_is_active(app)
136 && element.dirty(app)
137 && element.build_scope(app) == self
138 })
139 .collect();
140 assert!(
141 missed.is_empty(),
142 "buildScope missed some dirty elements. This probably indicates that the \
143 dirty list should have been resorted but was not: {missed:?}"
144 );
145 }
146 let dirty_elements = std::mem::take(&mut app.get_mut(self).dirty_elements);
147 for element in dirty_elements {
148 if element.build_scope(app) == self {
149 element.data_mut(app).in_dirty_list = false;
150 }
151 }
152 let scope = app.get_mut(self);
153 scope.dirty_elements_needs_resorting = None;
154 scope.build_scheduled = false;
155 }
156
157 fn dirty_element_index_after(self: Handle<Self>, app: &mut App, index: usize) -> usize {
158 if app.get(self).dirty_elements_needs_resorting != Some(true) {
159 return index + 1;
160 }
161 let mut index = index + 1;
162 sort_dirty_elements(app, self);
163 app.get_mut(self).dirty_elements_needs_resorting = Some(false);
164 while index > 0 && app.get(self).dirty_elements[index - 1].dirty(app) {
165 index -= 1;
166 }
167 if cfg!(debug_assertions) {
168 for i in (0..index).rev() {
169 let element = app.get(self).dirty_elements[i];
170 debug_assert!(
171 !element.dirty(app) || element.lifecycle(app) != ElementLifecycle::Active
172 );
173 }
174 }
175 index
176 }
177
178 pub(crate) fn set_building(self: Handle<Self>, app: &mut App, building: bool) {
179 app.get_mut(self).building = building;
180 }
181}
182
183fn sort_dirty_elements(app: &mut App, scope: Handle<BuildScope>) {
185 let mut keyed: Vec<(u32, bool, AnyElement)> = app
186 .get(scope)
187 .dirty_elements
188 .iter()
189 .map(|element| (element.depth(app), element.dirty(app), *element))
190 .collect();
191 keyed.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
192 app.get_mut(scope).dirty_elements = keyed.into_iter().map(|(_, _, element)| element).collect();
193}
194
195#[derive(Default)]
198struct InactiveElements {
199 locked: bool,
200 elements: HashSet<AnyElement>,
201}
202
203pub type BuildScopeCallback = Box<dyn FnOnce(&mut App)>;
205
206pub type BuildScheduledCallback = ValueChanged<AnyElement>;
208
209pub struct BuildOwner {
223 on_build_scheduled: Option<BuildScheduledCallback>,
225 focus_manager: Ref<FocusManager>,
226 inactive_elements: InactiveElements,
227 in_build_scope: bool,
230 global_key_registry: HashMap<GlobalKey, AnyElement>,
231 debug_state_lock_level: i32,
232 debug_building: bool,
233 debug_current_build_target: Option<AnyElement>,
234}
235
236impl BuildOwner {
237 pub fn new(
244 app: &mut App,
245 on_build_scheduled: Option<BuildScheduledCallback>,
246 ) -> Ref<BuildOwner> {
247 let focus_manager = FocusManager::new(app);
248 focus_manager.register_global_handlers(app);
249 BuildOwner::with_focus_manager(app, on_build_scheduled, focus_manager)
250 }
251
252 pub fn with_focus_manager(
255 app: &mut App,
256 on_build_scheduled: Option<BuildScheduledCallback>,
257 focus_manager: Ref<FocusManager>,
258 ) -> Ref<BuildOwner> {
259 app.create(BuildOwner {
260 on_build_scheduled,
261 focus_manager,
262 inactive_elements: InactiveElements::default(),
263 in_build_scope: false,
264 global_key_registry: HashMap::new(),
265 debug_state_lock_level: 0,
266 debug_building: false,
267 debug_current_build_target: None,
268 })
269 }
270
271 pub fn focus_manager(self: Handle<Self>, app: &App) -> Handle<FocusManager> {
276 app.get(self).focus_manager.handle()
277 }
278
279 pub fn set_focus_manager(self: Handle<Self>, app: &mut App, focus_manager: Ref<FocusManager>) {
281 app.get_mut(self).focus_manager = focus_manager;
282 }
283
284 pub fn set_on_build_scheduled(
286 self: Handle<Self>,
287 app: &mut App,
288 callback: Option<BuildScheduledCallback>,
289 ) {
290 app.get_mut(self).on_build_scheduled = callback;
291 }
292
293 pub fn schedule_build_for(self: Handle<Self>, app: &mut App, element: AnyElement) {
296 debug_assert!(element.owner(app) == Some(self));
297 debug_assert!(element.data(app).parent_build_scope.is_some());
298 debug_assert!(
299 element.dirty(app),
300 "scheduleBuildFor() called for a widget that is not marked as dirty."
301 );
302 let build_scope = element.build_scope(app);
303 debug_assert!(
304 app.get(self).debug_building || !element.in_dirty_list(app),
305 "BuildOwner.scheduleBuildFor() called on an Element that is already in the dirty \
306 list."
307 );
308 if !app.get(self).in_build_scope
309 && let Some(on_build_scheduled) = app.get(self).on_build_scheduled.clone()
310 {
311 on_build_scheduled(app, element);
312 }
313 build_scope.schedule_build_for(app, element);
314 }
315
316 pub(crate) fn debug_state_locked(self: Handle<Self>, app: &App) -> bool {
317 app.get(self).debug_state_lock_level > 0
318 }
319
320 pub fn debug_building(self: Handle<Self>, app: &App) -> bool {
324 app.get(self).debug_building
325 }
326
327 pub(crate) fn debug_current_build_target(self: Handle<Self>, app: &App) -> Option<AnyElement> {
328 app.get(self).debug_current_build_target
329 }
330
331 pub(crate) fn set_debug_current_build_target(
332 self: Handle<Self>,
333 app: &mut App,
334 target: Option<AnyElement>,
335 ) {
336 app.get_mut(self).debug_current_build_target = target;
337 }
338
339 pub fn lock_state(self: Handle<Self>, app: &mut App, callback: impl FnOnce(&mut App)) {
345 debug_assert!(app.get(self).debug_state_lock_level >= 0);
346 if cfg!(debug_assertions) {
347 app.get_mut(self).debug_state_lock_level += 1;
348 }
349 callback(app);
350 if cfg!(debug_assertions) {
351 app.get_mut(self).debug_state_lock_level -= 1;
352 }
353 debug_assert!(app.get(self).debug_state_lock_level >= 0);
354 }
355
356 pub fn build_scope(
378 self: Handle<Self>,
379 app: &mut App,
380 context: AnyElement,
381 callback: Option<BuildScopeCallback>,
382 ) {
383 let build_scope = context.build_scope(app);
384 if callback.is_none() && app.get(build_scope).dirty_elements.is_empty() {
385 return;
386 }
387 debug_assert!(app.get(self).debug_state_lock_level >= 0);
388 debug_assert!(!app.get(self).debug_building);
389 if cfg!(debug_assertions) {
390 let owner = app.get_mut(self);
391 owner.debug_state_lock_level += 1;
392 owner.debug_building = true;
393 }
394 app.get_mut(self).in_build_scope = true;
395 build_scope.set_building(app, true);
396 if let Some(callback) = callback {
397 debug_assert!(self.debug_state_locked(app));
398 let debug_previous_build_target = self.debug_current_build_target(app);
399 if cfg!(debug_assertions) {
400 self.set_debug_current_build_target(app, Some(context));
401 }
402 callback(app);
403 if cfg!(debug_assertions) {
404 debug_assert!(self.debug_current_build_target(app) == Some(context));
405 self.set_debug_current_build_target(app, debug_previous_build_target);
406 }
407 }
408 build_scope.flush_dirty_elements(app, context);
409 build_scope.set_building(app, false);
410 app.get_mut(self).in_build_scope = false;
411 debug_assert!(app.get(self).debug_building);
412 if cfg!(debug_assertions) {
413 let owner = app.get_mut(self);
414 owner.debug_building = false;
415 owner.debug_state_lock_level -= 1;
416 }
417 debug_assert!(app.get(self).debug_state_lock_level >= 0);
418 }
419
420 pub fn global_key_count(self: Handle<Self>, app: &App) -> usize {
423 app.get(self).global_key_registry.len()
424 }
425
426 pub(crate) fn register_global_key(
427 self: Handle<Self>,
428 app: &mut App,
429 key: &GlobalKey,
430 element: AnyElement,
431 ) {
432 if cfg!(debug_assertions)
433 && let Some(old_element) = app.get(self).global_key_registry.get(key).copied()
434 {
435 debug_assert!(
436 element.widget(app).widget_type() != old_element.widget(app).widget_type(),
437 "Multiple widgets used the same GlobalKey: {key:?}"
438 );
439 }
440 app.get_mut(self)
441 .global_key_registry
442 .insert(key.clone(), element);
443 }
444
445 pub(crate) fn unregister_global_key(
446 self: Handle<Self>,
447 app: &mut App,
448 key: &GlobalKey,
449 element: AnyElement,
450 ) {
451 if app.get(self).global_key_registry.get(key) == Some(&element) {
452 app.get_mut(self).global_key_registry.remove(key);
453 }
454 }
455
456 pub fn global_key_element(
458 self: Handle<Self>,
459 app: &App,
460 key: &GlobalKey,
461 ) -> Option<AnyElement> {
462 app.get(self).global_key_registry.get(key).copied()
463 }
464
465 pub(crate) fn inactive_add(self: Handle<Self>, app: &mut App, element: AnyElement) {
468 debug_assert!(!app.get(self).inactive_elements.locked);
469 debug_assert!(!app.get(self).inactive_elements.elements.contains(&element));
470 debug_assert!(element.parent(app).is_none());
471 match element.lifecycle(app) {
472 ElementLifecycle::Active => {
473 deactivate_recursively(app, element);
474 app.get_mut(self).inactive_elements.elements.insert(element);
475 }
476 ElementLifecycle::Inactive => {
477 app.get_mut(self).inactive_elements.elements.insert(element);
478 }
479 state @ (ElementLifecycle::Initial
480 | ElementLifecycle::Failed
481 | ElementLifecycle::Defunct) => {
482 panic!("{element:?} must not be deactivated when in {state:?} state.");
483 }
484 }
485 }
486
487 pub(crate) fn inactive_remove(self: Handle<Self>, app: &mut App, element: AnyElement) {
488 debug_assert!(!app.get(self).inactive_elements.locked);
489 debug_assert!(app.get(self).inactive_elements.elements.contains(&element));
490 debug_assert!(element.parent(app).is_none());
491 app.get_mut(self)
492 .inactive_elements
493 .elements
494 .remove(&element);
495 debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
496 }
497
498 pub fn debug_inactive_contains(self: Handle<Self>, app: &App, element: AnyElement) -> bool {
500 app.get(self).inactive_elements.elements.contains(&element)
501 }
502
503 fn inactive_unmount_all(self: Handle<Self>, app: &mut App) {
504 app.get_mut(self).inactive_elements.locked = true;
505 let mut elements: Vec<AnyElement> = app
506 .get_mut(self)
507 .inactive_elements
508 .elements
509 .drain()
510 .collect();
511 let mut keyed: Vec<(u32, bool, AnyElement)> = elements
512 .drain(..)
513 .map(|element| (element.depth(app), element.dirty(app), element))
514 .collect();
515 keyed.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
516 for (_, _, element) in keyed.into_iter().rev() {
517 unmount_recursively(app, element);
518 }
519 debug_assert!(app.get(self).inactive_elements.elements.is_empty());
520 app.get_mut(self).inactive_elements.locked = false;
521 }
522
523 pub fn finalize_tree(self: Handle<Self>, app: &mut App) {
530 self.lock_state(app, |app| self.inactive_unmount_all(app));
531 }
532}
533
534fn unmount_recursively(app: &mut App, element: AnyElement) {
539 let mut stack = vec![Walk::Enter(element)];
540 while let Some(step) = stack.pop() {
541 match step {
542 Walk::Enter(element) => {
543 debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
544 stack.push(Walk::Leave(element));
545 for child in element.children(app).into_iter().rev() {
546 debug_assert!(child.parent(app) == Some(element));
547 stack.push(Walk::Enter(child));
548 }
549 }
550 Walk::Leave(element) => {
551 element.unmount(app);
552 debug_assert!(element.lifecycle(app) == ElementLifecycle::Defunct);
553 app.release_tree_node(element.id());
557 }
558 }
559 }
560}
561
562fn deactivate_recursively(app: &mut App, element: AnyElement) {
566 let mut stack = vec![Walk::Enter(element)];
567 while let Some(step) = stack.pop() {
568 match step {
569 Walk::Enter(element) => {
570 debug_assert!(element.lifecycle(app) == ElementLifecycle::Active);
571 element.deactivate(app);
572 stack.push(Walk::Leave(element));
573 for child in element.children(app).into_iter().rev() {
574 stack.push(Walk::Enter(child));
575 }
576 }
577 Walk::Leave(element) => {
578 if cfg!(debug_assertions) {
579 element.debug_deactivated(app);
580 }
581 }
582 }
583 }
584}
585
586enum Walk {
589 Enter(AnyElement),
590 Leave(AnyElement),
591}
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::{ElementBase, IntoWidget, SingleChildRenderObjectElement, SizedBox};
597 use waft_foundation::AppCell;
598
599 #[test]
601 fn dirty_scope_resort_keeps_clean_siblings_before_pending_builds() {
602 let cell = AppCell::new();
603 let mut app = cell.borrow_mut();
604 let widget = SizedBox::shrink().into_widget();
605 let pending = widget.create_element(&mut app, widget.clone());
606 let cleaned = widget.create_element(&mut app, widget.clone());
607 let focus = FocusManager::new(&mut app);
608 let owner = BuildOwner::with_focus_manager(&mut app, None, focus);
609 for element in [pending, cleaned] {
610 element.assign_owner(&mut app, owner.handle());
611 let handle = element
612 .downcast::<SingleChildRenderObjectElement>(&app)
613 .unwrap();
614 ElementBase::mount(handle, &mut app, None, None);
615 }
616 pending.set_dirty(&mut app, true);
617 cleaned.set_dirty(&mut app, false);
618 let scope = BuildScope::new(&mut app, None);
619 app.get_mut(&scope).dirty_elements = vec![pending, cleaned];
620 app.get_mut(&scope).dirty_elements_needs_resorting = Some(true);
621 let next = scope.dirty_element_index_after(&mut app, 0);
622 assert_eq!(app.get(&scope).dirty_elements, [cleaned, pending]);
623 assert_eq!(
624 next, 1,
625 "the resume index must point after the last clean sibling"
626 );
627 assert!(app.get(&scope).dirty_elements[next].dirty(&app));
628 }
629}