use ribir_geom::{Point, Size};
use super::{WidgetCtx, WidgetCtxImpl};
use crate::{
prelude::ProviderCtx,
widget::{BoxClamp, WidgetTree},
widget_tree::WidgetId,
window::DelayEvent,
};
pub struct LayoutCtx<'a> {
id: WidgetId,
tree: &'a mut WidgetTree,
provider_ctx: ProviderCtx,
}
impl<'a> WidgetCtxImpl for LayoutCtx<'a> {
#[inline]
fn id(&self) -> WidgetId { self.id }
#[inline]
fn tree(&self) -> &WidgetTree { self.tree }
}
impl<'a> LayoutCtx<'a> {
pub(crate) fn new(id: WidgetId, tree: &'a mut WidgetTree) -> Self {
let provider_ctx = if let Some(p) = id.parent(tree) {
ProviderCtx::collect_from(p, tree)
} else {
ProviderCtx::default()
};
Self { id, tree, provider_ctx }
}
pub(crate) fn perform_layout(&mut self, clamp: BoxClamp) -> Size {
let tree2 = unsafe { &*(self.tree as *mut WidgetTree) };
let id = self.id();
debug_assert!(clamp.min.is_finite());
let size = id.assert_get(tree2).perform_layout(clamp, self);
debug_assert!(size.is_finite());
let info = self.tree.store.layout_info_or_default(id);
info.clamp = clamp;
info.size = Some(size);
self
.window()
.add_delay_event(DelayEvent::PerformedLayout(id));
size
}
pub fn perform_child_layout(&mut self, child: WidgetId, clamp: BoxClamp) -> Size {
let size = self
.get_calculated_size(child, clamp)
.unwrap_or_else(|| {
self.update_position(child, Point::zero());
let id = std::mem::replace(&mut self.id, child);
let size = self.perform_layout(clamp);
self.id = id;
size
});
self.provider_ctx.pop_providers_for(self.id);
size
}
#[inline]
pub fn update_position(&mut self, child: WidgetId, pos: Point) {
self.tree.store.layout_info_or_default(child).pos = pos;
}
#[inline]
pub fn position(&mut self, child: WidgetId) -> Option<Point> {
self
.tree
.store
.layout_info(child)
.map(|info| info.pos)
}
#[inline]
pub fn update_size(&mut self, child: WidgetId, size: Size) {
self.tree.store.layout_info_or_default(child).size = Some(size);
}
pub fn split_children(&mut self) -> (&mut Self, impl Iterator<Item = WidgetId> + '_) {
let tree = unsafe { &*(self.tree as *mut WidgetTree) };
let id = self.id;
(self, id.children(tree))
}
pub fn perform_single_child_layout(&mut self, clamp: BoxClamp) -> Option<Size> {
self
.single_child()
.map(|child| self.perform_child_layout(child, clamp))
}
pub fn assert_perform_single_child_layout(&mut self, clamp: BoxClamp) -> Size {
let child = self.assert_single_child();
self.perform_child_layout(child, clamp)
}
#[inline]
pub fn force_child_relayout(&mut self, child: WidgetId) -> bool {
assert_eq!(child.parent(self.tree), Some(self.id));
self.tree.store.force_layout(child).is_some()
}
fn get_calculated_size(&self, child: WidgetId, clamp: BoxClamp) -> Option<Size> {
let info = self.tree.store.layout_info(child)?;
if info.clamp == clamp { info.size } else { None }
}
}
impl<'w> AsRef<ProviderCtx> for LayoutCtx<'w> {
fn as_ref(&self) -> &ProviderCtx { &self.provider_ctx }
}
impl<'w> AsMut<ProviderCtx> for LayoutCtx<'w> {
fn as_mut(&mut self) -> &mut ProviderCtx { &mut self.provider_ctx }
}