Skip to main content

velox_engine/pod/
scope.rs

1//! 帧级与视图级渲染上下文:`FrameScope`、`Scope<V>`、`ActionScope` 与作用域 ID 派生。
2
3use core::any::TypeId;
4use core::cell::Cell;
5use core::marker::PhantomData;
6use core::ops::Deref;
7
8use crate::arena::{ScratchArena, StrRef};
9use crate::element::View;
10use crate::i18n::DynamicCatalog;
11use crate::i18n::{I18nArg, I18nContext, Locale, StaticCatalog, TextDirection};
12
13use super::events::{DragEvent, ImePreedit, SafeAreaInsets};
14use super::{CoreTheme, Handle, PodId, PodPool};
15
16/// 基于 Murmur3 Avalanche 最终混洗的零分配确定性子元素 ID 派生函数。
17///
18/// 彻底替代易撞车的 `parent_id.wrapping_add(1 / 100)` 线性偏移写法:
19/// 返回值恒将最高位设为 `1`(落在 `0x8000_0000..=0xFFFF_FFFF` 命名空间,永不为 `0`),
20/// 与应用层常见的用户显式正小整数 ID(`1..=2_147_483_647`)在数学上完全正交零碰撞。
21#[inline(always)]
22pub const fn derive_scoped_id(parent_seed: u32, salt: u32, local_id: u32) -> u32 {
23    let mut h = parent_seed.wrapping_mul(0x9E37_79B9) ^ salt.wrapping_mul(0x85EB_CA6B);
24    h ^= local_id.wrapping_add(0xC2B2_AE35);
25    h ^= h >> 16;
26    h = h.wrapping_mul(0x7FEB_352D);
27    h ^= h >> 15;
28    h = h.wrapping_mul(0x846C_A68B);
29    h ^= h >> 16;
30    h | 0x8000_0000
31}
32
33/// 帧级无状态渲染上下文(供 `Widget::render_once` 与 `div().child(cx, ...)` 使用)。
34pub struct FrameScope {
35    pub(crate) arena: ScratchArena,
36    pub(crate) theme: CoreTheme,
37    pub(crate) theme_override_ptr: Cell<*const CoreTheme>,
38    pub(crate) safe_area: SafeAreaInsets,
39    pub(crate) keyboard_inset: i16,
40    pub(crate) current_pod: PodId,
41    pub(crate) current_pod_gen: Option<u16>,
42    pub(crate) pool_ptr: *const PodPool,
43    pub(crate) now_ms: u32,
44    pub(crate) frame_requested: Cell<bool>,
45    pub(crate) id_stack: Cell<[u32; 8]>,
46    pub(crate) id_depth: Cell<u8>,
47    pub(crate) ime_preedit: ImePreedit,
48    pub(crate) i18n: I18nContext,
49    pub(crate) locale_override: Cell<Option<Locale>>,
50    pub(crate) catalog_override: Cell<Option<&'static StaticCatalog>>,
51}
52
53impl Default for FrameScope {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl FrameScope {
60
61    /// 创建默认帧级上下文。
62    pub fn new() -> Self {
63        Self::with_theme(CoreTheme::dark())
64    }
65
66
67    /// 使用指定主题创建帧级上下文。
68    pub fn with_theme(theme: CoreTheme) -> Self {
69        Self {
70            arena: ScratchArena::new(),
71            theme,
72            theme_override_ptr: Cell::new(core::ptr::null()),
73            safe_area: SafeAreaInsets::ZERO,
74            keyboard_inset: 0,
75            current_pod: PodId(0),
76            current_pod_gen: None,
77            pool_ptr: core::ptr::null(),
78            now_ms: 0,
79            frame_requested: Cell::new(false),
80            id_stack: Cell::new([0; 8]),
81            id_depth: Cell::new(0),
82            ime_preedit: ImePreedit::empty(),
83            i18n: I18nContext::new(Locale::EN_US),
84            locale_override: Cell::new(None),
85            catalog_override: Cell::new(None),
86        }
87    }
88
89    /// 获取当前正在组合输入的 IME 预编辑字符串(无预编辑内容时返回 `None`)。
90    #[inline]
91    pub fn ime_preedit(&self) -> Option<&str> {
92        if self.ime_preedit.is_empty() {
93            None
94        } else {
95            Some(self.ime_preedit.as_str())
96        }
97    }
98
99    /// 获取当前帧上下文中的完整 IME 预编辑状态(含可选光标区间)。
100    #[inline(always)]
101    pub const fn ime_preedit_state(&self) -> ImePreedit {
102        self.ime_preedit
103    }
104
105    /// 设置当前帧上下文中的 IME 预编辑状态(由引擎自动同步)。
106    #[inline(always)]
107    pub fn set_ime_preedit(&mut self, preedit: ImePreedit) {
108        self.ime_preedit = preedit;
109    }
110
111    /// 获取当前屏幕安全区域内边距(状态栏、刘海屏、底部 Home Indicator)。
112    #[inline(always)]
113    pub const fn safe_area(&self) -> SafeAreaInsets {
114        self.safe_area
115    }
116
117    /// 设置当前屏幕安全区域内边距。
118    #[inline(always)]
119    pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
120        self.safe_area = insets;
121    }
122
123    /// 获取当前屏幕软键盘占用的底部像素高度(`0` 表示未弹出)。
124    #[inline(always)]
125    pub const fn keyboard_inset(&self) -> i16 {
126        self.keyboard_inset
127    }
128
129    /// 设置当前屏幕软键盘占用的底部像素高度。
130    #[inline(always)]
131    pub fn set_keyboard_inset(&mut self, height: i16) {
132        self.keyboard_inset = height.max(0);
133    }
134
135    /// 在渲染期安全读取另一个子视图/兄弟视图 `Handle<T>` 的只读状态,返回局部借用守卫 [`super::PodReadGuard`]。
136    ///
137    /// 守卫通过 `Deref` 将引用生命周期严格限制在守卫存活的局部作用域内(不可泄漏为 `'a` 存入 `Element<'a>`),
138    /// 且在守卫析构前阻止目标槽位进入可变借用或 `View::render`。
139    #[inline]
140    pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<super::PodReadGuard<'s, T>> {
141        if self.pool_ptr.is_null() || handle.id == self.current_pod {
142            return None;
143        }
144        unsafe {
145            let pool = &*self.pool_ptr;
146            let res = pool.read_guarded(handle);
147            if res.is_some() {
148                pool.record_cross_read(self.current_pod, handle.id);
149            }
150            res
151        }
152    }
153
154    /// 在渲染期通过闭包安全读取另一个 `Handle<T>` 视图并提取计算结果。
155    #[inline]
156    pub fn read_with<T: View, R>(&self, handle: Handle<T>, f: impl FnOnce(&T) -> R) -> Option<R> {
157        let guard = self.read(handle)?;
158        Some(f(&*guard))
159    }
160
161    /// 获取瞬态帧内存池引用。
162    #[inline(always)]
163    pub fn arena(&self) -> &ScratchArena {
164        &self.arena
165    }
166
167    /// 获取可变帧内存池引用(用于帧开始时 `rewind()`)。
168    #[inline(always)]
169    pub fn arena_mut(&mut self) -> &mut ScratchArena {
170        self.theme_override_ptr.set(core::ptr::null());
171        self.locale_override.set(None);
172        self.catalog_override.set(None);
173        self.id_depth.set(0);
174        &mut self.arena
175    }
176
177    /// 返回当前生效的语言区域(若渲染期调用了 [`Self::override_locale`] 则优先返回覆盖值)。
178    #[inline(always)]
179    pub fn locale(&self) -> Locale {
180        self.locale_override.get().unwrap_or(self.i18n.locale)
181    }
182
183    /// 返回当前语言的默认书写方向(`Ltr` 或 `Rtl`)。
184    #[inline(always)]
185    pub fn text_direction(&self) -> TextDirection {
186        self.locale().text_direction()
187    }
188
189    /// 当前语言区域是否为从右到左(RTL)书写方向。
190    #[inline(always)]
191    pub fn is_rtl(&self) -> bool {
192        self.locale().is_rtl()
193    }
194
195    /// 设置帧级默认语言区域。
196    #[inline(always)]
197    pub fn set_locale(&mut self, locale: Locale) {
198        self.i18n.locale = locale;
199        self.locale_override.set(None);
200    }
201
202    /// 在当前帧渲染期间覆盖活跃语言区域(与 [`Self::override_theme`] 对称,零可变别名风险)。
203    #[inline(always)]
204    pub fn override_locale(&self, locale: Locale) {
205        self.locale_override.set(Some(locale));
206    }
207
208    /// 注册静态零堆多语言词典集合。
209    #[inline(always)]
210    pub fn set_i18n_catalog(&mut self, catalog: &'static StaticCatalog) {
211        self.i18n.static_catalog = Some(catalog);
212        self.catalog_override.set(None);
213    }
214
215    /// 在当前帧渲染期间临时覆盖静态词典集合(例如根视图挂载应用级词典)。
216    #[inline(always)]
217    pub fn override_i18n_catalog(&self, catalog: &'static StaticCatalog) {
218        self.catalog_override.set(Some(catalog));
219    }
220
221    /// 注册 `std` 运行时动态翻译目录(支持运行时热加载 JSON / `key=value` 语言包,优先于静态词典)。
222    #[inline]
223    pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<DynamicCatalog>) {
224        self.i18n.dynamic_catalog = Some(catalog);
225    }
226
227    #[inline]
228    fn resolve_i18n_template(&self, key: &str) -> Option<&str> {
229        let loc = self.locale();
230        if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
231            if let Some(v) = dyn_cat.lookup(loc, key) {
232                return Some(v);
233            }
234        }
235        if let Some(ov_cat) = self.catalog_override.get() {
236            if let Some(v) = ov_cat.lookup(loc, key) {
237                return Some(v);
238            }
239        }
240        if let Some(st_cat) = self.i18n.static_catalog {
241            if let Some(v) = st_cat.lookup(loc, key) {
242                return Some(v);
243            }
244        }
245        None
246    }
247
248    #[inline]
249    fn resolve_i18n_plural_template(&self, key: &str, count: i64) -> Option<&str> {
250        let loc = self.locale();
251        if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
252            if let Some(v) = dyn_cat.lookup_plural(loc, key, count) {
253                return Some(v);
254            }
255        }
256        if let Some(ov_cat) = self.catalog_override.get() {
257            if let Some(v) = ov_cat.lookup_plural(loc, key, count) {
258                return Some(v);
259            }
260        }
261        if let Some(st_cat) = self.i18n.static_catalog {
262            if let Some(v) = st_cat.lookup_plural(loc, key, count) {
263                return Some(v);
264            }
265        }
266        None
267    }
268
269    /// 翻译无参数文本键(未命中时回退键名本身;静态词典命中时零拷贝返回)。
270    #[inline]
271    pub fn t<'a>(&'a self, key: &str) -> StrRef<'a> {
272        let loc = self.locale();
273        if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
274            if let Some(v) = dyn_cat.lookup(loc, key) {
275                return self.arena.alloc_str(v);
276            }
277        }
278        if let Some(ov_cat) = self.catalog_override.get() {
279            if let Some(v) = ov_cat.lookup(loc, key) {
280                return StrRef::from(v);
281            }
282        }
283        if let Some(st_cat) = self.i18n.static_catalog {
284            if let Some(v) = st_cat.lookup(loc, key) {
285                return StrRef::from(v);
286            }
287        }
288        self.arena.alloc_str(key)
289    }
290
291    /// 翻译无参数文本键,若未命中任何词典则返回显式默认值 `fallback`。
292    #[inline]
293    pub fn t_or<'a>(&'a self, key: &str, fallback: &'a str) -> StrRef<'a> {
294        if let Some(v) = self.resolve_i18n_template(key) {
295            self.arena.alloc_str(v)
296        } else {
297            StrRef::from(fallback)
298        }
299    }
300
301    /// 翻译带命名/位置参数的文本键并在 `ScratchArena` 中零堆完成插值(如 `cx.t_args("greeting", &[("name", "Velox".into())])`)。
302    #[inline]
303    pub fn t_args<'a>(&'a self, key: &str, args: &[(&str, I18nArg<'_>)]) -> StrRef<'a> {
304        let tmpl = self.resolve_i18n_template(key).unwrap_or(key);
305        crate::i18n::format_template(&self.arena, tmpl, args)
306    }
307
308    /// 按 CLDR 复数规则翻译文本键并自动注入 `{count}` 参数(如 `cx.t_plural("files", 3)`)。
309    #[inline]
310    pub fn t_plural<'a>(&'a self, key: &str, count: i64) -> StrRef<'a> {
311        let tmpl = self.resolve_i18n_plural_template(key, count).unwrap_or(key);
312        crate::i18n::format_template(&self.arena, tmpl, &[("count", I18nArg::Int(count))])
313    }
314
315    /// 压入一层作用域 ID 种子(ImGui / egui 风格 Scoped ID Stack,最多支持 8 层嵌套)。
316    ///
317    /// 同一页面中多次复用相同子组件或列表项模板时,通过 `push_id` / `with_id` 自动隔离所有内部交互与动画 ID。
318    #[inline]
319    pub fn push_id(&self, seed: u32) {
320        let depth = self.id_depth.get() as usize;
321        let mut stack = self.id_stack.get();
322        let parent = if depth == 0 {
323            self.current_pod.0 as u32
324        } else {
325            stack[(depth - 1).min(7)]
326        };
327        let combined = derive_scoped_id(parent, 0x5343_4F50, seed);
328        if depth < 8 {
329            stack[depth] = combined;
330            self.id_stack.set(stack);
331            self.id_depth.set((depth + 1) as u8);
332        }
333    }
334
335    /// 弹出当前最顶层的作用域 ID 种子(与 [`Self::push_id`] 配对使用)。
336    #[inline]
337    pub fn pop_id(&self) {
338        let depth = self.id_depth.get();
339        if depth > 0 {
340            self.id_depth.set(depth - 1);
341        }
342    }
343
344    /// 在指定作用域 ID 种子内执行渲染闭包,退出时自动弹栈恢复外层作用域。
345    #[inline]
346    pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
347        self.push_id(seed);
348        let res = f(self);
349        self.pop_id();
350        res
351    }
352
353    /// 基于当前作用域 ID 栈与局部 ID 派生全局唯一、不与用户显式 ID 撞车的稳定 `u32` 元素 ID。
354    #[inline]
355    pub fn scoped_id(&self, local_id: u32) -> u32 {
356        let depth = self.id_depth.get() as usize;
357        let seed = if depth == 0 {
358            self.current_pod.0 as u32
359        } else {
360            self.id_stack.get()[(depth - 1).min(7)]
361        };
362        derive_scoped_id(seed, 0x4C4F_434C, local_id)
363    }
364
365    /// 获取当前主题配色令牌。
366    #[inline(always)]
367    pub fn theme(&self) -> &CoreTheme {
368        let ptr = self.theme_override_ptr.get();
369        if !ptr.is_null() {
370            unsafe { &*ptr }
371        } else {
372            &self.theme
373        }
374    }
375
376    /// 设置当前主题配色令牌。
377    #[inline(always)]
378    pub fn set_theme(&mut self, theme: CoreTheme) {
379        self.theme = theme;
380        self.theme_override_ptr.set(core::ptr::null());
381    }
382
383    /// 在当前帧渲染期间覆盖活跃主题配色(分配在 `ScratchArena` 中,零可变别名风险)。
384    #[inline]
385    pub fn override_theme(&self, theme: CoreTheme) {
386        if self.arena.can_alloc_slice::<CoreTheme>(1) {
387            let alloc_ref: &CoreTheme = self.arena.alloc(theme);
388            self.theme_override_ptr.set(alloc_ref as *const CoreTheme);
389        }
390    }
391
392    /// 获取当前正在渲染的 `PodId`。
393    #[inline(always)]
394    pub fn current_pod(&self) -> PodId {
395        self.current_pod
396    }
397
398    /// 引擎单调动画时钟(毫秒,自引擎创建起按 `step_frame_dt(dt)` 累加,约 49 天回绕)。
399    ///
400    /// 配合 [`Tween`](crate::motion::Tween) / [`Presence`](crate::motion::Presence) 实现与帧率无关的自定义动画。
401    #[inline(always)]
402    pub const fn now_ms(&self) -> u32 {
403        self.now_ms
404    }
405
406    /// 设置动画时钟(由引擎在每帧渲染前自动调用;自定义宿主或测试可手动设置)。
407    #[inline(always)]
408    pub fn set_now_ms(&mut self, now_ms: u32) {
409        self.now_ms = now_ms;
410    }
411
412    /// 请求引擎在下一帧继续重新渲染(用于由 `now_ms()` 驱动的连续动画,如旋转加载指示器)。
413    #[inline(always)]
414    pub fn request_frame(&self) {
415        self.frame_requested.set(true);
416    }
417
418    /// 若 `running` 为真则请求下一帧,并原样返回 `running`(便于 `cx.keep_animating(tween.is_running(now))`)。
419    #[inline(always)]
420    pub fn keep_animating(&self, running: bool) -> bool {
421        if running {
422            self.frame_requested.set(true);
423        }
424        running
425    }
426
427    /// 本帧渲染期间是否有视图请求了下一帧(`request_frame()` / `keep_animating(true)`)。
428    #[inline(always)]
429    pub fn is_frame_requested(&self) -> bool {
430        self.frame_requested.get()
431    }
432}
433
434/// 有状态视图渲染上下文 `Scope<V>`。
435///
436/// 通过 `#[repr(transparent)]` 与 `Deref<Target = FrameScope>` 保证与 `FrameScope` 内存布局 100% 一致,
437/// 自动兼容所有接受 `&FrameScope` 的 `.child(cx, ...)` 调用。
438#[repr(transparent)]
439pub struct Scope<V> {
440    pub(crate) frame: FrameScope,
441    _marker: PhantomData<V>,
442}
443
444impl<V> Default for Scope<V> {
445    fn default() -> Self {
446        Self::new()
447    }
448}
449
450impl<V> Scope<V> {
451    /// 创建视图作用域。
452    pub fn new() -> Self {
453        Self {
454            frame: FrameScope::new(),
455            _marker: PhantomData,
456        }
457    }
458
459    /// 设置当前所属的 `PodId`。
460    #[inline(always)]
461    pub fn set_current_pod(&mut self, id: PodId) {
462        self.frame.current_pod = id;
463    }
464
465    /// 获取当前主题配色。
466    #[inline(always)]
467    pub fn theme(&self) -> &CoreTheme {
468        self.frame.theme()
469    }
470
471    /// 获取帧内存池引用。
472    #[inline(always)]
473    pub fn arena(&self) -> &ScratchArena {
474        self.frame.arena()
475    }
476
477    /// 在指定作用域 ID 种子内执行视图渲染闭包(保留 `&'a Scope<V>` 以便直接调用 `cx.listener` / `cx.action` 并返回 `Element<'a>`)。
478    #[inline]
479    pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
480        self.frame.push_id(seed);
481        let res = f(self);
482        self.frame.pop_id();
483        res
484    }
485}
486
487impl<V: View> Scope<V> {
488    /// 将组件状态变更闭包分配至 `ScratchArena` 中,并在事件触发时自动路由回当前 `PodId` 对应的 `V` 实例。
489    ///
490    /// 默认在可变回调结束后自动标记当前有状态 `PodId` 为脏(消除逐字节读取未初始化 Padding 的 UB,并正确捕获 `Vec`/`String` 等堆内修改);
491    /// 若回调仅做只读判断无需重绘,可调用 [`ActionScope::skip_notify`]。
492    pub fn listener<'a, E, F>(&'a self, handler: F) -> &'a dyn Fn(E, &mut ActionScope)
493    where
494        E: 'a,
495        F: Fn(&mut V, E, &mut ActionScope) + 'a,
496    {
497        let pod_id = self.frame.current_pod;
498        let pod_gen = self.frame.current_pod_gen;
499        self.frame.arena.alloc(move |event: E, acx: &mut ActionScope| {
500            let prev_pod = acx.active_pod;
501            let prev_skip = acx.notify_skipped;
502            acx.active_pod = pod_id;
503            acx.notify_skipped = false;
504            if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
505                let view_ref = unsafe { &mut *(view_ptr as *mut V) };
506                handler(view_ref, event, acx);
507                acx.release_view_borrow(pod_id);
508                if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
509                    acx.notify();
510                }
511            }
512            acx.flush_signal_dirty_pods();
513            acx.notify_skipped = prev_skip;
514            acx.active_pod = prev_pod;
515        })
516    }
517
518    /// 构造无需事件参数的动作回调 `&'a dyn Fn(&mut ActionScope)`(直接用于 `on_dismiss` / `on_focus` / `on_click_raw`,消除手动 `arena.alloc` 包装)。
519    ///
520    /// 默认在可变回调结束后自动标记当前有状态 `PodId` 为脏;若无需重绘可调用 [`ActionScope::skip_notify`]。
521    pub fn action<'a, F>(&'a self, handler: F) -> &'a dyn Fn(&mut ActionScope)
522    where
523        F: Fn(&mut V, &mut ActionScope) + 'a,
524    {
525        let pod_id = self.frame.current_pod;
526        let pod_gen = self.frame.current_pod_gen;
527        self.frame.arena.alloc(move |acx: &mut ActionScope| {
528            let prev_pod = acx.active_pod;
529            let prev_skip = acx.notify_skipped;
530            acx.active_pod = pod_id;
531            acx.notify_skipped = false;
532            if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
533                let view_ref = unsafe { &mut *(view_ptr as *mut V) };
534                handler(view_ref, acx);
535                acx.release_view_borrow(pod_id);
536                if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
537                    acx.notify();
538                }
539            }
540            acx.flush_signal_dirty_pods();
541            acx.notify_skipped = prev_skip;
542            acx.active_pod = prev_pod;
543        })
544    }
545}
546
547impl<V> Deref for Scope<V> {
548    type Target = FrameScope;
549    #[inline(always)]
550    fn deref(&self) -> &Self::Target {
551        &self.frame
552    }
553}
554
555/// 事件回调执行期上下文(支持 `cx.notify()` 触发当前 `PodId` 局部脏标记与 `stop_propagation()` 阻断冒泡)。
556pub struct ActionScope<'p> {
557    pub(crate) active_pod: PodId,
558    pub(crate) pool: &'p mut PodPool,
559    pub(crate) click_pos: (i16, i16),
560    pub(crate) drag_event: DragEvent,
561    pub(crate) propagation_stopped: bool,
562    pub(crate) notify_skipped: bool,
563    pub(crate) now_ms: u32,
564    pub(crate) modifiers: super::events::KeyModifiers,
565    pub(crate) async_app: Option<crate::async_rt::AsyncApp>,
566}
567
568impl<'p> ActionScope<'p> {
569    #[inline(always)]
570    pub(crate) fn new(
571        active_pod: PodId,
572        pool: &'p mut PodPool,
573        click_pos: (i16, i16),
574        drag_event: DragEvent,
575        now_ms: u32,
576    ) -> Self {
577        Self {
578            active_pod,
579            pool,
580            click_pos,
581            drag_event,
582            propagation_stopped: false,
583            notify_skipped: false,
584            now_ms,
585            modifiers: super::events::KeyModifiers::NONE,
586            async_app: None,
587        }
588    }
589
590    #[inline(always)]
591    pub(crate) fn with_async_app(mut self, app: crate::async_rt::AsyncApp) -> Self {
592        self.async_app = Some(app);
593        self
594    }
595
596    #[inline(always)]
597    pub(crate) fn with_modifiers(mut self, modifiers: super::events::KeyModifiers) -> Self {
598        self.modifiers = modifiers;
599        self
600    }
601
602    /// 获取当前正在执行事件回调的视图句柄 [`Handle<V>`](带 ABA 代号与运行时类型校验;全平台 `#![no_std]` 可用)。
603    #[inline]
604    pub fn handle<V: View>(&self) -> Option<Handle<V>> {
605        let generation = self
606            .pool
607            .current_generation_for_type(self.active_pod, TypeId::of::<V>())?;
608        Some(Handle::with_generation(self.active_pod, generation))
609    }
610
611    /// 在当前事件回调中派生绑定到当前视图的 UI 前景异步任务(与 GPUI `cx.spawn(async move |this, cx| ...)` 对齐)。
612    ///
613    /// 返回 RAII [`crate::async_rt::Task<T>`]:存入视图字段可在覆盖或视图卸载时自动取消,或调用 `.detach()` 独立运行。
614    pub fn spawn<V, T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
615    where
616        V: View,
617        T: 'static,
618        F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
619        Fut: core::future::Future<Output = T> + 'static,
620    {
621        let handle = self
622            .handle::<V>()
623            .expect("ActionScope::spawn::<V> 类型与当前活跃视图不匹配");
624        let app = self
625            .async_app
626            .clone()
627            .expect("ActionScope 未绑定 ForegroundExecutor");
628        app.spawn_for(handle, f)
629    }
630
631    /// 在当前事件回调中派生不绑定特定视图句柄的 UI 前景异步任务(闭包接收 [`crate::async_rt::AsyncApp`])。
632    pub fn spawn_app<T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
633    where
634        T: 'static,
635        F: FnOnce(crate::async_rt::AsyncApp) -> Fut,
636        Fut: core::future::Future<Output = T> + 'static,
637    {
638        let app = self
639            .async_app
640            .clone()
641            .expect("ActionScope 未绑定 ForegroundExecutor");
642        app.spawn(f)
643    }
644
645    /// 获取绑定到当前引擎调度器后端的后台异步执行器句柄(用于 `.spawn(...)` / `.timer(Duration)`)。
646    #[inline]
647    pub fn background_executor(&self) -> crate::async_rt::BackgroundExecutor {
648        self.async_app
649            .as_ref()
650            .map(|app| app.background_executor())
651            .unwrap_or_else(crate::async_rt::BackgroundExecutor::new)
652    }
653
654    /// 在当前引擎配置的后台调度器中直接派生 CPU 密集型计算或阻塞 I/O 任务。
655    #[inline]
656    pub fn background_spawn<T, Fut>(&self, fut: Fut) -> crate::async_rt::Task<T>
657    where
658        T: Send + 'static,
659        Fut: core::future::Future<Output = T> + Send + 'static,
660    {
661        self.background_executor().spawn(fut)
662    }
663
664    /// 创建由当前引擎调度器时钟驱动的非阻塞异步定时器。
665    #[inline]
666    pub fn timer(&self, duration: core::time::Duration) -> crate::async_rt::Timer {
667        self.background_executor().timer(duration)
668    }
669
670    /// 排入一个延迟到当前事件冒泡结束后在 UI 主线程执行的回调(避免与当前视图可变借用冲突)。
671    #[inline]
672    pub fn defer<F>(&mut self, f: F)
673    where
674        F: FnOnce(&mut ActionScope) + 'static,
675    {
676        if let Some(app) = &self.async_app {
677            app.defer(f);
678        }
679    }
680
681    /// 排入一个延迟到当前事件冒泡结束后在当前视图上执行的回调(提供直接 `&mut V` 引用,与 GPUI `cx.defer` 对齐)。
682    pub fn defer_self<V, F>(&mut self, f: F)
683    where
684        V: View,
685        F: FnOnce(&mut V, &mut ActionScope) + 'static,
686    {
687        let Some(handle) = self.handle::<V>() else {
688            return;
689        };
690        if let Some(app) = &self.async_app {
691            app.defer(move |acx| {
692                let _ = acx.update(handle, f);
693            });
694        }
695    }
696
697    /// 标记当前正在处理事件的组件视图(`PodId`)为脏,将其压入局部重绘队列。
698    #[inline]
699    pub fn notify(&mut self) {
700        self.notify_skipped = false;
701        self.pool.mark_dirty(self.active_pod);
702    }
703
704    /// 显式声明本次 `listener` / `action` / `update` 回调未更改视图状态,跳过默认自动标脏。
705    #[inline(always)]
706    pub fn skip_notify(&mut self) {
707        self.notify_skipped = true;
708    }
709
710    /// 将当前响应式信号(`Signal<T>`)收集到的脏 `PodId` 刷入 `PodPool` 脏队列。
711    #[inline]
712    pub fn flush_signal_dirty_pods(&mut self) {
713        self.pool.flush_signal_dirty_pods();
714    }
715
716    /// 阻止当前事件继续向父级容器冒泡传递。
717    #[inline(always)]
718    pub fn stop_propagation(&mut self) {
719        self.propagation_stopped = true;
720    }
721
722    /// 当前事件是否已调用 `stop_propagation()` 停止冒泡。
723    #[inline(always)]
724    pub const fn is_propagation_stopped(&self) -> bool {
725        self.propagation_stopped
726    }
727
728    /// 标记指定句柄对应的子视图为脏。
729    #[inline]
730    pub fn notify_handle<T: View>(&mut self, handle: Handle<T>) {
731        if self.pool.get(handle).is_some() {
732            self.pool.mark_dirty(handle.id);
733        }
734    }
735
736    /// 在事件回调中读取另一个 `Handle<T>` 的只读状态(若目标视图已被可变借用则返回 `None`)。
737    #[inline]
738    pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<&'s T> {
739        if handle.id == self.active_pod {
740            return None;
741        }
742        self.pool.get(handle)
743    }
744
745    /// 在事件回调中安全更新另一个 `Handle<T>` 视图的状态并自动标记其局部脏区。
746    /// 若发生 `A -> B -> A` 循环重入,内层对已借用视图的 `update` 将安全返回 `None`,彻底杜绝双 `&mut` 别名 UB。
747    pub fn update<T: View, R>(
748        &mut self,
749        handle: Handle<T>,
750        f: impl FnOnce(&mut T, &mut ActionScope) -> R,
751    ) -> Option<R> {
752        if handle.id == self.active_pod {
753            return None;
754        }
755        let target_ptr =
756            self.pool
757                .acquire_raw_mut(handle.id, Some(handle.generation), TypeId::of::<T>())?;
758        let prev_pod = self.active_pod;
759        let prev_skip = self.notify_skipped;
760        self.active_pod = handle.id;
761        self.notify_skipped = false;
762        let target_ref = unsafe { &mut *(target_ptr as *mut T) };
763        let res = f(target_ref, self);
764        let skipped = self.notify_skipped;
765        self.pool.release_borrow(handle.id);
766        if core::mem::size_of::<T>() > 0 && !skipped {
767            self.pool.mark_dirty(handle.id);
768        }
769        self.flush_signal_dirty_pods();
770        self.notify_skipped = prev_skip;
771        self.active_pod = prev_pod;
772        Some(res)
773    }
774
775    /// 获取当前点击事件的屏幕坐标。
776    #[inline(always)]
777    pub const fn click_position(&self) -> (i16, i16) {
778        self.click_pos
779    }
780
781    /// 获取当前拖拽事件详情。
782    #[inline(always)]
783    pub const fn drag_event(&self) -> DragEvent {
784        self.drag_event
785    }
786
787    /// 事件触发时刻的引擎动画时钟(毫秒,与渲染期 `FrameScope::now_ms()` 同源,用于启动 `Tween` / `Presence`)。
788    #[inline(always)]
789    pub const fn now_ms(&self) -> u32 {
790        self.now_ms
791    }
792
793    /// 事件触发时刻的键盘修饰键状态(`Shift` / `Ctrl` / `Alt` / `Logo`)。
794    #[inline(always)]
795    pub const fn modifiers(&self) -> super::events::KeyModifiers {
796        self.modifiers
797    }
798
799    pub(crate) fn acquire_view_mut_ptr(
800        &mut self,
801        id: PodId,
802        expected_gen: Option<u16>,
803        expected_type: TypeId,
804    ) -> Option<*mut u8> {
805        self.pool.acquire_raw_mut(id, expected_gen, expected_type)
806    }
807
808    pub(crate) fn release_view_borrow(&mut self, id: PodId) {
809        self.pool.release_borrow(id);
810    }
811}