mgui-core 0.1.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 语义层 — 平台无关的无障碍抽象
//!
//! 阶段 **无障碍-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>,
}

/// 单 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 字节数;`selection` 用字符索引
/// (不是字节偏移),相等时表示只有光标。
#[derive(Clone, Debug, PartialEq)]
pub struct VirtualTextRun {
    pub character_lengths: Vec<u8>,
    pub selection: Option<(usize, usize)>,
    /// 单行 LTR 的逐字符起点(相对 TextRun bounds 左缘);多行/RTL 为 None
    pub character_positions: Option<Vec<f32>>,
    /// 逐字符宽度;与 character_positions 同时存在
    pub character_widths: Option<Vec<f32>>,
    /// 文本方向(RTL 目前不提供 positions/widths)
    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(),
        }
    }

    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
    }

    /// 禁用时同时退出焦点链:屏幕阅读器不应把焦点移到不可交互控件上。
    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>,
    /// 控件是否可交互(禁用状态时 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(),
            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
    }
}