mgui-core 0.5.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
//! 语义层 — 平台无关的无障碍抽象
//!
//! 阶段 **无障碍-A1** 引入。定义不依赖 AccessKit 的语义角色/数据结构,
//! 让 Widget 可以表达"我在做什么"而不绑定底层无障碍实现。
//!
//! 设计决策(对应 Advisor 建议):
//! - **core crate 只定义平台无关结构**(`SemanticsRole` + `SemanticsData`),
//!   accesskit / accesskit_winit 完全隔离在 runtime crate
//! - `SemanticsData.bounds` 存**逻辑像素**(与 `geometry::Rect` 一致),
//!   runtime 负责乘 DPR 转 AccessKit 需要的物理像素
//! - bounds 单位:同 `ElementTree.element_origin` + RO layout size
//!
//! 映射表(设计文档 §20):
//!
//! | mgui Role | AccessKit Role | 典型 Widget |
//! |-|-|-|
//! | `Button`          | Role::Button          | ButtonWidget |
//! | `CheckBox`        | Role::CheckBox        | CheckBoxWidget |
//! | `Slider`          | Role::Slider          | SliderWidget |
//! | `TextInput`       | Role::TextInput       | TextFieldWidget |
//! | `Label`           | Role::Label           | TextWidget |
//! | `Image`           | Role::Image           | ImageWidget |
//! | `Container`       | Role::GenericContainer| StackWidget / FlexWidget |
//! | `Unknown`         | Role::Unknown         | RRectWidget 等纯视觉 |

use crate::Rect;

/// 数值型控件的无障碍数值域
///
/// AccessKit 的 `SetValue` 依赖节点上的 min/max/step/current 元数据;
/// 只给一个格式化字符串的话,屏幕阅读器发出的 `NumericValue` 无法落到
/// 控件的真实值域上。Slider 这类 0..1 归一化控件必须同时提供本结构。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SemanticsNumericValue {
    pub value: f64,
    pub min: f64,
    pub max: f64,
    pub step: f64,
}

/// Widget 声明的语义快照(不含 bounds/children — 由 ElementTree 在构建时填入)
///
/// 这是 Widget trait `semantics()` 钩子的返回值。
/// Widget 声明"我是什么、叫什么、值是什么",ElementTree 负责在遍历 Element 树时
/// 填入 layout bounds / children 列表来组装完整的 SemanticsData。
#[derive(Clone, Debug)]
pub struct WidgetSemantics {
    /// 无障碍角色
    pub role: SemanticsRole,
    /// 可读标签(SR 读取的文字)
    pub label: Option<String>,
    /// 当前值(对有状态控件)
    /// - CheckBox → "checked" / "unchecked"
    /// - Slider → 0.0 ~ 1.0
    /// - TextInput → 占位符(编辑中 value 由 state override)
    pub value: Option<String>,
    /// 选中/勾选状态
    pub toggled: Option<bool>,
    /// 展开/收起状态(TreeItem / 折叠面板)
    pub expanded: Option<bool>,
    /// 列表项/Tab 选中状态
    pub selected: Option<bool>,
    /// 是否可交互
    pub enabled: bool,
    /// 焦点行为(true = Tab 焦点链节点 + 可接受 Action::Focus)
    pub focusable: bool,
    /// 数值控件的值域(Slider / Progress 等);None = 非数值控件
    pub numeric: Option<SemanticsNumericValue>,
    /// 模态对话框(焦点/读屏限制在子树内)
    pub modal: bool,
    /// 动态内容播报级别(Toast / 状态栏)
    pub live: Option<LiveRegion>,
    /// 虚拟子项(单 RO 虚拟列表/菜单的行语义,不进入元素树)
    pub virtual_items: Vec<VirtualSemanticItem>,
    /// 文本选区(宿主文本中的全局字符索引,anchor/focus);None = 无选区
    pub text_selection: Option<(usize, usize)>,
    /// 只读文本控件:可聚焦/选择/复制,但不暴露 SetValue 编辑动作
    pub read_only: bool,
}

/// 单 RO 组件的子项语义(TreeView 行 / 菜单项等)。
///
/// 组件在 `State::semantics()` 里按当前可见行生成;runtime 会为每项创建
/// AccessKit 子节点,并支持 Click / Expand / Collapse 动作路由。
#[derive(Clone, Debug, PartialEq)]
pub struct VirtualSemanticItem {
    /// 组件内稳定 id(TreeView 用 node key)
    pub id: u64,
    pub role: SemanticsRole,
    pub label: String,
    pub selected: Option<bool>,
    pub expanded: Option<bool>,
    pub enabled: bool,
    /// 相对父项(顶层项为宿主组件)左上角的逻辑像素边界
    pub bounds: Rect,
    /// 嵌套子项(如表格行的单元格)
    pub children: Vec<VirtualSemanticItem>,
    /// TextRun 专用:字符长度与选区;None = 普通虚拟项
    pub text_run: Option<VirtualTextRun>,
}

/// TextRun 虚拟子项的 AccessKit 文本信息。
///
/// `character_lengths` 是每个字符的 UTF-8 字节数;跨行选区由宿主的
/// `text_selection` 用字符索引(不是字节偏移)表达。
#[derive(Clone, Debug, PartialEq)]
pub struct VirtualTextRun {
    pub character_lengths: Vec<u8>,
    /// 本行首字符在宿主完整文本中的字符索引(跨行选区映射用)
    pub start_char: usize,
    /// 逐字符起点(相对 TextRun bounds;RTL 从右缘起算)
    pub character_positions: Option<Vec<f32>>,
    /// 逐字符宽度;与 character_positions 同时存在
    pub character_widths: Option<Vec<f32>>,
    /// 文本方向
    pub rtl: bool,
}

/// 读屏动态播报级别(AccessKit `Live`)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiveRegion {
    /// 空闲时播报(如状态文本)
    Polite,
    /// 立即打断播报(错误/Toast)
    Assertive,
}

impl WidgetSemantics {
    pub fn new(role: SemanticsRole) -> Self {
        Self {
            role,
            label: None,
            value: None,
            toggled: None,
            expanded: None,
            selected: None,
            enabled: true,
            focusable: matches!(
                role,
                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
            ),
            numeric: None,
            modal: false,
            live: None,
            virtual_items: Vec::new(),
            text_selection: None,
            read_only: false,
        }
    }

    pub fn with_read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn with_toggled(mut self, v: bool) -> Self {
        self.toggled = Some(v);
        self
    }

    pub fn with_expanded(mut self, expanded: bool) -> Self {
        self.expanded = Some(expanded);
        self
    }

    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    pub fn with_focusable(mut self, focusable: bool) -> Self {
        self.focusable = focusable && self.enabled;
        self
    }

    pub fn with_modal(mut self, modal: bool) -> Self {
        self.modal = modal;
        self
    }

    pub fn with_live(mut self, live: LiveRegion) -> Self {
        self.live = Some(live);
        self
    }

    /// 虚拟子项(TreeView 行 / 菜单项等单 RO 组件的子语义)
    pub fn with_virtual_items(mut self, items: Vec<VirtualSemanticItem>) -> Self {
        self.virtual_items = items;
        self
    }

    /// 文本选区(全局字符索引;anchor == focus 表示仅光标)
    pub fn with_text_selection(mut self, anchor: usize, focus: usize) -> Self {
        self.text_selection = Some((anchor, focus));
        self
    }

    /// 禁用时同时退出焦点链:屏幕阅读器不应把焦点移到不可交互控件上。
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        if !enabled {
            self.focusable = false;
        }
        self
    }

    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
        self
    }

    pub fn non_focusable(mut self) -> Self {
        self.focusable = false;
        self
    }
}

/// 语义角色 — 描述 Widget 在无障碍树中扮演什么
///
/// 这是 mgui 自己的中间表示,避免 core crate 依赖 accesskit。
/// runtime crate 负责把它翻译成 `accesskit::Role`。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SemanticsRole {
    /// 普通按钮(可聚焦 + 可 Click)
    Button,
    /// 复选框(可聚焦 + 可 Toggle)
    CheckBox,
    /// 滑块(可聚焦 + 可 SetValue `[0,1]`)
    Slider,
    /// 单行文本输入(可聚焦 + 可 SetValue)
    TextInput,
    /// 文本运行(TextInput 的虚拟子节点;支持 SetTextSelection)
    TextRun,
    /// 纯文本标签(只读,通常不可聚焦)
    Label,
    /// 静态图片
    Image,
    /// 容器 — 聚合子节点的语义父节点
    Container,
    /// 未知/无意义 — 纯视觉装饰层,从无障碍树中隐藏
    Unknown,
    /// 模态/非模态对话框
    Dialog,
    /// 页签
    Tab,
    /// 页签条容器
    TabList,
    /// 页签内容面板
    TabPanel,
    /// 列表容器
    List,
    /// 列表项
    ListItem,
    /// 下拉/组合框选项
    ListOption,
    /// 表格/网格
    Grid,
    /// 表格行(虚拟子项用)
    GridRow,
    /// 表格单元格(虚拟子项用)
    GridCell,
    /// 树
    Tree,
    /// 树节点
    TreeItem,
    /// 进度指示器
    Progress,
    /// Toast / 通知(配合 live region)
    Toast,
    /// 弹出菜单容器
    Menu,
    /// 菜单项(可 Click)
    MenuItem,
    /// 下拉组合框(可 Click / 展开)
    ComboBox,
    /// 单选组容器
    RadioGroup,
    /// 单选按钮(可 Click)
    RadioButton,
    /// 工具提示气泡
    Tooltip,
    /// 可拖动分隔条
    Splitter,
}

/// 单个节点的语义快照(与 Element 1:1 关联)
///
/// runtime crate 从 ElementTree 遍历收集 `Vec<(ElementId, SemanticsData)`,
/// 然后翻译成 `Vec<(accesskit::NodeId, accesskit::Node)>` 构建 TreeUpdate。
///
/// bounds 单位:逻辑像素(同 Element.origin + RO layout size)。
/// runtime 在推送 TreeUpdate 前乘 DPR 转物理像素。
#[derive(Clone, Debug)]
pub struct SemanticsData {
    /// 无障碍角色
    pub role: SemanticsRole,
    /// 可读标签(SR 读取的文字,优先于子节点文字)
    /// - Button: 通常来自 `.label` TextWidget 的内容
    /// - TextInput: placeholder 或当前 value
    /// - 纯视觉节点: None(由子节点聚合)
    pub label: Option<String>,
    /// 当前值(对有状态控件)
    /// - CheckBox → "checked" / "unchecked"
    /// - Slider → 0.0 ~ 1.0
    /// - TextInput → 输入文字
    pub value: Option<String>,
    /// 是否当前处于激活/选中状态(CheckBox checked, Slider enabled 等)
    pub toggled: Option<bool>,
    /// 展开/收起状态(TreeItem / 折叠面板)
    pub expanded: Option<bool>,
    /// 列表项/Tab 选中状态
    pub selected: Option<bool>,
    /// 是否模态对话框
    pub modal: bool,
    /// 动态内容播报级别(Toast 等)
    pub live: Option<LiveRegion>,
    /// 虚拟子项(单 RO 列表/菜单的行语义)
    pub virtual_items: Vec<VirtualSemanticItem>,
    /// 文本选区(宿主文本中的全局字符索引);None = 无选区
    pub text_selection: Option<(usize, usize)>,
    /// 只读文本控件(不暴露 SetValue)
    pub read_only: bool,
    /// 控件是否可交互(禁用状态时 SR 应告知用户)
    pub enabled: bool,
    /// 逻辑像素 bounds(位置 + 尺寸),runtime 乘 DPR 送 AccessKit
    pub bounds: Rect,
    /// 子节点 ElementId 列表(用于构建无障碍树结构)
    pub children: Vec<crate::id::ElementId>,
    /// 是否是焦点目标(默认 role 推断;显式覆盖)
    pub focusable: bool,
    /// 数值控件的值域(Slider 等);runtime 转成 AccessKit 的 numeric_value 系列属性
    pub numeric: Option<SemanticsNumericValue>,
}

impl SemanticsData {
    /// 子节点 ElementId 列表(只读)。
    pub fn children(&self) -> &[crate::id::ElementId] {
        &self.children
    }

    /// 最简构造:只给 role 和 bounds,其他用合理默认
    pub fn new(role: SemanticsRole, bounds: Rect) -> Self {
        Self {
            role,
            label: None,
            value: None,
            toggled: None,
            expanded: None,
            selected: None,
            modal: false,
            live: None,
            virtual_items: Vec::new(),
            text_selection: None,
            read_only: false,
            enabled: true,
            bounds,
            children: Vec::new(),
            focusable: matches!(
                role,
                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
            ),
            numeric: None,
        }
    }

    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
        self
    }

    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn with_toggled(mut self, v: bool) -> Self {
        self.toggled = Some(v);
        self
    }

    pub fn with_expanded(mut self, expanded: bool) -> Self {
        self.expanded = Some(expanded);
        self
    }

    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    pub fn with_modal(mut self, modal: bool) -> Self {
        self.modal = modal;
        self
    }

    pub fn with_live(mut self, live: LiveRegion) -> Self {
        self.live = Some(live);
        self
    }

    pub fn with_children(mut self, children: Vec<crate::id::ElementId>) -> Self {
        self.children = children;
        self
    }

    /// 文本选区(全局字符索引;anchor == focus 表示仅光标)
    pub fn with_text_selection(mut self, anchor: usize, focus: usize) -> Self {
        self.text_selection = Some((anchor, focus));
        self
    }
}