mgui-core 0.2.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! AspectRatio — 强制宽高比的单 child 容器

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};

/// AspectRatio RenderObject — 强制 child 宽高比
///
/// `ratio = width / height`。在父约束下选最大的符合 ratio 的 size。
/// 优先级:width 有界 → height = width / ratio;height 有界 → width = height * ratio。
pub struct AspectRatioRenderObject {
    pub aspect_ratio: f32,
    child: Option<SharedRO>,
    cached_size: Size,
}

impl AspectRatioRenderObject {
    pub fn new(ratio: f32, child: Option<Box<dyn RenderObject>>) -> Self {
        Self { aspect_ratio: ratio, child: child.map(make_ro_shared), cached_size: Size::ZERO }
    }

    /// 根据约束算符合 ratio 的最大 size
    fn resolve_size(&self, constraints: BoxConstraints) -> Size {
        assert!(self.aspect_ratio > 0.0, "aspect_ratio must be > 0");

        // 决定 self_size:在 constraints 内选最大的符合 ratio 的 size
        let result = if constraints.is_bounded_width() && constraints.is_bounded_height() {
            // 两边都有界 → 取更小的方向
            let by_width = Size::new(constraints.max_width, constraints.max_width / self.aspect_ratio);
            let by_height = Size::new(constraints.max_height * self.aspect_ratio, constraints.max_height);
            if by_width.height <= constraints.max_height && by_height.width <= constraints.max_width {
                // 都 fit — 取更大的那个(面积更大)
                let by_w_area = by_width.width * by_width.height;
                let by_h_area = by_height.width * by_height.height;
                if by_w_area >= by_h_area {
                    by_width
                } else {
                    by_height
                }
            } else if by_width.height <= constraints.max_height {
                by_width
            } else {
                by_height
            }
        } else if constraints.is_bounded_width() {
            Size::new(constraints.max_width, constraints.max_width / self.aspect_ratio)
        } else if constraints.is_bounded_height() {
            Size::new(constraints.max_height * self.aspect_ratio, constraints.max_height)
        } else {
            // 都无界 → 默认 0
            Size::ZERO
        };

        // 夹紧到约束内(防 min 约束)
        constraints.constrain(result)
    }
}

impl RenderObject for AspectRatioRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        let self_size = self.resolve_size(constraints);
        // tight child 到 self_size
        let child_constraints = BoxConstraints::tight(self_size);
        if let Some(child) = &mut self.child {
            child.layout_cached(child_constraints, ctx);
        }
        self.cached_size = self_size;
        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(offset, painter);
        }
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
    }

    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![(Point::ZERO, c.clone())]).unwrap_or_default()
    }

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

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

/// AspectRatio(强制宽高比)
///
/// ```ignore
/// AspectRatio::new(16.0 / 9.0).child(video_player)
/// ```
#[derive(Debug)]
pub struct AspectRatioWidget {
    pub aspect_ratio: f32,
    pub child: Option<WidgetNode>,
}

impl AspectRatioWidget {
    pub fn new(ratio: f32, child: impl Widget) -> Self {
        assert!(ratio > 0.0, "aspect_ratio must be > 0");
        Self { aspect_ratio: ratio, child: Some(WidgetNode::new(child)) }
    }

    /// 正方形(1:1)
    pub fn square(child: impl Widget) -> Self {
        Self::new(1.0, child)
    }
}

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

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

    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(AspectRatioRenderObject::new(self.aspect_ratio, Some(child_ro)))
    }

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