Skip to main content

mgui_core/
semantics.rs

1//! 语义层 — 平台无关的无障碍抽象
2//!
3//! 阶段 **无障碍-A1** 引入。定义不依赖 AccessKit 的语义角色/数据结构,
4//! 让 Widget 可以表达"我在做什么"而不绑定底层无障碍实现。
5//!
6//! 设计决策(对应 Advisor 建议):
7//! - **core crate 只定义平台无关结构**(`SemanticsRole` + `SemanticsData`),
8//!   accesskit / accesskit_winit 完全隔离在 runtime crate
9//! - `SemanticsData.bounds` 存**逻辑像素**(与 `geometry::Rect` 一致),
10//!   runtime 负责乘 DPR 转 AccessKit 需要的物理像素
11//! - bounds 单位:同 `ElementTree.element_origin` + RO layout size
12//!
13//! 映射表(设计文档 §20):
14//!
15//! | mgui Role | AccessKit Role | 典型 Widget |
16//! |-|-|-|
17//! | `Button`          | Role::Button          | ButtonWidget |
18//! | `CheckBox`        | Role::CheckBox        | CheckBoxWidget |
19//! | `Slider`          | Role::Slider          | SliderWidget |
20//! | `TextInput`       | Role::TextInput       | TextFieldWidget |
21//! | `Label`           | Role::Label           | TextWidget |
22//! | `Image`           | Role::Image           | ImageWidget |
23//! | `Container`       | Role::GenericContainer| StackWidget / FlexWidget |
24//! | `Unknown`         | Role::Unknown         | RRectWidget 等纯视觉 |
25
26use crate::Rect;
27
28/// 数值型控件的无障碍数值域
29///
30/// AccessKit 的 `SetValue` 依赖节点上的 min/max/step/current 元数据;
31/// 只给一个格式化字符串的话,屏幕阅读器发出的 `NumericValue` 无法落到
32/// 控件的真实值域上。Slider 这类 0..1 归一化控件必须同时提供本结构。
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct SemanticsNumericValue {
35    pub value: f64,
36    pub min: f64,
37    pub max: f64,
38    pub step: f64,
39}
40
41/// Widget 声明的语义快照(不含 bounds/children — 由 ElementTree 在构建时填入)
42///
43/// 这是 Widget trait `semantics()` 钩子的返回值。
44/// Widget 声明"我是什么、叫什么、值是什么",ElementTree 负责在遍历 Element 树时
45/// 填入 layout bounds / children 列表来组装完整的 SemanticsData。
46#[derive(Clone, Debug)]
47pub struct WidgetSemantics {
48    /// 无障碍角色
49    pub role: SemanticsRole,
50    /// 可读标签(SR 读取的文字)
51    pub label: Option<String>,
52    /// 当前值(对有状态控件)
53    /// - CheckBox → "checked" / "unchecked"
54    /// - Slider → 0.0 ~ 1.0
55    /// - TextInput → 占位符(编辑中 value 由 state override)
56    pub value: Option<String>,
57    /// 选中/勾选状态
58    pub toggled: Option<bool>,
59    /// 展开/收起状态(TreeItem / 折叠面板)
60    pub expanded: Option<bool>,
61    /// 列表项/Tab 选中状态
62    pub selected: Option<bool>,
63    /// 是否可交互
64    pub enabled: bool,
65    /// 焦点行为(true = Tab 焦点链节点 + 可接受 Action::Focus)
66    pub focusable: bool,
67    /// 数值控件的值域(Slider / Progress 等);None = 非数值控件
68    pub numeric: Option<SemanticsNumericValue>,
69    /// 模态对话框(焦点/读屏限制在子树内)
70    pub modal: bool,
71    /// 动态内容播报级别(Toast / 状态栏)
72    pub live: Option<LiveRegion>,
73    /// 虚拟子项(单 RO 虚拟列表/菜单的行语义,不进入元素树)
74    pub virtual_items: Vec<VirtualSemanticItem>,
75    /// 文本选区(宿主文本中的全局字符索引,anchor/focus);None = 无选区
76    pub text_selection: Option<(usize, usize)>,
77    /// 只读文本控件:可聚焦/选择/复制,但不暴露 SetValue 编辑动作
78    pub read_only: bool,
79}
80
81/// 单 RO 组件的子项语义(TreeView 行 / 菜单项等)。
82///
83/// 组件在 `State::semantics()` 里按当前可见行生成;runtime 会为每项创建
84/// AccessKit 子节点,并支持 Click / Expand / Collapse 动作路由。
85#[derive(Clone, Debug, PartialEq)]
86pub struct VirtualSemanticItem {
87    /// 组件内稳定 id(TreeView 用 node key)
88    pub id: u64,
89    pub role: SemanticsRole,
90    pub label: String,
91    pub selected: Option<bool>,
92    pub expanded: Option<bool>,
93    pub enabled: bool,
94    /// 相对父项(顶层项为宿主组件)左上角的逻辑像素边界
95    pub bounds: Rect,
96    /// 嵌套子项(如表格行的单元格)
97    pub children: Vec<VirtualSemanticItem>,
98    /// TextRun 专用:字符长度与选区;None = 普通虚拟项
99    pub text_run: Option<VirtualTextRun>,
100}
101
102/// TextRun 虚拟子项的 AccessKit 文本信息。
103///
104/// `character_lengths` 是每个字符的 UTF-8 字节数;跨行选区由宿主的
105/// `text_selection` 用字符索引(不是字节偏移)表达。
106#[derive(Clone, Debug, PartialEq)]
107pub struct VirtualTextRun {
108    pub character_lengths: Vec<u8>,
109    /// 本行首字符在宿主完整文本中的字符索引(跨行选区映射用)
110    pub start_char: usize,
111    /// 逐字符起点(相对 TextRun bounds;RTL 从右缘起算)
112    pub character_positions: Option<Vec<f32>>,
113    /// 逐字符宽度;与 character_positions 同时存在
114    pub character_widths: Option<Vec<f32>>,
115    /// 文本方向
116    pub rtl: bool,
117}
118
119/// 读屏动态播报级别(AccessKit `Live`)
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum LiveRegion {
122    /// 空闲时播报(如状态文本)
123    Polite,
124    /// 立即打断播报(错误/Toast)
125    Assertive,
126}
127
128impl WidgetSemantics {
129    pub fn new(role: SemanticsRole) -> Self {
130        Self {
131            role,
132            label: None,
133            value: None,
134            toggled: None,
135            expanded: None,
136            selected: None,
137            enabled: true,
138            focusable: matches!(
139                role,
140                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
141            ),
142            numeric: None,
143            modal: false,
144            live: None,
145            virtual_items: Vec::new(),
146            text_selection: None,
147            read_only: false,
148        }
149    }
150
151    pub fn with_read_only(mut self, read_only: bool) -> Self {
152        self.read_only = read_only;
153        self
154    }
155
156    pub fn with_label(mut self, label: impl Into<String>) -> Self {
157        self.label = Some(label.into());
158        self
159    }
160
161    pub fn with_value(mut self, value: impl Into<String>) -> Self {
162        self.value = Some(value.into());
163        self
164    }
165
166    pub fn with_toggled(mut self, v: bool) -> Self {
167        self.toggled = Some(v);
168        self
169    }
170
171    pub fn with_expanded(mut self, expanded: bool) -> Self {
172        self.expanded = Some(expanded);
173        self
174    }
175
176    pub fn with_selected(mut self, selected: bool) -> Self {
177        self.selected = Some(selected);
178        self
179    }
180
181    pub fn with_focusable(mut self, focusable: bool) -> Self {
182        self.focusable = focusable && self.enabled;
183        self
184    }
185
186    pub fn with_modal(mut self, modal: bool) -> Self {
187        self.modal = modal;
188        self
189    }
190
191    pub fn with_live(mut self, live: LiveRegion) -> Self {
192        self.live = Some(live);
193        self
194    }
195
196    /// 虚拟子项(TreeView 行 / 菜单项等单 RO 组件的子语义)
197    pub fn with_virtual_items(mut self, items: Vec<VirtualSemanticItem>) -> Self {
198        self.virtual_items = items;
199        self
200    }
201
202    /// 文本选区(全局字符索引;anchor == focus 表示仅光标)
203    pub fn with_text_selection(mut self, anchor: usize, focus: usize) -> Self {
204        self.text_selection = Some((anchor, focus));
205        self
206    }
207
208    /// 禁用时同时退出焦点链:屏幕阅读器不应把焦点移到不可交互控件上。
209    pub fn with_enabled(mut self, enabled: bool) -> Self {
210        self.enabled = enabled;
211        if !enabled {
212            self.focusable = false;
213        }
214        self
215    }
216
217    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
218        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
219        self
220    }
221
222    pub fn non_focusable(mut self) -> Self {
223        self.focusable = false;
224        self
225    }
226}
227
228/// 语义角色 — 描述 Widget 在无障碍树中扮演什么
229///
230/// 这是 mgui 自己的中间表示,避免 core crate 依赖 accesskit。
231/// runtime crate 负责把它翻译成 `accesskit::Role`。
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
233pub enum SemanticsRole {
234    /// 普通按钮(可聚焦 + 可 Click)
235    Button,
236    /// 复选框(可聚焦 + 可 Toggle)
237    CheckBox,
238    /// 滑块(可聚焦 + 可 SetValue `[0,1]`)
239    Slider,
240    /// 单行文本输入(可聚焦 + 可 SetValue)
241    TextInput,
242    /// 文本运行(TextInput 的虚拟子节点;支持 SetTextSelection)
243    TextRun,
244    /// 纯文本标签(只读,通常不可聚焦)
245    Label,
246    /// 静态图片
247    Image,
248    /// 容器 — 聚合子节点的语义父节点
249    Container,
250    /// 未知/无意义 — 纯视觉装饰层,从无障碍树中隐藏
251    Unknown,
252    /// 模态/非模态对话框
253    Dialog,
254    /// 页签
255    Tab,
256    /// 页签条容器
257    TabList,
258    /// 页签内容面板
259    TabPanel,
260    /// 列表容器
261    List,
262    /// 列表项
263    ListItem,
264    /// 下拉/组合框选项
265    ListOption,
266    /// 表格/网格
267    Grid,
268    /// 表格行(虚拟子项用)
269    GridRow,
270    /// 表格单元格(虚拟子项用)
271    GridCell,
272    /// 树
273    Tree,
274    /// 树节点
275    TreeItem,
276    /// 进度指示器
277    Progress,
278    /// Toast / 通知(配合 live region)
279    Toast,
280    /// 弹出菜单容器
281    Menu,
282    /// 菜单项(可 Click)
283    MenuItem,
284    /// 下拉组合框(可 Click / 展开)
285    ComboBox,
286    /// 单选组容器
287    RadioGroup,
288    /// 单选按钮(可 Click)
289    RadioButton,
290    /// 工具提示气泡
291    Tooltip,
292    /// 可拖动分隔条
293    Splitter,
294}
295
296/// 单个节点的语义快照(与 Element 1:1 关联)
297///
298/// runtime crate 从 ElementTree 遍历收集 `Vec<(ElementId, SemanticsData)`,
299/// 然后翻译成 `Vec<(accesskit::NodeId, accesskit::Node)>` 构建 TreeUpdate。
300///
301/// bounds 单位:逻辑像素(同 Element.origin + RO layout size)。
302/// runtime 在推送 TreeUpdate 前乘 DPR 转物理像素。
303#[derive(Clone, Debug)]
304pub struct SemanticsData {
305    /// 无障碍角色
306    pub role: SemanticsRole,
307    /// 可读标签(SR 读取的文字,优先于子节点文字)
308    /// - Button: 通常来自 `.label` TextWidget 的内容
309    /// - TextInput: placeholder 或当前 value
310    /// - 纯视觉节点: None(由子节点聚合)
311    pub label: Option<String>,
312    /// 当前值(对有状态控件)
313    /// - CheckBox → "checked" / "unchecked"
314    /// - Slider → 0.0 ~ 1.0
315    /// - TextInput → 输入文字
316    pub value: Option<String>,
317    /// 是否当前处于激活/选中状态(CheckBox checked, Slider enabled 等)
318    pub toggled: Option<bool>,
319    /// 展开/收起状态(TreeItem / 折叠面板)
320    pub expanded: Option<bool>,
321    /// 列表项/Tab 选中状态
322    pub selected: Option<bool>,
323    /// 是否模态对话框
324    pub modal: bool,
325    /// 动态内容播报级别(Toast 等)
326    pub live: Option<LiveRegion>,
327    /// 虚拟子项(单 RO 列表/菜单的行语义)
328    pub virtual_items: Vec<VirtualSemanticItem>,
329    /// 文本选区(宿主文本中的全局字符索引);None = 无选区
330    pub text_selection: Option<(usize, usize)>,
331    /// 只读文本控件(不暴露 SetValue)
332    pub read_only: bool,
333    /// 控件是否可交互(禁用状态时 SR 应告知用户)
334    pub enabled: bool,
335    /// 逻辑像素 bounds(位置 + 尺寸),runtime 乘 DPR 送 AccessKit
336    pub bounds: Rect,
337    /// 子节点 ElementId 列表(用于构建无障碍树结构)
338    pub children: Vec<crate::id::ElementId>,
339    /// 是否是焦点目标(默认 role 推断;显式覆盖)
340    pub focusable: bool,
341    /// 数值控件的值域(Slider 等);runtime 转成 AccessKit 的 numeric_value 系列属性
342    pub numeric: Option<SemanticsNumericValue>,
343}
344
345impl SemanticsData {
346    /// 子节点 ElementId 列表(只读)。
347    pub fn children(&self) -> &[crate::id::ElementId] {
348        &self.children
349    }
350
351    /// 最简构造:只给 role 和 bounds,其他用合理默认
352    pub fn new(role: SemanticsRole, bounds: Rect) -> Self {
353        Self {
354            role,
355            label: None,
356            value: None,
357            toggled: None,
358            expanded: None,
359            selected: None,
360            modal: false,
361            live: None,
362            virtual_items: Vec::new(),
363            text_selection: None,
364            read_only: false,
365            enabled: true,
366            bounds,
367            children: Vec::new(),
368            focusable: matches!(
369                role,
370                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
371            ),
372            numeric: None,
373        }
374    }
375
376    pub fn with_label(mut self, label: impl Into<String>) -> Self {
377        self.label = Some(label.into());
378        self
379    }
380
381    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
382        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
383        self
384    }
385
386    pub fn with_value(mut self, value: impl Into<String>) -> Self {
387        self.value = Some(value.into());
388        self
389    }
390
391    pub fn with_toggled(mut self, v: bool) -> Self {
392        self.toggled = Some(v);
393        self
394    }
395
396    pub fn with_expanded(mut self, expanded: bool) -> Self {
397        self.expanded = Some(expanded);
398        self
399    }
400
401    pub fn with_selected(mut self, selected: bool) -> Self {
402        self.selected = Some(selected);
403        self
404    }
405
406    pub fn with_modal(mut self, modal: bool) -> Self {
407        self.modal = modal;
408        self
409    }
410
411    pub fn with_live(mut self, live: LiveRegion) -> Self {
412        self.live = Some(live);
413        self
414    }
415
416    pub fn with_children(mut self, children: Vec<crate::id::ElementId>) -> Self {
417        self.children = children;
418        self
419    }
420
421    /// 文本选区(全局字符索引;anchor == focus 表示仅光标)
422    pub fn with_text_selection(mut self, anchor: usize, focus: usize) -> Self {
423        self.text_selection = Some((anchor, focus));
424        self
425    }
426}