Skip to main content

mgui_core/widget/
mod.rs

1//! Widget 子系统
2//!
3//! Widget 是声明式 UI 描述的不可变配置。
4//! 每个 Widget 描述"应该长什么样",通过 `create_render_object()`
5//! 桥接到 RenderObject 子系统进行实际的布局和绘制。
6//!
7//! 阶段 3 重构(State 上提到 Element 层):
8//! - `StatefulWidget` trait: 关联一个 `State<W>` 对象
9//! - `State` trait: 在 Element 节点上持久化的状态,生命周期由 Element 管理
10//!
11//! **架构分层说明**:
12//! 本 crate(mgui-core)保留:Widget/State/StatefulWidget trait + 框架层必须的
13//! primitive widget(RRectWidget/StackWidget/SizedBoxWidget/AlignWidget +
14//! Dialog/DialogBarrier/Tooltip — event.rs 生产代码直接构造)。
15//! Button/CheckBox/Slider/Switch 等独立 UI 组件已迁移到 `mgui-components` crate,
16//! 单向依赖 core(components → core,无循环)。
17
18use std::any::Any;
19use std::fmt::Debug;
20use std::rc::Rc;
21
22use crate::reactive::Signal;
23use crate::render_object::RenderObject;
24use crate::{GestureState, Point, WidgetEvent};
25
26// Overlay-aware capability 等公共类型 re-export,方便组件侧 State 直接 use
27// 同时 OverlayAware 也在当前模块作用域内,供 State trait 方法签名引用
28pub use overlay_host::{OverlayAnchor, OverlayAware, OverlayEvent, OverlayFocus, OverlayIntent, OverlayRef};
29
30// =================================================================
31// WidgetNode — 不可变 Widget 的句柄(Rc<dyn Widget>)
32// =================================================================
33
34/// Widget 树节点:持有 `Rc<dyn Widget>`,让 widget 树可被多处共享
35///
36/// WidgetNode 同时实现 Widget trait —— 转发到内部 Widget,
37/// 这样可以直接用 `child.create_render_object()` 等方法
38#[derive(Clone)]
39pub struct WidgetNode(pub Rc<dyn Widget>);
40
41impl WidgetNode {
42    pub fn new<W: Widget + 'static>(widget: W) -> Self {
43        Self(Rc::new(widget))
44    }
45
46    pub fn as_any(&self) -> &dyn Any {
47        self.0.as_any()
48    }
49
50    /// 内层 widget 的具体 TypeId。
51    ///
52    /// 必须有这个 inherent 方法:否则 `node.type_id()` 会解析到
53    /// `Any::type_id(&WidgetNode)`,对所有 widget 返回同一个 id。
54    pub fn type_id(&self) -> std::any::TypeId {
55        self.0.as_any().type_id()
56    }
57
58    pub fn is<T: 'static>(&self) -> bool {
59        self.0.as_any().is::<T>()
60    }
61
62    /// 两个节点是否同一个 `Rc`(局部 rebuild 的快速路径)。
63    pub fn ptr_eq(&self, other: &WidgetNode) -> bool {
64        Rc::ptr_eq(&self.0, &other.0)
65    }
66
67    /// 纯 stateless 子树是否可整体跳过:类型/key 相同 + 两侧均无 state
68    /// + 无动态 Signal + 输入等价。boundary 自身不参与跳过(layer 关系需维护)。
69    pub fn is_equivalent(&self, old: &WidgetNode) -> bool {
70        if widget_eq_disabled() {
71            return false;
72        }
73        if self.0.is_stateful() || old.0.is_stateful() {
74            return false;
75        }
76        if self.0.is_repaint_boundary() || old.0.is_repaint_boundary() {
77            return false;
78        }
79        if self.0.key() != old.0.key() {
80            return false;
81        }
82        if self.0.dynamic_signal().is_some() || old.0.dynamic_signal().is_some() {
83            return false; // Signal 值独立变化,不归 update 管
84        }
85        self.0.can_update(&*old.0) && self.0.is_equivalent(&*old.0)
86    }
87}
88
89impl std::fmt::Debug for WidgetNode {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("WidgetNode").field("type", &self.0.type_name()).finish()
92    }
93}
94
95// =================================================================
96// Widget trait (WidgetNode 实现并转发)
97// =================================================================
98
99/// 不可变 widget 配置:描述“要显示什么”,由 Element 树实例化并 diff。
100#[allow(unused_variables)]
101#[deny(missing_docs)]
102pub trait Widget: Any + Debug + 'static {
103    /// 类型擦除入口(用于 downcast 到具体 widget)。
104    fn as_any(&self) -> &dyn Any;
105
106    /// 类型名称(调试用,Debug impl 用)
107    fn type_name(&self) -> &'static str {
108        std::any::type_name::<Self>()
109    }
110
111    /// 是否 stateful(true 则 Element 自动创建 State 并持久化)
112    fn is_stateful(&self) -> bool {
113        false
114    }
115
116    /// 是否可聚焦(Tab 焦点链 + 键盘激活)
117    fn is_focusable(&self) -> bool {
118        false
119    }
120
121    /// 是否需要 IME(软键盘 —— TextField/TextBox 等输入组件)
122    fn wants_ime(&self) -> bool {
123        false
124    }
125
126    /// 是否捕获 Tab 键(编辑器等需要 Tab 缩进的输入组件)。
127    /// true 时框架焦点遍历跳过该组件,Tab/BackTab 直接投递给焦点 element。
128    fn captures_tab(&self) -> bool {
129        false
130    }
131
132    /// 创建 State 实例(仅 is_stateful=true 时 Element 会调)
133    fn create_state(&self) -> Option<Box<dyn State>> {
134        None
135    }
136
137    /// 创建 RenderObject(桥接到渲染子系统)
138    fn create_render_object(&self) -> Box<dyn RenderObject>;
139
140    /// 子 widget 列表(Element 树递归用)
141    fn children(&self) -> Vec<WidgetNode> {
142        Vec::new()
143    }
144
145    /// 子 widget + 各自在父内的 offset(Stack/Positioned 等需要)
146    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
147        self.children().into_iter().map(|c| (Point::ZERO, c)).collect()
148    }
149
150    /// 处理事件(*不可变* — Widget 是 Rc 共享的;stateful widget 通常把逻辑放在 State 里)
151    fn handle_event(&self, event: &WidgetEvent, local_pos: Point) {}
152
153    /// 是否接受滚动事件(ScrollView/ListView 返回 true)
154    fn accepts_scroll(&self) -> bool {
155        false
156    }
157
158    /// 唯一标识(用于 ListView 复用 Element)
159    fn key(&self) -> Option<u64> {
160        None
161    }
162
163    /// 手势竞技场仲裁(返回 Some 表示参与指针竞争)
164    fn gesture_state(&self) -> Option<GestureState> {
165        None
166    }
167
168    /// 返回需要订阅的 Signal(PositionedWidget 用)
169    fn dynamic_signal(&self) -> Option<Signal<Point>> {
170        None
171    }
172
173    /// 返回无障碍语义(阶段 A11y)
174    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
175        None
176    }
177
178    /// 如果是 InheritedWidget,返回引用(主题/布局约束等传播)
179    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
180        None
181    }
182
183    /// Element diff 时判断新旧 widget 是否"兼容"(类型相同 + key 相同)
184    /// 默认:type_id 比较
185    fn can_update(&self, old: &dyn Widget) -> bool {
186        self.as_any().type_id() == old.as_any().type_id()
187    }
188
189    /// P0-1:新旧 widget 的**全部输入**是否等价(不含 State)。
190    ///
191    /// 默认 `false` = 保守重建。返回 `true` 必须保证 `create_render_object`、
192    /// layout/paint、children 的输入完全一致。纯 stateless 子树可据此整体跳过;
193    /// stateful widget 仍会执行 build,只用它判断自己的 RO 是否可保留。
194    fn is_equivalent(&self, _old: &dyn Widget) -> bool {
195        false
196    }
197
198    /// 是否 RepaintBoundary(dirty 重绘边界)
199    fn is_repaint_boundary(&self) -> bool {
200        false
201    }
202
203    /// 逐子节点可见性(按 `children()` 顺序)。`None` = 全部可见(默认,零行为变化)。
204    /// `Some(vec)` 与 `children()` 等长;`false` 表示该子节点的**整棵子树**
205    /// (含其内部 RepaintBoundary layer)不参与合成。
206    ///
207    /// 框架在 `paint_layer_recursive` 中沿 element 祖先链上溯此列表,
208    /// 被隐藏分支的 layer 不 push 进本帧 sub_layers(即不被 blit)。
209    fn visible_children(&self) -> Option<Vec<bool>> {
210        None
211    }
212
213    /// 父容器在布局阶段读取的子节点元数据(如 Flex 的 grow/basis)。
214    /// 默认 `None`(无元数据)。`Expanded`/`Flexible` 等 override 返回 `ParentData::Flex`。
215    fn parent_data(&self) -> Option<crate::layout::ParentData> {
216        None
217    }
218}
219
220// WidgetNode 实现 Widget trait —— 转发到内部 Widget
221impl Widget for WidgetNode {
222    fn as_any(&self) -> &dyn Any {
223        self.0.as_any()
224    }
225    fn type_name(&self) -> &'static str {
226        self.0.type_name()
227    }
228    fn is_stateful(&self) -> bool {
229        self.0.is_stateful()
230    }
231    fn is_focusable(&self) -> bool {
232        self.0.is_focusable()
233    }
234    fn wants_ime(&self) -> bool {
235        self.0.wants_ime()
236    }
237    fn captures_tab(&self) -> bool {
238        self.0.captures_tab()
239    }
240    fn create_state(&self) -> Option<Box<dyn State>> {
241        self.0.create_state()
242    }
243    fn create_render_object(&self) -> Box<dyn RenderObject> {
244        self.0.create_render_object()
245    }
246    fn children(&self) -> Vec<WidgetNode> {
247        self.0.children()
248    }
249    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
250        self.0.children_with_positions()
251    }
252    fn handle_event(&self, event: &WidgetEvent, local_pos: Point) {
253        self.0.handle_event(event, local_pos)
254    }
255    fn accepts_scroll(&self) -> bool {
256        self.0.accepts_scroll()
257    }
258    fn key(&self) -> Option<u64> {
259        self.0.key()
260    }
261    fn gesture_state(&self) -> Option<GestureState> {
262        self.0.gesture_state()
263    }
264    fn dynamic_signal(&self) -> Option<Signal<Point>> {
265        self.0.dynamic_signal()
266    }
267    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
268        self.0.semantics()
269    }
270    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
271        self.0.as_inherited()
272    }
273    fn can_update(&self, old: &dyn Widget) -> bool {
274        self.0.can_update(old)
275    }
276    fn is_equivalent(&self, old: &dyn Widget) -> bool {
277        self.0.is_equivalent(old)
278    }
279    fn is_repaint_boundary(&self) -> bool {
280        self.0.is_repaint_boundary()
281    }
282    fn visible_children(&self) -> Option<Vec<bool>> {
283        self.0.visible_children()
284    }
285    fn parent_data(&self) -> Option<crate::layout::ParentData> {
286        self.0.parent_data()
287    }
288}
289
290// =================================================================
291// StatefulWidget trait(marker + convenience)
292// =================================================================
293
294/// StatefulWidget 标记 trait:等价于在 Widget 上 is_stateful()=true
295pub trait StatefulWidget: Widget {}
296
297/// P0-1 逃生阀:环境变量只读一次,避免热路径每帧查环境。
298fn state_apply_disabled() -> bool {
299    static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
300    *DISABLED.get_or_init(|| std::env::var_os("MGUI_DISABLE_STATE_APPLY").is_some())
301}
302
303/// 当前进程是否允许 state→RO 就地更新。
304///
305/// 跨 crate 的 State(如 TextField)若自行实现 `apply_to_ro`,应先检查此值,
306/// 保证 `MGUI_DISABLE_STATE_APPLY=1` 逃生阀仍然生效。
307pub fn state_apply_enabled() -> bool {
308    !state_apply_disabled()
309}
310
311/// Widget 等价性逃生阀(`MGUI_DISABLE_WIDGET_EQ=1` 强制全部重建)。
312fn widget_eq_disabled() -> bool {
313    static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
314    *DISABLED.get_or_init(|| std::env::var_os("MGUI_DISABLE_WIDGET_EQ").is_some())
315}
316
317/// 相邻兄弟 widget 列表是否逐项等价(容器实现 `is_equivalent` 的公共 helper)。
318pub fn children_equivalent(a: &[WidgetNode], b: &[WidgetNode]) -> bool {
319    a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.is_equivalent(y))
320}
321
322/// 可选单子节点等价(单 child 容器 helper)。
323pub fn optional_child_equivalent(a: &Option<WidgetNode>, b: &Option<WidgetNode>) -> bool {
324    match (a, b) {
325        (Some(a), Some(b)) => a.is_equivalent(b),
326        (None, None) => true,
327        _ => false,
328    }
329}
330
331// =================================================================
332// State trait
333// =================================================================
334
335/// State — 在 Element 节点上持久化的状态对象
336///
337/// Widget 不可变(每次 rebuild 都是新实例),State 跟着 Element 走,
338/// 即使 Widget 实例换了,State 仍保留 pressed/hover/checked 等可变字段。
339#[allow(unused_variables)]
340#[deny(missing_docs)]
341pub trait State: Any {
342    /// 类型擦除入口(只读)。
343    fn as_any(&self) -> &dyn Any;
344
345    /// **必须显式实现**(框架约定)
346    fn as_any_mut(&mut self) -> &mut dyn Any;
347
348    /// 当前关联的 widget 节点(由框架在 mount/update 时写入)。
349    fn widget(&self) -> &WidgetNode;
350
351    /// 框架在 widget 更新时调用,State 据此 adopt 新配置(保留自身字段)。
352    fn set_widget(&mut self, widget: WidgetNode);
353
354    /// 首次挂载、State 创建后调用一次。
355    fn init_state(&mut self) {}
356
357    /// widget 被替换(同类型复用)后调用;默认空实现。
358    fn did_update_widget(&mut self) {}
359
360    /// Element 卸载时调用;释放订阅/定时器等资源。
361    fn dispose(&mut self) {}
362
363    /// build 阶段:从 ctx 取主题等,返回子节点列表(默认 widget().children())
364    fn build(&self, ctx: &mut crate::inherited::BuildContext<'_>) -> Vec<WidgetNode> {
365        let _ = ctx;
366        self.widget().children()
367    }
368
369    /// 创建 RenderObject —— 默认转发到 widget().create_render_object()
370    /// (大多数 State 不需要自己实现,除非需要定制 RenderObject)
371    fn create_render_object(&self) -> Box<dyn RenderObject> {
372        self.widget().create_render_object()
373    }
374
375    /// P0-1:尝试把当前 state 就地写回已有 RO。
376    ///
377    /// 默认把 state 交给 RO 侧匹配(`RenderObject::apply_state`);组件通常只需
378    /// 在自己的 RO 实现该方法即可。返回 `Unsupported` 时框架回退到
379    /// `create_render_object`(行为与旧版本一致)。
380    ///
381    /// 逃生阀 `MGUI_DISABLE_STATE_APPLY=1` 会强制全部回退(进程内只读一次)。
382    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> crate::render_object::StateApply {
383        if state_apply_disabled() {
384            return crate::render_object::StateApply::Unsupported;
385        }
386        ro.apply_state(self.as_any_mut())
387    }
388
389    /// State 侧语义覆盖:用于暴露静态 widget 无法提供的动态值
390    /// (例如 TextField 的当前文本)。None = 使用 `widget.semantics()`。
391    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
392        None
393    }
394
395    /// 处理指针/键盘/IME 事件(`local_pos` 已折算到本 element 坐标系)。
396    fn handle_event(&mut self, event: &WidgetEvent, local_pos: Point) {}
397
398    /// 每帧 tick(长按计时器、动画控制器等需要时间的机制;now_ms = 当前时间戳毫秒)
399    fn tick(&mut self, _now_ms: u64) {}
400
401    /// 覆盖层打开时的键盘导航钩子(方向键 / Home / End / Enter / Space)。
402    ///
403    /// 框架在把 KeyDown 路由到焦点元素**之前**调用**最上层 overlay** 根
404    /// element 的 State;返回 true = 已消费,不再向下路由。
405    /// 典型实现:Menu / Dropdown / ContextMenu 的方向键选择与 Enter 激活。
406    fn handle_overlay_key(&mut self, _key: crate::KeyCode, _mods: crate::KeyModifiers) -> bool {
407        false
408    }
409
410    /// ScrollView/ListView 特有:滚动动画中
411    fn is_animating(&self) -> bool {
412        false
413    }
414
415    /// 下一次需要 tick 的延迟(毫秒);None = 无定时任务。
416    ///
417    /// `is_animating == false` 但未来需要翻转的状态(光标闪烁等)用它向
418    /// Runner 预约唤醒 —— 不必持续 Poll,也不会因事件循环休眠而停闪。
419    fn next_animation_delay(&self, _now_ms: u64) -> Option<u64> {
420        None
421    }
422
423    /// State 请求框架重建本 element 的 children(build + diff,与 update 同路径)。
424    ///
425    /// handle_event 里改了**影响 children 的状态**(如 TabbedPane 切换内容页)后
426    /// 返回 true —— 一次性,框架取走后应复位。框架在下一帧 `paint_frame` 开头
427    /// 统一处理(事件 dispatch 正在遍历 hit 链,不能原地重建子树)。
428    fn take_needs_build(&mut self) -> bool {
429        false
430    }
431
432    /// 竞技场仲裁:有持续型手势胜出 → 返回 Accepted 独占指针
433    fn gesture_state(&self) -> Option<GestureState> {
434        None
435    }
436
437    /// 被竞争失败:放弃进行中的手势
438    fn reject_gestures(&mut self) {}
439
440    /// 是否处理 build panic(ErrorBoundary 用)
441    fn handles_build_error(&self) -> bool {
442        false
443    }
444
445    /// build panic 时回调
446    fn on_build_error(&mut self, msg: &str) {
447        let _ = msg;
448    }
449
450    /// TextField/TextBox 用:IME 光标区域(x, y, line_height) — 多行感知
451    fn ime_cursor_area(&self) -> Option<(f32, f32, f32)> {
452        None
453    }
454
455    /// Overlay-aware capability 探测 —— 返回 self 若实现了 OverlayAware trait,否则 None
456    ///
457    /// 默认返回 None(core 不感知任何组件 overlay 协议),组件侧 State 按需 override。
458    /// ElementTree 在 `process_overlay_intents` 中用此探测,统一消费各组件的 overlay 意图。
459    fn as_overlay_aware(&mut self) -> Option<&mut dyn OverlayAware> {
460        None
461    }
462}
463
464// =================================================================
465// 子模块声明
466// =================================================================
467pub mod overlay_host;
468pub mod primitives;
469
470// =================================================================
471// 子模块 re-exports
472// =================================================================
473pub use primitives::{RRectWidget, StackWidget};
474// 向后兼容别名:TooltipPlacement = AnchorPlacement
475pub use overlay_host::AnchorPlacement as TooltipPlacement;