use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use crate::arena::Arena;
use crate::id::{ElementId, LayerId};
use crate::paint::{LayerEffect, PaintList};
use crate::reactive::SubscriberId;
pub use crate::render_object::{make_ro_shared, SharedRO};
use crate::render_object::{BoxConstraints, LayoutContext, RRectRenderObject, RenderObject};
use crate::widget::{State, Widget, WidgetNode};
use crate::{Color, GestureState, KeyCode, Point, Rect, Size, WidgetEvent};
pub struct Element {
pub(crate) id: ElementId,
pub(crate) parent: Option<ElementId>,
pub(crate) children: Vec<ElementId>,
pub(crate) widget: WidgetNode,
pub(crate) render_object: SharedRO,
pub(crate) subscriber_id: SubscriberId,
pub(crate) dirty: bool,
pub(crate) needs_ro_sync: bool,
pub(crate) subtree_ro_dirty: bool,
pub(crate) ro_replaced: bool,
pub(crate) active: bool,
pub(crate) state: Option<Box<dyn State>>,
pub(crate) layer: Option<LayerId>,
pub(crate) layout_offset: Point,
pub(crate) visible_in_parent: bool,
dependents: HashSet<ElementId>,
pub(crate) is_inherited: bool,
pub(crate) inherited_stale: bool,
}
impl Element {
pub fn id(&self) -> ElementId {
self.id
}
pub fn parent(&self) -> Option<ElementId> {
self.parent
}
pub fn children(&self) -> &[ElementId] {
&self.children
}
pub fn widget(&self) -> &WidgetNode {
&self.widget
}
pub fn render_object(&self) -> &SharedRO {
&self.render_object
}
pub fn is_active(&self) -> bool {
self.active
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn state(&self) -> Option<&dyn State> {
self.state.as_deref()
}
pub fn state_mut(&mut self) -> Option<&mut dyn State> {
self.state.as_deref_mut()
}
pub fn state_box_mut(&mut self) -> Option<&mut Box<dyn State>> {
self.state.as_mut()
}
pub fn layer(&self) -> Option<LayerId> {
self.layer
}
pub fn layout_offset(&self) -> Point {
self.layout_offset
}
pub fn is_inherited(&self) -> bool {
self.is_inherited
}
pub fn subscriber_id(&self) -> SubscriberId {
self.subscriber_id
}
}
pub fn locate_element_in_ro_tree(ro: &dyn RenderObject, id: ElementId, origin: Point) -> Option<(Point, Size)> {
if ro.element_id() == Some(id) {
return Some((origin, ro.content_size()));
}
let mut found = None;
ro.for_each_child(&mut |off, child| {
if found.is_some() {
return;
}
let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
if let Some(pair) = locate_element_in_ro_tree(child.borrow().as_ref(), id, child_origin) {
found = Some(pair);
}
});
found
}
pub fn locate_element_via_tree_pair(
tree: &ElementTree,
ro: &dyn RenderObject,
target: ElementId,
cur_el: ElementId,
origin: Point,
) -> Option<Point> {
if cur_el == target {
return Some(origin);
}
let child_ids: Vec<ElementId> = tree.elements.get(cur_el).map(|el| el.children.clone()).unwrap_or_default();
let mut index = 0usize;
let mut found = None;
ro.for_each_child(&mut |off, child_ro| {
if found.is_some() {
return;
}
if let Some(&cid) = child_ids.get(index) {
let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
if let Some(p) = locate_element_via_tree_pair(tree, child_ro.borrow().as_ref(), target, cid, child_origin) {
found = Some(p);
}
}
index += 1;
});
found
}
pub type TextMeasurer = fn(&str, f32, Option<f32>) -> (f32, f32);
pub struct ElementTree {
pub(crate) elements: Arena<ElementId, Element>,
pub(crate) root: Option<ElementId>,
inactive: HashMap<InactiveKey, Vec<ElementId>>,
inactive_total: usize,
focused: Option<ElementId>,
focus_visible: bool,
focus_within_ancestors: Vec<ElementId>,
pointer_capture: Option<ElementId>,
gesture_winner: Option<ElementId>,
pointer_down_chain: Vec<ElementId>,
overlays: Vec<OverlayEntry>,
next_overlay_handle: u32,
subscriber_to_element: HashMap<crate::reactive::SubscriberId, ElementId>,
pub(crate) layer_tree: LayerTree,
z_order_counter: u32,
last_hit_target: Option<ElementId>,
build_requests: Vec<ElementId>,
event_chain: Vec<ElementId>,
paint_slots: Vec<Option<LayerPaint>>,
top_layers_scratch: Vec<LayerId>,
last_layout_ns: u64,
last_paint_ns: u64,
pub(crate) text_measurer: Option<TextMeasurer>,
stateful_registry: Vec<ElementId>,
stateful_set: HashSet<ElementId>,
overlay_aware_registry: Vec<ElementId>,
repaint_generation: u64,
viewport_size: Option<Size>,
semantics_revision: u64,
reactive_scope: u64,
layer_order_dirty: bool,
full_layout_needed: bool,
signal_dirty_elements: Vec<ElementId>,
last_any_signal_epoch: u64,
origin_cache: RefCell<Option<HashMap<ElementId, (Point, usize)>>>,
focus_chain_cache: RefCell<Option<(u64, Vec<ElementId>)>>,
}
static RESOURCE_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static NEXT_REACTIVE_SCOPE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn next_reactive_scope() -> u64 {
NEXT_REACTIVE_SCOPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
pub fn request_full_repaint() {
RESOURCE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn resource_epoch() -> u64 {
RESOURCE_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
}
mod dirty;
mod event;
mod layer;
mod overlay;
mod overlay_host;
pub use layer::{paint_frame, FramePaint, Layer, LayerPaint, LayerTree};
use overlay::OverlayEntry;
pub use overlay::OverlayHandle;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct InactiveKey {
type_id: TypeId,
key: Option<u64>, }
fn inactive_key(widget: &WidgetNode) -> InactiveKey {
let type_id = widget.type_id();
let key_hash = widget.0.key();
InactiveKey { type_id, key: key_hash }
}
impl Default for ElementTree {
fn default() -> Self {
Self::new()
}
}
pub mod inherited_methods;
pub mod mount;
pub mod state;
impl ElementTree {
pub fn root_id(&self) -> Option<ElementId> {
self.root
}
pub fn element(&self, id: ElementId) -> Option<&Element> {
self.elements.get(id)
}
pub fn elements(&self) -> impl Iterator<Item = (ElementId, &Element)> + '_ {
self.elements.iter()
}
pub fn element_count(&self) -> usize {
self.elements.len()
}
pub fn layer_tree(&self) -> &LayerTree {
&self.layer_tree
}
pub fn text_measurer(&self) -> Option<TextMeasurer> {
self.text_measurer
}
pub fn set_text_measurer(&mut self, measurer: Option<TextMeasurer>) {
self.text_measurer = measurer;
}
pub fn audit_render_protocol(&self) -> Vec<String> {
fn collect(ro: &dyn RenderObject, out: &mut Vec<*const ()>) {
out.push(ro as *const dyn RenderObject as *const ());
ro.for_each_child(&mut |_, child| {
collect(child.borrow().as_ref(), out);
});
}
let mut problems = Vec::new();
for (id, el) in self.elements.iter() {
if !el.active {
continue;
}
let mut slots = 0usize;
el.render_object.borrow().for_each_child(&mut |_, _| slots += 1);
if slots > el.children.len() {
problems.push(format!(
"element {id:?} ({}) 的 RO 有 {slots} 个直接子 RO,element 树只挂了 {} 个子节点;多出来的是 create_render_object 自造的影子 RO(不 mount ⇒ 不渲染、不收事件),State::build() 应返回这些 children",
el.widget.0.type_name(),
el.children.len()
));
}
if el.children.is_empty() {
continue;
}
let mut ptrs = Vec::new();
collect(el.render_object.borrow().as_ref(), &mut ptrs);
for &cid in &el.children {
let Some(child) = self.elements.get(cid) else { continue };
let ptr = child.render_object.borrow().as_ref() as *const dyn RenderObject as *const ();
let count = ptrs.iter().filter(|&&p| p == ptr).count();
if count != 1 {
problems.push(format!(
"element {id:?} ({}) 的 child {cid:?} ({}) 在其 RO 子树出现 {count} 次(期望 1)",
el.widget.0.type_name(),
child.widget.0.type_name()
));
}
}
}
problems
}
pub(crate) fn element_subtree_visible(&self, eid: ElementId) -> bool {
let Some(start) = self.elements.get(eid) else { return true };
if !start.visible_in_parent {
return false;
}
let mut cursor = start.parent;
while let Some(pid) = cursor {
let Some(pel) = self.elements.get(pid) else { break };
if !pel.visible_in_parent {
return false;
}
cursor = pel.parent;
}
true
}
pub fn semantics_revision(&self) -> u64 {
self.semantics_revision
}
pub fn last_layout_ns(&self) -> u64 {
self.last_layout_ns
}
pub fn last_paint_ns(&self) -> u64 {
self.last_paint_ns
}
pub(crate) fn bump_semantics_revision(&mut self) {
self.semantics_revision = self.semantics_revision.wrapping_add(1);
}
pub(crate) fn layout_origins(&self) -> HashMap<ElementId, (Point, usize)> {
let mut out = HashMap::new();
if let Some(root) = self.root {
self.collect_layout_origins(root, Point::ZERO, 0, &mut out);
}
for entry in &self.overlays {
let origin = entry.layer_offset(self);
self.collect_layout_origins(entry.root_element, origin, 0, &mut out);
}
out
}
pub(crate) fn invalidate_origin_cache(&self) {
*self.origin_cache.borrow_mut() = None;
}
fn origin_map(&self) -> std::cell::Ref<'_, HashMap<ElementId, (Point, usize)>> {
if self.origin_cache.borrow().is_none() {
let origins = self.layout_origins();
*self.origin_cache.borrow_mut() = Some(origins);
}
std::cell::Ref::map(self.origin_cache.borrow(), |cache| cache.as_ref().expect("origin cache initialised"))
}
fn collect_layout_origins(
&self,
id: ElementId,
origin: Point,
depth: usize,
out: &mut HashMap<ElementId, (Point, usize)>,
) {
let Some(el) = self.elements.get(id) else { return };
if !el.active {
return;
}
out.insert(id, (origin, depth));
let offsets: Vec<Point> = {
let mut offsets = Vec::with_capacity(el.children.len());
el.render_object.borrow().for_each_child(&mut |off, _| offsets.push(off));
offsets
};
for (index, &child) in el.children.iter().enumerate() {
let off = offsets.get(index).copied().unwrap_or(Point::ZERO);
self.collect_layout_origins(child, Point::new(origin.x + off.x, origin.y + off.y), depth + 1, out);
}
}
}