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