use std::{cell::RefCell, rc::Rc};
use cranpose_core::NodeId;
use cranpose_ui_graphics::{Rect, Size};
use cranpose_ui_layout::{MeasurePolicy, Placement};
use super::{ChildPlacement, LayoutCells, NodeCache};
use crate::{
layout::{LayoutChildMeasureState, LayoutRuntimeState},
render_state::AppContext,
};
pub(crate) struct LayoutParts {
cache: NodeCache,
layout_state: LayoutCells,
runtime_state: RefCell<LayoutRuntimeState>,
record: LayoutChildMeasureState,
}
impl LayoutParts {
pub(crate) fn new(runtime_state: LayoutRuntimeState) -> Self {
Self {
cache: NodeCache::default(),
layout_state: LayoutCells::default(),
runtime_state: RefCell::new(runtime_state),
record: LayoutChildMeasureState::default(),
}
}
pub(crate) fn empty() -> Self {
Self::new(LayoutRuntimeState::new(
super::layout_node::empty_measure_policy(),
))
}
pub(crate) fn release_for_recycle(&self) {
self.cache.advance_revision();
self.record.start_over();
self.runtime_state.borrow_mut().release_for_recycle();
}
#[inline]
pub(crate) fn refill(
parts: &Rc<Self>,
policy: Rc<dyn MeasurePolicy>,
) -> Result<(), Rc<dyn MeasurePolicy>> {
if Rc::strong_count(parts) != 1 {
return Err(policy);
}
Self::refill_held(parts, policy)
}
#[inline(never)]
fn refill_held(
parts: &Rc<Self>,
policy: Rc<dyn MeasurePolicy>,
) -> Result<(), Rc<dyn MeasurePolicy>> {
let mut runtime_state = parts.runtime_state.borrow_mut();
if Rc::weak_count(parts) != runtime_state.own_parts_handles() {
return Err(policy);
}
runtime_state.refill(policy)?;
parts.cache.start_over();
parts.layout_state.start_over();
Ok(())
}
pub(crate) fn cache(&self) -> &NodeCache {
&self.cache
}
pub(crate) fn layout_state(&self) -> &LayoutCells {
&self.layout_state
}
pub(crate) fn record(&self) -> &LayoutChildMeasureState {
&self.record
}
pub(crate) fn place(
&self,
node_id: Option<NodeId>,
at: ChildPlacement,
placer: Option<NodeId>,
context: &AppContext,
) {
self.layout_state.place_child(node_id, at, placer, context);
}
pub(crate) fn set_size(&self, node_id: Option<NodeId>, size: Size, context: &AppContext) {
self.layout_state.set_size(node_id, size, context);
}
pub(crate) fn clear_placed(&self, node_id: Option<NodeId>, context: &AppContext) {
self.layout_state.clear_placed(node_id, context);
}
pub(crate) fn note_child_placements(&self, placements: &[Placement]) {
let with_z = placements.iter().any(|placement| placement.z_index != 0.0);
self.layout_state.set_places_children_with_z_index(with_z);
}
pub(crate) fn runtime_state(&self) -> &RefCell<LayoutRuntimeState> {
&self.runtime_state
}
pub(crate) fn placed_coordinator_rect(&self, ordinal: usize, node_size: Size) -> Option<Rect> {
self.runtime_state
.borrow()
.placed_coordinator_rect(ordinal, node_size)
}
}
impl Drop for LayoutParts {
fn drop(&mut self) {
if self.layout_state.places_children_with_z_index() {
super::layout_state::count_z_index_placer(false);
}
}
}