1use core::any::TypeId;
4use core::cell::Cell;
5use core::marker::PhantomData;
6use core::mem::size_of;
7
8use crate::arena::SmallVec;
9use crate::element::{Element, View};
10use crate::solver::Region;
11
12use super::{FrameScope, Handle, PodId, Scope};
13
14pub const POD_SLOT_BYTES: usize = 256;
16
17pub const MAX_PODS: usize = 16;
19
20pub(super) type ReadersMask = u64;
21
22pub(crate) struct PodVTable {
24 type_id: fn() -> TypeId,
25 pub(super) render_fn: unsafe fn(*mut u8, *mut FrameScope) -> Element<'static>,
26 drop_fn: unsafe fn(*mut u8),
27}
28
29const STATE_FLAG_BORROWED: u8 = 1 << 0;
30const STATE_FLAG_EXPANDING: u8 = 1 << 1;
31const STATE_FLAG_NEEDS_NEXT_FRAME: u8 = 1 << 2;
32
33pub(super) const LAYOUT_FLAG_SUBTREE_CLEAN: u8 = 1 << 0;
34pub(super) const LAYOUT_FLAG_HAS_SUBVIEWS: u8 = 1 << 1;
35pub(super) const LAYOUT_FLAG_DIRTY_DESCENDANT: u8 = 1 << 2;
36pub(super) const LAYOUT_FLAG_CLAIMED: u8 = 1 << 3;
37pub(super) const LAYOUT_FLAG_MULTI_MOUNTED: u8 = 1 << 4;
38pub(super) const LAYOUT_FLAG_PARENT_NON_AUTO_W: u8 = 1 << 5;
39pub(super) const LAYOUT_FLAG_PARENT_NON_AUTO_H: u8 = 1 << 6;
40
41pub(crate) struct PodSlot {
42 pub(super) vtable: Option<&'static PodVTable>,
43 pub(crate) cached_element: Cell<*const Element<'static>>,
44 pub(crate) cached_layout: Cell<*mut u8>,
45 pub(crate) cached_bounds: Cell<Region>,
46 pub(crate) render_count: Cell<u32>,
47 pub(crate) generation: u16,
48 pub(crate) readers_mask: Cell<ReadersMask>,
49 pub(crate) pass1_min_w: Cell<i16>,
50 pub(crate) pass1_pref_w: Cell<i16>,
51 pub(crate) pass3_min_h: Cell<i16>,
52 pub(crate) pass3_pref_h: Cell<i16>,
53 pub(crate) dirty: bool,
54 pub(crate) active_readers: Cell<u8>,
55 state_flags: Cell<u8>,
56 pub(crate) layout_flags: Cell<u8>,
57 heap_ptr: *mut u8,
58}
59
60impl PodSlot {
61 const fn empty() -> Self {
62 Self {
63 vtable: None,
64 cached_element: Cell::new(core::ptr::null()),
65 cached_layout: Cell::new(core::ptr::null_mut()),
66 cached_bounds: Cell::new(Region::EMPTY),
67 render_count: Cell::new(0),
68 generation: 0,
69 readers_mask: Cell::new(0),
70 pass1_min_w: Cell::new(0),
71 pass1_pref_w: Cell::new(0),
72 pass3_min_h: Cell::new(0),
73 pass3_pref_h: Cell::new(0),
74 dirty: false,
75 active_readers: Cell::new(0),
76 state_flags: Cell::new(0),
77 layout_flags: Cell::new(0),
78 heap_ptr: core::ptr::null_mut(),
79 }
80 }
81
82 #[inline(always)]
83 pub(super) const fn occupied(&self) -> bool {
84 self.vtable.is_some()
85 }
86
87 #[inline(always)]
88 pub(super) fn is_borrowed(&self) -> bool {
89 (self.state_flags.get() & STATE_FLAG_BORROWED) != 0
90 }
91
92 #[inline(always)]
93 pub(super) fn set_borrowed(&self, val: bool) {
94 if val {
95 self.state_flags
96 .set(self.state_flags.get() | STATE_FLAG_BORROWED);
97 } else {
98 self.state_flags
99 .set(self.state_flags.get() & !STATE_FLAG_BORROWED);
100 }
101 }
102
103 #[inline(always)]
104 pub(super) fn is_expanding(&self) -> bool {
105 (self.state_flags.get() & STATE_FLAG_EXPANDING) != 0
106 }
107
108 #[inline(always)]
109 pub(super) fn set_expanding(&self, val: bool) {
110 if val {
111 self.state_flags
112 .set(self.state_flags.get() | STATE_FLAG_EXPANDING);
113 } else {
114 self.state_flags
115 .set(self.state_flags.get() & !STATE_FLAG_EXPANDING);
116 }
117 }
118
119 #[inline(always)]
120 pub(super) fn set_needs_next_frame(&self, val: bool) {
121 if val {
122 self.state_flags
123 .set(self.state_flags.get() | STATE_FLAG_NEEDS_NEXT_FRAME);
124 } else {
125 self.state_flags
126 .set(self.state_flags.get() & !STATE_FLAG_NEEDS_NEXT_FRAME);
127 }
128 }
129
130 #[inline(always)]
131 fn take_needs_next_frame(&self) -> bool {
132 let flags = self.state_flags.get();
133 let had = (flags & STATE_FLAG_NEEDS_NEXT_FRAME) != 0;
134 if had {
135 self.state_flags.set(flags & !STATE_FLAG_NEEDS_NEXT_FRAME);
136 }
137 had
138 }
139
140 #[inline(always)]
141 fn reset_runtime_state(&mut self, dirty: bool) {
142 self.dirty = dirty;
143 self.state_flags.set(0);
144 self.layout_flags.set(0);
145 self.active_readers.set(0);
146 self.readers_mask.set(0);
147 self.pass1_min_w.set(0);
148 self.pass1_pref_w.set(0);
149 self.pass3_min_h.set(0);
150 self.pass3_pref_h.set(0);
151 self.render_count.set(0);
152 self.cached_element.set(core::ptr::null());
153 self.cached_layout.set(core::ptr::null_mut());
154 self.cached_bounds.set(Region::EMPTY);
155 }
156}
157
158pub struct PodReadGuard<'s, T: View> {
163 value: &'s T,
164 readers: &'s Cell<u8>,
165}
166
167impl<T: View> core::ops::Deref for PodReadGuard<'_, T> {
168 type Target = T;
169
170 #[inline(always)]
171 fn deref(&self) -> &Self::Target {
172 self.value
173 }
174}
175
176impl<T: View> Drop for PodReadGuard<'_, T> {
177 #[inline(always)]
178 fn drop(&mut self) {
179 self.readers.set(self.readers.get().saturating_sub(1));
180 }
181}
182pub struct PodPool {
185 pool_id: Cell<u16>,
186 pub(crate) skipped_renders: Cell<u16>,
187 pub(crate) relayout_boundary_hits: Cell<u16>,
188 pub(super) slots: std::vec::Vec<PodSlot>,
189 dirty_queue: SmallVec<PodId, MAX_PODS>,
190 external_dirty: bool,
194 _not_send_sync: PhantomData<*mut ()>,
195}
196
197impl Default for PodPool {
198 fn default() -> Self {
199 Self::new()
200 }
201}
202
203impl Drop for PodPool {
204 fn drop(&mut self) {
205 let pid = self.pool_id.get();
206 for (idx, slot) in self.slots.iter_mut().enumerate() {
207 if let Some(vt) = slot.vtable.take() {
208 crate::signal::remove_pod_subscriptions(pid, PodId(idx as u16));
209 if !slot.heap_ptr.is_null() {
210 let ptr = slot.heap_ptr;
211 slot.heap_ptr = core::ptr::null_mut();
212 unsafe {
213 (vt.drop_fn)(ptr);
214 }
215 }
216 }
217 }
218 }
219}
220
221impl PodPool {
222 pub const fn new() -> Self {
224 Self {
225 pool_id: Cell::new(0),
226 skipped_renders: Cell::new(0),
227 relayout_boundary_hits: Cell::new(0),
228 slots: std::vec::Vec::new(),
229 dirty_queue: SmallVec::new(),
230 external_dirty: false,
231 _not_send_sync: PhantomData,
232 }
233 }
234
235 #[inline(always)]
236 pub(crate) fn ensure_pool_id(&self) -> u16 {
237 let id = self.pool_id.get();
238 if id != 0 {
239 id
240 } else {
241 let next = crate::signal::alloc_pool_id();
242 self.pool_id.set(next);
243 next
244 }
245 }
246
247 #[inline(always)]
248 pub(super) fn slot_storage_ptr(&self, slot: &PodSlot) -> *mut u8 {
249 slot.heap_ptr
250 }
251
252 pub fn try_insert<V: View>(&mut self, view: V) -> Option<Handle<V>> {
254
255 unsafe fn render_trampoline<V: View>(
256 ptr: *mut u8,
257 frame_ptr: *mut FrameScope,
258 ) -> Element<'static> {
259 unsafe {
260 let view = &mut *(ptr as *mut V);
261 let scope_ptr = frame_ptr as *mut Scope<V>;
262 let el = view.render(&mut *scope_ptr);
263 core::mem::transmute::<Element<'_>, Element<'static>>(el)
264 }
265 }
266
267 unsafe fn drop_trampoline<V>(ptr: *mut u8) {
268 unsafe {
269 let _ = std::boxed::Box::from_raw(ptr as *mut V);
270 }
271 }
272
273 let vtable: &'static PodVTable = &PodVTable {
274 type_id: TypeId::of::<V>,
275 render_fn: render_trampoline::<V>,
276 drop_fn: drop_trampoline::<V>,
277 };
278
279 if self.slots.is_empty() {
280 self.slots.resize_with(MAX_PODS, PodSlot::empty);
281 }
282
283 let mut target_idx = self.slots.iter().position(|s| !s.occupied());
284 if target_idx.is_none() && self.slots.len() < u16::MAX as usize {
285 target_idx = Some(self.slots.len());
286 self.slots.push(PodSlot::empty());
287 }
288 let idx = target_idx?;
289 let slot = &mut self.slots[idx];
290 let boxed = std::boxed::Box::new(view);
291 slot.heap_ptr = std::boxed::Box::into_raw(boxed) as *mut u8;
292 slot.vtable = Some(vtable);
293 slot.reset_runtime_state(true);
294 let generation = slot.generation;
295 let pod_id = PodId(idx as u16);
296 self.mark_dirty(pod_id);
297 Some(Handle::with_generation(pod_id, generation))
298 }
299
300 pub fn insert<V: View>(&mut self, view: V) -> Handle<V> {
302 self.try_insert(view)
303 .expect("PodPool slot capacity exhausted")
304 }
305
306 pub fn remove<V: View>(&mut self, handle: Handle<V>) -> bool {
308 let idx = handle.id.0 as usize;
309 let Some(slot) = self.slots.get_mut(idx) else {
310 return false;
311 };
312 if slot.is_borrowed() || slot.active_readers.get() > 0 || slot.generation != handle.generation {
313 return false;
314 }
315 let Some(vt) = slot.vtable else {
316 return false;
317 };
318 if (vt.type_id)() != TypeId::of::<V>() {
319 return false;
320 }
321 let vt = slot.vtable.take().unwrap();
322 slot.generation = slot.generation.wrapping_add(1);
323 slot.reset_runtime_state(false);
324 crate::signal::remove_pod_subscriptions(self.pool_id.get(), handle.id);
325 if !slot.heap_ptr.is_null() {
326 let ptr = slot.heap_ptr;
327 slot.heap_ptr = core::ptr::null_mut();
328 unsafe {
329 (vt.drop_fn)(ptr);
330 }
331 }
332 if let Some(pos) = self.dirty_queue.iter().position(|&x| x == handle.id) {
333 self.dirty_queue.remove(pos);
334 }
335 self.invalidate_all_cached_elements();
336 true
337 }
338
339 #[inline]
341 pub fn contains_pod(&self, id: PodId) -> bool {
342 self.slots
343 .get(id.0 as usize)
344 .map(|s| s.occupied())
345 .unwrap_or(false)
346 }
347
348 pub fn get_mut<V: View>(&mut self, handle: Handle<V>) -> Option<&mut V> {
350 let idx = handle.id.0 as usize;
351 let slot = self.slots.get(idx)?;
352 if slot.is_borrowed() || slot.active_readers.get() > 0 || slot.generation != handle.generation {
353 return None;
354 }
355 let vt = slot.vtable?;
356 if (vt.type_id)() == TypeId::of::<V>() {
357 slot.cached_element.set(core::ptr::null());
358 slot.layout_flags
359 .set(slot.layout_flags.get() & !LAYOUT_FLAG_SUBTREE_CLEAN);
360 let ptr = self.slot_storage_ptr(slot) as *mut V;
361 Some(unsafe { &mut *ptr })
362 } else {
363 None
364 }
365 }
366
367 pub fn update<V: View, R>(&mut self, handle: Handle<V>, f: impl FnOnce(&mut V) -> R) -> Option<R> {
369 let idx = handle.id.0 as usize;
370 let slot = self.slots.get(idx)?;
371 if slot.is_borrowed() || slot.active_readers.get() > 0 || slot.generation != handle.generation {
372 return None;
373 }
374 let vt = slot.vtable?;
375 if (vt.type_id)() != TypeId::of::<V>() {
376 return None;
377 }
378 slot.set_borrowed(true);
379 let ptr = self.slot_storage_ptr(slot);
380 let res = f(unsafe { &mut *(ptr as *mut V) });
381 slot.set_borrowed(false);
382 if size_of::<V>() > 0 {
383 self.mark_dirty(handle.id);
384 }
385 self.flush_signal_dirty_pods();
386 Some(res)
387 }
388
389 pub fn get<V: View>(&self, handle: Handle<V>) -> Option<&V> {
391 let idx = handle.id.0 as usize;
392 let slot = self.slots.get(idx)?;
393 if slot.is_borrowed() || slot.generation != handle.generation {
394 return None;
395 }
396 let vt = slot.vtable?;
397 if (vt.type_id)() == TypeId::of::<V>() {
398 let ptr = self.slot_storage_ptr(slot) as *const V;
399 Some(unsafe { &*ptr })
400 } else {
401 None
402 }
403 }
404
405 pub fn read_guarded<V: View>(&self, handle: Handle<V>) -> Option<PodReadGuard<'_, V>> {
407 let idx = handle.id.0 as usize;
408 let slot = self.slots.get(idx)?;
409 if slot.is_borrowed() || slot.generation != handle.generation {
410 return None;
411 }
412 let vt = slot.vtable?;
413 if (vt.type_id)() == TypeId::of::<V>() {
414 slot.active_readers
415 .set(slot.active_readers.get().saturating_add(1));
416 let ptr = self.slot_storage_ptr(slot) as *const V;
417 Some(PodReadGuard {
418 value: unsafe { &*ptr },
419 readers: &slot.active_readers,
420 })
421 } else {
422 None
423 }
424 }
425
426 pub(crate) fn acquire_raw_mut(
428 &self,
429 id: PodId,
430 expected_gen: Option<u16>,
431 expected_type: TypeId,
432 ) -> Option<*mut u8> {
433 let slot = self.slots.get(id.0 as usize)?;
434 if slot.is_borrowed() || slot.active_readers.get() > 0 {
435 return None;
436 }
437 if let Some(g) = expected_gen {
438 if slot.generation != g {
439 return None;
440 }
441 }
442 let vt = slot.vtable?;
443 if (vt.type_id)() == expected_type {
444 slot.set_borrowed(true);
445 Some(self.slot_storage_ptr(slot))
446 } else {
447 None
448 }
449 }
450
451 #[inline]
453 pub(crate) fn current_generation_for_type(
454 &self,
455 id: PodId,
456 expected_type: TypeId,
457 ) -> Option<u16> {
458 let slot = self.slots.get(id.0 as usize)?;
459 let vt = slot.vtable?;
460 if (vt.type_id)() == expected_type {
461 Some(slot.generation)
462 } else {
463 None
464 }
465 }
466
467 #[inline]
469 pub(crate) fn release_borrow(&self, id: PodId) {
470 if let Some(slot) = self.slots.get(id.0 as usize) {
471 slot.set_borrowed(false);
472 }
473 }
474
475 #[inline]
477 pub(crate) fn record_cross_read(&self, reader: PodId, target: PodId) {
478 let bits = (size_of::<ReadersMask>() * 8) as u16;
479 if reader.0 < bits {
480 if let Some(slot) = self.slots.get(target.0 as usize) {
481 let bit: ReadersMask = 1 << reader.0;
482 slot.readers_mask.set(slot.readers_mask.get() | bit);
483 }
484 }
485 }
486
487 #[inline]
489 pub fn flush_signal_dirty_pods(&mut self) {
490 let pid = self.ensure_pool_id();
491 crate::signal::drain_pending_dirty_pods(pid, |pod_id| {
492 self.mark_dirty(pod_id);
493 });
494 }
495
496 pub fn mark_dirty(&mut self, id: PodId) {
498 let mut cascade_mask: ReadersMask = 0;
499 if let Some(slot) = self.slots.get_mut(id.0 as usize) {
500 if slot.occupied() {
501 slot.dirty = true;
502 self.external_dirty = true;
503 slot.cached_element.set(core::ptr::null());
504 slot.layout_flags
505 .set(slot.layout_flags.get() & !LAYOUT_FLAG_SUBTREE_CLEAN);
506 cascade_mask = slot.readers_mask.get();
507 if !self.dirty_queue.iter().any(|&x| x == id) {
508 self.dirty_queue.push(id);
509 }
510 }
511 }
512 while cascade_mask != 0 {
513 let bit = cascade_mask.trailing_zeros() as u16;
514 cascade_mask &= cascade_mask - 1;
515 let reader_id = PodId(bit);
516 if reader_id != id {
517 if let Some(r_slot) = self.slots.get_mut(reader_id.0 as usize) {
518 if r_slot.occupied() && !r_slot.dirty {
519 r_slot.dirty = true;
520 r_slot.cached_element.set(core::ptr::null());
521 r_slot
522 .layout_flags
523 .set(r_slot.layout_flags.get() & !LAYOUT_FLAG_SUBTREE_CLEAN);
524 cascade_mask |= r_slot.readers_mask.get();
525 if !self.dirty_queue.iter().any(|&x| x == reader_id) {
526 self.dirty_queue.push(reader_id);
527 }
528 }
529 }
530 }
531 }
532 }
533
534 #[inline]
536 pub fn invalidate_all_cached_elements(&self) {
537 for slot in self.slots.iter() {
538 slot.cached_element.set(core::ptr::null());
539 slot.cached_layout.set(core::ptr::null_mut());
540 slot.layout_flags.set(0);
541 }
542 }
543
544 pub fn mark_all_dirty(&mut self) {
546 for (idx, slot) in self.slots.iter_mut().enumerate() {
547 if slot.occupied() {
548 slot.dirty = true;
549 self.external_dirty = true;
550 slot.cached_element.set(core::ptr::null());
551 slot.cached_layout.set(core::ptr::null_mut());
552 slot.layout_flags.set(0);
553 let id = PodId(idx as u16);
554 if !self.dirty_queue.iter().any(|&x| x == id) {
555 self.dirty_queue.push(id);
556 }
557 }
558 }
559 }
560
561 #[inline]
563 pub fn render_count(&self, id: PodId) -> u32 {
564 self.slots
565 .get(id.0 as usize)
566 .map(|s| s.render_count.get())
567 .unwrap_or(0)
568 }
569
570 #[inline]
572 pub fn skipped_render_count(&self) -> u32 {
573 self.skipped_renders.get() as u32
574 }
575
576 #[inline]
578 pub fn relayout_boundary_hits(&self) -> u32 {
579 self.relayout_boundary_hits.get() as u32
580 }
581
582 #[inline]
584 pub fn is_dirty(&self, id: PodId) -> bool {
585 self.slots
586 .get(id.0 as usize)
587 .map(|s| s.occupied() && s.dirty)
588 .unwrap_or(false)
589 }
590
591 #[inline]
593 pub fn has_dirty(&self) -> bool {
594 !self.dirty_queue.is_empty()
595 }
596
597 #[inline]
599 pub fn has_external_dirty(&self) -> bool {
600 self.external_dirty
601 }
602
603 #[inline]
605 pub fn has_any_clean_occupied(&self) -> bool {
606 self.slots
607 .iter()
608 .any(|s| s.occupied() && !s.dirty && !s.cached_element.get().is_null())
609 }
610
611 #[inline]
613 pub fn dirty_pods(&self) -> &[PodId] {
614 self.dirty_queue.as_slice()
615 }
616
617 #[inline]
619 pub fn cached_bounds(&self, id: PodId) -> Region {
620 self.slots
621 .get(id.0 as usize)
622 .map(|s| s.cached_bounds.get())
623 .unwrap_or(Region::EMPTY)
624 }
625
626 #[inline]
628 pub fn set_cached_bounds(&mut self, id: PodId, bounds: Region) {
629 if let Some(slot) = self.slots.get_mut(id.0 as usize) {
630 slot.cached_bounds.set(bounds);
631 }
632 }
633
634 pub fn clear_dirty(&mut self) {
636 self.dirty_queue.clear();
637 self.external_dirty = false;
638 for (idx, slot) in self.slots.iter_mut().enumerate() {
639 if slot.occupied() && slot.take_needs_next_frame() {
640 slot.dirty = true;
641 slot.cached_element.set(core::ptr::null());
642 slot.layout_flags
643 .set(slot.layout_flags.get() & !LAYOUT_FLAG_SUBTREE_CLEAN);
644 self.dirty_queue.push(PodId(idx as u16));
645 } else {
646 slot.dirty = false;
647 }
648 }
649 }
650
651}