mgui-core 0.7.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
use super::*;

/// 在父容器内按指定 `offset` 摆放子节点(不影响父容器布局)
///
/// 阶段 5-G 扩展:可选 `signal: Signal<Point>` 用于**外部驱动**位置。
/// - `None` → 静态位置(`self.offset`)
/// - `Some(signal)` → paint/hit_test 走 `enter_subscriber(ro_id) + signal.get()`
///   实时读值,并**自动让 RO 作为 signal 的 subscriber**(signal.set 触发 RO 所在
///   element dirty → paint 重跑)。
pub struct PositionedRenderObject {
    pub offset: Point,
    pub signal: Option<Signal<Point>>,
    child: Option<SharedRO>,
    cached_size: Size,
    /// RO 自己的 SubscriberId(让 signal 知道订阅自己);由 ElementTree::set_ro_subscriber 写入
    ro_subscriber_id: Option<crate::reactive::SubscriberId>,
}

impl PositionedRenderObject {
    pub fn new(offset: Point, child: impl RenderObject + 'static) -> Self {
        Self {
            offset,
            signal: None,
            child: Some(make_ro_shared(Box::new(child))),
            cached_size: Size::ZERO,
            ro_subscriber_id: None,
        }
    }

    /// 阶段 5-G:动态位置(外部 Signal 驱动)
    pub fn new_dynamic(offset: Point, signal: Signal<Point>, child: impl RenderObject + 'static) -> Self {
        Self {
            offset,
            signal: Some(signal),
            child: Some(make_ro_shared(Box::new(child))),
            cached_size: Size::ZERO,
            ro_subscriber_id: None,
        }
    }

    /// ElementTree 在 mount 时调用,把 element 的 SubscriberId 注入 RO,
    /// 让 paint/hit_test 走 enter_subscriber + signal.get() 时 RO 成为
    /// signal 的 subscriber(从而 Signal::set 触发 element dirty)。
    pub fn set_ro_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
        self.ro_subscriber_id = Some(id);
    }

    /// 阶段 5-G:实时 offset(signal 存在时进入 subscriber 上下文读 signal;
    /// 没有 subscriber id 时退化为读 self.offset)
    fn current_offset(&self) -> Point {
        match (&self.signal, self.ro_subscriber_id) {
            (Some(sig), Some(sub_id)) => {
                crate::reactive::enter_subscriber(sub_id);
                let p = sig.get();
                crate::reactive::exit_subscriber();
                p
            }
            _ => self.offset,
        }
    }
}

impl RenderObject for PositionedRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // offset 是摆放位置,不参与尺寸计算(Positioned 语义:不影响父容器布局)
        let child_size =
            if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
        self.cached_size = constraints.constrain(child_size);
        self.cached_size
    }

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

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

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        if let Some(child) = &self.child {
            let off = self.current_offset();
            return child.borrow().hit_test(position, Point::new(offset.x + off.x, offset.y + off.y));
        }
        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() {
                // stateful 子:替换 child slot 的 RO 为 state-driven RO
                if let Some(new_ro) = stateful_ros.first_mut() {
                    *child = new_ro.clone();
                }
                child.borrow_mut().set_element_id(cid);
            }
        }
    }

    /// 阶段 2-E:element_origin 遍历用 — child 在当前 offset 处
    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        let off = self.current_offset();
        self.child.as_ref().map(|c| vec![(off, c.clone())]).unwrap_or_default()
    }

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

    /// 阶段 4-D:Positioned 包装一层, push_child 在原 offset 上再加一层
    /// 但 push_child 调用时 caller 应该传 final position,我们这里覆盖 offset
    /// 简化:push 时如果 self.offset 是 0,用 caller 的 offset;否则保留 self.offset
    /// 实际 mount 时 caller 知道完整 offset,所以这里支持 caller offset
    fn push_child(&mut self, offset: Point, child: SharedRO) {
        // Positioned 内部只一个 child。mount 时 caller 应该不调 push_child 直接
        // (因为 Positioned 已经有 child slot);但提供 noop 兼容
        let _ = (offset, child);
    }

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

    /// 阶段 5-G:必须放在 `impl RenderObject for PositionedRenderObject` 块内
    /// (在 `impl PositionedRenderObject` 块里只是 inherent method,不会覆盖 trait 默认 noop,
    /// 导致 `Box<dyn RenderObject>::set_subscriber_id` 调到这里走 noop,Signal 订阅链路断裂)
    fn set_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
        self.set_ro_subscriber_id(id);
    }

    /// 属性动画:从 `AnimatedOffsetState` 就地读当前呈现 offset 写进 `self.offset`。
    ///
    /// paint / hit_test / child_slots 三处都走 `current_offset()`,signal=None 时
    /// 返回 `self.offset` —— 写它即可保证像素、命中、语义 origin 三处同源(语义
    /// origin 还需要 state 的 `tick_changes_geometry=true` 触发 `origin_cache` 失效)。
    /// 幂等:值未变返回 `Unchanged`。
    fn apply_state(&mut self, state: &mut dyn std::any::Any) -> StateApply {
        let s = match state.downcast_ref::<crate::widget::animated::AnimatedOffsetState>() {
            Some(s) => s,
            None => return StateApply::Unsupported,
        };
        let next = s.presented_offset();
        if (next.x - self.offset.x).abs() < f32::EPSILON && (next.y - self.offset.y).abs() < f32::EPSILON {
            return StateApply::Unchanged;
        }
        self.offset = next;
        StateApply::Updated
    }
}