use std::cell::Cell;
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub struct EdgeInsets {
pub left: f32,
pub top: f32,
pub right: f32,
pub bottom: f32,
}
impl EdgeInsets {
pub const ZERO: Self = Self {
left: 0.0,
top: 0.0,
right: 0.0,
bottom: 0.0,
};
pub fn all(v: f32) -> Self {
Self {
left: v,
top: v,
right: v,
bottom: v,
}
}
}
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub struct WindowInsets {
pub safe_area: EdgeInsets,
pub ime: EdgeInsets,
}
impl WindowInsets {
pub const ZERO: Self = Self {
safe_area: EdgeInsets::ZERO,
ime: EdgeInsets::ZERO,
};
pub fn effective(&self) -> EdgeInsets {
EdgeInsets {
left: self.safe_area.left.max(self.ime.left),
top: self.safe_area.top.max(self.ime.top),
right: self.safe_area.right.max(self.ime.right),
bottom: self.safe_area.bottom.max(self.ime.bottom),
}
}
}
#[derive(Default)]
struct InsetsDomain {
insets: Cell<WindowInsets>,
generation: Cell<u64>,
ime_refocus: Cell<bool>,
}
fn domain() -> std::rc::Rc<InsetsDomain> {
crate::core::app_context::current_app().extension::<InsetsDomain>()
}
pub fn window_insets() -> WindowInsets {
domain().insets.get()
}
pub fn insets_generation() -> u64 {
domain().generation.get()
}
pub fn set_window_insets(new: WindowInsets) {
let dom = domain();
let old = dom.insets.get();
if old == new {
return;
}
dom.insets.set(new);
dom.generation.set(dom.generation.get().wrapping_add(1));
if old.ime != new.ime {
dom.ime_refocus.set(true);
}
crate::core::dirty_registry::defer_action(move |arena, root, _| {
if let Some(el) = arena.get(root) {
el.dirty
.set(el.dirty.get() | crate::core::element::DirtyFlags::MEASURE);
}
crate::core::dirty_registry::register_dirty(
root,
crate::core::element::DirtyFlags::MEASURE,
);
crate::core::dirty_registry::bump_subtree_gen(root);
});
}
pub(crate) fn take_ime_refocus() -> bool {
domain().ime_refocus.replace(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn effective_is_per_edge_max() {
let w = WindowInsets {
safe_area: EdgeInsets {
left: 5.0,
top: 40.0,
right: 0.0,
bottom: 20.0,
},
ime: EdgeInsets {
left: 0.0,
top: 0.0,
right: 8.0,
bottom: 260.0,
},
};
let e = w.effective();
assert_eq!(e.left, 5.0);
assert_eq!(e.top, 40.0);
assert_eq!(e.right, 8.0);
assert_eq!(e.bottom, 260.0);
}
}