use std::cell::{Cell, RefCell};
use cranpose_core::{NodeId, PackedU64, collections::growth_slack::GrowthSlack};
use crate::modifier::{Point, Size};
pub(crate) struct PlacementPass {
id: Cell<u64>,
unplaced: Cell<usize>,
cleared: RefCell<Vec<NodeId>>,
left_unplaced: RefCell<Vec<NodeId>>,
}
impl PlacementPass {
pub(crate) const fn new() -> Self {
Self {
id: Cell::new(1),
unplaced: Cell::new(0),
cleared: RefCell::new(Vec::new()),
left_unplaced: RefCell::new(Vec::new()),
}
}
pub(crate) fn begin(&self) {
self.id.set(self.id.get() + 1);
self.unplaced.set(0);
self.cleared.borrow_mut().clear();
}
pub(crate) fn trim(&self) {
self.cleared.borrow_mut().trim_growth_slack();
self.left_unplaced.borrow_mut().trim_growth_slack();
}
pub(crate) fn take_cleared(&self) -> Vec<NodeId> {
std::mem::take(&mut *self.cleared.borrow_mut())
}
pub(crate) fn keep_cleared(&self, cleared: Vec<NodeId>) {
*self.cleared.borrow_mut() = cleared;
}
pub(crate) fn keep_unplaced(&self, nodes: &[NodeId]) {
self.left_unplaced.borrow_mut().extend_from_slice(nodes);
}
pub(crate) fn take_unplaced(&self, output: &mut Vec<NodeId>) {
output.clear();
std::mem::swap(&mut *self.left_unplaced.borrow_mut(), output);
}
pub(crate) fn with_unplaced_nodes(&self) -> Option<u64> {
(self.unplaced.get() > 0).then(|| self.id.get())
}
pub(super) fn clear(&self, node_id: Option<NodeId>) -> u64 {
self.unplaced.set(self.unplaced.get() + 1);
if let Some(node_id) = node_id {
self.cleared.borrow_mut().push(node_id);
}
self.id.get()
}
pub(super) fn restore(&self, cleared_in: u64) -> bool {
let restored = cleared_in == self.id.get();
if restored {
self.unplaced.set(self.unplaced.get().saturating_sub(1));
}
restored
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct LayoutState {
pub(super) size: Size,
pub(super) position: Point,
pub(super) is_placed: bool,
pub(super) cleared_in_pass: PackedU64,
pub(super) content_offset: Point,
pub(super) z_index: f32,
pub(super) places_children_with_z_index: bool,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct ChildPlacement {
pub(super) position: Point,
pub(super) z_index: f32,
}
impl ChildPlacement {
pub(crate) fn new(position: Point, z_index: f32) -> Self {
Self { position, z_index }
}
}
impl LayoutState {
pub fn size(&self) -> Size {
self.size
}
pub fn position(&self) -> Point {
self.position
}
pub fn content_offset(&self) -> Point {
self.content_offset
}
pub fn at_origin(mut self) -> Self {
self.position = Point::default();
self
}
pub fn is_placed(&self) -> bool {
self.is_placed
}
pub fn z_index(&self) -> f32 {
self.z_index
}
pub fn places_children_with_z_index(&self) -> bool {
self.places_children_with_z_index
}
pub(crate) fn unplaced_in(&self, pass: u64) -> bool {
!self.is_placed && self.cleared_in_pass.get() == pass
}
}
pub(super) fn count_z_index_placer(places: bool) {
crate::thread_state::cells(|cells| {
let reasons = &cells.z_order_reasons;
reasons.set(if places {
reasons.get() + 1
} else {
reasons.get().saturating_sub(1)
});
});
}