mgui-core 0.4.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! Align — 按 Alignment 定位单 child,可选 width/heightFactor

use crate::id::ElementId;
use crate::paint::PaintList;
use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
use crate::widget::{Widget, WidgetNode};
use crate::{Color, Point, Size};

use super::alignment::Alignment;

/// Align RenderObject — 按 Alignment 定位 child;可选 width/heightFactor
pub struct AlignRenderObject {
    pub alignment: Alignment,
    pub width_factor: Option<f32>,
    pub height_factor: Option<f32>,
    child: Option<SharedRO>,
    cached_size: Size,
    child_cached_size: Size,
    pub child_offset: Point,
}

impl AlignRenderObject {
    pub fn new(
        alignment: Alignment,
        width_factor: Option<f32>,
        height_factor: Option<f32>,
        child: Option<Box<dyn RenderObject>>,
    ) -> Self {
        Self {
            alignment,
            width_factor,
            height_factor,
            child: child.map(make_ro_shared),
            cached_size: Size::ZERO,
            child_cached_size: Size::ZERO,
            child_offset: Point::ZERO,
        }
    }
}

impl RenderObject for AlignRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 1. 用 loosed 约束测 child(Align 不强制 child 大小)
        let child_constraints = BoxConstraints {
            min_width: 0.0,
            max_width: constraints.max_width,
            min_height: 0.0,
            max_height: constraints.max_height,
        };
        self.child_cached_size =
            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };

        // 2. 算 self_size(per-axis):
        //    单轴 factor 是 Some → 该轴 self_size = child_size * factor
        //    单轴 constraints tight → self_size = constraints tight 值
        //    否则 → constrain(child_size, constraints)
        let child_size = self.child_cached_size;
        let self_size = if constraints.is_tight() {
            Size::new(constraints.min_width, constraints.min_height)
        } else {
            let w = if let Some(wf) = self.width_factor {
                child_size.width * wf
            } else {
                child_size.width.clamp(constraints.min_width, constraints.max_width)
            };
            let h = if let Some(hf) = self.height_factor {
                child_size.height * hf
            } else {
                child_size.height.clamp(constraints.min_height, constraints.max_height)
            };
            Size::new(w, h)
        };
        self.cached_size = self_size;

        // 3. child_offset = alignment * (self_size - child_size)
        //    alignment (0..1) → 实际偏移比例(0 左/上, 0.5 中心, 1 右/下)
        let delta_w = (self_size.width - child_size.width).max(0.0);
        let delta_h = (self_size.height - child_size.height).max(0.0);
        self.child_offset = Point::new(self.alignment.x * delta_w, self.alignment.y * delta_h);

        self_size
    }

    fn content_size(&self) -> Size {
        self.cached_size
    }

    fn paint(&self, offset: Point, painter: &mut PaintList) {
        if let Some(child) = &self.child {
            child.borrow().paint(Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y), painter);
        }
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        if let Some(child) = &self.child {
            child
                .borrow()
                .hit_test(position, Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y))
        } else {
            None
        }
    }

    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        if let Some(child) = &mut self.child {
            if let Some(&cid) = child_ids.first() {
                if let Some(new_ro) = stateful_ros.first_mut() {
                    *child = new_ro.clone();
                }
                child.borrow_mut().set_element_id(cid);
            }
        }
    }

    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        self.child.as_ref().map(|c| vec![(self.child_offset, c.clone())]).unwrap_or_default()
    }

    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
        if let Some(c) = &self.child {
            f(self.child_offset, c);
        }
    }

    fn children_count(&self) -> usize {
        if self.child.is_some() {
            1
        } else {
            0
        }
    }
}

/// Align(子节点对齐)
///
/// ```ignore
/// Align::new(Alignment::CENTER)          // 居中
///      .width_factor(1.0)                // self_width = child_width * 1.0
///      .height_factor(1.0)               // self_height = child_height * 1.0
///      .child(button)
/// ```
#[derive(Debug)]
pub struct AlignWidget {
    pub alignment: Alignment,
    pub width_factor: Option<f32>,
    pub height_factor: Option<f32>,
    pub child: Option<WidgetNode>,
}

impl AlignWidget {
    pub fn new(alignment: Alignment, child: impl Widget) -> Self {
        Self { alignment, width_factor: None, height_factor: None, child: Some(WidgetNode::new(child)) }
    }

    pub fn width_factor(mut self, f: f32) -> Self {
        self.width_factor = Some(f);
        self
    }
    pub fn height_factor(mut self, f: f32) -> Self {
        self.height_factor = Some(f);
        self
    }

    pub fn center(child: impl Widget) -> Self {
        Self::new(Alignment::CENTER, child)
    }
    pub fn top_left(child: impl Widget) -> Self {
        Self::new(Alignment::TOP_LEFT, child)
    }
    pub fn top_center(child: impl Widget) -> Self {
        Self::new(Alignment::TOP_CENTER, child)
    }
    pub fn bottom_center(child: impl Widget) -> Self {
        Self::new(Alignment::BOTTOM_CENTER, child)
    }
}

impl Widget for AlignWidget {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let child_ro = match &self.child {
            Some(c) => c.0.create_render_object(),
            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        };
        Box::new(AlignRenderObject::new(self.alignment, self.width_factor, self.height_factor, Some(child_ro)))
    }

    fn children(&self) -> Vec<WidgetNode> {
        match &self.child {
            Some(c) => vec![c.clone()],
            None => vec![],
        }
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        let Some(o) = old.as_any().downcast_ref::<AlignWidget>() else {
            return false;
        };
        self.alignment == o.alignment
            && self.width_factor == o.width_factor
            && self.height_factor == o.height_factor
            && crate::widget::optional_child_equivalent(&self.child, &o.child)
    }
}

/// Center(Align::CENTER 语法糖)
#[derive(Debug)]
pub struct CenterWidget {
    pub child: Option<WidgetNode>,
}

impl CenterWidget {
    pub fn new(child: impl Widget) -> Self {
        Self { child: Some(WidgetNode::new(child)) }
    }
}

impl Widget for CenterWidget {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let child_ro = match &self.child {
            Some(c) => c.0.create_render_object(),
            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        };
        Box::new(AlignRenderObject::new(Alignment::CENTER, None, None, Some(child_ro)))
    }

    fn children(&self) -> Vec<WidgetNode> {
        match &self.child {
            Some(c) => vec![c.clone()],
            None => vec![],
        }
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any()
            .downcast_ref::<CenterWidget>()
            .is_some_and(|o| crate::widget::optional_child_equivalent(&self.child, &o.child))
    }

    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
        use crate::semantics::{SemanticsRole, WidgetSemantics};
        Some(WidgetSemantics::new(SemanticsRole::Container).non_focusable())
    }
}