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            InputEvent::Pinch {
74                x,
75                y,
76                delta_scale_x1000,
77            } => self.dispatch_pinch_at(x, y, delta_scale_x1000),
78            InputEvent::Rotate { delta_deg10, .. } => {
79                self.last_rotate_deg10 = delta_deg10;
80                self.interaction_dirty = true;
81                true
82            }
83            InputEvent::ScrollPixel { x, y, dx, dy } => {
84                let mut handled = false;
85                if dy != 0 {
86                    handled |= self.dispatch_scroll_axis_at(x, y, dy, false);
87                }
88                if dx != 0 {
89                    handled |= self.dispatch_scroll_axis_at(x, y, dx, true);
90                }
91                handled
92            }
93            InputEvent::FileHovered { x, y } => {
94                self.file_drop_hover = Some((x, y));
95                self.interaction_dirty = true;
96                true
97            }
98            InputEvent::FileDropped { .. } => {
99                self.file_drop_hover = None;
100                self.interaction_dirty = true;
101                true
102            }
103            InputEvent::FileHoverCancelled => {
104                self.file_drop_hover = None;
105                self.interaction_dirty = true;
106                true
107            }
108            InputEvent::SystemThemeChanged { dark } => {
109                if self.system_theme_dark != dark {
110                    self.system_theme_dark = dark;
111                    self.interaction_dirty = true;
112                    true
113                } else {
114                    false
115                }
116            }
117        }
118    }
119
120    fn mark_focused_or_root_dirty(&mut self) {
121        self.interaction_dirty = true;
122        if let Some(root_id) = self.root_pod {
123            let focused_idx = self.interaction.focused_index;
124            let owner = self
125                .cached_hit_regions()
126                .iter()
127                .rev()
128                .find(|h| focused_idx.is_some() && h.focus_index == focused_idx)
129                .map(|h| Self::resolve_hit_pod(root_id, h.owner_pod))
130                .unwrap_or(root_id);
131            self.pool.mark_dirty(owner);
132        }
133    }
134
135    fn apply_ime_preedit(&mut self, preedit: ImePreedit) -> bool {
136        if self.ime_preedit == preedit {
137            return false;
138        }
139        self.ime_preedit = preedit;
140        self.frame_scope.set_ime_preedit(preedit);
141        self.mark_focused_or_root_dirty();
142        true
143    }
144
145    /// 返回当前正在进行的 IME 预编辑(组合输入)字符串;未组合时返回空串 `""`。
146    #[inline]
147    pub fn ime_preedit(&self) -> &str {
148        self.ime_preedit.as_str()
149    }
150
151    /// 返回当前完整的 IME 预编辑状态(含字节级光标选区区间)。
152    #[inline(always)]
153    pub const fn ime_preedit_state(&self) -> ImePreedit {
154        self.ime_preedit
155    }
156
157    /// 返回系统 IME 会话当前是否处于激活态。
158    #[inline(always)]
159    pub const fn ime_enabled(&self) -> bool {
160        self.ime_enabled
161    }
162
163    /// 计算当前聚焦输入控件的精准屏幕逻辑矩形,供 `winit` / `wayland` / 移动端原生 IME 候选窗零漂移跟随。
164    ///
165    /// - 优先定位当前拥有键盘焦点且可编辑(`on_text_input` / 聚焦 `HitRegion`)的屏幕边界;
166    /// - 当存在正在组合的预编辑文本(`ime_preedit`)时自动按组合宽度推进水平锚点,确保中文/日文/韩文候选窗紧贴光标。
167    pub fn ime_cursor_rect(&self) -> Option<Region> {
168        let fidx = self.interaction.focused_index?;
169        let hits = self.cached_hit_regions();
170        let hit = hits
171            .iter()
172            .rev()
173            .find(|h| h.focus_index == Some(fidx))?;
174        let eff = hit.bounds.intersect(hit.clip);
175        if eff.is_empty() {
176            return None;
177        }
178        let preedit_advance = if !self.ime_preedit.is_empty() {
179            let chars = self.ime_preedit.as_str().chars().count().min(32) as i16;
180            chars.saturating_mul(8)
181        } else {
182            0
183        };
184        let cx = eff
185            .x
186            .saturating_add(8)
187            .saturating_add(preedit_advance)
188            .min(eff.right().saturating_sub(2));
189        let h = eff.h.clamp(16, 36);
190        Some(Region::new(cx, eff.y, 2, h))
191    }
192
193    /// 派发系统 IME 组合输入预编辑更新(如拼音 `"zhongwen"` 与候选光标区间)。
194    #[inline]
195    pub fn dispatch_ime_preedit(&mut self, text: &str, cursor: Option<(usize, usize)>) -> bool {
196        let preedit = ImePreedit::from_str(text, cursor);
197        self.apply_ime_preedit(preedit)
198    }
199
200    /// 派发系统 IME 最终提交的 UTF-8 文本(如 `"中文"`):自动清空预编辑状态并逐字符送入当前聚焦输入控件。
201    pub fn dispatch_ime_commit(&mut self, text: &str) -> bool {
202        let mut handled = false;
203        if !self.ime_preedit.is_empty() {
204            self.ime_preedit = ImePreedit::empty();
205            self.frame_scope.set_ime_preedit(ImePreedit::empty());
206            self.mark_focused_or_root_dirty();
207            handled = true;
208        }
209        for ch in text.chars() {
210            if self.dispatch_key(KeyCode::Char(ch)) {
211                handled = true;
212            }
213        }
214        handled
215    }
216
217    /// 返回当前拥有焦点的可交互/文本输入区域(逻辑像素坐标),供桌面端 `winit::Window::set_ime_cursor_area`
218    /// 将系统输入法候选框精确对齐至输入框位置。
219    pub fn focused_bounds(&self) -> Option<Region> {
220        let hits = self.cached_hit_regions();
221        if let Some(fidx) = self.interaction.focused_index {
222            if let Some(hit) = hits.iter().rev().find(|h| h.focus_index == Some(fidx)) {
223                return Some(hit.bounds);
224            }
225        }
226        // 回退:若存在显式注册了文本键盘回调的活跃输入区,也提供其边界供 IME 锚定
227        hits.iter()
228            .rev()
229            .find(|h| h.on_key_input().is_some())
230            .map(|h| h.bounds)
231    }
232
233    /// 判断当前焦点节点(或活跃热区)是否接受键盘文本输入。
234    pub fn has_focused_text_input(&self) -> bool {
235        let hits = self.cached_hit_regions();
236        let focused_idx = self.interaction.focused_index;
237        hits.iter().rev().any(|h| {
238            h.on_key_input().is_some()
239                && (focused_idx.is_none() || h.focus_index == focused_idx)
240        })
241    }
242
243    /// 派发系统级返回事件(Android 返回键 / iOS 左边缘右滑返回 / 浏览器后退):
244    /// 优先调用当前活动树中注册了 `.on_navigate_back(...)` 的处理器;若无,则回退到屏幕中心右滑返回手势(`SwipeDir::Right`)。
245    #[inline(never)]
246    pub fn dispatch_navigate_back(&mut self) -> bool {
247        let Some(root_id) = self.root_pod else {
248            return false;
249        };
250        self.ensure_hits_available();
251        let hits = self.cached_hit_regions();
252        for hit in hits.iter().rev() {
253            if let Some(cb) = hit.on_navigate_back() {
254                let cx = hit.bounds.x + hit.bounds.w / 2;
255                let cy = hit.bounds.y + hit.bounds.h / 2;
256                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
257                {
258                    let mut acx = self.make_action_scope(owner, (cx, cy), DragEvent::default());
259                    cb(&mut acx);
260                }
261                self.flush_async_after_event();
262                self.interaction_dirty = true;
263                return true;
264            }
265        }
266        let cx = self.viewport.x + self.viewport.w / 2;
267        let cy = self.viewport.y + self.viewport.h / 2;
268        self.dispatch_swipe(cx, cy, SwipeDir::Right)
269    }
270
271
272    /// 派发物理按键、字符输入或旋转编码器按键事件(支持无触摸屏 MCU 的焦点切换、`Enter` 触发与聚焦输入框文本编辑)。
273    #[inline(never)]
274    pub fn dispatch_key(&mut self, key: KeyCode) -> bool {
275        let Some(root_id) = self.root_pod else {
276            return false;
277        };
278        self.ensure_hits_available();
279        let hits = self.cached_hit_regions();
280
281        // 0. 顶层浮层 / 模态框的 Escape 关闭通道:优先逆序派发给注册了 `on_navigate_back` 的浮层或焦点节点
282        if matches!(key, KeyCode::Escape) {
283            for hit in hits.iter().rev() {
284                if let Some(cb) = hit.on_navigate_back() {
285                    let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
286                    let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
287                    let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
288                    {
289                        let mut acx =
290                            self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
291                        cb(&mut acx);
292                    }
293                    self.flush_async_after_event();
294                    self.interaction_dirty = true;
295                    return true;
296                }
297            }
298        }
299
300        // 0.5 非文本控件局部键盘导航(Slider / Tabs / RadioGroup / 展开的 Select):
301        // 仅拦截方向键 / Home / End / Enter / Space,绝不吞掉 Tab / BackTab 焦点切换!
302        let is_nav_key = matches!(
303            key,
304            KeyCode::Up
305                | KeyCode::Down
306                | KeyCode::Left
307                | KeyCode::Right
308                | KeyCode::Home
309                | KeyCode::End
310                | KeyCode::Enter
311                | KeyCode::Space
312        );
313        if is_nav_key {
314            let focused_idx = self.interaction.focused_index;
315            // 优先派发给当前显式聚焦且注册了 `on_key_nav` 的控件
316            if let Some(fidx) = focused_idx {
317                for hit in hits.iter().rev() {
318                    if hit.focus_index == Some(fidx) {
319                        if let Some(on_nav) = hit.on_key_nav() {
320                            let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
321                            let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
322                            let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
323                            {
324                                let mut acx = self.make_action_scope(
325                                    owner,
326                                    (cx_px, cy_py),
327                                    DragEvent::default(),
328                                );
329                                on_nav(key, &mut acx);
330                            }
331                            self.flush_async_after_event();
332                            self.interaction_dirty = true;
333                            return true;
334                        }
335                    }
336                }
337            }
338            // 次优先:顶层打开的弹出菜单(如展开态 Select / Dropdown)即使未显式 Tab 聚焦也支持方向键选择
339            for hit in hits.iter().rev() {
340                if hit.occlude {
341                    if let Some(on_nav) = hit.on_key_nav() {
342                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
343                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
344                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
345                        {
346                            let mut acx =
347                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
348                            on_nav(key, &mut acx);
349                        }
350                        self.flush_async_after_event();
351                        self.interaction_dirty = true;
352                        return true;
353                    }
354                    break;
355                }
356            }
357        }
358
359        // 1. 优先检查当前焦点元素是否注册了 `on_key_input`(如聚焦中的 TextInput / CodeEditor 接收编辑与导航键)
360        let is_edit_key = matches!(
361            key,
362            KeyCode::Char(_)
363                | KeyCode::Space
364                | KeyCode::Backspace
365                | KeyCode::Delete
366                | KeyCode::Enter
367                | KeyCode::Tab
368                | KeyCode::BackTab
369                | KeyCode::Up
370                | KeyCode::Down
371                | KeyCode::Left
372                | KeyCode::Right
373                | KeyCode::Home
374                | KeyCode::End
375                | KeyCode::PageUp
376                | KeyCode::PageDown
377                | KeyCode::Escape
378        );
379        if is_edit_key {
380            let focused_idx = self.interaction.focused_index;
381            // Tab / BackTab / Space / Escape 仅在当前显式聚焦文本控件时由其消费,绝不吞掉未聚焦时的全局导航/按钮激活/退出通道
382            let require_explicit_focus = matches!(
383                key,
384                KeyCode::Tab | KeyCode::BackTab | KeyCode::Space | KeyCode::Escape
385            );
386            let cur_mods = self.modifiers;
387            for hit in hits.iter().rev() {
388                let matches_focus = if require_explicit_focus {
389                    focused_idx.is_some() && hit.focus_index == focused_idx
390                } else {
391                    focused_idx.is_none() || hit.focus_index == focused_idx
392                };
393                if matches_focus {
394                    if let Some(on_key_in) = hit.on_key_input() {
395                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
396                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
397                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
398                        {
399                            let mut acx = self
400                                .make_action_scope(owner, (cx_px, cy_py), DragEvent::default())
401                                .with_modifiers(cur_mods);
402                            on_key_in(key, &mut acx);
403                        }
404                        self.flush_async_after_event();
405                        self.interaction_dirty = true;
406                        return true;
407                    }
408                }
409            }
410            if matches!(
411                key,
412                KeyCode::Char(_)
413                    | KeyCode::Backspace
414                    | KeyCode::Delete
415                    | KeyCode::Home
416                    | KeyCode::End
417                    | KeyCode::PageUp
418                    | KeyCode::PageDown
419            ) {
420                return false;
421            }
422        }
423
424        let explicit_max = hits
425            .iter()
426            .filter_map(|h| h.focus_index)
427            .max()
428            .map(|m| m + 1)
429            .unwrap_or(0);
430        let clickable_count = hits.iter().filter(|h| h.on_click().is_some()).count() as u16;
431        let max_focus = if explicit_max > 0 {
432            explicit_max
433        } else {
434            clickable_count
435        };
436
437        match key {
438            KeyCode::Tab | KeyCode::Down | KeyCode::Right => {
439                if max_focus == 0 {
440                    return false;
441                }
442                let next = match self.interaction.focused_index {
443                    Some(cur) => (cur + 1) % max_focus,
444                    None => 0,
445                };
446                self.interaction.focused_index = Some(next);
447                self.interaction.focus_visible = true;
448                self.interaction_dirty = true;
449                return true;
450            }
451            KeyCode::BackTab | KeyCode::Up | KeyCode::Left => {
452                if max_focus == 0 {
453                    return false;
454                }
455                let prev = match self.interaction.focused_index {
456                    Some(cur) => (cur + max_focus - 1) % max_focus,
457                    None => max_focus - 1,
458                };
459                self.interaction.focused_index = Some(prev);
460                self.interaction.focus_visible = true;
461                self.interaction_dirty = true;
462                return true;
463            }
464            KeyCode::Enter | KeyCode::Space => {
465                if max_focus == 0 {
466                    return false;
467                }
468                let fidx = match self.interaction.focused_index {
469                    Some(idx) => idx,
470                    None => {
471                        self.interaction.focused_index = Some(0);
472                        self.interaction.focus_visible = true;
473                        self.interaction_dirty = true;
474                        0
475                    }
476                };
477                if explicit_max > 0 {
478                    for hit in hits.iter().rev() {
479                        if hit.focus_index == Some(fidx) {
480                            if let Some(on_click) = hit.on_click() {
481                                let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
482                                let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
483                                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
484                                {
485                                    let mut acx = self.make_action_scope(
486                                        owner,
487                                        (cx_px, cy_py),
488                                        DragEvent::default(),
489                                    );
490                                    on_click(&mut acx);
491                                }
492                                self.flush_async_after_event();
493                                self.interaction_dirty = true;
494                                return true;
495                            }
496                        }
497                    }
498                } else if let Some(hit) = hits
499                    .iter()
500                    .filter(|h| h.on_click().is_some())
501                    .nth(fidx as usize)
502                {
503                    if let Some(on_click) = hit.on_click() {
504                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
505                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
506                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
507                        {
508                            let mut acx =
509                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
510                            on_click(&mut acx);
511                        }
512                        self.flush_async_after_event();
513                        self.interaction_dirty = true;
514                        return true;
515                    }
516                }
517            }
518            KeyCode::Escape => {
519                if self.interaction.focused_index.is_some() || self.interaction.focus_visible {
520                    self.interaction.focused_index = None;
521                    self.interaction.focus_visible = false;
522                    self.interaction_dirty = true;
523                    return true;
524                }
525            }
526            KeyCode::Char(_)
527            | KeyCode::Backspace
528            | KeyCode::Delete
529            | KeyCode::Home
530            | KeyCode::End
531            | KeyCode::PageUp
532            | KeyCode::PageDown => {}
533        }
534        false
535    }
536
537    /// 派发键盘按键抬起事件。
538    pub fn dispatch_key_up(&mut self, _key: KeyCode) -> bool {
539        false
540    }
541
542}