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}
76
77/// 单 RO 组件的子项语义(TreeView 行 / 菜单项等)。
78///
79/// 组件在 `State::semantics()` 里按当前可见行生成;runtime 会为每项创建
80/// AccessKit 子节点,并支持 Click / Expand / Collapse 动作路由。
81#[derive(Clone, Debug, PartialEq)]
82pub struct VirtualSemanticItem {
83    /// 组件内稳定 id(TreeView 用 node key)
84    pub id: u64,
85    pub role: SemanticsRole,
86    pub label: String,
87    pub selected: Option<bool>,
88    pub expanded: Option<bool>,
89    pub enabled: bool,
90    /// 相对父项(顶层项为宿主组件)左上角的逻辑像素边界
91    pub bounds: Rect,
92    /// 嵌套子项(如表格行的单元格)
93    pub children: Vec<VirtualSemanticItem>,
94    /// TextRun 专用:字符长度与选区;None = 普通虚拟项
95    pub text_run: Option<VirtualTextRun>,
96}
97
98/// TextRun 虚拟子项的 AccessKit 文本信息。
99///
100/// `character_lengths` 是每个字符的 UTF-8 字节数;`selection` 用字符索引
101/// (不是字节偏移),相等时表示只有光标。
102#[derive(Clone, Debug, PartialEq)]
103pub struct VirtualTextRun {
104    pub character_lengths: Vec<u8>,
105    pub selection: Option<(usize, usize)>,
106    /// 单行 LTR 的逐字符起点(相对 TextRun bounds 左缘);多行/RTL 为 None
107    pub character_positions: Option<Vec<f32>>,
108    /// 逐字符宽度;与 character_positions 同时存在
109    pub character_widths: Option<Vec<f32>>,
110    /// 文本方向(RTL 目前不提供 positions/widths)
111    pub rtl: bool,
112}
113
114/// 读屏动态播报级别(AccessKit `Live`)
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub enum LiveRegion {
117    /// 空闲时播报(如状态文本)
118    Polite,
119    /// 立即打断播报(错误/Toast)
120    Assertive,
121}
122
123impl WidgetSemantics {
124    pub fn new(role: SemanticsRole) -> Self {
125        Self {
126            role,
127            label: None,
128            value: None,
129            toggled: None,
130            expanded: None,
131            selected: None,
132            enabled: true,
133            focusable: matches!(
134                role,
135                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
136            ),
137            numeric: None,
138            modal: false,
139            live: None,
140            virtual_items: Vec::new(),
141        }
142    }
143
144    pub fn with_label(mut self, label: impl Into<String>) -> Self {
145        self.label = Some(label.into());
146        self
147    }
148
149    pub fn with_value(mut self, value: impl Into<String>) -> Self {
150        self.value = Some(value.into());
151        self
152    }
153
154    pub fn with_toggled(mut self, v: bool) -> Self {
155        self.toggled = Some(v);
156        self
157    }
158
159    pub fn with_expanded(mut self, expanded: bool) -> Self {
160        self.expanded = Some(expanded);
161        self
162    }
163
164    pub fn with_selected(mut self, selected: bool) -> Self {
165        self.selected = Some(selected);
166        self
167    }
168
169    pub fn with_focusable(mut self, focusable: bool) -> Self {
170        self.focusable = focusable && self.enabled;
171        self
172    }
173
174    pub fn with_modal(mut self, modal: bool) -> Self {
175        self.modal = modal;
176        self
177    }
178
179    pub fn with_live(mut self, live: LiveRegion) -> Self {
180        self.live = Some(live);
181        self
182    }
183
184    /// 虚拟子项(TreeView 行 / 菜单项等单 RO 组件的子语义)
185    pub fn with_virtual_items(mut self, items: Vec<VirtualSemanticItem>) -> Self {
186        self.virtual_items = items;
187        self
188    }
189
190    /// 禁用时同时退出焦点链:屏幕阅读器不应把焦点移到不可交互控件上。
191    pub fn with_enabled(mut self, enabled: bool) -> Self {
192        self.enabled = enabled;
193        if !enabled {
194            self.focusable = false;
195        }
196        self
197    }
198
199    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
200        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
201        self
202    }
203
204    pub fn non_focusable(mut self) -> Self {
205        self.focusable = false;
206        self
207    }
208}
209
210/// 语义角色 — 描述 Widget 在无障碍树中扮演什么
211///
212/// 这是 mgui 自己的中间表示,避免 core crate 依赖 accesskit。
213/// runtime crate 负责把它翻译成 `accesskit::Role`。
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub enum SemanticsRole {
216    /// 普通按钮(可聚焦 + 可 Click)
217    Button,
218    /// 复选框(可聚焦 + 可 Toggle)
219    CheckBox,
220    /// 滑块(可聚焦 + 可 SetValue `[0,1]`)
221    Slider,
222    /// 单行文本输入(可聚焦 + 可 SetValue)
223    TextInput,
224    /// 文本运行(TextInput 的虚拟子节点;支持 SetTextSelection)
225    TextRun,
226    /// 纯文本标签(只读,通常不可聚焦)
227    Label,
228    /// 静态图片
229    Image,
230    /// 容器 — 聚合子节点的语义父节点
231    Container,
232    /// 未知/无意义 — 纯视觉装饰层,从无障碍树中隐藏
233    Unknown,
234    /// 模态/非模态对话框
235    Dialog,
236    /// 页签
237    Tab,
238    /// 页签条容器
239    TabList,
240    /// 页签内容面板
241    TabPanel,
242    /// 列表容器
243    List,
244    /// 列表项
245    ListItem,
246    /// 下拉/组合框选项
247    ListOption,
248    /// 表格/网格
249    Grid,
250    /// 表格行(虚拟子项用)
251    GridRow,
252    /// 表格单元格(虚拟子项用)
253    GridCell,
254    /// 树
255    Tree,
256    /// 树节点
257    TreeItem,
258    /// 进度指示器
259    Progress,
260    /// Toast / 通知(配合 live region)
261    Toast,
262    /// 弹出菜单容器
263    Menu,
264    /// 菜单项(可 Click)
265    MenuItem,
266    /// 下拉组合框(可 Click / 展开)
267    ComboBox,
268    /// 单选组容器
269    RadioGroup,
270    /// 单选按钮(可 Click)
271    RadioButton,
272    /// 工具提示气泡
273    Tooltip,
274    /// 可拖动分隔条
275    Splitter,
276}
277
278/// 单个节点的语义快照(与 Element 1:1 关联)
279///
280/// runtime crate 从 ElementTree 遍历收集 `Vec<(ElementId, SemanticsData)`,
281/// 然后翻译成 `Vec<(accesskit::NodeId, accesskit::Node)>` 构建 TreeUpdate。
282///
283/// bounds 单位:逻辑像素(同 Element.origin + RO layout size)。
284/// runtime 在推送 TreeUpdate 前乘 DPR 转物理像素。
285#[derive(Clone, Debug)]
286pub struct SemanticsData {
287    /// 无障碍角色
288    pub role: SemanticsRole,
289    /// 可读标签(SR 读取的文字,优先于子节点文字)
290    /// - Button: 通常来自 `.label` TextWidget 的内容
291    /// - TextInput: placeholder 或当前 value
292    /// - 纯视觉节点: None(由子节点聚合)
293    pub label: Option<String>,
294    /// 当前值(对有状态控件)
295    /// - CheckBox → "checked" / "unchecked"
296    /// - Slider → 0.0 ~ 1.0
297    /// - TextInput → 输入文字
298    pub value: Option<String>,
299    /// 是否当前处于激活/选中状态(CheckBox checked, Slider enabled 等)
300    pub toggled: Option<bool>,
301    /// 展开/收起状态(TreeItem / 折叠面板)
302    pub expanded: Option<bool>,
303    /// 列表项/Tab 选中状态
304    pub selected: Option<bool>,
305    /// 是否模态对话框
306    pub modal: bool,
307    /// 动态内容播报级别(Toast 等)
308    pub live: Option<LiveRegion>,
309    /// 虚拟子项(单 RO 列表/菜单的行语义)
310    pub virtual_items: Vec<VirtualSemanticItem>,
311    /// 控件是否可交互(禁用状态时 SR 应告知用户)
312    pub enabled: bool,
313    /// 逻辑像素 bounds(位置 + 尺寸),runtime 乘 DPR 送 AccessKit
314    pub bounds: Rect,
315    /// 子节点 ElementId 列表(用于构建无障碍树结构)
316    pub children: Vec<crate::id::ElementId>,
317    /// 是否是焦点目标(默认 role 推断;显式覆盖)
318    pub focusable: bool,
319    /// 数值控件的值域(Slider 等);runtime 转成 AccessKit 的 numeric_value 系列属性
320    pub numeric: Option<SemanticsNumericValue>,
321}
322
323impl SemanticsData {
324    /// 子节点 ElementId 列表(只读)。
325    pub fn children(&self) -> &[crate::id::ElementId] {
326        &self.children
327    }
328
329    /// 最简构造:只给 role 和 bounds,其他用合理默认
330    pub fn new(role: SemanticsRole, bounds: Rect) -> Self {
331        Self {
332            role,
333            label: None,
334            value: None,
335            toggled: None,
336            expanded: None,
337            selected: None,
338            modal: false,
339            live: None,
340            virtual_items: Vec::new(),
341            enabled: true,
342            bounds,
343            children: Vec::new(),
344            focusable: matches!(
345                role,
346                SemanticsRole::Button | SemanticsRole::CheckBox | SemanticsRole::Slider | SemanticsRole::TextInput
347            ),
348            numeric: None,
349        }
350    }
351
352    pub fn with_label(mut self, label: impl Into<String>) -> Self {
353        self.label = Some(label.into());
354        self
355    }
356
357    pub fn with_numeric_value(mut self, value: f64, min: f64, max: f64, step: f64) -> Self {
358        self.numeric = Some(SemanticsNumericValue { value, min, max, step });
359        self
360    }
361
362    pub fn with_value(mut self, value: impl Into<String>) -> Self {
363        self.value = Some(value.into());
364        self
365    }
366
367    pub fn with_toggled(mut self, v: bool) -> Self {
368        self.toggled = Some(v);
369        self
370    }
371
372    pub fn with_expanded(mut self, expanded: bool) -> Self {
373        self.expanded = Some(expanded);
374        self
375    }
376
377    pub fn with_selected(mut self, selected: bool) -> Self {
378        self.selected = Some(selected);
379        self
380    }
381
382    pub fn with_modal(mut self, modal: bool) -> Self {
383        self.modal = modal;
384        self
385    }
386
387    pub fn with_live(mut self, live: LiveRegion) -> Self {
388        self.live = Some(live);
389        self
390    }
391
392    pub fn with_children(mut self, children: Vec<crate::id::ElementId>) -> Self {
393        self.children = children;
394        self
395    }
396}