mgui-core 0.2.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Widget 子系统
//!
//! Widget 是声明式 UI 描述的不可变配置。
//! 每个 Widget 描述"应该长什么样",通过 `create_render_object()`
//! 桥接到 RenderObject 子系统进行实际的布局和绘制。
//!
//! 阶段 3 重构(State 上提到 Element 层):
//! - `StatefulWidget` trait: 关联一个 `State<W>` 对象
//! - `State` trait: 在 Element 节点上持久化的状态,生命周期由 Element 管理
//!
//! **架构分层说明**:
//! 本 crate(mgui-core)保留:Widget/State/StatefulWidget trait + 框架层必须的
//! primitive widget(RRectWidget/StackWidget/SizedBoxWidget/AlignWidget +
//! Dialog/DialogBarrier/Tooltip — event.rs 生产代码直接构造)。
//! Button/CheckBox/Slider/Switch 等独立 UI 组件已迁移到 `mgui-components` crate,
//! 单向依赖 core(components → core,无循环)。

use std::any::Any;
use std::fmt::Debug;
use std::rc::Rc;

use crate::reactive::Signal;
use crate::render_object::RenderObject;
use crate::{GestureState, Point, Rect, WidgetEvent};

/// 事件消费上下文。
///
/// 默认 `Bubble`;交互控件在“真正激活”(典型是 PointerUp 触发点击)后调用
/// [`EventContext::stop`],ElementTree 便不再把该事件投递给祖先。
///
/// PointerDown/Move 不应 stop:父级 ScrollView / GestureDetector 需要它们来
/// 启动拖拽与手势仲裁。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EventContext {
    handled: bool,
}

impl EventContext {
    pub fn stop(&mut self) {
        self.handled = true;
    }

    pub fn is_handled(&self) -> bool {
        self.handled
    }
}

// Overlay-aware capability 等公共类型 re-export,方便组件侧 State 直接 use
// 同时 OverlayAware 也在当前模块作用域内,供 State trait 方法签名引用
pub use overlay_host::{OverlayAnchor, OverlayAware, OverlayEvent, OverlayFocus, OverlayIntent, OverlayRef};

// =================================================================
// WidgetNode — 不可变 Widget 的句柄(Rc<dyn Widget>)
// =================================================================

/// Widget 树节点:持有 `Rc<dyn Widget>`,让 widget 树可被多处共享
///
/// WidgetNode 同时实现 Widget trait —— 转发到内部 Widget,
/// 这样可以直接用 `child.create_render_object()` 等方法
#[derive(Clone)]
pub struct WidgetNode(pub Rc<dyn Widget>);

impl WidgetNode {
    pub fn new<W: Widget + 'static>(widget: W) -> Self {
        Self(Rc::new(widget))
    }

    pub fn as_any(&self) -> &dyn Any {
        self.0.as_any()
    }

    /// 内层 widget 的具体 TypeId。
    ///
    /// 必须有这个 inherent 方法:否则 `node.type_id()` 会解析到
    /// `Any::type_id(&WidgetNode)`,对所有 widget 返回同一个 id。
    pub fn type_id(&self) -> std::any::TypeId {
        self.0.as_any().type_id()
    }

    pub fn is<T: 'static>(&self) -> bool {
        self.0.as_any().is::<T>()
    }

    /// 两个节点是否同一个 `Rc`(局部 rebuild 的快速路径)。
    pub fn ptr_eq(&self, other: &WidgetNode) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }

    /// 纯 stateless 子树是否可整体跳过:类型/key 相同 + 两侧均无 state
    /// + 无动态 Signal + 输入等价。boundary 自身不参与跳过(layer 关系需维护)。
    pub fn is_equivalent(&self, old: &WidgetNode) -> bool {
        if widget_eq_disabled() {
            return false;
        }
        if self.0.is_stateful() || old.0.is_stateful() {
            return false;
        }
        if self.0.is_repaint_boundary() || old.0.is_repaint_boundary() {
            return false;
        }
        if self.0.key() != old.0.key() {
            return false;
        }
        if self.0.dynamic_signal().is_some() || old.0.dynamic_signal().is_some() {
            return false; // Signal 值独立变化,不归 update 管
        }
        self.0.can_update(&*old.0) && self.0.is_equivalent(&*old.0)
    }
}

impl std::fmt::Debug for WidgetNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WidgetNode").field("type", &self.0.type_name()).finish()
    }
}

// =================================================================
// Widget trait (WidgetNode 实现并转发)
// =================================================================

/// 不可变 widget 配置:描述“要显示什么”,由 Element 树实例化并 diff。
#[allow(unused_variables)]
#[deny(missing_docs)]
pub trait Widget: Any + Debug + 'static {
    /// 类型擦除入口(用于 downcast 到具体 widget)。
    fn as_any(&self) -> &dyn Any;

    /// 类型名称(调试用,Debug impl 用)
    fn type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    /// 是否 stateful(true 则 Element 自动创建 State 并持久化)
    fn is_stateful(&self) -> bool {
        false
    }

    /// 是否可聚焦(Tab 焦点链 + 键盘激活)
    fn is_focusable(&self) -> bool {
        false
    }

    /// 是否需要 IME(软键盘 —— TextField/TextBox 等输入组件)
    fn wants_ime(&self) -> bool {
        false
    }

    /// 是否捕获 Tab 键(编辑器等需要 Tab 缩进的输入组件)。
    /// true 时框架焦点遍历跳过该组件,Tab/BackTab 直接投递给焦点 element。
    fn captures_tab(&self) -> bool {
        false
    }

    /// 创建 State 实例(仅 is_stateful=true 时 Element 会调)
    fn create_state(&self) -> Option<Box<dyn State>> {
        None
    }

    /// 创建 RenderObject(桥接到渲染子系统)
    fn create_render_object(&self) -> Box<dyn RenderObject>;

    /// 子 widget 列表(Element 树递归用)
    fn children(&self) -> Vec<WidgetNode> {
        Vec::new()
    }

    /// 子 widget + 各自在父内的 offset(Stack/Positioned 等需要)
    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.children().into_iter().map(|c| (Point::ZERO, c)).collect()
    }

    /// 处理事件(*不可变* — Widget 是 Rc 共享的;stateful widget 通常把逻辑放在 State 里)
    fn handle_event(&self, event: &WidgetEvent, local_pos: Point) {}

    /// 带消费语义的事件处理;默认转发 [`Self::handle_event`] 并继续冒泡。
    fn handle_event_ctx(&self, event: &WidgetEvent, local_pos: Point, _ctx: &mut EventContext) {
        self.handle_event(event, local_pos);
    }

    /// 是否接受滚动事件(ScrollView/ListView 返回 true)
    fn accepts_scroll(&self) -> bool {
        false
    }

    /// 唯一标识(用于 ListView 复用 Element)
    fn key(&self) -> Option<u64> {
        None
    }

    /// 手势竞技场仲裁(返回 Some 表示参与指针竞争)
    fn gesture_state(&self) -> Option<GestureState> {
        None
    }

    /// 返回需要订阅的 Signal(PositionedWidget 用)
    fn dynamic_signal(&self) -> Option<Signal<Point>> {
        None
    }

    /// 返回无障碍语义(阶段 A11y)
    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
        None
    }

    /// 如果是 InheritedWidget,返回引用(主题/布局约束等传播)
    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
        None
    }

    /// Element diff 时判断新旧 widget 是否"兼容"(类型相同 + key 相同)
    /// 默认:type_id 比较
    fn can_update(&self, old: &dyn Widget) -> bool {
        self.as_any().type_id() == old.as_any().type_id()
    }

    /// P0-1:新旧 widget 的**全部输入**是否等价(不含 State)。
    ///
    /// 默认 `false` = 保守重建。返回 `true` 必须保证 `create_render_object`、
    /// layout/paint、children 的输入完全一致。纯 stateless 子树可据此整体跳过;
    /// stateful widget 仍会执行 build,只用它判断自己的 RO 是否可保留。
    fn is_equivalent(&self, _old: &dyn Widget) -> bool {
        false
    }

    /// 是否 RepaintBoundary(dirty 重绘边界)
    fn is_repaint_boundary(&self) -> bool {
        false
    }

    /// 逐子节点可见性(按 `children()` 顺序)。`None` = 全部可见(默认,零行为变化)。
    /// `Some(vec)` 与 `children()` 等长;`false` 表示该子节点的**整棵子树**
    /// (含其内部 RepaintBoundary layer)不参与合成。
    ///
    /// 框架在 `paint_layer_recursive` 中沿 element 祖先链上溯此列表,
    /// 被隐藏分支的 layer 不 push 进本帧 sub_layers(即不被 blit)。
    fn visible_children(&self) -> Option<Vec<bool>> {
        None
    }

    /// 父容器在布局阶段读取的子节点元数据(如 Flex 的 grow/basis)。
    /// 默认 `None`(无元数据)。`Expanded`/`Flexible` 等 override 返回 `ParentData::Flex`。
    fn parent_data(&self) -> Option<crate::layout::ParentData> {
        None
    }
}

// WidgetNode 实现 Widget trait —— 转发到内部 Widget
impl Widget for WidgetNode {
    fn as_any(&self) -> &dyn Any {
        self.0.as_any()
    }
    fn type_name(&self) -> &'static str {
        self.0.type_name()
    }
    fn is_stateful(&self) -> bool {
        self.0.is_stateful()
    }
    fn is_focusable(&self) -> bool {
        self.0.is_focusable()
    }
    fn wants_ime(&self) -> bool {
        self.0.wants_ime()
    }
    fn captures_tab(&self) -> bool {
        self.0.captures_tab()
    }
    fn create_state(&self) -> Option<Box<dyn State>> {
        self.0.create_state()
    }
    fn create_render_object(&self) -> Box<dyn RenderObject> {
        self.0.create_render_object()
    }
    fn children(&self) -> Vec<WidgetNode> {
        self.0.children()
    }
    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.0.children_with_positions()
    }
    fn handle_event(&self, event: &WidgetEvent, local_pos: Point) {
        self.0.handle_event(event, local_pos)
    }
    fn handle_event_ctx(&self, event: &WidgetEvent, local_pos: Point, ctx: &mut EventContext) {
        self.0.handle_event_ctx(event, local_pos, ctx)
    }
    fn accepts_scroll(&self) -> bool {
        self.0.accepts_scroll()
    }
    fn key(&self) -> Option<u64> {
        self.0.key()
    }
    fn gesture_state(&self) -> Option<GestureState> {
        self.0.gesture_state()
    }
    fn dynamic_signal(&self) -> Option<Signal<Point>> {
        self.0.dynamic_signal()
    }
    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
        self.0.semantics()
    }
    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
        self.0.as_inherited()
    }
    fn can_update(&self, old: &dyn Widget) -> bool {
        self.0.can_update(old)
    }
    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        self.0.is_equivalent(old)
    }
    fn is_repaint_boundary(&self) -> bool {
        self.0.is_repaint_boundary()
    }
    fn visible_children(&self) -> Option<Vec<bool>> {
        self.0.visible_children()
    }
    fn parent_data(&self) -> Option<crate::layout::ParentData> {
        self.0.parent_data()
    }
}

// =================================================================
// StatefulWidget trait(marker + convenience)
// =================================================================

/// StatefulWidget 标记 trait:等价于在 Widget 上 is_stateful()=true
pub trait StatefulWidget: Widget {}

/// P0-1 逃生阀:环境变量只读一次,避免热路径每帧查环境。
fn state_apply_disabled() -> bool {
    static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *DISABLED.get_or_init(|| std::env::var_os("MGUI_DISABLE_STATE_APPLY").is_some())
}

/// 当前进程是否允许 state→RO 就地更新。
///
/// 跨 crate 的 State(如 TextField)若自行实现 `apply_to_ro`,应先检查此值,
/// 保证 `MGUI_DISABLE_STATE_APPLY=1` 逃生阀仍然生效。
pub fn state_apply_enabled() -> bool {
    !state_apply_disabled()
}

/// Widget 等价性逃生阀(`MGUI_DISABLE_WIDGET_EQ=1` 强制全部重建)。
fn widget_eq_disabled() -> bool {
    static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *DISABLED.get_or_init(|| std::env::var_os("MGUI_DISABLE_WIDGET_EQ").is_some())
}

/// 相邻兄弟 widget 列表是否逐项等价(容器实现 `is_equivalent` 的公共 helper)。
pub fn children_equivalent(a: &[WidgetNode], b: &[WidgetNode]) -> bool {
    a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.is_equivalent(y))
}

/// 可选单子节点等价(单 child 容器 helper)。
pub fn optional_child_equivalent(a: &Option<WidgetNode>, b: &Option<WidgetNode>) -> bool {
    match (a, b) {
        (Some(a), Some(b)) => a.is_equivalent(b),
        (None, None) => true,
        _ => false,
    }
}

// =================================================================
// State trait
// =================================================================

/// State — 在 Element 节点上持久化的状态对象
///
/// Widget 不可变(每次 rebuild 都是新实例),State 跟着 Element 走,
/// 即使 Widget 实例换了,State 仍保留 pressed/hover/checked 等可变字段。
#[allow(unused_variables)]
#[deny(missing_docs)]
pub trait State: Any {
    /// 类型擦除入口(只读)。
    fn as_any(&self) -> &dyn Any;

    /// **必须显式实现**(框架约定)
    fn as_any_mut(&mut self) -> &mut dyn Any;

    /// 当前关联的 widget 节点(由框架在 mount/update 时写入)。
    fn widget(&self) -> &WidgetNode;

    /// 框架在 widget 更新时调用,State 据此 adopt 新配置(保留自身字段)。
    fn set_widget(&mut self, widget: WidgetNode);

    /// 首次挂载、State 创建后调用一次。
    fn init_state(&mut self) {}

    /// widget 被替换(同类型复用)后调用;默认空实现。
    fn did_update_widget(&mut self) {}

    /// Element 卸载时调用;释放订阅/定时器等资源。
    fn dispose(&mut self) {}

    /// build 阶段:从 ctx 取主题等,返回子节点列表(默认 widget().children())
    fn build(&self, ctx: &mut crate::inherited::BuildContext<'_>) -> Vec<WidgetNode> {
        let _ = ctx;
        self.widget().children()
    }

    /// 创建 RenderObject —— 默认转发到 widget().create_render_object()
    /// (大多数 State 不需要自己实现,除非需要定制 RenderObject)
    fn create_render_object(&self) -> Box<dyn RenderObject> {
        self.widget().create_render_object()
    }

    /// P0-1:尝试把当前 state 就地写回已有 RO。
    ///
    /// 默认把 state 交给 RO 侧匹配(`RenderObject::apply_state`);组件通常只需
    /// 在自己的 RO 实现该方法即可。返回 `Unsupported` 时框架回退到
    /// `create_render_object`(行为与旧版本一致)。
    ///
    /// 逃生阀 `MGUI_DISABLE_STATE_APPLY=1` 会强制全部回退(进程内只读一次)。
    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> crate::render_object::StateApply {
        if state_apply_disabled() {
            return crate::render_object::StateApply::Unsupported;
        }
        ro.apply_state(self.as_any_mut())
    }

    /// State 侧语义覆盖:用于暴露静态 widget 无法提供的动态值
    /// (例如 TextField 的当前文本)。None = 使用 `widget.semantics()`。
    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
        None
    }

    /// 处理指针/键盘/IME 事件(`local_pos` 已折算到本 element 坐标系)。
    fn handle_event(&mut self, event: &WidgetEvent, local_pos: Point) {}

    /// 带消费语义的事件处理;默认转发 [`Self::handle_event`] 并继续冒泡。
    fn handle_event_ctx(&mut self, event: &WidgetEvent, local_pos: Point, _ctx: &mut EventContext) {
        self.handle_event(event, local_pos);
    }

    /// 无障碍 ScrollIntoView:把相对本元素左上角的 `target` 矩形滚动到可视区。
    ///
    /// 由 [`crate::ElementTree::reveal`] 沿目标元素祖先链调用;返回 true 表示
    /// 本 State 是滚动容器并已处理。默认 false。
    fn scroll_into_view(&mut self, _target: Rect) -> bool {
        false
    }

    /// 每帧 tick(长按计时器、动画控制器等需要时间的机制;now_ms = 当前时间戳毫秒)
    fn tick(&mut self, _now_ms: u64) {}

    /// 覆盖层打开时的键盘导航钩子(方向键 / Home / End / Enter / Space)。
    ///
    /// 框架在把 KeyDown 路由到焦点元素**之前**调用**最上层 overlay** 根
    /// element 的 State;返回 true = 已消费,不再向下路由。
    /// 典型实现:Menu / Dropdown / ContextMenu 的方向键选择与 Enter 激活。
    fn handle_overlay_key(&mut self, _key: crate::KeyCode, _mods: crate::KeyModifiers) -> bool {
        false
    }

    /// ScrollView/ListView 特有:滚动动画中
    fn is_animating(&self) -> bool {
        false
    }

    /// 下一次需要 tick 的延迟(毫秒);None = 无定时任务。
    ///
    /// `is_animating == false` 但未来需要翻转的状态(光标闪烁等)用它向
    /// Runner 预约唤醒 —— 不必持续 Poll,也不会因事件循环休眠而停闪。
    fn next_animation_delay(&self, _now_ms: u64) -> Option<u64> {
        None
    }

    /// State 请求框架重建本 element 的 children(build + diff,与 update 同路径)。
    ///
    /// handle_event 里改了**影响 children 的状态**(如 TabbedPane 切换内容页)后
    /// 返回 true —— 一次性,框架取走后应复位。框架在下一帧 `paint_frame` 开头
    /// 统一处理(事件 dispatch 正在遍历 hit 链,不能原地重建子树)。
    fn take_needs_build(&mut self) -> bool {
        false
    }

    /// 竞技场仲裁:有持续型手势胜出 → 返回 Accepted 独占指针
    fn gesture_state(&self) -> Option<GestureState> {
        None
    }

    /// 被竞争失败:放弃进行中的手势
    fn reject_gestures(&mut self) {}

    /// 是否处理 build panic(ErrorBoundary 用)
    fn handles_build_error(&self) -> bool {
        false
    }

    /// build panic 时回调
    fn on_build_error(&mut self, msg: &str) {
        let _ = msg;
    }

    /// TextField/TextBox 用:IME 光标区域(x, y, line_height) — 多行感知
    fn ime_cursor_area(&self) -> Option<(f32, f32, f32)> {
        None
    }

    /// Overlay-aware capability 探测 —— 返回 self 若实现了 OverlayAware trait,否则 None
    ///
    /// 默认返回 None(core 不感知任何组件 overlay 协议),组件侧 State 按需 override。
    /// ElementTree 在 `process_overlay_intents` 中用此探测,统一消费各组件的 overlay 意图。
    fn as_overlay_aware(&mut self) -> Option<&mut dyn OverlayAware> {
        None
    }
}

// =================================================================
// 子模块声明
// =================================================================
pub mod overlay_host;
pub mod primitives;

// =================================================================
// 子模块 re-exports
// =================================================================
pub use primitives::{RRectWidget, StackWidget};
// 向后兼容别名:TooltipPlacement = AnchorPlacement
pub use overlay_host::AnchorPlacement as TooltipPlacement;