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    /// 获取供操作系统输入法(IME)候选框精准跟随的光标逻辑屏幕矩形:
234    /// 优先返回本帧 Pass 4 捕获的 `.ime_caret()` 精确光标位置,无显式光标节点时回退至 [`Self::focused_bounds`]。
235    #[inline]
236    pub fn ime_cursor_bounds(&self) -> Option<Region> {
237        self.motion
238            .ime_caret_bounds()
239            .or_else(|| self.focused_bounds())
240    }
241
242    /// 判断当前焦点节点(或活跃热区)是否接受键盘文本输入。
243    pub fn has_focused_text_input(&self) -> bool {
244        let hits = self.cached_hit_regions();
245        let focused_idx = self.interaction.focused_index;
246        hits.iter().rev().any(|h| {
247            h.on_key_input().is_some()
248                && (focused_idx.is_none() || h.focus_index == focused_idx)
249        })
250    }
251
252    /// 派发系统级返回事件(Android 返回键 / iOS 左边缘右滑返回 / 浏览器后退):
253    /// 优先调用当前活动树中注册了 `.on_navigate_back(...)` 的处理器;若无,则回退到屏幕中心右滑返回手势(`SwipeDir::Right`)。
254    #[inline(never)]
255    pub fn dispatch_navigate_back(&mut self) -> bool {
256        let Some(root_id) = self.root_pod else {
257            return false;
258        };
259        self.ensure_hits_available();
260        let hits = self.cached_hit_regions();
261        for hit in hits.iter().rev() {
262            if let Some(cb) = hit.on_navigate_back() {
263                let cx = hit.bounds.x + hit.bounds.w / 2;
264                let cy = hit.bounds.y + hit.bounds.h / 2;
265                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
266                {
267                    let mut acx = self.make_action_scope(owner, (cx, cy), DragEvent::default());
268                    cb(&mut acx);
269                }
270                self.flush_async_after_event();
271                self.interaction_dirty = true;
272                return true;
273            }
274        }
275        let cx = self.viewport.x + self.viewport.w / 2;
276        let cy = self.viewport.y + self.viewport.h / 2;
277        self.dispatch_swipe(cx, cy, SwipeDir::Right)
278    }
279
280
281    /// 派发物理按键、字符输入或旋转编码器按键事件(支持无触摸屏 MCU 的焦点切换、`Enter` 触发与聚焦输入框文本编辑)。
282    #[inline(never)]
283    pub fn dispatch_key(&mut self, key: KeyCode) -> bool {
284        let Some(root_id) = self.root_pod else {
285            return false;
286        };
287        self.ensure_hits_available();
288        let hits = self.cached_hit_regions();
289
290        // 0. 顶层浮层 / 模态框的 Escape 关闭通道:优先逆序派发给注册了 `on_navigate_back` 的浮层或焦点节点
291        if matches!(key, KeyCode::Escape) {
292            for hit in hits.iter().rev() {
293                if let Some(cb) = hit.on_navigate_back() {
294                    let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
295                    let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
296                    let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
297                    {
298                        let mut acx =
299                            self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
300                        cb(&mut acx);
301                    }
302                    self.flush_async_after_event();
303                    self.interaction_dirty = true;
304                    return true;
305                }
306            }
307        }
308
309        // 0.5 非文本控件局部键盘导航(Slider / Tabs / RadioGroup / 展开的 Select):
310        // 仅拦截方向键 / Home / End / Enter / Space,绝不吞掉 Tab / BackTab 焦点切换!
311        let is_nav_key = matches!(
312            key,
313            KeyCode::Up
314                | KeyCode::Down
315                | KeyCode::Left
316                | KeyCode::Right
317                | KeyCode::Home
318                | KeyCode::End
319                | KeyCode::Enter
320                | KeyCode::Space
321        );
322        if is_nav_key {
323            let focused_idx = self.interaction.focused_index;
324            // 优先派发给当前显式聚焦且注册了 `on_key_nav` 的控件
325            if let Some(fidx) = focused_idx {
326                for hit in hits.iter().rev() {
327                    if hit.focus_index == Some(fidx) {
328                        if let Some(on_nav) = hit.on_key_nav() {
329                            let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
330                            let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
331                            let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
332                            {
333                                let mut acx = self.make_action_scope(
334                                    owner,
335                                    (cx_px, cy_py),
336                                    DragEvent::default(),
337                                );
338                                on_nav(key, &mut acx);
339                            }
340                            self.flush_async_after_event();
341                            self.interaction_dirty = true;
342                            return true;
343                        }
344                    }
345                }
346            }
347            // 次优先:顶层打开的弹出菜单(如展开态 Select / Dropdown)即使未显式 Tab 聚焦也支持方向键选择
348            for hit in hits.iter().rev() {
349                if hit.occlude {
350                    if let Some(on_nav) = hit.on_key_nav() {
351                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
352                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
353                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
354                        {
355                            let mut acx =
356                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
357                            on_nav(key, &mut acx);
358                        }
359                        self.flush_async_after_event();
360                        self.interaction_dirty = true;
361                        return true;
362                    }
363                    break;
364                }
365            }
366        }
367
368        // 1. 优先检查当前焦点元素是否注册了 `on_key_input`(如聚焦中的 TextInput / CodeEditor 接收编辑与导航键)
369        let is_edit_key = matches!(
370            key,
371            KeyCode::Char(_)
372                | KeyCode::Space
373                | KeyCode::Backspace
374                | KeyCode::Delete
375                | KeyCode::Enter
376                | KeyCode::Tab
377                | KeyCode::BackTab
378                | KeyCode::Up
379                | KeyCode::Down
380                | KeyCode::Left
381                | KeyCode::Right
382                | KeyCode::Home
383                | KeyCode::End
384                | KeyCode::PageUp
385                | KeyCode::PageDown
386                | KeyCode::Escape
387        );
388        if is_edit_key {
389            let focused_idx = self.interaction.focused_index;
390            // Tab / BackTab / Space / Escape 仅在当前显式聚焦文本控件时由其消费,绝不吞掉未聚焦时的全局导航/按钮激活/退出通道
391            let require_explicit_focus = matches!(
392                key,
393                KeyCode::Tab | KeyCode::BackTab | KeyCode::Space | KeyCode::Escape
394            );
395            let cur_mods = self.modifiers;
396            for hit in hits.iter().rev() {
397                let matches_focus = if require_explicit_focus {
398                    focused_idx.is_some() && hit.focus_index == focused_idx
399                } else {
400                    focused_idx.is_none() || hit.focus_index == focused_idx
401                };
402                if matches_focus {
403                    if let Some(on_key_in) = hit.on_key_input() {
404                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
405                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
406                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
407                        {
408                            let mut acx = self
409                                .make_action_scope(owner, (cx_px, cy_py), DragEvent::default())
410                                .with_modifiers(cur_mods);
411                            on_key_in(key, &mut acx);
412                        }
413                        self.flush_async_after_event();
414                        self.interaction_dirty = true;
415                        return true;
416                    }
417                }
418            }
419            if matches!(
420                key,
421                KeyCode::Char(_)
422                    | KeyCode::Backspace
423                    | KeyCode::Delete
424                    | KeyCode::Home
425                    | KeyCode::End
426                    | KeyCode::PageUp
427                    | KeyCode::PageDown
428            ) {
429                return false;
430            }
431        }
432
433        let explicit_max = hits
434            .iter()
435            .filter_map(|h| h.focus_index)
436            .max()
437            .map(|m| m + 1)
438            .unwrap_or(0);
439        let clickable_count = hits.iter().filter(|h| h.on_click().is_some()).count() as u16;
440        let max_focus = if explicit_max > 0 {
441            explicit_max
442        } else {
443            clickable_count
444        };
445
446        match key {
447            KeyCode::Tab | KeyCode::Down | KeyCode::Right => {
448                if max_focus == 0 {
449                    return false;
450                }
451                let next = match self.interaction.focused_index {
452                    Some(cur) => (cur + 1) % max_focus,
453                    None => 0,
454                };
455                self.interaction.focused_index = Some(next);
456                self.interaction.focus_visible = true;
457                self.interaction_dirty = true;
458                return true;
459            }
460            KeyCode::BackTab | KeyCode::Up | KeyCode::Left => {
461                if max_focus == 0 {
462                    return false;
463                }
464                let prev = match self.interaction.focused_index {
465                    Some(cur) => (cur + max_focus - 1) % max_focus,
466                    None => max_focus - 1,
467                };
468                self.interaction.focused_index = Some(prev);
469                self.interaction.focus_visible = true;
470                self.interaction_dirty = true;
471                return true;
472            }
473            KeyCode::Enter | KeyCode::Space => {
474                if max_focus == 0 {
475                    return false;
476                }
477                let fidx = match self.interaction.focused_index {
478                    Some(idx) => idx,
479                    None => {
480                        self.interaction.focused_index = Some(0);
481                        self.interaction.focus_visible = true;
482                        self.interaction_dirty = true;
483                        0
484                    }
485                };
486                if explicit_max > 0 {
487                    for hit in hits.iter().rev() {
488                        if hit.focus_index == Some(fidx) {
489                            if let Some(on_click) = hit.on_click() {
490                                let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
491                                let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
492                                let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
493                                {
494                                    let mut acx = self.make_action_scope(
495                                        owner,
496                                        (cx_px, cy_py),
497                                        DragEvent::default(),
498                                    );
499                                    on_click(&mut acx);
500                                }
501                                self.flush_async_after_event();
502                                self.interaction_dirty = true;
503                                return true;
504                            }
505                        }
506                    }
507                } else if let Some(hit) = hits
508                    .iter()
509                    .filter(|h| h.on_click().is_some())
510                    .nth(fidx as usize)
511                {
512                    if let Some(on_click) = hit.on_click() {
513                        let cx_px = hit.bounds.x + (hit.bounds.w >> 1);
514                        let cy_py = hit.bounds.y + (hit.bounds.h >> 1);
515                        let owner = Self::resolve_hit_pod(root_id, hit.owner_pod);
516                        {
517                            let mut acx =
518                                self.make_action_scope(owner, (cx_px, cy_py), DragEvent::default());
519                            on_click(&mut acx);
520                        }
521                        self.flush_async_after_event();
522                        self.interaction_dirty = true;
523                        return true;
524                    }
525                }
526            }
527            KeyCode::Escape => {
528                if self.interaction.focused_index.is_some() || self.interaction.focus_visible {
529                    self.interaction.focused_index = None;
530                    self.interaction.focus_visible = false;
531                    self.interaction_dirty = true;
532                    return true;
533                }
534            }
535            KeyCode::Char(_)
536            | KeyCode::Backspace
537            | KeyCode::Delete
538            | KeyCode::Home
539            | KeyCode::End
540            | KeyCode::PageUp
541            | KeyCode::PageDown => {}
542        }
543        false
544    }
545
546    /// 派发键盘按键抬起事件。
547    pub fn dispatch_key_up(&mut self, _key: KeyCode) -> bool {
548        false
549    }
550
551}