Skip to main content

velox_engine/engine/
mod.rs

1//! Velox 核心渲染与事件调度引擎 `VeloxEngine`。
2//!
3//! 模块职责划分:
4//! - `mod`:`GestureConfig`、`VeloxEngine` 结构体、视图树生命周期(`mount_root`/`insert_view`/`view`/`remove_view`)与配置接口;
5//! - `frame`:帧步进、局部脏子树重排、Pass-4-Only 快路径、分数 DPI 光栅化与无障碍树导出;
6//! - `pointer`:指针、手势(拖拽/长按/连发/滑动)、滚轮与点击派发;
7//! - `keyboard`:统一 `dispatch_event`、焦点键盘导航、系统返回与原生 IME 预编辑/提交闭环。
8
9mod frame;
10mod keyboard;
11mod pointer;
12
13use crate::arena::SmallVec;
14use crate::damage::DamageTracker;
15use crate::element::View;
16use crate::motion::{DrawOp, DrawOpSnapshot, MotionCache};
17use crate::pod::{
18    ActionScope, CoreTheme, DragEvent, FrameScope, Handle, ImePreedit, KeyModifiers, PodId,
19    PodPool, PointerKind, SafeAreaInsets,
20};
21use crate::renderers::software::precompute_occlusion_clips;
22use crate::solver::{HitRegion, InteractionState, LayoutNode, Region};
23
24/// 单帧默认绘制指令容量基准。
25pub const MAX_DRAW_OPS: usize = 128;
26
27/// 单帧默认可交互热区容量基准。
28pub const MAX_HIT_REGIONS: usize = 64;
29
30/// 引擎触摸与手势交互参数配置(替代硬编码阈值)。
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct GestureConfig {
33    /// 拖拽移动抑制长按/点击的位移死区(默认 `8px`)。
34    pub drag_slop_px: i16,
35    /// 四向快速滑动手势(`SwipeDir`)最小位移(默认 `16px`)。
36    pub swipe_threshold_px: i16,
37    /// 移动端左边缘右滑返回手势触发宽度与位移阈值(默认 `24px`)。
38    pub edge_back_width_px: i16,
39    /// 长按事件触发时长(默认 `500ms`)。
40    pub long_press_ms: u16,
41    /// 按住自动连发首次触发延迟(默认 `400ms`)。
42    pub repeat_delay_ms: u16,
43    /// 按住自动连发周期(默认 `100ms`)。
44    pub repeat_interval_ms: u16,
45    /// 是否允许非触摸指针(鼠标 / 手写笔)在空白可滚动区域按住左键拖动滚动页面(默认 `false`)。
46    ///
47    /// - 桌面鼠标环境下默认为 `false`:滚动页面仅通过鼠标滚轮或滚动条,避免按住鼠标拖选/误触把整个页面拖走;
48    /// - 触摸屏([`PointerKind::Touch`])始终支持跟手拖拽滚动与松手惯性滚动,不受此项限制;
49    /// - 若地图/白板等场景需要在桌面允许鼠标拖动画布,可显式设为 `true` 或在画布上注册 `.on_drag(...)`。
50    pub mouse_drag_scroll: bool,
51}
52
53impl GestureConfig {
54    /// 编译期默认手势参数常量(支持 `VeloxEngine::new` 的 `#![no_std]` `const fn` 构造)。
55    #[inline(always)]
56    pub const fn const_default() -> Self {
57        Self {
58            drag_slop_px: 8,
59            swipe_threshold_px: 16,
60            edge_back_width_px: 24,
61            long_press_ms: 500,
62            repeat_delay_ms: 400,
63            repeat_interval_ms: 100,
64            mouse_drag_scroll: false,
65        }
66    }
67}
68
69impl Default for GestureConfig {
70    #[inline(always)]
71    fn default() -> Self {
72        Self::const_default()
73    }
74}
75
76/// 引擎内置作用域快捷键表容量。
77pub const ENGINE_KEYMAP_CAP: usize = 64;
78
79/// Velox 核心渲染与事件调度引擎。
80pub struct VeloxEngine {
81    pool: PodPool,
82    frame_scope: FrameScope,
83    async_rt: crate::async_rt::ForegroundExecutor,
84    motion: MotionCache,
85    damage: DamageTracker,
86    prev_snapshots: SmallVec<DrawOpSnapshot, MAX_DRAW_OPS>,
87    cached_ops_buf: std::vec::Vec<DrawOp<'static>>,
88    cached_hits_buf: std::vec::Vec<HitRegion<'static>>,
89    cached_ops_ptr: *const DrawOp<'static>,
90    cached_ops_len: u32,
91    cached_hits_ptr: *const HitRegion<'static>,
92    cached_hits_len: u32,
93    cached_layout_ptr: *mut LayoutNode<'static, 'static>,
94    tree_cursor_mark: u32,
95    tree_temp_mark: u32,
96    ops_cursor_mark: u32,
97    frame_cached: bool,
98    partial_relayout_count: u16,
99    solve_count: u32,
100    fast_paint_count: u32,
101    dropped_draw_ops: u32,
102    viewport: Region,
103    dpi_scale: i16,
104    scale_factor: f32,
105    gesture_config: GestureConfig,
106    root_pod: Option<PodId>,
107    interaction: InteractionState,
108    pressed_hit_id: u32,
109    press_start_x: i16,
110    press_start_y: i16,
111    press_hold_ms: u16,
112    repeat_accum_ms: u16,
113    last_drag_vy: i16,
114    last_arena_used_bytes: u32,
115    modifiers: KeyModifiers,
116    active_pointer_kind: PointerKind,
117    ime_preedit: ImePreedit,
118    ime_enabled: bool,
119    first_frame: bool,
120    interaction_dirty: bool,
121    has_pressed_hit: bool,
122    drag_fired_on_down: bool,
123    long_press_fired: bool,
124    long_press_handled: bool,
125    pointer_capture_id: Option<u32>,
126    active_drag_payload: Option<crate::pod::DragPayload>,
127    system_theme_dark: bool,
128    last_pinch_delta_x1000: i16,
129    last_rotate_deg10: i16,
130    file_drop_hover: Option<(i16, i16)>,
131    dropped_files: std::vec::Vec<std::path::PathBuf>,
132    keymap: crate::keymap::Keymap<ENGINE_KEYMAP_CAP>,
133}
134
135impl VeloxEngine {
136
137    /// 创建指定屏幕宽高 `(width, height)` 的 Velox 核心引擎实例。
138    pub fn new(width: i16, height: i16) -> Self {
139        Self {
140            pool: PodPool::new(),
141            frame_scope: FrameScope::new(),
142            async_rt: crate::async_rt::ForegroundExecutor::new(),
143            motion: MotionCache::new(),
144            damage: DamageTracker::new(),
145            prev_snapshots: SmallVec::new(),
146            cached_ops_buf: std::vec::Vec::new(),
147            cached_hits_buf: std::vec::Vec::new(),
148            cached_ops_ptr: core::ptr::null(),
149            cached_ops_len: 0,
150            cached_hits_ptr: core::ptr::null(),
151            cached_hits_len: 0,
152            cached_layout_ptr: core::ptr::null_mut(),
153            tree_cursor_mark: 0,
154            tree_temp_mark: 0,
155            ops_cursor_mark: 0,
156            frame_cached: false,
157            solve_count: 0,
158            partial_relayout_count: 0,
159            fast_paint_count: 0,
160            dropped_draw_ops: 0,
161            viewport: Region::new(0, 0, width, height),
162            dpi_scale: 1,
163            scale_factor: 1.0,
164            gesture_config: GestureConfig::const_default(),
165            root_pod: None,
166            interaction: InteractionState::const_default(),
167            pressed_hit_id: 0,
168            press_start_x: 0,
169            press_start_y: 0,
170            press_hold_ms: 0,
171            repeat_accum_ms: 0,
172            last_drag_vy: 0,
173            last_arena_used_bytes: 0,
174            modifiers: KeyModifiers::NONE,
175            active_pointer_kind: PointerKind::Touch,
176            ime_preedit: ImePreedit::empty(),
177            ime_enabled: false,
178            first_frame: true,
179            interaction_dirty: false,
180            has_pressed_hit: false,
181            drag_fired_on_down: false,
182            long_press_fired: false,
183            long_press_handled: false,
184            pointer_capture_id: None,
185            active_drag_payload: None,
186            system_theme_dark: true,
187            last_pinch_delta_x1000: 0,
188            last_rotate_deg10: 0,
189            file_drop_hover: None,
190            dropped_files: std::vec::Vec::new(),
191            keymap: crate::keymap::Keymap::new(),
192        }
193    }
194
195    /// 显式设置指针捕获目标元素 ID(拖拽或滑块期间锁定后续指针事件不脱靶)。
196    #[inline(always)]
197    pub fn set_pointer_capture(&mut self, hit_id: u32) {
198        self.pointer_capture_id = Some(hit_id);
199    }
200
201    /// 释放当前指针捕获。
202    #[inline(always)]
203    pub fn release_pointer_capture(&mut self) {
204        self.pointer_capture_id = None;
205    }
206
207    /// 获取当前正在捕获指针的元素 ID。
208    #[inline(always)]
209    pub const fn pointer_capture_id(&self) -> Option<u32> {
210        self.pointer_capture_id
211    }
212
213    /// 开始一次应用内跨控件拖拽并附加自定义载荷 [`DragPayload`](crate::pod::DragPayload)。
214    #[inline(always)]
215    pub fn begin_drag_payload(&mut self, payload: crate::pod::DragPayload) {
216        self.active_drag_payload = Some(payload);
217        self.interaction_dirty = true;
218    }
219
220    /// 查询当前活跃的应用内拖拽载荷。
221    #[inline(always)]
222    pub const fn active_drag_payload(&self) -> Option<crate::pod::DragPayload> {
223        self.active_drag_payload
224    }
225
226    /// 消费并结束当前应用内拖拽载荷。
227    #[inline(always)]
228    pub fn take_drag_payload(&mut self) -> Option<crate::pod::DragPayload> {
229        self.interaction_dirty = true;
230        self.active_drag_payload.take()
231    }
232
233    /// 查询当前宿主操作系统是否处于暗黑模式(随 `InputEvent::SystemThemeChanged` 自动热更新)。
234    #[inline(always)]
235    pub const fn system_theme_is_dark(&self) -> bool {
236        self.system_theme_dark
237    }
238
239    /// 获取最近一次双指缩放千分比增量(如 `+50` 表示放大 5%)。
240    #[inline(always)]
241    pub const fn last_pinch_delta_x1000(&self) -> i16 {
242        self.last_pinch_delta_x1000
243    }
244
245    /// 获取最近一次双指旋转增量(单位 `0.1°`)。
246    #[inline(always)]
247    pub const fn last_rotate_deg10(&self) -> i16 {
248        self.last_rotate_deg10
249    }
250
251    /// 查询当前外部 OS 文件拖拽悬停坐标(未悬停返回 `None`)。
252    #[inline(always)]
253    pub const fn file_drop_hover_pos(&self) -> Option<(i16, i16)> {
254        self.file_drop_hover
255    }
256
257    /// 记录外部 OS 拖入的文件路径并派发 `FileDropped` 事件。
258    pub fn push_dropped_file(&mut self, path: std::path::PathBuf, x: i16, y: i16) {
259        self.dropped_files.push(path);
260        self.file_drop_hover = None;
261        self.interaction_dirty = true;
262        let _ = (x, y);
263    }
264
265    /// 读取并清空所有已拖入窗口的外部 OS 文件路径。
266    pub fn take_dropped_files(&mut self) -> std::vec::Vec<std::path::PathBuf> {
267        core::mem::take(&mut self.dropped_files)
268    }
269
270    /// 只读访问引擎作用域快捷键路由表 [`Keymap`](crate::keymap::Keymap)。
271    #[inline(always)]
272    pub fn keymap(&self) -> &crate::keymap::Keymap<ENGINE_KEYMAP_CAP> {
273        &self.keymap
274    }
275
276    /// 可变访问引擎作用域快捷键路由表(用于注册单键或弦键命令绑定)。
277    #[inline(always)]
278    pub fn keymap_mut(&mut self) -> &mut crate::keymap::Keymap<ENGINE_KEYMAP_CAP> {
279        &mut self.keymap
280    }
281
282    /// 结合当前引擎修饰键状态与焦点作用域链解析快捷键命令(支持两段弦键与超时复位)。
283    pub fn resolve_key_action(
284        &mut self,
285        context_chain: &[&str],
286        key: crate::pod::KeyCode,
287    ) -> crate::keymap::KeymapMatch {
288        let stroke = crate::keymap::KeyStroke::new(key, self.modifiers);
289        let now_ms = self.frame_scope.now_ms();
290        self.keymap.resolve(context_chain, stroke, now_ms)
291    }
292
293    /// 在未初始化静态槽位中原地构造 [`VeloxEngine`],彻底消除 MCU 上先在栈上构造再拷贝的峰值栈开销。
294    #[inline]
295    pub fn init_at(slot: &mut core::mem::MaybeUninit<Self>, width: i16, height: i16) -> &mut Self {
296        slot.write(Self::new(width, height))
297    }
298
299    /// 尝试注册一个独立的子视图(不触发 panic);若 `#![no_std]` `PodPool` Slab 或槽位耗尽返回 `None`。
300    #[inline]
301    pub fn try_insert_view<V: View>(&mut self, view: V) -> Option<Handle<V>> {
302        let handle = self.pool.try_insert(view)?;
303        self.invalidate_frame_cache();
304        Some(handle)
305    }
306
307    #[inline(always)]
308    pub(super) fn invalidate_frame_cache(&mut self) {
309        self.frame_cached = false;
310        self.cached_ops_ptr = core::ptr::null();
311        self.cached_ops_len = 0;
312        self.cached_hits_ptr = core::ptr::null();
313        self.cached_hits_len = 0;
314        {
315            self.cached_ops_buf.clear();
316            self.cached_hits_buf.clear();
317        }
318    }
319
320    #[inline(always)]
321    pub(super) fn resolve_hit_pod(root_id: PodId, hit_owner: u16) -> PodId {
322        if hit_owner == u16::MAX {
323            root_id
324        } else {
325            PodId(hit_owner)
326        }
327    }
328
329    #[inline]
330    pub(super) fn make_action_scope(
331        &mut self,
332        owner: PodId,
333        click_pos: (i16, i16),
334        drag_ev: DragEvent,
335    ) -> ActionScope<'_> {
336        let acx = ActionScope::new(
337            owner,
338            &mut self.pool,
339            click_pos,
340            drag_ev,
341            self.frame_scope.now_ms,
342        );
343        let acx = acx.with_async_app(self.async_rt.async_app());
344        acx
345    }
346
347    /// 在交互事件回调结束后立即排空已就绪的前景协程、`defer` 队列与取消清理,
348    /// 保证同次交互中 `acx.defer` 立刻生效且刚 `acx.spawn` 出的协程 0 延迟跑到首个 `.await`。
349    #[inline]
350    pub(super) fn flush_async_after_event(&mut self) {
351        if self.async_rt.has_work_to_poll() {
352            let _ = self.poll_async_tasks();
353        }
354    }
355
356    #[allow(clippy::too_many_arguments)]
357    pub(super) fn cache_ops_and_hits_into<'a>(
358        arena: &crate::arena::ScratchArena,
359        ops: &mut [DrawOp<'a>],
360        hits: &[HitRegion<'a>],
361        cached_ops_buf: &mut std::vec::Vec<DrawOp<'static>>,
362        cached_hits_buf: &mut std::vec::Vec<HitRegion<'static>>,
363        cached_ops_ptr: &mut *const DrawOp<'static>,
364        cached_ops_len: &mut u32,
365        cached_hits_ptr: &mut *const HitRegion<'static>,
366        cached_hits_len: &mut u32,
367        _dropped_draw_ops: &mut u32,
368        frame_cached: &mut bool,
369        last_arena_used_bytes: &mut u32,
370    ) {
371        precompute_occlusion_clips(ops);
372        {
373            cached_ops_buf.clear();
374            // SAFETY: `ops` 与 `hits` 内引用的 `StrRef` / `SpriteSource` / `DivInteractivity` 均驻留于
375            // `self.frame_scope.arena()`(或 `'static`),且 `invalidate_frame_cache()` 在任何 `arena.rewind()`
376            // 之前清空 `cached_ops_buf` / `cached_hits_buf`,从而在 Pass-4-Only 帧中彻底避免向 `Bump` 重复分配内存。
377            let static_ops: &[DrawOp<'static>] = unsafe {
378                core::slice::from_raw_parts(ops.as_ptr() as *const DrawOp<'static>, ops.len())
379            };
380            cached_ops_buf.extend_from_slice(static_ops);
381            *cached_ops_ptr = cached_ops_buf.as_ptr();
382            *cached_ops_len = cached_ops_buf.len() as u32;
383
384            cached_hits_buf.clear();
385            let static_hits: &[HitRegion<'static>] = unsafe {
386                core::slice::from_raw_parts(hits.as_ptr() as *const HitRegion<'static>, hits.len())
387            };
388            cached_hits_buf.extend_from_slice(static_hits);
389            *cached_hits_ptr = cached_hits_buf.as_ptr();
390            *cached_hits_len = cached_hits_buf.len() as u32;
391            *frame_cached = true;
392            *last_arena_used_bytes = arena.used_bytes() as u32;
393        }
394    }
395
396    #[inline(always)]
397    pub(super) fn invalidate_layout_cache(&mut self) {
398        self.invalidate_frame_cache();
399        self.cached_layout_ptr = core::ptr::null_mut();
400        self.tree_cursor_mark = 0;
401        self.tree_temp_mark = 0;
402        self.ops_cursor_mark = 0;
403    }
404
405    /// 获取当前键盘修饰键状态。
406    #[inline(always)]
407    pub const fn modifiers(&self) -> KeyModifiers {
408        self.modifiers
409    }
410
411    /// 更新当前键盘修饰键状态。
412    #[inline(always)]
413    pub fn set_modifiers(&mut self, modifiers: KeyModifiers) {
414        self.modifiers = modifiers;
415    }
416
417    /// 获取或修改手势判定参数配置。
418    #[inline(always)]
419    pub const fn gesture_config(&self) -> GestureConfig {
420        self.gesture_config
421    }
422
423    /// 设置自定义手势判定参数配置。
424    #[inline(always)]
425    pub fn set_gesture_config(&mut self, config: GestureConfig) {
426        self.gesture_config = config;
427    }
428
429    /// 获取当前活跃指针输入设备来源类型([`PointerKind::Touch`] / [`PointerKind::Mouse`] / [`PointerKind::Pen`])。
430    #[inline(always)]
431    pub const fn pointer_kind(&self) -> PointerKind {
432        self.active_pointer_kind
433    }
434
435    /// 设置当前指针输入设备来源类型(桌面平台应设为 [`PointerKind::Mouse`],触屏设为 [`PointerKind::Touch`])。
436    #[inline(always)]
437    pub fn set_pointer_kind(&mut self, kind: PointerKind) {
438        self.active_pointer_kind = kind;
439    }
440
441    /// 判断当前指针设备是否允许在空白可滚动区域通过按住拖拽触发跟手/惯性滚动。
442    #[inline(always)]
443    pub(super) const fn allows_drag_scroll(&self) -> bool {
444        matches!(self.active_pointer_kind, PointerKind::Touch)
445            || self.gesture_config.mouse_drag_scroll
446    }
447
448    /// 获取累计因超出 `MAX_DRAW_OPS`(`no_std` 下)而被截断的绘制指令数量(用于可观测容量监控)。
449    #[inline(always)]
450    pub const fn dropped_draw_ops_count(&self) -> u32 {
451        self.dropped_draw_ops
452    }
453
454    /// 获取累计执行的完整布局求解次数(Pass 1~4,用于性能剖析与单帧条带缓存验证)。
455    #[inline(always)]
456    pub const fn layout_solve_count(&self) -> u32 {
457        self.solve_count
458    }
459
460    /// 获取累计通过子视图布局隔离边界(Relayout Boundary)执行 $O(\text{dirty\_pod})$ 原地局部重排(跳过全局 `build_layout_tree` 与全局 Pass 1~3)完成的帧计数。
461    #[inline(always)]
462    pub const fn partial_relayout_count(&self) -> u32 {
463        self.partial_relayout_count as u32
464    }
465
466    /// 获取累计命中子视图布局隔离边界(包含原地局部重排与跳过未脏 `SubView` 子树 Pass 1~3)的次数。
467    #[inline(always)]
468    pub fn relayout_boundary_hits(&self) -> u32 {
469        self.pool.relayout_boundary_hits()
470    }
471
472    /// 获取累计通过 Pass-4-Only 快径(跳过 `View::render()` 与 Pass 1~3 水平/折行测量)完成的帧计数。
473    #[inline(always)]
474    pub const fn fast_paint_pass_count(&self) -> u32 {
475        self.fast_paint_count
476    }
477
478    /// 获取累计因 `SubView` 未脏而直接复用缓存 `Element` 跳过 `View::render()` 的命中次数。
479    #[inline(always)]
480    pub fn subview_cache_hits(&self) -> u32 {
481        self.pool.skipped_render_count()
482    }
483
484    /// 获取指定视图句柄自创建以来实际执行 `View::render()` 的次数。
485    #[inline(always)]
486    pub fn pod_render_count<V: View>(&self, handle: Handle<V>) -> u32 {
487        self.pool.render_count(handle.pod_id())
488    }
489
490    /// 设置物理像素 HiDPI 缩放倍率(默认 `1`,桌面端可设为 `2` 实现 2x Retina 矢量光栅化)。
491    /// 设置 HiDPI 整数缩放倍率(如 `1` / `2` / `3`,同步更新精确浮点 `scale_factor`)。
492    #[inline(always)]
493    pub fn set_dpi_scale(&mut self, scale: i16) {
494        let s = scale.max(1);
495        self.dpi_scale = s;
496        self.scale_factor = s as f32;
497    }
498
499    /// 设置精确分数 DPI 缩放因子(如 `1.25` / `1.5` / `1.75` / `2.0`,支持 Pixel Snapping)。
500    #[inline(always)]
501    pub fn set_scale_factor(&mut self, scale_factor: f32) {
502        let sf = scale_factor.clamp(0.5, 4.0);
503        self.scale_factor = sf;
504        self.dpi_scale = ((sf + 0.5) as i16).max(1);
505    }
506
507    /// 获取当前整数 HiDPI 缩放倍率(兼容旧接口)。
508    #[inline(always)]
509    pub const fn dpi_scale(&self) -> i16 {
510        self.dpi_scale
511    }
512
513    /// 获取当前精确分数 DPI 缩放因子(如 `1.5`)。
514    #[inline(always)]
515    pub const fn scale_factor(&self) -> f32 {
516        self.scale_factor
517    }
518
519    /// 获取视口矩形区域。
520    #[inline(always)]
521    pub const fn viewport_region(&self) -> Region {
522        self.viewport
523    }
524
525    /// 调整视口尺寸(触发全屏重绘)。
526    pub fn resize(&mut self, width: i16, height: i16) {
527        let new_vp = Region::new(0, 0, width, height);
528        if new_vp != self.viewport {
529            self.viewport = new_vp;
530            self.first_frame = true;
531            self.invalidate_layout_cache();
532            self.pool.mark_all_dirty();
533        }
534    }
535
536    /// 强制标记整帧为脏并在下一帧完整重绘视口(适用于离屏截图导出或外部显存重建)。
537    pub fn force_full_repaint(&mut self) {
538        self.first_frame = true;
539        self.invalidate_layout_cache();
540        self.pool.mark_all_dirty();
541    }
542
543    /// 返回当前引擎生效的全局主题配色([`CoreTheme`])。
544    #[inline(always)]
545    pub fn theme(&self) -> CoreTheme {
546        *self.frame_scope.theme()
547    }
548
549    /// 设置全局主题配色。
550    pub fn set_theme(&mut self, theme: CoreTheme) {
551        self.frame_scope.set_theme(theme);
552        self.invalidate_layout_cache();
553        self.pool.mark_all_dirty();
554    }
555
556    /// 返回当前引擎生效的国际化语言区域([`crate::i18n::Locale`])。
557    #[inline(always)]
558    pub fn locale(&self) -> crate::i18n::Locale {
559        self.frame_scope.locale()
560    }
561
562    /// 运行时热切换全局语言区域:同步刷新 `FrameScope`、失效布局缓存并标脏整棵视图树(零重启切换语言)。
563    pub fn set_locale(&mut self, locale: crate::i18n::Locale) {
564        if self.frame_scope.locale() != locale {
565            self.frame_scope.set_locale(locale);
566            self.first_frame = true;
567            self.invalidate_layout_cache();
568            self.pool.mark_all_dirty();
569        }
570    }
571
572    /// 注册静态零堆多语言词典集合并标记整棵视图树重绘。
573    pub fn set_i18n_catalog(&mut self, catalog: &'static crate::i18n::StaticCatalog) {
574        self.frame_scope.set_i18n_catalog(catalog);
575        self.first_frame = true;
576        self.invalidate_layout_cache();
577        self.pool.mark_all_dirty();
578    }
579
580    /// 注册运行时动态翻译目录(支持 JSON / `key=value` 语言包热加载)并标记整棵视图树重绘。
581    pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<crate::i18n::DynamicCatalog>) {
582        self.frame_scope.set_dynamic_catalog(catalog);
583        self.first_frame = true;
584        self.invalidate_layout_cache();
585        self.pool.mark_all_dirty();
586    }
587
588    /// 获取当前屏幕安全区域内边距。
589    #[inline(always)]
590    pub const fn safe_area(&self) -> SafeAreaInsets {
591        self.frame_scope.safe_area()
592    }
593
594    /// 设置移动端/异形屏安全区域内边距并标记根视图重绘。
595    pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
596        if self.frame_scope.safe_area() != insets {
597            self.frame_scope.set_safe_area(insets);
598            self.first_frame = true;
599            self.invalidate_layout_cache();
600            self.pool.mark_all_dirty();
601        }
602    }
603
604    /// 获取当前屏幕软键盘占用的底部像素高度。
605    #[inline(always)]
606    pub const fn keyboard_inset(&self) -> i16 {
607        self.frame_scope.keyboard_inset()
608    }
609
610    /// 设置屏幕软键盘占用的底部像素高度并标记根视图重绘。
611    pub fn set_keyboard_inset(&mut self, height: i16) {
612        let clamped = height.max(0);
613        if self.frame_scope.keyboard_inset() != clamped {
614            self.frame_scope.set_keyboard_inset(clamped);
615            self.first_frame = true;
616            self.invalidate_layout_cache();
617            self.pool.mark_all_dirty();
618        }
619    }
620
621    /// 挂载根视图组件,返回其强类型句柄 `Handle<V>`。
622    pub fn mount_root<V: View>(&mut self, view: V) -> Handle<V> {
623        let handle = self.pool.insert(view);
624        self.root_pod = Some(handle.pod_id());
625        self.pool.set_cached_bounds(handle.pod_id(), self.viewport);
626        self.first_frame = true;
627        self.invalidate_layout_cache();
628        handle
629    }
630
631    /// 在 `PodPool` 中注册一个独立子视图,返回其句柄。
632    pub fn insert_view<V: View>(&mut self, view: V) -> Handle<V> {
633        self.pool.insert(view)
634    }
635
636    /// 销毁并移除一个子视图(调用其 `Drop` 并回收 `PodPool` 槽位与内存)。
637    pub fn remove_view<V: View>(&mut self, handle: Handle<V>) -> bool {
638        let removed = self.pool.remove(handle);
639        if removed {
640            if self.root_pod == Some(handle.pod_id()) {
641                self.root_pod = None;
642            }
643            self.invalidate_layout_cache();
644            if let Some(root) = self.root_pod {
645                self.pool.mark_dirty(root);
646            }
647        }
648        removed
649    }
650
651    /// 获取视图可变引用并自动标记该视图为脏。
652    pub fn view_mut<V: View>(&mut self, handle: Handle<V>) -> Option<&mut V> {
653        self.pool.mark_dirty(handle.pod_id());
654        self.pool.get_mut(handle)
655    }
656
657    /// 通过闭包修改视图状态,仅在视图字段实际发生变更时自动标记该视图为脏。
658    pub fn update_view<V: View, R>(&mut self, handle: Handle<V>, f: impl FnOnce(&mut V) -> R) -> Option<R> {
659        self.pool.update(handle, f)
660    }
661
662    /// 获取视图只读引用。
663    pub fn view<V: View>(&self, handle: Handle<V>) -> Option<&V> {
664        self.pool.get(handle)
665    }
666
667    /// 获取跨帧动画与滚动缓存池。
668    #[inline(always)]
669    pub fn motion_mut(&mut self) -> &mut MotionCache {
670        self.interaction_dirty = true;
671        &mut self.motion
672    }
673
674    /// 获取最近一帧 `ScratchArena` 的峰值使用字节数。
675    #[inline(always)]
676    pub const fn last_arena_used_bytes(&self) -> usize {
677        self.last_arena_used_bytes as usize
678    }
679
680    /// 获取最近一次 `step_frame_dt` 合并生成的 8 槽位脏矩形列表(供模拟器脏矩形红框透视使用)。
681    #[inline(always)]
682    pub fn last_damage(&self) -> &[Region] {
683        self.damage.regions()
684    }
685
686    /// 获取当前物理按键/旋钮聚焦的元素序号。
687    #[inline(always)]
688    pub const fn focused_index(&self) -> Option<u16> {
689        self.interaction.focused_index
690    }
691
692    /// 返回当前焦点是否处于键盘导航激活的可见焦点态(`:focus-visible`)。
693    #[inline(always)]
694    pub const fn is_focus_visible(&self) -> bool {
695        self.interaction.focus_visible
696    }
697
698    /// 设置当前物理按键/旋钮聚焦的元素序号。
699    #[inline(always)]
700    pub fn set_focused_index(&mut self, idx: Option<u16>) {
701        if self.interaction.focused_index != idx {
702            self.interaction.focused_index = idx;
703            if idx.is_none() {
704                self.interaction.focus_visible = false;
705            }
706            self.interaction_dirty = true;
707        }
708    }
709
710    /// 是否存在待处理的脏视图、响应式信号更新、交互状态变更、就绪异步任务或正在进行中的过渡动画。
711    #[inline]
712    pub fn needs_redraw(&self) -> bool {
713        if self.async_rt.has_ready_work() {
714            return true;
715        }
716        self.first_frame
717            || self.interaction_dirty
718            || self.frame_scope.frame_requested.get()
719            || self.pool.has_dirty()
720            || crate::signal::has_pending_dirty_pods()
721            || self.motion.has_active_animations()
722    }
723
724    /// 获取引擎单调动画时钟(毫秒)。
725    #[inline(always)]
726    pub const fn clock_ms(&self) -> u32 {
727        self.frame_scope.now_ms
728    }
729
730    /// 注入自定义可插拔异步调度器后端(链式构建器),如 [`crate::async_rt::ManualScheduler`] 或第三方运行时适配器。
731    pub fn with_scheduler(
732        self,
733        backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
734    ) -> Self {
735        self.async_rt.set_backend(backend);
736        self
737    }
738
739    /// 在运行时切换当前引擎所使用的底层可插拔异步调度器后端。
740    pub fn set_scheduler(
741        &mut self,
742        backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
743    ) {
744        self.async_rt.set_backend(backend);
745    }
746
747    /// 返回当前引擎所绑定异步调度器的名称(如 `"velox-native-std"` / `"velox-manual"`)。
748    #[inline]
749    pub fn scheduler_name(&self) -> &'static str {
750        self.async_rt.scheduler_name()
751    }
752
753    /// 返回当前引擎所绑定异步调度器的能力描述符。
754    #[inline]
755    pub fn scheduler_capabilities(&self) -> crate::async_rt::SchedulerCapabilities {
756        self.async_rt.scheduler_capabilities()
757    }
758
759    /// 注入平台级异步唤醒回调(当后台线程池任务完成或定时器到期时触发事件循环零轮询唤醒)。
760    pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
761        self.async_rt.set_wake_ui(waker);
762    }
763
764    /// 在 UI 主线程排空所有已就绪的前景异步协程与 `defer` 回调;返回是否至少推进了 1 项任务或回调。
765    pub fn poll_async_tasks(&mut self) -> bool {
766        self.async_rt
767            .poll_ready(&mut self.pool, self.frame_scope.now_ms)
768    }
769
770    /// 是否存在立即待执行的前景就绪异步任务或 `defer` 回调。
771    #[inline]
772    pub fn has_pending_async_tasks(&self) -> bool {
773        self.async_rt.has_ready_work()
774    }
775
776    /// 返回当前仍活跃挂载在前景执行器中的协程数量(用于监控与测试验证取消回收无泄漏)。
777    #[inline]
778    pub fn active_async_task_count(&self) -> usize {
779        self.async_rt.active_task_count()
780    }
781
782    /// 在 UI 主线程前景执行器上派生异步任务(闭包接收 [`crate::async_rt::AsyncApp`])。
783    pub fn spawn<T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
784    where
785        T: 'static,
786        F: FnOnce(crate::async_rt::AsyncApp) -> Fut,
787        Fut: core::future::Future<Output = T> + 'static,
788    {
789        self.async_rt.spawn(f)
790    }
791
792    /// 在 UI 主线程前景执行器上为指定视图句柄派生绑定异步任务(闭包接收 `(Handle<V>, AsyncApp)`)。
793    pub fn spawn_for<V, T, F, Fut>(
794        &mut self,
795        handle: Handle<V>,
796        f: F,
797    ) -> crate::async_rt::Task<T>
798    where
799        V: View,
800        T: 'static,
801        F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
802        Fut: core::future::Future<Output = T> + 'static,
803    {
804        self.async_rt.async_app().spawn_for(handle, f)
805    }
806
807    /// 在后台常驻线程池中执行 CPU 密集型计算或阻塞 I/O,返回可 `.await` 的 [`crate::async_rt::Task<T>`]。
808    #[inline]
809    pub fn background_spawn<T, Fut>(&self, fut: Fut) -> crate::async_rt::Task<T>
810    where
811        T: Send + 'static,
812        Fut: core::future::Future<Output = T> + Send + 'static,
813    {
814        self.background_executor().spawn(fut)
815    }
816
817    /// 获取绑定到当前引擎调度器后端的后台执行器句柄(用于 `.spawn(...)` / `.timer(Duration)`)。
818    #[inline]
819    pub fn background_executor(&self) -> crate::async_rt::BackgroundExecutor {
820        self.async_rt.background_executor()
821    }
822
823    /// 创建由当前引擎调度器时钟驱动的非阻塞异步定时器。
824    #[inline]
825    pub fn timer(&self, duration: core::time::Duration) -> crate::async_rt::Timer {
826        self.background_executor().timer(duration)
827    }
828
829    /// 排入一个延迟到下次前景异步轮询执行的 UI 主线程回调。
830    #[inline]
831    pub fn defer<F>(&mut self, f: F)
832    where
833        F: FnOnce(&mut ActionScope) + 'static,
834    {
835        self.async_rt.defer(f);
836    }
837
838    /// 立即结束所有单次过渡动画并停留在目标状态(用于“减少动态效果”无障碍设置或测试快进)。
839    pub fn finish_animations(&mut self) {
840        self.motion.finish_all();
841        self.invalidate_frame_cache();
842        if let Some(root) = self.root_pod {
843            self.pool.mark_dirty(root);
844        }
845    }
846
847}
848
849impl HitRegion<'_> {
850    #[inline(always)]
851    const fn active_bg_or_focus(&self) -> bool {
852        self.has_active_bg || self.focus_index.is_some() || self.scroll_target.is_some()
853    }
854}