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