Skip to main content

velox_engine/async_rt/
foreground.rs

1//! UI 主线程前景异步执行器 [`ForegroundExecutor`] 与前景协程上下文 [`AsyncApp`]。
2//!
3//! 关键设计:
4//! - **UI 主线程单线程执行**:前景协程不要求 `Send`,可直接安全操作 `PodPool` 与线程局部 `Signal<T>`;
5//! - **RAII 活动引擎守卫**:仅在 `VeloxEngine::poll_async_tasks` 期间临时挂载 `*mut PodPool`,
6//!   协程跨 `.await` 挂起时自动摘除,杜绝悬垂指针与双 `&mut` 别名;
7//! - **零轮询事件驱动唤醒**:后台任务完成或定时器到期时通过 `wake_ui`(如 `WinitUserEvent::WakeAsync`)
8//!   精准唤醒休眠中的事件循环,空闲期间保持 0% CPU。
9
10use core::any::TypeId;
11use core::cell::{Cell, RefCell};
12use core::future::Future;
13use core::pin::Pin;
14use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use core::task::{Context, Poll, Waker};
16use core::time::Duration;
17use std::boxed::Box;
18use std::collections::{HashMap, VecDeque};
19use std::rc::Rc;
20use std::sync::{Arc, Mutex};
21use std::task::Wake;
22use std::vec::Vec;
23
24use crate::element::View;
25use crate::pod::{ActionScope, DragEvent, Handle, PodId, PodPool};
26
27use super::backend::SchedulerBackend;
28use super::scheduler::SchedulerCapabilities;
29use super::std_scheduler::{BackgroundExecutor, NativeStdScheduler, Timer};
30use super::task::{Task, TaskShared};
31
32// ============================================================================
33// 线程局部活动引擎上下文守卫(仅在 poll_ready 栈帧内有效)
34// ============================================================================
35
36#[derive(Copy, Clone)]
37struct ActiveEngineCtx {
38    pool_ptr: *mut PodPool,
39    now_ms: u32,
40}
41
42impl ActiveEngineCtx {
43    const EMPTY: Self = Self {
44        pool_ptr: core::ptr::null_mut(),
45        now_ms: 0,
46    };
47}
48
49std::thread_local! {
50    static ACTIVE_ENGINE_CTX: Cell<ActiveEngineCtx> = const { Cell::new(ActiveEngineCtx::EMPTY) };
51}
52
53struct ActiveEngineGuard {
54    prev: ActiveEngineCtx,
55}
56
57impl ActiveEngineGuard {
58    #[inline]
59    fn enter(pool: &mut PodPool, now_ms: u32) -> Self {
60        let prev = ACTIVE_ENGINE_CTX.with(|c| {
61            c.replace(ActiveEngineCtx {
62                pool_ptr: pool as *mut PodPool,
63                now_ms,
64            })
65        });
66        Self { prev }
67    }
68}
69
70impl Drop for ActiveEngineGuard {
71    #[inline]
72    fn drop(&mut self) {
73        ACTIVE_ENGINE_CTX.with(|c| c.set(self.prev));
74    }
75}
76
77// ============================================================================
78// 前景执行器跨线程唤醒与就绪队列
79// ============================================================================
80
81type WakeUiFn = Arc<dyn Fn() + Send + Sync>;
82
83pub(crate) struct ForegroundShared {
84    next_id: AtomicU64,
85    ready_queue: Mutex<VecDeque<u64>>,
86    cancelled_ids: Mutex<Vec<u64>>,
87    wake_ui: Mutex<Option<WakeUiFn>>,
88    backend: Mutex<Arc<dyn SchedulerBackend>>,
89}
90
91impl ForegroundShared {
92    fn new(backend: Arc<dyn SchedulerBackend>) -> Arc<Self> {
93        Arc::new(Self {
94            next_id: AtomicU64::new(1),
95            ready_queue: Mutex::new(VecDeque::new()),
96            cancelled_ids: Mutex::new(Vec::new()),
97            wake_ui: Mutex::new(None),
98            backend: Mutex::new(backend),
99        })
100    }
101
102    fn backend(&self) -> Arc<dyn SchedulerBackend> {
103        let guard = self.backend.lock().unwrap_or_else(|e| e.into_inner());
104        Arc::clone(&guard)
105    }
106
107    fn set_backend(&self, backend: Arc<dyn SchedulerBackend>) {
108        let mut guard = self.backend.lock().unwrap_or_else(|e| e.into_inner());
109        *guard = backend;
110    }
111
112    fn set_wake_ui(&self, waker: WakeUiFn) {
113        let mut guard = self.wake_ui.lock().unwrap_or_else(|e| e.into_inner());
114        *guard = Some(waker);
115    }
116
117    fn notify_ui(&self) {
118        let cb = {
119            let guard = self.wake_ui.lock().unwrap_or_else(|e| e.into_inner());
120            guard.as_ref().map(Arc::clone)
121        };
122        if let Some(cb) = cb {
123            cb();
124        }
125    }
126
127    fn enqueue_ready(&self, task_id: u64) {
128        {
129            let mut q = self.ready_queue.lock().unwrap_or_else(|e| e.into_inner());
130            q.push_back(task_id);
131        }
132        self.notify_ui();
133    }
134
135    fn enqueue_cancel(&self, task_id: u64) {
136        {
137            let mut c = self.cancelled_ids.lock().unwrap_or_else(|e| e.into_inner());
138            c.push(task_id);
139        }
140        self.notify_ui();
141    }
142
143    fn has_ready(&self) -> bool {
144        let q = self.ready_queue.lock().unwrap_or_else(|e| e.into_inner());
145        !q.is_empty()
146    }
147
148    fn has_cancelled(&self) -> bool {
149        let c = self
150            .cancelled_ids
151            .lock()
152            .unwrap_or_else(|e| e.into_inner());
153        !c.is_empty()
154    }
155}
156
157struct FgTaskWaker {
158    shared: Arc<ForegroundShared>,
159    task_id: u64,
160    queued: Arc<AtomicBool>,
161    cancelled: Arc<AtomicBool>,
162}
163
164impl FgTaskWaker {
165    fn schedule(&self) {
166        if self.cancelled.load(Ordering::Acquire) {
167            return;
168        }
169        if !self.queued.swap(true, Ordering::AcqRel) {
170            self.shared.enqueue_ready(self.task_id);
171        }
172    }
173}
174
175impl Wake for FgTaskWaker {
176    fn wake(self: Arc<Self>) {
177        self.schedule();
178    }
179    fn wake_by_ref(self: &Arc<Self>) {
180        self.schedule();
181    }
182}
183
184struct FgTaskEntry {
185    future: Pin<Box<dyn Future<Output = ()>>>,
186    cancelled: Arc<AtomicBool>,
187    queued: Arc<AtomicBool>,
188}
189
190pub(crate) struct ForegroundLocal {
191    tasks: HashMap<u64, FgTaskEntry>,
192    defers: VecDeque<Box<dyn FnOnce(&mut ActionScope)>>,
193}
194
195impl ForegroundLocal {
196    fn new() -> Self {
197        Self {
198            tasks: HashMap::new(),
199            defers: VecDeque::new(),
200        }
201    }
202}
203
204/// UI 主线程前景异步执行器(由 [`crate::engine::VeloxEngine`] 持有)。
205pub struct ForegroundExecutor {
206    shared: Arc<ForegroundShared>,
207    local: Rc<RefCell<ForegroundLocal>>,
208}
209
210impl Default for ForegroundExecutor {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216impl ForegroundExecutor {
217    /// 创建一个绑定默认内置 [`NativeStdScheduler`] 的主线程前景异步执行器。
218    pub fn new() -> Self {
219        Self::with_backend(NativeStdScheduler::global())
220    }
221
222    /// 创建一个绑定自定义可插拔 [`SchedulerBackend`] 的主线程前景异步执行器。
223    pub fn with_backend(backend: Arc<dyn SchedulerBackend>) -> Self {
224        Self {
225            shared: ForegroundShared::new(backend),
226            local: Rc::new(RefCell::new(ForegroundLocal::new())),
227        }
228    }
229
230    /// 切换当前前景执行器及其派生的所有 [`AsyncApp`] 所使用的底层 [`SchedulerBackend`]。
231    pub fn set_backend(&self, backend: Arc<dyn SchedulerBackend>) {
232        self.shared.set_backend(backend);
233    }
234
235    /// 获取当前配置的底层 [`SchedulerBackend`] 引用。
236    #[inline]
237    pub fn backend(&self) -> Arc<dyn SchedulerBackend> {
238        self.shared.backend()
239    }
240
241    /// 获取绑定到当前调度器后端的 [`BackgroundExecutor`]。
242    #[inline]
243    pub fn background_executor(&self) -> BackgroundExecutor {
244        BackgroundExecutor::with_backend(self.shared.backend())
245    }
246
247    /// 返回当前调度器后端名称。
248    #[inline]
249    pub fn scheduler_name(&self) -> &'static str {
250        self.shared.backend().name()
251    }
252
253    /// 返回当前调度器能力描述符。
254    #[inline]
255    pub fn scheduler_capabilities(&self) -> SchedulerCapabilities {
256        self.shared.backend().capabilities()
257    }
258
259    /// 注入平台级唤醒回调(如 `WinitUserEvent::WakeAsync` / Wayland `eventfd` / 移动端 Looper 唤醒)。
260    pub fn set_wake_ui(&self, waker: impl Fn() + Send + Sync + 'static) {
261        self.shared.set_wake_ui(Arc::new(waker));
262    }
263
264    /// 构造一个轻量 `Clone` 的前景协程上下文句柄 [`AsyncApp`]。
265    #[inline]
266    pub fn async_app(&self) -> AsyncApp {
267        AsyncApp {
268            shared: Arc::clone(&self.shared),
269            local: Rc::clone(&self.local),
270        }
271    }
272
273    /// 在 UI 主线程前景执行器上派生异步任务(接收 [`AsyncApp`])。
274    pub fn spawn<T, F, Fut>(&self, f: F) -> Task<T>
275    where
276        T: 'static,
277        F: FnOnce(AsyncApp) -> Fut,
278        Fut: Future<Output = T> + 'static,
279    {
280        self.async_app().spawn(f)
281    }
282
283    /// 排入一个延迟到当前事件冒泡结束后在 UI 主线程执行的回调(与 GPUI `cx.defer` 对齐)。
284    pub fn defer<F>(&self, f: F)
285    where
286        F: FnOnce(&mut ActionScope) + 'static,
287    {
288        self.local.borrow_mut().defers.push_back(Box::new(f));
289        self.shared.notify_ui();
290    }
291
292    /// 是否存在立即待执行的前景就绪任务或延迟 `defer` 回调(用于判断 `needs_redraw`)。
293    #[inline]
294    pub fn has_ready_work(&self) -> bool {
295        self.shared.has_ready() || !self.local.borrow().defers.is_empty()
296    }
297
298    /// 是否存在待执行任务、延迟回调或待回收的已取消协程(用于事件结束后的轻量清理)。
299    #[inline]
300    pub(crate) fn has_work_to_poll(&self) -> bool {
301        self.has_ready_work() || self.shared.has_cancelled()
302    }
303
304    /// 返回当前仍活跃挂载在前台执行器中的协程数量(用于测试验证取消与回收零泄漏)。
305    #[inline]
306    pub fn active_task_count(&self) -> usize {
307        self.local.borrow().tasks.len()
308    }
309
310    /// 在 UI 主线程排空所有已就绪的前景协程与 `defer` 回调;返回是否至少推进了 1 项任务或回调。
311    pub fn poll_ready(&self, pool: &mut PodPool, now_ms: u32) -> bool {
312        let _guard = ActiveEngineGuard::enter(pool, now_ms);
313        let mut did_work = false;
314
315        // 上限 64 轮防止恶意自唤醒 `yield` 饿死主渲染帧
316        for _round in 0..64 {
317            // 1. 回收被 Drop 取消的协程,立即释放其捕获状态
318            let cancelled_batch: Vec<u64> = {
319                let mut c = self
320                    .shared
321                    .cancelled_ids
322                    .lock()
323                    .unwrap_or_else(|e| e.into_inner());
324                core::mem::take(&mut *c)
325            };
326            if !cancelled_batch.is_empty() {
327                let mut loc = self.local.borrow_mut();
328                for id in cancelled_batch {
329                    loc.tasks.remove(&id);
330                }
331            }
332
333            // 2. 取出当前一轮所有已就绪的前景任务 ID
334            let ready_batch: Vec<u64> = {
335                let mut q = self
336                    .shared
337                    .ready_queue
338                    .lock()
339                    .unwrap_or_else(|e| e.into_inner());
340                q.drain(..).collect()
341            };
342
343            let mut progressed_this_round = false;
344
345            for task_id in ready_batch {
346                // 先从 HashMap 移出到局部栈再 poll,允许协程内部重入调用 cx.spawn / cx.defer 而无 RefCell 冲突
347                let entry_opt = self.local.borrow_mut().tasks.remove(&task_id);
348                let Some(mut entry) = entry_opt else {
349                    continue;
350                };
351                entry.queued.store(false, Ordering::Release);
352                if entry.cancelled.load(Ordering::Acquire) {
353                    continue;
354                }
355
356                did_work = true;
357                progressed_this_round = true;
358
359                let waker = Waker::from(Arc::new(FgTaskWaker {
360                    shared: Arc::clone(&self.shared),
361                    task_id,
362                    queued: Arc::clone(&entry.queued),
363                    cancelled: Arc::clone(&entry.cancelled),
364                }));
365                let mut cx = Context::from_waker(&waker);
366                match entry.future.as_mut().poll(&mut cx) {
367                    Poll::Ready(()) => {}
368                    Poll::Pending => {
369                        if !entry.cancelled.load(Ordering::Acquire) {
370                            self.local.borrow_mut().tasks.insert(task_id, entry);
371                        }
372                    }
373                }
374            }
375
376            // 3. 排空本轮积攒的所有 `defer` 延迟回调
377            loop {
378                let next_defer = self.local.borrow_mut().defers.pop_front();
379                let Some(cb) = next_defer else {
380                    break;
381                };
382                did_work = true;
383                progressed_this_round = true;
384                let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
385                if !ctx.pool_ptr.is_null() {
386                    let pool_ref = unsafe { &mut *ctx.pool_ptr };
387                    let mut acx = ActionScope::new(
388                        PodId(u16::MAX),
389                        pool_ref,
390                        (0, 0),
391                        DragEvent::default(),
392                        ctx.now_ms,
393                    )
394                    .with_async_app(self.async_app());
395                    cb(&mut acx);
396                    acx.flush_signal_dirty_pods();
397                }
398            }
399
400            // 将期间通过 Signal<T> 写入产生的脏视图同步刷入 PodPool
401            let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
402            if !ctx.pool_ptr.is_null() {
403                unsafe { &mut *ctx.pool_ptr }.flush_signal_dirty_pods();
404            }
405
406            if !progressed_this_round || !self.has_ready_work() {
407                break;
408            }
409        }
410
411        did_work
412    }
413}
414
415// ============================================================================
416// 前景协程跨 `.await` 上下文句柄 `AsyncApp`
417// ============================================================================
418
419/// 前景 UI 协程持有的异步应用上下文(与 GPUI `AsyncApp` 对齐)。
420///
421/// `!Send`(绑定 UI 主线程),可自由跨 `.await` 存活并随时安全访问 `PodPool`、派生子任务、
422/// 发起 `background_spawn` 后台计算与 `timer` 定时器。
423#[derive(Clone)]
424pub struct AsyncApp {
425    shared: Arc<ForegroundShared>,
426    local: Rc<RefCell<ForegroundLocal>>,
427}
428
429impl AsyncApp {
430    /// 获取绑定到当前引擎调度器后端的后台异步执行器句柄(用于 `.spawn(...)` / `.timer(Duration)`)。
431    #[inline]
432    pub fn background_executor(&self) -> BackgroundExecutor {
433        BackgroundExecutor::with_backend(self.shared.backend())
434    }
435
436    /// 在当前引擎配置的后台调度器中执行 CPU 密集型计算或阻塞 I/O,返回可 `.await` 的 [`Task<T>`]。
437    #[inline]
438    pub fn background_spawn<T, Fut>(&self, fut: Fut) -> Task<T>
439    where
440        T: Send + 'static,
441        Fut: Future<Output = T> + Send + 'static,
442    {
443        self.background_executor().spawn(fut)
444    }
445
446    /// 创建由当前引擎调度器时钟驱动的非阻塞异步定时器(与 GPUI `cx.background_executor().timer(dur)` 等价简写)。
447    #[inline]
448    pub fn timer(&self, duration: Duration) -> Timer {
449        self.background_executor().timer(duration)
450    }
451
452    /// 返回当前引擎配置的调度器名称。
453    #[inline]
454    pub fn scheduler_name(&self) -> &'static str {
455        self.shared.backend().name()
456    }
457
458    /// 在 UI 主线程前景执行器上派生子异步任务(不绑定特定视图句柄)。
459    pub fn spawn<T, F, Fut>(&self, f: F) -> Task<T>
460    where
461        T: 'static,
462        F: FnOnce(AsyncApp) -> Fut,
463        Fut: Future<Output = T> + 'static,
464    {
465        let task_id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
466        let cancelled = Arc::new(AtomicBool::new(false));
467        let queued = Arc::new(AtomicBool::new(true));
468
469        let shared_for_cancel = Arc::clone(&self.shared);
470        let on_cancel: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
471            shared_for_cancel.enqueue_cancel(task_id);
472        });
473        let task_shared = TaskShared::new(Arc::clone(&cancelled), Some(on_cancel));
474        let task_out = Arc::clone(&task_shared);
475
476        let fut = f(self.clone());
477        let wrapped = async move {
478            let output = fut.await;
479            if !task_out.is_cancelled() {
480                task_out.complete(output);
481            }
482        };
483
484        self.local.borrow_mut().tasks.insert(
485            task_id,
486            FgTaskEntry {
487                future: Box::pin(wrapped),
488                cancelled,
489                queued,
490            },
491        );
492        self.shared.enqueue_ready(task_id);
493        Task::from_shared(task_shared)
494    }
495
496    /// 在 UI 主线程前景执行器上为指定视图句柄派生绑定异步任务(闭包接收 `(Handle<V>, AsyncApp)`)。
497    pub fn spawn_for<V, T, F, Fut>(&self, handle: Handle<V>, f: F) -> Task<T>
498    where
499        V: View,
500        T: 'static,
501        F: FnOnce(Handle<V>, AsyncApp) -> Fut,
502        Fut: Future<Output = T> + 'static,
503    {
504        self.spawn(move |cx| f(handle, cx))
505    }
506
507    /// 排入一个延迟到本轮前景调度末尾执行的 UI 主线程回调。
508    #[inline]
509    pub fn defer<F>(&self, f: F)
510    where
511        F: FnOnce(&mut ActionScope) + 'static,
512    {
513        self.local.borrow_mut().defers.push_back(Box::new(f));
514        self.shared.notify_ui();
515    }
516
517    /// 在前景协程中安全更新任意 [`Handle<V>`] 视图的状态(自动校验 ABA `generation`、防重入、标脏并刷新信号)。
518    /// 若目标视图已卸载或正在被可变借用,则安全返回 `None` 绝不 panic。
519    pub fn update<V: View, R>(
520        &mut self,
521        handle: Handle<V>,
522        f: impl FnOnce(&mut V, &mut ActionScope) -> R,
523    ) -> Option<R> {
524        let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
525        if ctx.pool_ptr.is_null() {
526            return None;
527        }
528        let pool = unsafe { &mut *ctx.pool_ptr };
529        let target_ptr = pool.acquire_raw_mut(handle.id, Some(handle.generation), TypeId::of::<V>())?;
530        let mut acx = ActionScope::new(
531            handle.id,
532            pool,
533            (0, 0),
534            DragEvent::default(),
535            ctx.now_ms,
536        )
537        .with_async_app(self.clone());
538        let view_ref = unsafe { &mut *(target_ptr as *mut V) };
539        let res = f(view_ref, &mut acx);
540        let skipped = acx.notify_skipped;
541        acx.release_view_borrow(handle.id);
542        if core::mem::size_of::<V>() > 0 && !skipped {
543            acx.notify();
544        }
545        acx.flush_signal_dirty_pods();
546        Some(res)
547    }
548
549    /// 在前景协程中只读读取任意 [`Handle<V>`] 视图的快照数据(若目标视图已卸载则返回 `None`)。
550    pub fn read<V: View, R>(&self, handle: Handle<V>, f: impl FnOnce(&V) -> R) -> Option<R> {
551        let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
552        if ctx.pool_ptr.is_null() {
553            return None;
554        }
555        let pool = unsafe { &*ctx.pool_ptr };
556        let view = pool.get(handle)?;
557        Some(f(view))
558    }
559
560    /// 显式标记指定视图句柄为脏。
561    pub fn notify_handle<V: View>(&mut self, handle: Handle<V>) {
562        let ctx = ACTIVE_ENGINE_CTX.with(|c| c.get());
563        if ctx.pool_ptr.is_null() {
564            return;
565        }
566        let pool = unsafe { &mut *ctx.pool_ptr };
567        if pool.get(handle).is_some() {
568            pool.mark_dirty(handle.id);
569        }
570    }
571
572    /// 获取当前引擎单调动画时钟(毫秒)。
573    #[inline]
574    pub fn now_ms(&self) -> u32 {
575        ACTIVE_ENGINE_CTX.with(|c| c.get().now_ms)
576    }
577}