mgui-core 0.5.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 核心事件类型 —— 原 mgui-events crate,已合入 mgui-core
//!
//! KeyCode / PointerData / WidgetEvent + GestureState + 手势常量
//! 所有 Widget / Element / RenderObject / Gesture 共享的事件协议。

use crate::geometry::Point;

// =================================================================
// 手势系统共享常量 (core 和 gesture 模块都需要)
// =================================================================

/// 判定"手指还在原处没拖动"的位移阈值(像素)
pub const TOUCH_SLOP: f32 = 4.0;
/// 双击的两次抬起之间的最大间隔(毫秒)
pub const DOUBLE_TAP_TIMEOUT_MS: u64 = 300;
/// 长按触发超时(毫秒)
pub const LONG_PRESS_TIMEOUT_MS: u64 = 500;

// =================================================================
// 鼠标按键(给 PointerDown/Up 区分左右键,支持右键 ContextMenu)
// =================================================================
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MouseButton {
    #[default]
    Left,
    Right,
    Middle,
    Other(u16),
}

/// 手势识别器状态机
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GestureState {
    /// 尚未定论,继续喂事件
    Possible,
    /// 已确认,竞技场胜出
    Accepted,
    /// 已否决(超 slop / 竞争失败)
    Rejected,
}

// =================================================================
// 键盘修饰符位图 (u8,位标志)
// =================================================================
/// 键盘修饰符位图 — 配合 KeyDown/KeyUp 一起发送。
/// - bit 0 = Shift
/// - bit 1 = Ctrl
/// - bit 2 = Alt
/// - bit 3 = Meta
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct KeyModifiers(pub u8);

impl KeyModifiers {
    pub const SHIFT: u8 = 1 << 0;
    pub const CTRL: u8 = 1 << 1;
    pub const ALT: u8 = 1 << 2;
    pub const META: u8 = 1 << 3;

    pub fn shift(&self) -> bool {
        self.0 & Self::SHIFT != 0
    }
    pub fn ctrl(&self) -> bool {
        self.0 & Self::CTRL != 0
    }
    pub fn alt(&self) -> bool {
        self.0 & Self::ALT != 0
    }
    pub fn meta(&self) -> bool {
        self.0 & Self::META != 0
    }
    pub fn none() -> Self {
        KeyModifiers(0)
    }
    pub fn ctrl_only() -> Self {
        KeyModifiers(Self::CTRL)
    }
    pub fn shift_only() -> Self {
        KeyModifiers(Self::SHIFT)
    }

    /// 平台「命令键」:macOS 是 ⌘(META),其他平台是 Ctrl。
    ///
    /// 复制/粘贴/全选/按词移动等跨平台快捷键应判断它而不是 `ctrl()`。
    pub fn command(&self) -> bool {
        #[cfg(target_os = "macos")]
        {
            self.0 & Self::META != 0
        }
        #[cfg(not(target_os = "macos"))]
        {
            self.0 & Self::CTRL != 0
        }
    }

    /// 仅按下平台命令键(测试/模拟快捷键用)。
    pub fn command_only() -> Self {
        #[cfg(target_os = "macos")]
        {
            KeyModifiers(Self::META)
        }
        #[cfg(not(target_os = "macos"))]
        {
            KeyModifiers(Self::CTRL)
        }
    }
}

// =================================================================
// 键盘按键
// =================================================================
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyCode {
    Enter,
    Space,
    Escape,
    Tab,
    /// Shift+Tab(winit 侧通过 modifiers 判断)
    BackTab,
    LeftArrow,
    RightArrow,
    UpArrow,
    DownArrow,
    PageUp,
    PageDown,
    Backspace,
    Delete,
    Home,
    End,
    /// 可打印字符(winit logical_key 的单字符)
    Char(char),
    /// F2 —— 常用的「就地编辑 / 重命名」键(DataGrid 单元格、TreeView 节点都按它进编辑)
    F2,
    /// F3 —— 开发期 Inspector Overlay 开关
    F3,
    /// F11 —— 常用全屏切换键
    F11,
    /// 其他未识别键
    Other,
}

/// 指针事件负载 — 位置 + 时间戳 + 按键类型(右键 ContextMenu)
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct PointerData {
    /// 全局坐标(窗口逻辑像素)
    pub position: Point,
    /// 事件时间戳(应用启动起的毫秒数,runtime 提供)
    pub timestamp_ms: u64,
    /// 按键(PointerDown/Up 有效;Move/Scroll 忽略)
    pub button: MouseButton,
    /// 点击时按下的修饰键(Shift+点击扩选、Ctrl+点击等)
    pub modifiers: KeyModifiers,
}

impl PointerData {
    pub fn new(position: Point, timestamp_ms: u64) -> Self {
        Self { position, timestamp_ms, button: MouseButton::default(), modifiers: KeyModifiers::none() }
    }

    /// 是否主键(Left):只有主键参与点击/拖拽激活,右键留给 ContextMenu。
    pub fn is_primary(&self) -> bool {
        self.button == MouseButton::Left
    }

    pub fn with_button(position: Point, timestamp_ms: u64, button: MouseButton) -> Self {
        Self { position, timestamp_ms, button, modifiers: KeyModifiers::none() }
    }

    /// 附加修饰键(链式 builder)
    pub fn with_modifiers(mut self, modifiers: KeyModifiers) -> Self {
        self.modifiers = modifiers;
        self
    }

    /// 测试/无时间要求的便捷构造(timestamp = 0,button = Left)
    pub fn at(position: Point) -> Self {
        Self { position, timestamp_ms: 0, button: MouseButton::Left, modifiers: KeyModifiers::none() }
    }

    pub fn at_right(position: Point) -> Self {
        Self { position, timestamp_ms: 0, button: MouseButton::Right, modifiers: KeyModifiers::none() }
    }
}

/// Widget 内部事件枚举
///
/// 经 hit_test → Element 树冒泡。
/// 包含:Pointer(Down/Up/Move/Leave/Enter/Scroll) / Key(Down/Up) /
/// Focus(Gained/Lost/Within) / IME(Enabled/Disabled/Preedit/Commit) /
/// 无障碍语义动作(SetText/SetValue/SetExpanded/SetTextSelection,定向投递不经 hit_test)。
///
/// 整体 enum 只能 Clone,不能 Copy(含 String 负载)。
#[derive(Clone, Debug, PartialEq)]
pub enum WidgetEvent {
    PointerDown(PointerData),
    PointerUp(PointerData),
    PointerMove(PointerData),
    /// 指针离开当前命中的 element
    PointerLeave,
    /// 指针进入新 element(可选派发,当前未使用)
    PointerEnter,
    /// 指针交互被取消(不是 Up)。
    ///
    /// 触发场景:手势竞技场选出胜者、捕获目标失效、窗口失焦/鼠标离开窗口。
    /// 收到后控件应清掉 pressed/dragging/down_pos 等瞬态,但不要触发点击。
    PointerCancel,
    /// 滚轮/触控板滚动:(dx, dy);正 dy = 内容向上移动
    Scroll(f32, f32),
    KeyDown(KeyCode, KeyModifiers),
    KeyUp(KeyCode, KeyModifiers),
    /// 获得焦点(发给刚被聚焦的 element)
    ///
    /// **注意**:这只表示"键盘焦点在这儿",不代表该画焦点环。用鼠标点出来的焦点
    /// 不该出现环(否则点一下按钮就多一圈高亮),要画环请听
    /// [`WidgetEvent::FocusVisibleChanged`]。
    FocusGained,
    /// 焦点环可见性变化(等价 CSS `:focus-visible`)。
    ///
    /// 由 `ElementTree` 按**焦点来路**决定并投递:Tab / 方向键等键盘导航 → `true`;
    /// 鼠标点击、程序化 `request_focus` → `false`。已聚焦的控件在收到键盘事件时也会
    /// 转成 `true`(先点一下、再用空格切换,环就该亮起来)。
    /// 控件规则:`focused` 决定"能不能响应键盘",`focus_visible` 只决定"画不画环"。
    FocusVisibleChanged(bool),
    /// 失去焦点(发给刚失焦的 element)
    FocusLost,
    /// 焦点进入/离开本元素子树(发给焦点目标的祖先;用于 Tooltip 聚焦展示等)
    FocusWithin(bool),
    /// IME 启用(输入框聚焦后系统挂起输入法)
    ImeEnabled,
    /// IME 停用
    ImeDisabled,
    /// IME 组合中:`text` 是预编辑串,`cursor` 是光标在其中的字节偏移区间
    ImePreedit(String, Option<(usize, usize)>),
    /// IME 提交:`text` 为最终插入的文本
    ImeCommit(String),
    /// 无障碍 SetValue:整体替换文本输入框内容(平台语义动作,定向投递)
    SetText(String),
    /// 无障碍 SetValue:设置数值控件值 ∈ `[0,1]`(平台语义动作,定向投递)
    SetValue(f32),
    /// 无障碍展开/收起:`item` 为虚拟项稳定 key(None = 宿主自身)
    SetExpanded {
        item: Option<u64>,
        expanded: bool,
    },
    /// 无障碍文本选区:anchor/focus 均为字符索引(不是字节偏移)
    SetTextSelection {
        anchor: usize,
        focus: usize,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn command_modifier_is_platform_aware() {
        let command = KeyModifiers::command_only();
        assert!(command.command());
        #[cfg(target_os = "macos")]
        {
            assert!(command.meta() && !command.ctrl(), "macOS 命令键应为 META");
            assert!(!KeyModifiers::ctrl_only().command(), "macOS 上 Ctrl 不是命令键");
        }
        #[cfg(not(target_os = "macos"))]
        {
            assert!(command.ctrl() && !command.meta(), "非 macOS 命令键应为 CTRL");
            assert!(!KeyModifiers(KeyModifiers::META).command(), "非 macOS 上 META 不触发命令键");
        }
    }
}