Skip to main content

mgui_core/render_object/
positioned.rs

1use super::*;
2
3/// 在父容器内按指定 `offset` 摆放子节点(不影响父容器布局)
4///
5/// 阶段 5-G 扩展:可选 `signal: Signal<Point>` 用于**外部驱动**位置。
6/// - `None` → 静态位置(`self.offset`)
7/// - `Some(signal)` → paint/hit_test 走 `enter_subscriber(ro_id) + signal.get()`
8///   实时读值,并**自动让 RO 作为 signal 的 subscriber**(signal.set 触发 RO 所在
9///   element dirty → paint 重跑)。
10pub struct PositionedRenderObject {
11    pub offset: Point,
12    pub signal: Option<Signal<Point>>,
13    child: Option<SharedRO>,
14    cached_size: Size,
15    /// RO 自己的 SubscriberId(让 signal 知道订阅自己);由 ElementTree::set_ro_subscriber 写入
16    ro_subscriber_id: Option<crate::reactive::SubscriberId>,
17}
18
19impl PositionedRenderObject {
20    pub fn new(offset: Point, child: impl RenderObject + 'static) -> Self {
21        Self {
22            offset,
23            signal: None,
24            child: Some(make_ro_shared(Box::new(child))),
25            cached_size: Size::ZERO,
26            ro_subscriber_id: None,
27        }
28    }
29
30    /// 阶段 5-G:动态位置(外部 Signal 驱动)
31    pub fn new_dynamic(offset: Point, signal: Signal<Point>, child: impl RenderObject + 'static) -> Self {
32        Self {
33            offset,
34            signal: Some(signal),
35            child: Some(make_ro_shared(Box::new(child))),
36            cached_size: Size::ZERO,
37            ro_subscriber_id: None,
38        }
39    }
40
41    /// ElementTree 在 mount 时调用,把 element 的 SubscriberId 注入 RO,
42    /// 让 paint/hit_test 走 enter_subscriber + signal.get() 时 RO 成为
43    /// signal 的 subscriber(从而 Signal::set 触发 element dirty)。
44    pub fn set_ro_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
45        self.ro_subscriber_id = Some(id);
46    }
47
48    /// 阶段 5-G:实时 offset(signal 存在时进入 subscriber 上下文读 signal;
49    /// 没有 subscriber id 时退化为读 self.offset)
50    fn current_offset(&self) -> Point {
51        match (&self.signal, self.ro_subscriber_id) {
52            (Some(sig), Some(sub_id)) => {
53                crate::reactive::enter_subscriber(sub_id);
54                let p = sig.get();
55                crate::reactive::exit_subscriber();
56                p
57            }
58            _ => self.offset,
59        }
60    }
61}
62
63impl RenderObject for PositionedRenderObject {
64    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
65        // offset 是摆放位置,不参与尺寸计算(Positioned 语义:不影响父容器布局)
66        let child_size =
67            if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
68        self.cached_size = constraints.constrain(child_size);
69        self.cached_size
70    }
71
72    fn content_size(&self) -> Size {
73        self.cached_size
74    }
75
76    fn paint(&self, offset: Point, painter: &mut PaintList) {
77        if let Some(child) = &self.child {
78            let off = self.current_offset();
79            child.borrow().paint(Point::new(offset.x + off.x, offset.y + off.y), painter);
80        }
81    }
82
83    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
84        if let Some(child) = &self.child {
85            let off = self.current_offset();
86            return child.borrow().hit_test(position, Point::new(offset.x + off.x, offset.y + off.y));
87        }
88        None
89    }
90
91    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
92        if let Some(child) = &mut self.child {
93            if let Some(&cid) = child_ids.first() {
94                // stateful 子:替换 child slot 的 RO 为 state-driven RO
95                if let Some(new_ro) = stateful_ros.first_mut() {
96                    *child = new_ro.clone();
97                }
98                child.borrow_mut().set_element_id(cid);
99            }
100        }
101    }
102
103    /// 阶段 2-E:element_origin 遍历用 — child 在当前 offset 处
104    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
105        let off = self.current_offset();
106        self.child.as_ref().map(|c| vec![(off, c.clone())]).unwrap_or_default()
107    }
108
109    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
110        if let Some(c) = &self.child {
111            f(self.current_offset(), c);
112        }
113    }
114
115    /// 阶段 4-D:Positioned 包装一层, push_child 在原 offset 上再加一层
116    /// 但 push_child 调用时 caller 应该传 final position,我们这里覆盖 offset
117    /// 简化:push 时如果 self.offset 是 0,用 caller 的 offset;否则保留 self.offset
118    /// 实际 mount 时 caller 知道完整 offset,所以这里支持 caller offset
119    fn push_child(&mut self, offset: Point, child: SharedRO) {
120        // Positioned 内部只一个 child。mount 时 caller 应该不调 push_child 直接
121        // (因为 Positioned 已经有 child slot);但提供 noop 兼容
122        let _ = (offset, child);
123    }
124
125    fn children_count(&self) -> usize {
126        if self.child.is_some() {
127            1
128        } else {
129            0
130        }
131    }
132
133    /// 阶段 5-G:必须放在 `impl RenderObject for PositionedRenderObject` 块内
134    /// (在 `impl PositionedRenderObject` 块里只是 inherent method,不会覆盖 trait 默认 noop,
135    /// 导致 `Box<dyn RenderObject>::set_subscriber_id` 调到这里走 noop,Signal 订阅链路断裂)
136    fn set_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
137        self.set_ro_subscriber_id(id);
138    }
139
140    /// 属性动画:从 `AnimatedOffsetState` 就地读当前呈现 offset 写进 `self.offset`。
141    ///
142    /// paint / hit_test / child_slots 三处都走 `current_offset()`,signal=None 时
143    /// 返回 `self.offset` —— 写它即可保证像素、命中、语义 origin 三处同源(语义
144    /// origin 还需要 state 的 `tick_changes_geometry=true` 触发 `origin_cache` 失效)。
145    /// 幂等:值未变返回 `Unchanged`。
146    fn apply_state(&mut self, state: &mut dyn std::any::Any) -> StateApply {
147        let s = match state.downcast_ref::<crate::widget::animated::AnimatedOffsetState>() {
148            Some(s) => s,
149            None => return StateApply::Unsupported,
150        };
151        let next = s.presented_offset();
152        if (next.x - self.offset.x).abs() < f32::EPSILON && (next.y - self.offset.y).abs() < f32::EPSILON {
153            return StateApply::Unchanged;
154        }
155        self.offset = next;
156        StateApply::Updated
157    }
158}