Skip to main content

mgui_core/
events.rs

1//! 核心事件类型 —— 原 mgui-events crate,已合入 mgui-core
2//!
3//! KeyCode / PointerData / WidgetEvent + GestureState + 手势常量
4//! 所有 Widget / Element / RenderObject / Gesture 共享的事件协议。
5
6use crate::geometry::Point;
7
8// =================================================================
9// 手势系统共享常量 (core 和 gesture 模块都需要)
10// =================================================================
11
12/// 判定"手指还在原处没拖动"的位移阈值(像素)
13pub const TOUCH_SLOP: f32 = 4.0;
14/// 双击的两次抬起之间的最大间隔(毫秒)
15pub const DOUBLE_TAP_TIMEOUT_MS: u64 = 300;
16/// 长按触发超时(毫秒)
17pub const LONG_PRESS_TIMEOUT_MS: u64 = 500;
18
19// =================================================================
20// 鼠标按键(给 PointerDown/Up 区分左右键,支持右键 ContextMenu)
21// =================================================================
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
23pub enum MouseButton {
24    #[default]
25    Left,
26    Right,
27    Middle,
28    Other(u16),
29}
30
31/// 手势识别器状态机
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum GestureState {
34    /// 尚未定论,继续喂事件
35    Possible,
36    /// 已确认,竞技场胜出
37    Accepted,
38    /// 已否决(超 slop / 竞争失败)
39    Rejected,
40}
41
42// =================================================================
43// 键盘修饰符位图 (u8,位标志)
44// =================================================================
45/// 键盘修饰符位图 — 配合 KeyDown/KeyUp 一起发送。
46/// - bit 0 = Shift
47/// - bit 1 = Ctrl
48/// - bit 2 = Alt
49/// - bit 3 = Meta
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
51pub struct KeyModifiers(pub u8);
52
53impl KeyModifiers {
54    pub const SHIFT: u8 = 1 << 0;
55    pub const CTRL: u8 = 1 << 1;
56    pub const ALT: u8 = 1 << 2;
57    pub const META: u8 = 1 << 3;
58
59    pub fn shift(&self) -> bool {
60        self.0 & Self::SHIFT != 0
61    }
62    pub fn ctrl(&self) -> bool {
63        self.0 & Self::CTRL != 0
64    }
65    pub fn alt(&self) -> bool {
66        self.0 & Self::ALT != 0
67    }
68    pub fn meta(&self) -> bool {
69        self.0 & Self::META != 0
70    }
71    pub fn none() -> Self {
72        KeyModifiers(0)
73    }
74    pub fn ctrl_only() -> Self {
75        KeyModifiers(Self::CTRL)
76    }
77    pub fn shift_only() -> Self {
78        KeyModifiers(Self::SHIFT)
79    }
80
81    /// 平台「命令键」:macOS 是 ⌘(META),其他平台是 Ctrl。
82    ///
83    /// 复制/粘贴/全选/按词移动等跨平台快捷键应判断它而不是 `ctrl()`。
84    pub fn command(&self) -> bool {
85        #[cfg(target_os = "macos")]
86        {
87            self.0 & Self::META != 0
88        }
89        #[cfg(not(target_os = "macos"))]
90        {
91            self.0 & Self::CTRL != 0
92        }
93    }
94
95    /// 仅按下平台命令键(测试/模拟快捷键用)。
96    pub fn command_only() -> Self {
97        #[cfg(target_os = "macos")]
98        {
99            KeyModifiers(Self::META)
100        }
101        #[cfg(not(target_os = "macos"))]
102        {
103            KeyModifiers(Self::CTRL)
104        }
105    }
106}
107
108// =================================================================
109// 键盘按键
110// =================================================================
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum KeyCode {
113    Enter,
114    Space,
115    Escape,
116    Tab,
117    /// Shift+Tab(winit 侧通过 modifiers 判断)
118    BackTab,
119    LeftArrow,
120    RightArrow,
121    UpArrow,
122    DownArrow,
123    PageUp,
124    PageDown,
125    Backspace,
126    Delete,
127    Home,
128    End,
129    /// 可打印字符(winit logical_key 的单字符)
130    Char(char),
131    /// F2 —— 常用的「就地编辑 / 重命名」键(DataGrid 单元格、TreeView 节点都按它进编辑)
132    F2,
133    /// F3 —— 开发期 Inspector Overlay 开关
134    F3,
135    /// F11 —— 常用全屏切换键
136    F11,
137    /// 其他未识别键
138    Other,
139}
140
141/// 指针事件负载 — 位置 + 时间戳 + 按键类型(右键 ContextMenu)
142#[derive(Clone, Copy, Debug, PartialEq, Default)]
143pub struct PointerData {
144    /// 全局坐标(窗口逻辑像素)
145    pub position: Point,
146    /// 事件时间戳(应用启动起的毫秒数,runtime 提供)
147    pub timestamp_ms: u64,
148    /// 按键(PointerDown/Up 有效;Move/Scroll 忽略)
149    pub button: MouseButton,
150    /// 点击时按下的修饰键(Shift+点击扩选、Ctrl+点击等)
151    pub modifiers: KeyModifiers,
152}
153
154impl PointerData {
155    pub fn new(position: Point, timestamp_ms: u64) -> Self {
156        Self { position, timestamp_ms, button: MouseButton::default(), modifiers: KeyModifiers::none() }
157    }
158
159    /// 是否主键(Left):只有主键参与点击/拖拽激活,右键留给 ContextMenu。
160    pub fn is_primary(&self) -> bool {
161        self.button == MouseButton::Left
162    }
163
164    pub fn with_button(position: Point, timestamp_ms: u64, button: MouseButton) -> Self {
165        Self { position, timestamp_ms, button, modifiers: KeyModifiers::none() }
166    }
167
168    /// 附加修饰键(链式 builder)
169    pub fn with_modifiers(mut self, modifiers: KeyModifiers) -> Self {
170        self.modifiers = modifiers;
171        self
172    }
173
174    /// 测试/无时间要求的便捷构造(timestamp = 0,button = Left)
175    pub fn at(position: Point) -> Self {
176        Self { position, timestamp_ms: 0, button: MouseButton::Left, modifiers: KeyModifiers::none() }
177    }
178
179    pub fn at_right(position: Point) -> Self {
180        Self { position, timestamp_ms: 0, button: MouseButton::Right, modifiers: KeyModifiers::none() }
181    }
182}
183
184/// Widget 内部事件枚举
185///
186/// 经 hit_test → Element 树冒泡。
187/// 包含:Pointer(Down/Up/Move/Leave/Enter/Scroll) / Key(Down/Up) /
188/// Focus(Gained/Lost/Within) / IME(Enabled/Disabled/Preedit/Commit) /
189/// 无障碍语义动作(SetText/SetValue/SetExpanded/SetTextSelection,定向投递不经 hit_test)。
190///
191/// 整体 enum 只能 Clone,不能 Copy(含 String 负载)。
192#[derive(Clone, Debug, PartialEq)]
193pub enum WidgetEvent {
194    PointerDown(PointerData),
195    PointerUp(PointerData),
196    PointerMove(PointerData),
197    /// 指针离开当前命中的 element
198    PointerLeave,
199    /// 指针进入新 element(可选派发,当前未使用)
200    PointerEnter,
201    /// 指针交互被取消(不是 Up)。
202    ///
203    /// 触发场景:手势竞技场选出胜者、捕获目标失效、窗口失焦/鼠标离开窗口。
204    /// 收到后控件应清掉 pressed/dragging/down_pos 等瞬态,但不要触发点击。
205    PointerCancel,
206    /// 滚轮/触控板滚动:(dx, dy);正 dy = 内容向上移动
207    Scroll(f32, f32),
208    KeyDown(KeyCode, KeyModifiers),
209    KeyUp(KeyCode, KeyModifiers),
210    /// 获得焦点(发给刚被聚焦的 element)
211    ///
212    /// **注意**:这只表示"键盘焦点在这儿",不代表该画焦点环。用鼠标点出来的焦点
213    /// 不该出现环(否则点一下按钮就多一圈高亮),要画环请听
214    /// [`WidgetEvent::FocusVisibleChanged`]。
215    FocusGained,
216    /// 焦点环可见性变化(等价 CSS `:focus-visible`)。
217    ///
218    /// 由 `ElementTree` 按**焦点来路**决定并投递:Tab / 方向键等键盘导航 → `true`;
219    /// 鼠标点击、程序化 `request_focus` → `false`。已聚焦的控件在收到键盘事件时也会
220    /// 转成 `true`(先点一下、再用空格切换,环就该亮起来)。
221    /// 控件规则:`focused` 决定"能不能响应键盘",`focus_visible` 只决定"画不画环"。
222    FocusVisibleChanged(bool),
223    /// 失去焦点(发给刚失焦的 element)
224    FocusLost,
225    /// 焦点进入/离开本元素子树(发给焦点目标的祖先;用于 Tooltip 聚焦展示等)
226    FocusWithin(bool),
227    /// IME 启用(输入框聚焦后系统挂起输入法)
228    ImeEnabled,
229    /// IME 停用
230    ImeDisabled,
231    /// IME 组合中:`text` 是预编辑串,`cursor` 是光标在其中的字节偏移区间
232    ImePreedit(String, Option<(usize, usize)>),
233    /// IME 提交:`text` 为最终插入的文本
234    ImeCommit(String),
235    /// 无障碍 SetValue:整体替换文本输入框内容(平台语义动作,定向投递)
236    SetText(String),
237    /// 无障碍 SetValue:设置数值控件值 ∈ `[0,1]`(平台语义动作,定向投递)
238    SetValue(f32),
239    /// 无障碍展开/收起:`item` 为虚拟项稳定 key(None = 宿主自身)
240    SetExpanded {
241        item: Option<u64>,
242        expanded: bool,
243    },
244    /// 无障碍文本选区:anchor/focus 均为字符索引(不是字节偏移)
245    SetTextSelection {
246        anchor: usize,
247        focus: usize,
248    },
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn command_modifier_is_platform_aware() {
257        let command = KeyModifiers::command_only();
258        assert!(command.command());
259        #[cfg(target_os = "macos")]
260        {
261            assert!(command.meta() && !command.ctrl(), "macOS 命令键应为 META");
262            assert!(!KeyModifiers::ctrl_only().command(), "macOS 上 Ctrl 不是命令键");
263        }
264        #[cfg(not(target_os = "macos"))]
265        {
266            assert!(command.ctrl() && !command.meta(), "非 macOS 命令键应为 CTRL");
267            assert!(!KeyModifiers(KeyModifiers::META).command(), "非 macOS 上 META 不触发命令键");
268        }
269    }
270}