Skip to main content

velox_engine/engine/
keyboard.rs

1//! 统一事件入口 `dispatch_event`、原生 IME 组合输入状态机、系统返回与键盘/旋钮焦点导航。
2
3use crate::pod::{DragEvent, ImePreedit, InputEvent, KeyCode, SwipeDir};
4use crate::solver::Region;
5
6use super::VeloxEngine;
7
8impl VeloxEngine {
9    /// 统一派发输入事件(支持 `PointerDown` / `PointerMove` / `PointerUp` / `Scroll` / `KeyDown` / `KeyUp` / `ModifiersChanged`)。
10    #[inline(never)]
11    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
12        match event {
13            InputEvent::PointerDown { x, y } => self.dispatch_pointer_down(x, y),
14            InputEvent::PointerMove { x, y } => self.dispatch_pointer_move(x, y),
15            InputEvent::PointerUp { x, y } => self.dispatch_pointer_up(x, y),
16            InputEvent::PointerSecondaryDown { x, y } => {
17                self.dispatch_pointer_secondary_down(x, y)
18            }
19            InputEvent::PointerSecondaryUp { .. } => false,
20            InputEvent::PointerLeave => self.dispatch_pointer_leave(),
21            InputEvent::PointerCancel => {
22                self.interaction.is_pressed = false;
23                self.has_pressed_hit = false;
24                self.drag_fired_on_down = false;
25                self.press_hold_ms = 0;
26                self.repeat_accum_ms = 0;
27                self.long_press_fired = false;
28                self.long_press_handled = false;
29                self.last_drag_vy = 0;
30                self.interaction_dirty = true;
31                true
32            }
33            InputEvent::PointerKindChanged(kind) => {
34                self.active_pointer_kind = kind;
35                false
36            }
37            InputEvent::Scroll { x, y, delta_y } => self.dispatch_scroll_axis_at(x, y, delta_y, false),
38            InputEvent::ScrollX { x, y, delta_x } => self.dispatch_scroll_axis_at(x, y, delta_x, true),
39            InputEvent::KeyDown(key) => self.dispatch_key(key),
40            InputEvent::KeyUp(_) => false,
41            InputEvent::ModifiersChanged(mods) => {
42                self.modifiers = mods;
43                false
44            }
45            InputEvent::Backspace => self.dispatch_key(KeyCode::Backspace),
46            InputEvent::Delete => self.dispatch_key(KeyCode::Delete),
47            InputEvent::TextCommit(ch) => self.dispatch_key(KeyCode::Char(ch)),
48            InputEvent::ImeEnabled => {
49                self.ime_enabled = true;
50                false
51            }
52            InputEvent::ImeDisabled => {
53                self.ime_enabled = false;
54                if !self.ime_preedit.is_empty() {
55                    self.ime_preedit = ImePreedit::empty();
56                    self.frame_scope.set_ime_preedit(ImePreedit::empty());
57                    self.mark_focused_or_root_dirty();
58                    true
59                } else {
60                    false
61                }
62            }
63            InputEvent::ImePreedit(preedit) => self.apply_ime_preedit(preedit),
64            InputEvent::NavigateBack => self.dispatch_navigate_back(),
65            InputEvent::SafeAreaChanged(insets) => {
66                self.set_safe_area(insets);
67                true
68            }
69            InputEvent::KeyboardInsetChanged(height) => {
70                self.set_keyboard_inset(height);
71                true
72            }
73        }
74    }
75
76    fn mark_focused_or_root_dirty(&mut self) {
77        self.interaction_dirty = true;
78        if let Some(root_id) = self.root_pod {
79            let focused_idx = self.interaction.focused_index;
80            let owner = self
81                .cached_hit_regions()
82                .iter()
83                .rev()
84                .find(|h| focused_idx.is_some() && h.focus_index == focused_idx)
85                .map(|h| Self::resolve_hit_pod(root_id, h.owner_pod))
86                .unwrap_or(root_id);
87            self.pool.mark_dirty(owner);
88        }
89    }
90
91    fn apply_ime_preedit(&mut self, preedit: ImePreedit) -> bool {
92        if self.ime_preedit == preedit {
93            return false;
94        }
95        self.ime_preedit = preedit;
96        self.frame_scope.set_ime_preedit(preedit);
97        self.mark_focused_or_root_dirty();
98        true
99    }
100
101    /// 返回当前正在进行的 IME 预编辑(组合输入)字符串;未组合时返回空串 `""`。
102    #[inline]
103    pub fn ime_preedit(&self) -> &str {
104        self.ime_preedit.as_str()
105    }
106
107    /// 返回当前完整的 IME 预编辑状态(含字节级光标选区区间)。
108    #[inline(always)]
109    pub const fn ime_preedit_state(&self) -> ImePreedit {
110        self.ime_preedit
111    }
112
113    /// 返回系统 IME 会话当前是否处于激活态。
114    #[inline(always)]
115    pub const fn ime_enabled(&self) -> bool {
116        self.ime_enabled
117    }
118
119    /// 派发系统 IME 组合输入预编辑更新(如拼音 `"zhongwen"` 与候选光标区间)。
120    #[inline]
121    pub fn dispatch_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
122        let preedit = ImePreedit::from_str(text, cursor);
123        self.apply_ime_preedit(preedit)
124    }
125
126    /// 派发系统 IME 最终提交的 UTF-8 文本(如 `"中文"`):自动清空预编辑状态并逐字符送入当前聚焦输入控件。
127    pub fn dispatch_ime_commit(&mut self, text: &str) -> bool {
128        let mut handled = false;
129        if !self.ime_preedit.is_empty() {
130            self.ime_preedit = ImePreedit::empty();
131            self.frame_scope.set_ime_preedit(ImePreedit::empty());
132            self.mark_focused_or_root_dirty();
133            handled = true;
134        }
135        for ch in text.chars() {
136            if self.dispatch_key(KeyCode::Char(ch)) {
137                handled = true;
138            }
139        }
140        handled
141    }
142
143    /// 返回当前拥有焦点的可交互/文本输入区域(逻辑像素坐标),供桌面端 `winit::Window::set_ime_cursor_area`
144    /// 将系统输入法候选框精确对齐至输入框位置。
145    pub fn focused_bounds(&self) -> Option<Region> {
146        let hits = self.cached_hit_regions();
147        if let Some(fidx) = self.interaction.focused_index {
148            if let Some(hit) = hits.iter().rev().find(|h| h.focus_index == Some(fidx)) {
149                return Some(hit.bounds);
150            }
151        }
152        // 回退:若存在显式注册了文本键盘回调的活跃输入区,也提供其边界供 IME 锚定
153        hits.iter()
154            .rev()
155            .find(|h| h.on_key_input().is_some())
156            .map(|h| h.bounds)
157    }
158
159    /// 判断当前焦点节点(或活跃热区)是否接受键盘文本输入。
160    pub fn has_focused_text_input(&self) -> bool {
161        let hits = self.cached_hit_regions();
162        let focused_idx = self.interaction.focused_index;
163        hits.iter().rev().any(|h| {
164            h.on_key_input().is_some()
165                && (focused_idx.is_none() || h.focus_index == focused_idx)
166        })
167    }
168
169    /// 派发系统级返回事件(Android 返回键 / iOS 左边缘右滑返回 / 浏览器后退):
170    /// 优先调用当前活动树中注册了 `.on_navigate_back(...)` 的处理器;若无,则回退到屏幕中心右滑返回手势(`SwipeDir::Right`)。
171    #[inline(never)]
172    pub fn dispatch_navigate_back(&mut self) -> bool {
173        let Some(root_id) = self.root_pod else {
174            return false;
175        };
176        self.ensure_hits_available();
177        let hits = self.cached_hit_regions();
178        for hit in hits.iter().rev() {
179            if let Some(cb) = hit.on_navigate_back() {
180                let cx = hit.bounds.x + hit.bounds.w / 2;
181                let cy = hit.bounds.y + hit.bounds.h / 2;
182                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
183                {
184                    let mut acx = self.make_action_scope(owner, (cx, cy), DragEvent::default());
185                    cb(&mut acx);
186                }
187                self.flush_async_after_event();
188                self.interaction_dirty = true;
189                return true;
190            }
191        }
192        let cx = self.viewport.x + self.viewport.w / 2;
193        let cy = self.viewport.y + self.viewport.h / 2;
194        self.dispatch_swipe(cx, cy, SwipeDir::Right)
195    }
196
197
198    /// 派发物理按键、字符输入或旋转编码器按键事件(支持无触摸屏 MCU 的焦点切换、`Enter` 触发与聚焦输入框文本编辑)。
199    #[inline(never)]
200    pub fn dispatch_key(&mut self, key: KeyCode) -> bool {
201        let Some(root_id) = self.root_pod else {
202            return false;
203        };
204        self.ensure_hits_available();
205        let hits = self.cached_hit_regions();
206
207        // 0. 顶层浮层 / 模态框的 Escape 关闭通道:优先逆序派发给注册了 `on_navigate_back` 的浮层或焦点节点
208        if matches!(key, KeyCode::Escape) {
209            for hit in hits.iter().rev() {
210                if let Some(cb) = hit.on_navigate_back() {
211                    let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
212                    let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
213                    let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
214                    {
215                        let mut acx =
216                            self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
217                        cb(&mut acx);
218                    }
219                    self.flush_async_after_event();
220                    self.interaction_dirty = true;
221                    return true;
222                }
223            }
224        }
225
226        // 0.5 非文本控件局部键盘导航(Slider / Tabs / RadioGroup / 展开的 Select):
227        // 仅拦截方向键 / Home / End / Enter / Space,绝不吞掉 Tab / BackTab 焦点切换!
228        let is_nav_key = matches!(
229            key,
230            KeyCode::Up
231                | KeyCode::Down
232                | KeyCode::Left
233                | KeyCode::Right
234                | KeyCode::Home
235                | KeyCode::End
236                | KeyCode::Enter
237                | KeyCode::Space
238        );
239        if is_nav_key {
240            let focused_idx = self.interaction.focused_index;
241            // 优先派发给当前显式聚焦且注册了 `on_key_nav` 的控件
242            if let Some(fidx) = focused_idx {
243                for hit in hits.iter().rev() {
244                    if hit.focus_index == Some(fidx) {
245                        if let Some(on_nav) = hit.on_key_nav() {
246                            let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
247                            let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
248                            let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
249                            {
250                                let mut acx = self.make_action_scope(
251                                    owner,
252                                    (cx_px, cy_py),
253                                    DragEvent::default(),
254                                );
255                                on_nav(key, &mut acx);
256                            }
257                            self.flush_async_after_event();
258                            self.interaction_dirty = true;
259                            return true;
260                        }
261                    }
262                }
263            }
264            // 次优先:顶层打开的弹出菜单(如展开态 Select / Dropdown)即使未显式 Tab 聚焦也支持方向键选择
265            for hit in hits.iter().rev() {
266                if hit.occlude {
267                    if let Some(on_nav) = hit.on_key_nav() {
268                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
269                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
270                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
271                        {
272                            let mut acx =
273                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
274                            on_nav(key, &mut acx);
275                        }
276                        self.flush_async_after_event();
277                        self.interaction_dirty = true;
278                        return true;
279                    }
280                    break;
281                }
282            }
283        }
284
285        // 1. 优先检查当前焦点元素是否注册了 `on_key_input`(如聚焦中的 TextInput / CodeEditor 接收编辑与导航键)
286        let is_edit_key = matches!(
287            key,
288            KeyCode::Char(_)
289                | KeyCode::Space
290                | KeyCode::Backspace
291                | KeyCode::Delete
292                | KeyCode::Enter
293                | KeyCode::Tab
294                | KeyCode::BackTab
295                | KeyCode::Up
296                | KeyCode::Down
297                | KeyCode::Left
298                | KeyCode::Right
299                | KeyCode::Home
300                | KeyCode::End
301                | KeyCode::PageUp
302                | KeyCode::PageDown
303                | KeyCode::Escape
304        );
305        if is_edit_key {
306            let focused_idx = self.interaction.focused_index;
307            // Tab / BackTab / Space / Escape 仅在当前显式聚焦文本控件时由其消费,绝不吞掉未聚焦时的全局导航/按钮激活/退出通道
308            let require_explicit_focus = matches!(
309                key,
310                KeyCode::Tab | KeyCode::BackTab | KeyCode::Space | KeyCode::Escape
311            );
312            let cur_mods = self.modifiers;
313            for hit in hits.iter().rev() {
314                let matches_focus = if require_explicit_focus {
315                    focused_idx.is_some() && hit.focus_index == focused_idx
316                } else {
317                    focused_idx.is_none() || hit.focus_index == focused_idx
318                };
319                if matches_focus {
320                    if let Some(on_key_in) = hit.on_key_input() {
321                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
322                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
323                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
324                        {
325                            let mut acx = self
326                                .make_action_scope(owner, (cx_px, cy_py), DragEvent::default())
327                                .with_modifiers(cur_mods);
328                            on_key_in(key, &mut acx);
329                        }
330                        self.flush_async_after_event();
331                        self.interaction_dirty = true;
332                        return true;
333                    }
334                }
335            }
336            if matches!(
337                key,
338                KeyCode::Char(_)
339                    | KeyCode::Backspace
340                    | KeyCode::Delete
341                    | KeyCode::Home
342                    | KeyCode::End
343                    | KeyCode::PageUp
344                    | KeyCode::PageDown
345            ) {
346                return false;
347            }
348        }
349
350        let explicit_max = hits
351            .iter()
352            .filter_map(|h| h.focus_index)
353            .max()
354            .map(|m| m + 1)
355            .unwrap_or(0);
356        let clickable_count = hits.iter().filter(|h| h.on_click().is_some()).count() as u16;
357        let max_focus = if explicit_max > 0 {
358            explicit_max
359        } else {
360            clickable_count
361        };
362
363        match key {
364            KeyCode::Tab | KeyCode::Down | KeyCode::Right => {
365                if max_focus == 0 {
366                    return false;
367                }
368                let next = match self.interaction.focused_index {
369                    Some(cur) => (cur + 1) % max_focus,
370                    None => 0,
371                };
372                self.interaction.focused_index = Some(next);
373                self.interaction.focus_visible = true;
374                self.interaction_dirty = true;
375                return true;
376            }
377            KeyCode::BackTab | KeyCode::Up | KeyCode::Left => {
378                if max_focus == 0 {
379                    return false;
380                }
381                let prev = match self.interaction.focused_index {
382                    Some(cur) => (cur + max_focus - 1) % max_focus,
383                    None => max_focus - 1,
384                };
385                self.interaction.focused_index = Some(prev);
386                self.interaction.focus_visible = true;
387                self.interaction_dirty = true;
388                return true;
389            }
390            KeyCode::Enter | KeyCode::Space => {
391                if max_focus == 0 {
392                    return false;
393                }
394                let fidx = match self.interaction.focused_index {
395                    Some(idx) => idx,
396                    None => {
397                        self.interaction.focused_index = Some(0);
398                        self.interaction.focus_visible = true;
399                        self.interaction_dirty = true;
400                        0
401                    }
402                };
403                if explicit_max > 0 {
404                    for hit in hits.iter().rev() {
405                        if hit.focus_index == Some(fidx) {
406                            if let Some(on_click) = hit.on_click() {
407                                let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
408                                let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
409                                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
410                                {
411                                    let mut acx = self.make_action_scope(
412                                        owner,
413                                        (cx_px, cy_py),
414                                        DragEvent::default(),
415                                    );
416                                    on_click(&mut acx);
417                                }
418                                self.flush_async_after_event();
419                                self.interaction_dirty = true;
420                                return true;
421                            }
422                        }
423                    }
424                } else if let Some(hit) = hits
425                    .iter()
426                    .filter(|h| h.on_click().is_some())
427                    .nth(fidx as usize)
428                {
429                    if let Some(on_click) = hit.on_click() {
430                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
431                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
432                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
433                        {
434                            let mut acx =
435                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
436                            on_click(&mut acx);
437                        }
438                        self.flush_async_after_event();
439                        self.interaction_dirty = true;
440                        return true;
441                    }
442                }
443            }
444            KeyCode::Escape => {
445                if self.interaction.focused_index.is_some() || self.interaction.focus_visible {
446                    self.interaction.focused_index = None;
447                    self.interaction.focus_visible = false;
448                    self.interaction_dirty = true;
449                    return true;
450                }
451            }
452            KeyCode::Char(_)
453            | KeyCode::Backspace
454            | KeyCode::Delete
455            | KeyCode::Home
456            | KeyCode::End
457            | KeyCode::PageUp
458            | KeyCode::PageDown => {}
459        }
460        false
461    }
462
463    /// 派发键盘按键抬起事件。
464    pub fn dispatch_key_up(&mut self, _key: KeyCode) -> bool {
465        false
466    }
467
468}