Skip to main content

rgpui/
app.rs

1//! 应用核心 —— 提供 App 上下文、实体生命周期管理及事件调度。
2
3/// 内部不变量:值为 `None` 说明前提被破坏(类型不符、状态缺失等),必须立刻暴露。
4///
5/// 统一走这里而不是散落的 `unwrap`:语义与原先一致(同样 panic),但把「这是不变量
6/// 断言」的意图写进调用点,模块级 `deny` 仍能拦住随手写的 unwrap。
7#[inline]
8#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
9fn invariant<T>(value: Option<T>, message: &str) -> T {
10    match value {
11        Some(value) => value,
12        None => panic!("{message}"),
13    }
14}
15
16/// 内部不变量:结果为 `Err` 说明前提被破坏(类型 downcast 失败等),必须立刻暴露。
17#[inline]
18#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
19fn invariant_result<T, E>(result: Result<T, E>, message: &str) -> T {
20    match result {
21        Ok(value) => value,
22        Err(_) => panic!("{message}"),
23    }
24}
25use crate::scheduler::Instant;
26use std::{
27    any::{TypeId, type_name},
28    cell::{Cell, Ref, RefCell, RefMut},
29    marker::PhantomData,
30    mem,
31    ops::{Deref, DerefMut},
32    path::{Path, PathBuf},
33    rc::{Rc, Weak},
34    sync::{Arc, atomic::Ordering::SeqCst},
35    time::Duration,
36};
37
38use anyhow::{Context as _, Result, anyhow};
39use derive_more::{Deref, DerefMut};
40use futures::{
41    Future, FutureExt,
42    channel::oneshot,
43    future::{LocalBoxFuture, Shared},
44};
45use itertools::Itertools;
46use parking_lot::RwLock;
47use slotmap::SlotMap;
48
49use crate::collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
50use crate::debug_panic;
51use crate::http_client::{HttpClient, Url};
52use crate::rgpui_util::ResultExt;
53use crate::util::debounce::Debouncer;
54pub use async_context::*;
55#[cfg(feature = "bench")]
56pub use bench_context::{BenchAppContext, BenchReport, BenchWindowContext, bench_platform};
57pub use context::*;
58pub use entity_map::*;
59#[cfg(any(test, feature = "test-support"))]
60pub use headless_app_context::*;
61use smallvec::SmallVec;
62#[cfg(any(test, feature = "test-support"))]
63pub use test_app::*;
64#[cfg(any(test, feature = "test-support"))]
65pub use test_context::*;
66#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
67pub use visual_test_context::*;
68
69#[cfg(any(feature = "inspector", debug_assertions))]
70use crate::InspectorElementRegistry;
71use crate::{
72    Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Arena,
73    ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle,
74    DispatchPhase, DisplayId, EventEmitter, FocusHandle, FocusMap, FocusedWindowInfo,
75    ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu,
76    MenuItem, NetworkStatus, OsInfo, OwnedMenu, PathPromptOptions, PermissionStatus,
77    PermissionType, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
78    PlatformKeyboardMapper, Point, PowerSaveBlocker, PowerSaveBlockerKind, Priority, PromptBuilder,
79    PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
80    Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
81    SystemPowerEvent, Task, TextRenderingMode, TextSystem, ThermalState, Tray, TrayIconEvent,
82    TrayMenuItem, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
83    WindowInvalidator,
84    colors::{Colors, GlobalColors},
85    hash, init_app_menus,
86    root::Root,
87};
88
89mod async_context;
90#[cfg(feature = "bench")]
91#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
92// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
93mod bench_context;
94mod context;
95mod entity_map;
96#[cfg(any(test, feature = "test-support"))]
97#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
98// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
99mod headless_app_context;
100#[cfg(any(test, feature = "test-support"))]
101#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
102// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
103mod test_app;
104#[cfg(any(test, feature = "test-support"))]
105#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
106// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
107mod test_context;
108#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
109#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
110// 测试支撑模块:断言失败就该炸(同 clippy.toml 的 allow-*-in-tests 口径)
111mod visual_test_context;
112
113/// 应用完全退出前,[Context::on_app_quit] 返回的 future 可运行的最大时长。
114pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
115
116/// [`RefCell<App>`] 的临时封装,用于调试双重借用问题。
117/// 稳定后强烈建议移除。
118#[doc(hidden)]
119pub struct AppCell {
120    app: RefCell<App>,
121    /// 当前借用组的起点(尝试借用位置 + 共享/可变种类)。
122    ///
123    /// 重叠的共享借用只记第一个(`borrow` 先探测 `try_borrow_mut` 是否成功,
124    /// 成功说明这是一组新借用的第一个);释放后旧值会残留,由下一个借用组
125    /// 覆盖。冲突诊断靠它给出「已借用的位置」。
126    borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
127}
128
129/// 借用冲突的可读诊断:尝试借用的位置、种类与已存在借用组的起点。
130///
131/// 有意的取舍(对齐上游 `c408f8efc4`):诊断只在失败路径格式化,
132/// `try_borrow_mut` 以 anyhow 结果返回,不再夹带标准库的 `BorrowMutError`。
133pub(crate) struct AppBorrowError {
134    attempted: &'static std::panic::Location<'static>,
135    kind: &'static str,
136    origin: Option<(&'static std::panic::Location<'static>, &'static str)>,
137}
138
139impl std::fmt::Display for AppBorrowError {
140    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        let Self {
142            attempted,
143            kind,
144            origin,
145        } = self;
146        write!(
147            formatter,
148            "RefCell already borrowed: attempted {kind} App borrow at {attempted}; "
149        )?;
150        match origin {
151            Some((origin, existing_kind)) => write!(
152                formatter,
153                "existing {existing_kind} borrow group began at {origin}"
154            ),
155            None => write!(formatter, "origin unavailable"),
156        }
157    }
158}
159
160impl std::fmt::Debug for AppBorrowError {
161    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        std::fmt::Display::fmt(self, formatter)
163    }
164}
165
166impl std::error::Error for AppBorrowError {}
167
168impl AppCell {
169    #[doc(hidden)]
170    #[track_caller]
171    pub fn borrow(&self) -> AppRef<'_> {
172        if option_env!("TRACK_THREAD_BORROWS").is_some() {
173            let thread_id = std::thread::current().id();
174            eprintln!("borrowed {thread_id:?}");
175        }
176        // 重叠的共享借用保留第一个起点:先探测 `try_borrow_mut` 是否成功,
177        // 成功说明这是新借用组的第一个共享借用。
178        let starts_borrow_group = self.app.try_borrow_mut().is_ok();
179        let attempted = std::panic::Location::caller();
180        let borrow = match self.app.try_borrow() {
181            Ok(borrow) => borrow,
182            Err(_) => self.borrow_failed(AppBorrowError {
183                attempted,
184                kind: "shared",
185                origin: self.borrow_origin.get(),
186            }),
187        };
188        if starts_borrow_group {
189            self.borrow_origin
190                .set(Some((std::panic::Location::caller(), "shared")));
191        }
192        AppRef(borrow)
193    }
194
195    #[doc(hidden)]
196    #[track_caller]
197    pub fn borrow_mut(&self) -> AppRefMut<'_> {
198        match self.try_borrow_mut() {
199            Ok(borrow) => borrow,
200            Err(error) => self.borrow_failed(error),
201        }
202    }
203
204    #[doc(hidden)]
205    #[track_caller]
206    pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>> {
207        if option_env!("TRACK_THREAD_BORROWS").is_some() {
208            let thread_id = std::thread::current().id();
209            eprintln!("borrowed {thread_id:?}");
210        }
211        let borrow = match self.app.try_borrow_mut() {
212            Ok(borrow) => borrow,
213            Err(_error) => {
214                return Err(AppBorrowError {
215                    attempted: std::panic::Location::caller(),
216                    kind: "mutable",
217                    origin: self.borrow_origin.get(),
218                }
219                .into());
220            }
221        };
222        self.borrow_origin
223            .set(Some((std::panic::Location::caller(), "mutable")));
224        Ok(AppRefMut(borrow))
225    }
226
227    /// 借用冲突的统一 panic 出口:共享与可变借用共用同一份诊断格式。
228    #[cold]
229    #[track_caller]
230    #[allow(clippy::panic)] // 契约:借用冲突必须立刻炸,错误消息已携带双端位置
231    fn borrow_failed(&self, error: impl std::fmt::Display) -> ! {
232        panic!("{error}")
233    }
234}
235
236#[doc(hidden)]
237#[derive(Deref, DerefMut)]
238pub struct AppRef<'a>(Ref<'a, App>);
239
240impl Drop for AppRef<'_> {
241    fn drop(&mut self) {
242        if option_env!("TRACK_THREAD_BORROWS").is_some() {
243            let thread_id = std::thread::current().id();
244            eprintln!("dropped borrow from {thread_id:?}");
245        }
246    }
247}
248
249#[doc(hidden)]
250#[derive(Deref, DerefMut)]
251pub struct AppRefMut<'a>(RefMut<'a, App>);
252
253impl Drop for AppRefMut<'_> {
254    fn drop(&mut self) {
255        if option_env!("TRACK_THREAD_BORROWS").is_some() {
256            let thread_id = std::thread::current().id();
257            eprintln!("dropped {thread_id:?}");
258        }
259    }
260}
261
262/// 对 RGPUI 应用的引用,通常在应用的 `main` 函数中构建。
263/// 除初始配置和启动阶段外,你不会频繁与此类型交互。
264pub struct Application(Rc<AppCell>);
265
266/// 通过 [`Application::run_embedded`] 启动的应用的强引用句柄。
267///
268/// 丢弃此句柄将释放应用,因此嵌入方必须持有它直到应用结束运行。
269/// 持有期间,它就是嵌入方在外部运行循环每次交还控制权时重新进入 RGPUI 的入口。
270pub struct ApplicationHandle {
271    app: Rc<AppCell>,
272}
273
274impl ApplicationHandle {
275    /// 使用应用上下文调用 `f`。不可在已在 update 内部的代码中重入调用;
276    /// 应用状态是 `RefCell`,双重借用会 panic。
277    pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
278        let cx = &mut *self.app.borrow_mut();
279        f(cx)
280    }
281
282    /// 用于跨 await 点使用的 [`AsyncApp`]。它弱引用应用;保持应用存活仍是此句柄的职责。
283    pub fn to_async(&self) -> AsyncApp {
284        self.update(|cx| cx.to_async())
285    }
286}
287
288/// 表示尚未完全启动的应用。配置完成后,
289/// 使用 `App::run` 启动应用。
290impl Application {
291    /// 使用调用方提供的平台实现构建应用。
292    pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
293        Self(App::new_app(
294            platform,
295            Arc::new(()),
296            Arc::new(NullHttpClient),
297        ))
298    }
299
300    /// 强制禁用无障碍(AccessKit)集成来构建应用。
301    ///
302    /// 在此模式下,无障碍 API(如 [`div().role()`][crate::StatefulInteractiveElement::role])
303    /// 会静默地不执行任何操作。
304    ///
305    /// 参见[无障碍指南](crate::_accessibility)了解被禁用功能的概述。
306    pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
307        let this = Self::with_platform(platform);
308        this.0.borrow_mut().accessibility_force_disabled = true;
309        this
310    }
311
312    /// 设置应用的资源来源。
313    pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
314        let mut context_lock = self.0.borrow_mut();
315        let asset_source = Arc::new(asset_source);
316        context_lock.asset_source = asset_source.clone();
317        context_lock.svg_renderer = SvgRenderer::new(asset_source);
318        drop(context_lock);
319        self
320    }
321
322    /// 设置应用的 HTTP 客户端。
323    pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
324        let mut context_lock = self.0.borrow_mut();
325        context_lock.http_client = http_client;
326        drop(context_lock);
327        self
328    }
329
330    /// 配置应用自动退出的时机。
331    /// 默认使用 [`QuitMode::Default`]。
332    pub fn with_quit_mode(self, mode: QuitMode) -> Self {
333        self.0.borrow_mut().quit_mode = mode;
334        self
335    }
336
337    /// 启动应用。提供的回调将在应用完全启动后被调用。
338    pub fn run<F>(self, on_finish_launching: F)
339    where
340        F: 'static + FnOnce(&mut App),
341    {
342        let this = self.0.clone();
343        let platform = self.0.borrow().platform.clone();
344        platform.run(Box::new(move || {
345            let cx = &mut *this.borrow_mut();
346            on_finish_launching(cx);
347        }));
348    }
349
350    /// 为自行驱动运行循环的嵌入方启动应用。
351    ///
352    /// 在普通平台上,`Platform::run` 会在应用生命周期内阻塞,应用状态由
353    /// [`Application::run`] 的栈帧保持存活。嵌入平台(即运行循环归属他方,
354    /// 例如编译为 Wasm guest 的 RGPUI,或托管在外部原生应用中的 RGPUI 视图)
355    /// 实现 `Platform::run` 时会调用启动回调后立即返回。本方法支持这种模式:
356    /// 它返回一个 [`ApplicationHandle`] 来保持应用存活,并允许嵌入方在外部运行
357    /// 循环交还控制权时重新进入应用。
358    pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
359    where
360        F: 'static + FnOnce(&mut App),
361    {
362        let this = self.0.clone();
363        let platform = self.0.borrow().platform.clone();
364        platform.run(Box::new(move || {
365            let cx = &mut *this.borrow_mut();
366            on_finish_launching(cx);
367        }));
368        ApplicationHandle { app: self.0 }
369    }
370
371    /// 注册一个处理器,当平台指示应用打开一个或多个 URL 时被调用。
372    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
373    where
374        F: 'static + FnMut(Vec<String>),
375    {
376        self.0.borrow().platform.on_open_urls(Box::new(callback));
377        self
378    }
379
380    /// 当已运行的应用再次被启动时调用处理器。
381    /// 在 macOS 上,双击应用图标或通过 Dock 启动应用时会触发此回调。
382    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
383    where
384        F: 'static + FnMut(&mut App),
385    {
386        let this = Rc::downgrade(&self.0);
387        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
388            if let Some(app) = this.upgrade() {
389                callback(&mut app.borrow_mut());
390            }
391        }));
392        self
393    }
394
395    /// 当系统从休眠中唤醒时调用处理器。
396    pub fn on_system_wake<F>(&self, mut callback: F) -> &Self
397    where
398        F: 'static + FnMut(&mut App),
399    {
400        let this = Rc::downgrade(&self.0);
401        self.0
402            .borrow_mut()
403            .platform
404            .on_system_wake(Box::new(move || {
405                if let Some(app) = this.upgrade() {
406                    callback(&mut app.borrow_mut());
407                }
408            }));
409        self
410    }
411
412    /// 返回与此应用关联的 [`BackgroundExecutor`] 句柄,可用于在后台生成 future。
413    pub fn background_executor(&self) -> BackgroundExecutor {
414        self.0.borrow().background_executor.clone()
415    }
416
417    /// 返回与此应用关联的 [`ForegroundExecutor`] 句柄,可用于在前台生成 future。
418    pub fn foreground_executor(&self) -> ForegroundExecutor {
419        self.0.borrow().foreground_executor.clone()
420    }
421
422    /// 返回与此应用关联的 [`TextSystem`] 引用。
423    pub fn text_system(&self) -> Arc<TextSystem> {
424        self.0.borrow().text_system.clone()
425    }
426
427    /// 返回应用 bundle 中指定名称的可执行文件的文件 URL
428    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
429        self.0.borrow().path_for_auxiliary_executable(name)
430    }
431}
432
433type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
434type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
435pub(crate) type KeystrokeObserver =
436    Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
437type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
438type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
439type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
440type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
441
442/// 定义应用自动退出的时机。
443#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
444pub enum QuitMode {
445    /// macOS 上使用 [`QuitMode::Explicit`],其他平台使用 [`QuitMode::LastWindowClosed`]。
446    #[default]
447    Default,
448    /// 最后一个窗口关闭时自动退出。
449    LastWindowClosed,
450    /// 仅在通过 [`App::quit`] 请求时退出。
451    Explicit,
452}
453
454/// 控制 RGPUI 在响应键盘输入时何时隐藏鼠标光标。
455///
456/// 鼠标移动时的恢复由平台层处理;此枚举仅描述
457/// *触发*隐藏的策略。
458#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
459pub enum CursorHideMode {
460    /// 从不自动隐藏光标。
461    Never,
462    /// 在产生字符的按键(打字)时隐藏。
463    OnTyping,
464    /// 在产生字符的按键时隐藏,*以及*当按键绑定
465    /// 解析为消耗该按键的动作时也隐藏。
466    #[default]
467    OnTypingAndAction,
468}
469
470#[doc(hidden)]
471#[derive(Clone, PartialEq, Eq)]
472pub struct SystemWindowTab {
473    pub id: WindowId,
474    pub title: SharedString,
475    pub handle: AnyWindowHandle,
476    pub last_active_at: Instant,
477}
478
479impl SystemWindowTab {
480    /// 创建窗口标签页的新实例。
481    pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
482        Self {
483            id: handle.id,
484            title,
485            handle,
486            last_active_at: Instant::now(),
487        }
488    }
489}
490
491/// 管理窗口标签页的控制器。
492#[derive(Default)]
493pub struct SystemWindowTabController {
494    visible: Option<bool>,
495    tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
496}
497
498impl Global for SystemWindowTabController {}
499
500impl SystemWindowTabController {
501    /// 创建窗口标签页控制器的新实例。
502    pub fn new() -> Self {
503        Self {
504            visible: None,
505            tab_groups: FxHashMap::default(),
506        }
507    }
508
509    /// 初始化全局窗口标签页控制器。
510    pub fn init(cx: &mut App) {
511        cx.set_global(SystemWindowTabController::new());
512    }
513
514    /// 获取所有标签页分组。
515    pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
516        &self.tab_groups
517    }
518
519    /// 获取下一个标签页分组的窗口句柄。
520    pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
521        let controller = cx.global::<SystemWindowTabController>();
522        let current_group = controller
523            .tab_groups
524            .iter()
525            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
526
527        let current_group = current_group?;
528        // 按 group_id 排序确保稳定的循环顺序
529        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
530        group_ids.sort();
531        let idx = group_ids.iter().position(|g| *g == current_group)?;
532        let next_idx = (idx + 1) % group_ids.len();
533
534        controller
535            .tab_groups
536            .get(group_ids[next_idx])
537            .and_then(|tabs| {
538                tabs.iter()
539                    .max_by_key(|tab| tab.last_active_at)
540                    .or_else(|| tabs.first())
541                    .map(|tab| &tab.handle)
542            })
543    }
544
545    /// 获取上一个标签页分组的窗口句柄。
546    pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
547        let controller = cx.global::<SystemWindowTabController>();
548        let current_group = controller
549            .tab_groups
550            .iter()
551            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
552
553        let current_group = current_group?;
554        // 按 group_id 排序确保稳定的循环顺序
555        let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
556        group_ids.sort();
557        let idx = group_ids.iter().position(|g| *g == current_group)?;
558        let prev_idx = if idx == 0 {
559            group_ids.len() - 1
560        } else {
561            idx - 1
562        };
563
564        controller
565            .tab_groups
566            .get(group_ids[prev_idx])
567            .and_then(|tabs| {
568                tabs.iter()
569                    .max_by_key(|tab| tab.last_active_at)
570                    .or_else(|| tabs.first())
571                    .map(|tab| &tab.handle)
572            })
573    }
574
575    /// 获取同一窗口中的所有标签页。
576    pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
577        self.tab_groups
578            .values()
579            .find(|tabs| tabs.iter().any(|tab| tab.id == id))
580    }
581
582    /// 初始化系统窗口标签页控制器的可见性。
583    pub fn init_visible(cx: &mut App, visible: bool) {
584        let mut controller = cx.global_mut::<SystemWindowTabController>();
585        if controller.visible.is_none() {
586            controller.visible = Some(visible);
587        }
588    }
589
590    /// 获取系统窗口标签页控制器的可见性。
591    pub fn is_visible(&self) -> bool {
592        self.visible.unwrap_or(false)
593    }
594
595    /// 设置系统窗口标签页控制器的可见性。
596    pub fn set_visible(cx: &mut App, visible: bool) {
597        let mut controller = cx.global_mut::<SystemWindowTabController>();
598        controller.visible = Some(visible);
599    }
600
601    /// 更新窗口的最后活跃时间。
602    pub fn update_last_active(cx: &mut App, id: WindowId) {
603        let mut controller = cx.global_mut::<SystemWindowTabController>();
604        for windows in controller.tab_groups.values_mut() {
605            for tab in windows.iter_mut() {
606                if tab.id == id {
607                    tab.last_active_at = Instant::now();
608                }
609            }
610        }
611    }
612
613    /// 更新标签页在其分组中的位置。
614    pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
615        let mut controller = cx.global_mut::<SystemWindowTabController>();
616        for (_, windows) in controller.tab_groups.iter_mut() {
617            if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
618                if ix < windows.len() && current_pos != ix {
619                    let window_tab = windows.remove(current_pos);
620                    windows.insert(ix, window_tab);
621                }
622                break;
623            }
624        }
625    }
626
627    /// 更新标签页的标题。
628    pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
629        let controller = cx.global::<SystemWindowTabController>();
630        let tab = controller
631            .tab_groups
632            .values()
633            .flat_map(|windows| windows.iter())
634            .find(|tab| tab.id == id);
635
636        if tab.map_or(true, |t| t.title == title) {
637            return;
638        }
639
640        let mut controller = cx.global_mut::<SystemWindowTabController>();
641        for windows in controller.tab_groups.values_mut() {
642            for tab in windows.iter_mut() {
643                if tab.id == id {
644                    tab.title = title;
645                    return;
646                }
647            }
648        }
649    }
650
651    /// 将标签页插入标签页分组。
652    pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
653        let mut controller = cx.global_mut::<SystemWindowTabController>();
654        let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
655            return;
656        };
657
658        let mut expected_tab_ids: Vec<_> = tabs
659            .iter()
660            .filter(|tab| tab.id != id)
661            .map(|tab| tab.id)
662            .sorted()
663            .collect();
664
665        let mut tab_group_id = None;
666        for (group_id, group_tabs) in &controller.tab_groups {
667            let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
668            if tab_ids == expected_tab_ids {
669                tab_group_id = Some(*group_id);
670                break;
671            }
672        }
673
674        if let Some(tab_group_id) = tab_group_id {
675            if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
676                tabs.push(tab);
677            }
678        } else {
679            let new_group_id = controller.tab_groups.len();
680            controller.tab_groups.insert(new_group_id, tabs);
681        }
682    }
683
684    /// 从标签页分组中移除标签页。
685    pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
686        let mut controller = cx.global_mut::<SystemWindowTabController>();
687        let mut removed_tab = None;
688
689        controller.tab_groups.retain(|_, tabs| {
690            if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
691                removed_tab = Some(tabs.remove(pos));
692            }
693            !tabs.is_empty()
694        });
695
696        removed_tab
697    }
698
699    /// 将标签页移动到新的标签页分组。
700    pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
701        let mut removed_tab = Self::remove_tab(cx, id);
702        let mut controller = cx.global_mut::<SystemWindowTabController>();
703
704        if let Some(tab) = removed_tab {
705            let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
706            controller.tab_groups.insert(new_group_id, vec![tab]);
707        }
708    }
709
710    /// 将所有标签页分组合并为一个分组。
711    pub fn merge_all_windows(cx: &mut App, id: WindowId) {
712        let mut controller = cx.global_mut::<SystemWindowTabController>();
713        let Some(initial_tabs) = controller.tabs(id) else {
714            return;
715        };
716
717        let initial_tabs_len = initial_tabs.len();
718        let mut all_tabs = initial_tabs.clone();
719
720        for (_, mut tabs) in controller.tab_groups.drain() {
721            tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
722            all_tabs.extend(tabs);
723        }
724
725        controller.tab_groups.insert(0, all_tabs);
726    }
727
728    /// 在标签页分组中向后方向选择下一个标签页。
729    pub fn select_next_tab(cx: &mut App, id: WindowId) {
730        let mut controller = cx.global_mut::<SystemWindowTabController>();
731        let Some(tabs) = controller.tabs(id) else {
732            return;
733        };
734
735        let current_index = invariant(
736            tabs.iter().position(|tab| tab.id == id),
737            "tab id must exist in the tab list",
738        );
739        let next_index = (current_index + 1) % tabs.len();
740
741        let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
742            window.activate_window();
743        });
744    }
745
746    /// 在标签页分组中向前方向选择上一个标签页。
747    pub fn select_previous_tab(cx: &mut App, id: WindowId) {
748        let mut controller = cx.global_mut::<SystemWindowTabController>();
749        let Some(tabs) = controller.tabs(id) else {
750            return;
751        };
752
753        let current_index = invariant(
754            tabs.iter().position(|tab| tab.id == id),
755            "tab id must exist in the tab list",
756        );
757        let previous_index = if current_index == 0 {
758            tabs.len() - 1
759        } else {
760            current_index - 1
761        };
762
763        let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
764            window.activate_window();
765        });
766    }
767}
768
769pub(crate) enum GpuiMode {
770    #[cfg(any(test, feature = "test-support"))]
771    Test {
772        skip_drawing: bool,
773    },
774    Production,
775}
776
777impl GpuiMode {
778    #[cfg(any(test, feature = "test-support"))]
779    pub fn test() -> Self {
780        GpuiMode::Test {
781            skip_drawing: false,
782        }
783    }
784
785    #[inline]
786    pub(crate) fn skip_drawing(&self) -> bool {
787        match self {
788            #[cfg(any(test, feature = "test-support"))]
789            GpuiMode::Test { skip_drawing } => *skip_drawing,
790            GpuiMode::Production => false,
791        }
792    }
793}
794
795/// 包含整个应用的状态,作为引用传递给各种回调。
796/// 其他 [Context] 通过解引用转换为此类型。
797/// 需要 `App` 的引用来访问 [Entity] 的状态。
798pub struct App {
799    pub(crate) this: Weak<AppCell>,
800    pub(crate) platform: Rc<dyn Platform>,
801    text_system: Arc<TextSystem>,
802
803    pub(crate) actions: Rc<ActionRegistry>,
804    pub(crate) active_drag: Option<AnyDrag>,
805    pub(crate) background_executor: BackgroundExecutor,
806    pub(crate) foreground_executor: ForegroundExecutor,
807    pub(crate) entities: EntityMap,
808    pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
809    pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
810    pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
811    pub(crate) focus_handles: Arc<FocusMap>,
812    pub(crate) keymap: Rc<RefCell<Keymap>>,
813    pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
814    pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
815    pub(crate) global_action_listeners:
816        TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
817    pending_effects: VecDeque<Effect>,
818
819    pub(crate) observers: SubscriberSet<EntityId, Handler>,
820    pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
821    pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
822    pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
823    pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
824    pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
825    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
826    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
827    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
828    pub(crate) restart_observers: SubscriberSet<(), Handler>,
829    pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
830
831    /// 每个 App 的元素 arena。在不同 App 实例间隔离元素分配
832    /// (对多个 App 并发运行的测试很重要)。
833    ///
834    /// 单独放在 `Rc` 分配里:绘制期间通过线程局部的裸指针
835    /// (`CURRENT_ELEMENT_ARENA`)访问它,而那时 `&mut App` 仍然存活。
836    /// 若内联在 `App` 结构体内,这些访问会与 `&mut App` 独占的内存别名,
837    /// 属于未定义行为。
838    pub(crate) element_arena: Rc<RefCell<Arena>>,
839    /// 每个 App 的事件 arena。
840    pub(crate) event_arena: Arena,
841
842    // Drop globals last. We need to ensure all tasks owned by entities and
843    // callbacks are marked cancelled at this point as this will also shutdown
844    // the tokio runtime. As any task attempting to spawn a blocking tokio task,
845    // might panic.
846    pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
847    /// 全局版本号(Retained 依赖追踪 P1):任何写路径递增,读路径按当前记录器打戳。
848    pub(crate) global_generations: TypeIdHashMap<crate::fast::dependencies::Generation>,
849    /// 当前全局依赖记录器栈(`&self` 读路径打戳用 interior mutability;平时为空)。
850    /// 与实体记录器同步压栈/弹栈,嵌套视图各自独立记录。
851    pub(crate) global_recorders: RefCell<Vec<crate::fast::dependencies::DependencyRecorder>>,
852    // assets
853    pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
854    asset_source: Arc<dyn AssetSource>,
855    pub(crate) svg_renderer: SvgRenderer,
856    http_client: Arc<dyn HttpClient>,
857
858    // below is plain data, the drop order is insignificant here
859    pub(crate) pending_notifications: FxHashSet<EntityId>,
860    pub(crate) pending_global_notifications: TypeIdHashSet,
861    /// 按 key 隔离的防抖器注册表(`App::debounce` 方法版)。
862    pub(crate) debouncers: FxHashMap<SharedString, Debouncer>,
863    /// 应用上报的错误环(`App::report_error` 写入,检查器“报错”卡片与崩溃快照读取;
864    /// 有界 50 条,Chrome Console 的应用内对应物)。
865    pub(crate) recent_errors: std::collections::VecDeque<(u64, SharedString)>,
866    /// 错误环序号(单调递增,关闭不回收)。
867    pub(crate) error_seq: u64,
868    /// 崩溃快照落盘目录(`App::enable_crash_recorder` 设置;`None` 关闭滚动记录)。
869    pub(crate) crash_recorder_dir: Option<std::path::PathBuf>,
870    pub(crate) restart_path: Option<PathBuf>,
871    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
872    pub(crate) propagate_event: bool,
873    pub(crate) prompt_builder: Option<PromptBuilder>,
874    pub(crate) window_invalidators_by_entity:
875        FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
876    pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
877    pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
878    #[cfg(any(feature = "inspector", debug_assertions))]
879    pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
880    #[cfg(any(feature = "inspector", debug_assertions))]
881    pub(crate) inspector_element_registry: InspectorElementRegistry,
882    #[cfg(any(test, feature = "test-support", debug_assertions))]
883    pub(crate) name: Option<&'static str>,
884    pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
885
886    pub(crate) window_update_stack: Vec<WindowId>,
887    pub(crate) mode: GpuiMode,
888    pub(crate) cursor_hide_mode: CursorHideMode,
889    pub(crate) reduce_motion: bool,
890    /// 应用是否已通过 [`App::set_reduce_motion`] 显式指定过减少动态效果。
891    /// 置位后不再被平台(系统无障碍设置)的值改写。
892    pub(crate) reduce_motion_override: bool,
893    /// 共享时钟的原点,用于相位锁定同步的重复动画。
894    pub(crate) synced_animation_epoch: Instant,
895    /// 应用是否由 [`Application::new_inaccessible`] 创建。
896    /// 设置此标志时不会调用任何 accesskit API。
897    pub(crate) accessibility_force_disabled: bool,
898    flushing_effects: bool,
899    pending_updates: usize,
900    quit_mode: QuitMode,
901    /// 没有窗口时是否保持运行,由 [`App::set_keep_alive_without_windows`] 设置。
902    ///
903    /// 判据必须在核心层读得到:窗口全部关闭后的自动退出发生在 `App` 里,
904    /// 只把这个意图交给平台(平台侧存了却没人读)等于没生效。
905    keep_alive_without_windows: Cell<bool>,
906    quitting: bool,
907
908    // We need to ensure the leak detector drops last, after all tasks, callbacks and things have been dropped.
909    // Otherwise it may report false positives.
910    #[cfg(any(test, feature = "leak-detection"))]
911    _ref_counts: Arc<RwLock<EntityRefCounts>>,
912}
913
914impl App {
915    #[allow(clippy::new_ret_no_self)]
916    pub(crate) fn new_app(
917        platform: Rc<dyn Platform>,
918        asset_source: Arc<dyn AssetSource>,
919        http_client: Arc<dyn HttpClient>,
920    ) -> Rc<AppCell> {
921        let background_executor = platform.background_executor();
922        let foreground_executor = platform.foreground_executor();
923        assert!(
924            background_executor.is_main_thread(),
925            "must construct App on main thread"
926        );
927
928        let text_system = Arc::new(TextSystem::new(platform.text_system()));
929        let entities = EntityMap::new();
930        let keyboard_layout = platform.keyboard_layout();
931        let keyboard_mapper = platform.keyboard_mapper();
932        let synced_animation_epoch = background_executor.now();
933
934        #[cfg(any(test, feature = "leak-detection"))]
935        let _ref_counts = entities.ref_counts_drop_handle();
936
937        let app = Rc::new_cyclic(|this| AppCell {
938            app: RefCell::new(App {
939                this: this.clone(),
940                platform: platform.clone(),
941                text_system,
942                text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
943                mode: GpuiMode::Production,
944                actions: Rc::new(ActionRegistry::default()),
945                flushing_effects: false,
946                pending_updates: 0,
947                active_drag: None,
948                background_executor,
949                foreground_executor,
950                svg_renderer: SvgRenderer::new(asset_source.clone()),
951                loading_assets: Default::default(),
952                asset_source,
953                http_client,
954                globals_by_type: Default::default(),
955                global_generations: Default::default(),
956                global_recorders: RefCell::new(Vec::new()),
957                entities,
958                new_entity_observers: SubscriberSet::new(),
959                windows: SlotMap::with_key(),
960                window_update_stack: Vec::new(),
961                window_handles: FxHashMap::default(),
962                focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
963                keymap: Rc::new(RefCell::new(Keymap::default())),
964                keyboard_layout,
965                keyboard_mapper,
966                global_action_listeners: Default::default(),
967                pending_effects: VecDeque::new(),
968                pending_notifications: FxHashSet::default(),
969                pending_global_notifications: Default::default(),
970                debouncers: FxHashMap::default(),
971                recent_errors: Default::default(),
972                error_seq: 0,
973                crash_recorder_dir: None,
974                observers: SubscriberSet::new(),
975                tracked_entities: FxHashMap::default(),
976                window_invalidators_by_entity: FxHashMap::default(),
977                current_window_by_entity: FxHashMap::default(),
978                event_listeners: SubscriberSet::new(),
979                release_listeners: SubscriberSet::new(),
980                keystroke_observers: SubscriberSet::new(),
981                keystroke_interceptors: SubscriberSet::new(),
982                keyboard_layout_observers: SubscriberSet::new(),
983                thermal_state_observers: SubscriberSet::new(),
984                global_observers: SubscriberSet::new(),
985                quit_observers: SubscriberSet::new(),
986                restart_observers: SubscriberSet::new(),
987                restart_path: None,
988                window_closed_observers: SubscriberSet::new(),
989                layout_id_buffer: Default::default(),
990                propagate_event: true,
991                prompt_builder: Some(PromptBuilder::Default),
992                #[cfg(any(feature = "inspector", debug_assertions))]
993                inspector_renderer: None,
994                #[cfg(any(feature = "inspector", debug_assertions))]
995                inspector_element_registry: InspectorElementRegistry::default(),
996                quit_mode: QuitMode::default(),
997                keep_alive_without_windows: Cell::new(false),
998                quitting: false,
999                cursor_hide_mode: CursorHideMode::default(),
1000                reduce_motion: false,
1001                reduce_motion_override: false,
1002                synced_animation_epoch,
1003                accessibility_force_disabled: false,
1004
1005                #[cfg(any(test, feature = "test-support", debug_assertions))]
1006                name: None,
1007                element_arena: Rc::new(RefCell::new(Arena::new(1024 * 1024))),
1008                event_arena: Arena::new(1024 * 1024),
1009
1010                #[cfg(any(test, feature = "leak-detection"))]
1011                _ref_counts,
1012            }),
1013            borrow_origin: Cell::new(None),
1014        });
1015
1016        init_app_menus(platform.as_ref(), &app.borrow());
1017        SystemWindowTabController::init(&mut app.borrow_mut());
1018
1019        platform.on_keyboard_layout_change(Box::new({
1020            let app = Rc::downgrade(&app);
1021            move || {
1022                if let Some(app) = app.upgrade() {
1023                    let cx = &mut app.borrow_mut();
1024                    cx.keyboard_layout = cx.platform.keyboard_layout();
1025                    cx.keyboard_mapper = cx.platform.keyboard_mapper();
1026                    cx.keyboard_layout_observers
1027                        .clone()
1028                        .retain(&(), move |callback| (callback)(cx));
1029                }
1030            }
1031        }));
1032
1033        platform.on_thermal_state_change(Box::new({
1034            let app = Rc::downgrade(&app);
1035            move || {
1036                if let Some(app) = app.upgrade() {
1037                    let cx = &mut app.borrow_mut();
1038                    cx.thermal_state_observers
1039                        .clone()
1040                        .retain(&(), move |callback| (callback)(cx));
1041                }
1042            }
1043        }));
1044
1045        platform.on_quit(Box::new({
1046            let cx = Rc::downgrade(&app);
1047            move || {
1048                if let Some(cx) = cx.upgrade() {
1049                    cx.borrow_mut().shutdown();
1050                }
1051            }
1052        }));
1053
1054        app
1055    }
1056
1057    #[doc(hidden)]
1058    pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
1059        self.entities.ref_counts_drop_handle()
1060    }
1061
1062    /// 捕获当前所有拥有存活句柄的实体的快照。
1063    ///
1064    /// 返回的 [`LeakDetectorSnapshot`] 稍后可传递给
1065    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) 以验证快照之后
1066    /// 创建的实体是否仍然存活。
1067    #[cfg(any(test, feature = "leak-detection"))]
1068    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
1069        self.entities.leak_detector_snapshot()
1070    }
1071
1072    /// 断言在 `snapshot` 之后创建的实体没有仍然存活的句柄。
1073    ///
1074    /// 快照时已被跟踪的实体会被忽略,即使它们仍有句柄。
1075    /// 只有 *新* 实体(其 `EntityId` 不在快照中)才被视为泄漏。
1076    ///
1077    /// # panic
1078    ///
1079    /// 如果存在新的实体句柄则 panic。panic 消息会列出每个
1080    /// 泄漏实体的类型名称,当设置了 `LEAK_BACKTRACE` 时
1081    /// 还会包含分配位置的回溯信息。
1082    #[cfg(any(test, feature = "leak-detection"))]
1083    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1084        self.entities.assert_no_new_leaks(snapshot)
1085    }
1086
1087    /// 优雅地退出应用。通过 [`Context::on_app_quit`] 注册的处理器将获得
1088    /// `SHUTDOWN_TIMEOUT` 的时间来完成,然后才会退出。
1089    pub fn shutdown(&mut self) {
1090        let mut futures = Vec::new();
1091
1092        for observer in self.quit_observers.remove(&()) {
1093            futures.push(observer(self));
1094        }
1095
1096        self.windows.clear();
1097        self.window_handles.clear();
1098        self.flush_effects();
1099        self.quitting = true;
1100
1101        let futures = futures::future::join_all(futures);
1102        if self
1103            .foreground_executor
1104            .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
1105            .is_err()
1106        {
1107            log::error!("timed out waiting on app_will_quit");
1108        }
1109
1110        self.quitting = false;
1111    }
1112
1113    /// 获取当前键盘布局的 ID。
1114    pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
1115        self.keyboard_layout.as_ref()
1116    }
1117
1118    /// 获取当前键盘映射器。
1119    pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
1120        &self.keyboard_mapper
1121    }
1122
1123    /// 当当前键盘布局发生变化时调用处理器
1124    pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
1125    where
1126        F: 'static + FnMut(&mut App),
1127    {
1128        let (subscription, activate) = self.keyboard_layout_observers.insert(
1129            (),
1130            Box::new(move |cx| {
1131                callback(cx);
1132                true
1133            }),
1134        );
1135        activate();
1136        subscription
1137    }
1138
1139    /// 通过平台的标准例程优雅退出应用。
1140    pub fn quit(&self) {
1141        self.platform.quit();
1142    }
1143
1144    /// 返回当前响应键盘输入时隐藏光标的策略。
1145    pub fn cursor_hide_mode(&self) -> CursorHideMode {
1146        self.cursor_hide_mode
1147    }
1148
1149    /// 设置 RGPUI 在响应键盘输入时隐藏光标的策略。
1150    pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
1151        self.cursor_hide_mode = mode;
1152    }
1153
1154    /// 根据平台判断光标当前是否可见。当键盘输入隐藏了光标且
1155    /// 用户尚未移动鼠标恢复时,此方法返回 `false`。
1156    ///
1157    /// 参见 [`App::set_cursor_hide_mode`]。
1158    pub fn is_cursor_visible(&self) -> bool {
1159        self.platform.is_cursor_visible()
1160    }
1161
1162    /// 返回非必要动画(如加载旋转器)是否应以静态状态渲染而非动画播放。
1163    pub fn reduce_motion(&self) -> bool {
1164        self.reduce_motion
1165    }
1166
1167    /// 设置非必要动画(如加载旋转器)是否应以静态状态渲染而非动画播放。
1168    ///
1169    /// 一旦调用过,本值即视为应用的显式决定,后续创建窗口不会再被系统
1170    /// 「减少动态效果」设置改写;若想让应用跟随系统,改用
1171    /// [`App::reduce_motion`] 读取即可,平台值会在每次创建窗口时同步进来。
1172    /// Linux 上系统在运行时切换「减少动态效果」不会热更新到已开窗口,需重启应用。
1173    pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
1174        self.reduce_motion_override = true;
1175        if self.reduce_motion != reduce_motion {
1176            self.reduce_motion = reduce_motion;
1177            self.refresh_windows();
1178        }
1179    }
1180
1181    /// 从平台读取系统「减少动态效果」设置并同步进来。
1182    ///
1183    /// 应用已显式指定过(见 [`App::set_reduce_motion`])时不做任何事。
1184    /// 由窗口创建流程调用,这是平台值进入核心层的唯一路径。
1185    fn sync_reduce_motion_from_platform(&mut self) {
1186        if self.reduce_motion_override {
1187            return;
1188        }
1189        let reduce_motion = self.platform.reduce_motion_enabled();
1190        if self.reduce_motion != reduce_motion {
1191            self.reduce_motion = reduce_motion;
1192            self.refresh_windows();
1193        }
1194    }
1195
1196    /// 调度应用中所有窗口重绘。可在更新周期内多次调用,
1197    /// 仍只会产生一次重绘。
1198    pub fn refresh_windows(&mut self) {
1199        self.pending_effects.push_back(Effect::RefreshWindows);
1200    }
1201
1202    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
1203        self.start_update();
1204        let result = update(self);
1205        self.finish_update();
1206        result
1207    }
1208
1209    pub(crate) fn start_update(&mut self) {
1210        self.pending_updates += 1;
1211    }
1212
1213    pub(crate) fn finish_update(&mut self) {
1214        if !self.flushing_effects && self.pending_updates == 1 {
1215            self.flushing_effects = true;
1216            self.flush_effects();
1217            self.flushing_effects = false;
1218        }
1219        self.pending_updates -= 1;
1220    }
1221
1222    /// 安排一个回调,当给定实体在其对应上下文中调用 `notify` 时被调用。
1223    pub fn observe<W>(
1224        &mut self,
1225        entity: &Entity<W>,
1226        mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
1227    ) -> Subscription
1228    where
1229        W: 'static,
1230    {
1231        self.observe_internal(entity, move |e, cx| {
1232            on_notify(e, cx);
1233            true
1234        })
1235    }
1236
1237    pub(crate) fn detect_accessed_entities<R>(
1238        &mut self,
1239        callback: impl FnOnce(&mut App) -> R,
1240    ) -> (R, FxHashSet<EntityId>) {
1241        let accessed_entities_start = self.entities.accessed_entities.get_mut().clone();
1242        let result = callback(self);
1243        let entities_accessed_in_callback = self
1244            .entities
1245            .accessed_entities
1246            .get_mut()
1247            .difference(&accessed_entities_start)
1248            .copied()
1249            .collect::<FxHashSet<EntityId>>();
1250        (result, entities_accessed_in_callback)
1251    }
1252
1253    pub(crate) fn record_entities_accessed(
1254        &mut self,
1255        window_handle: AnyWindowHandle,
1256        invalidator: WindowInvalidator,
1257        entities: &FxHashSet<EntityId>,
1258    ) {
1259        let mut tracked_entities =
1260            std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
1261        for entity in tracked_entities.iter() {
1262            self.window_invalidators_by_entity
1263                .entry(*entity)
1264                .and_modify(|windows| {
1265                    windows.remove(&window_handle.id);
1266                });
1267        }
1268        for entity in entities.iter() {
1269            self.window_invalidators_by_entity
1270                .entry(*entity)
1271                .or_default()
1272                .insert(window_handle.id, invalidator.clone());
1273            self.current_window_by_entity
1274                .insert(*entity, window_handle.id);
1275        }
1276        tracked_entities.clear();
1277        tracked_entities.extend(entities.iter().copied());
1278        self.tracked_entities
1279            .insert(window_handle.id, tracked_entities);
1280    }
1281
1282    pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
1283        let (subscription, activate) = self.observers.insert(key, value);
1284        self.defer(move |_| activate());
1285        subscription
1286    }
1287
1288    pub(crate) fn observe_internal<W>(
1289        &mut self,
1290        entity: &Entity<W>,
1291        mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
1292    ) -> Subscription
1293    where
1294        W: 'static,
1295    {
1296        let entity_id = entity.entity_id();
1297        let handle = entity.downgrade();
1298        self.new_observer(
1299            entity_id,
1300            Box::new(move |cx| {
1301                if let Some(entity) = handle.upgrade() {
1302                    on_notify(entity, cx)
1303                } else {
1304                    false
1305                }
1306            }),
1307        )
1308    }
1309
1310    /// 安排一个回调,当给定实体发出给定类型的事件时被调用。
1311    /// 回调会收到发出实体的句柄和发出事件的引用。
1312    pub fn subscribe<T, Event>(
1313        &mut self,
1314        entity: &Entity<T>,
1315        mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
1316    ) -> Subscription
1317    where
1318        T: 'static + EventEmitter<Event>,
1319        Event: 'static,
1320    {
1321        self.subscribe_internal(entity, move |entity, event, cx| {
1322            on_event(entity, event, cx);
1323            true
1324        })
1325    }
1326
1327    pub(crate) fn new_subscription(
1328        &mut self,
1329        key: EntityId,
1330        value: (TypeId, Listener),
1331    ) -> Subscription {
1332        let (subscription, activate) = self.event_listeners.insert(key, value);
1333        self.defer(move |_| activate());
1334        subscription
1335    }
1336    pub(crate) fn subscribe_internal<T, Evt>(
1337        &mut self,
1338        entity: &Entity<T>,
1339        mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
1340    ) -> Subscription
1341    where
1342        T: 'static + EventEmitter<Evt>,
1343        Evt: 'static,
1344    {
1345        let entity_id = entity.entity_id();
1346        let handle = entity.downgrade();
1347        self.new_subscription(
1348            entity_id,
1349            (
1350                TypeId::of::<Evt>(),
1351                Box::new(move |event, cx| {
1352                    let event: &Evt = invariant(event.downcast_ref(), "invalid event type");
1353                    if let Some(entity) = handle.upgrade() {
1354                        on_event(entity, event, cx)
1355                    } else {
1356                        false
1357                    }
1358                }),
1359            ),
1360        )
1361    }
1362
1363    /// 返回应用中所有打开窗口的句柄。
1364    /// 每个句柄可以向下转型为该窗口根视图的类型化句柄。
1365    /// 要查找给定类型的所有窗口,可以使用 filter。
1366    pub fn windows(&self) -> Vec<AnyWindowHandle> {
1367        self.windows
1368            .keys()
1369            .flat_map(|window_id| self.window_handles.get(&window_id).copied())
1370            .collect()
1371    }
1372
1373    /// 返回按屏幕上出现顺序排列的窗口句柄,从前到后。
1374    ///
1375    /// 返回列表中的第一个窗口是应用的活动/最顶层窗口。
1376    ///
1377    /// 如果平台尚未实现此方法,返回 None。
1378    pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1379        self.platform.window_stack()
1380    }
1381
1382    /// 返回当前在平台级别获得焦点的窗口的句柄(如果存在)。
1383    pub fn active_window(&self) -> Option<AnyWindowHandle> {
1384        self.platform.active_window()
1385    }
1386
1387    /// 使用给定选项和给定函数返回的根视图打开一个新窗口。
1388    /// 该函数使用 `Window` 调用,可用于与窗口特定功能交互。
1389    pub fn open_window<V: 'static + Render>(
1390        &mut self,
1391        options: crate::WindowOptions,
1392        build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
1393    ) -> anyhow::Result<WindowHandle<V>> {
1394        self.update(|cx| {
1395            let id = cx.windows.insert(None);
1396            let handle = WindowHandle::new(id);
1397            match Window::new(handle.into(), options, cx) {
1398                Ok(mut window) => {
1399                    // 确保存在全局主题:Root 渲染需要主题;若未显式初始化则使用默认主题。
1400                    if !cx.has_global::<crate::theme::Theme>() {
1401                        cx.set_global(crate::theme::Theme::default());
1402                    }
1403                    cx.window_update_stack.push(id);
1404                    let root_view: AnyView = build_root_view(&mut window, cx).into();
1405                    cx.window_update_stack.pop();
1406                    // 自动将用户视图包装进 Root,以提供 tooltip/dialog 等全局覆盖层支持。
1407                    // 若用户已显式传入 Root(例如对话框测试),则不重复包装。
1408                    let root_view = if root_view.clone().downcast::<Root>().is_ok() {
1409                        root_view
1410                    } else {
1411                        cx.new(|cx| Root::new(root_view, cx)).into()
1412                    };
1413                    window.root.replace(root_view);
1414                    // 系统「减少动态效果」设置的写入点:装饰性动画元素在绘制期读
1415                    // `App::reduce_motion`,此前无人赋值,故在每次创建窗口时同步一次平台值。
1416                    cx.sync_reduce_motion_from_platform();
1417                    window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
1418
1419                    // allow a window to draw at least once before returning
1420                    // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
1421                    // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
1422                    // where DispatchTree::root_node_id asserts on empty nodes
1423                    let clear = window.draw(cx);
1424                    clear.clear(cx);
1425
1426                    cx.window_handles.insert(id, window.handle);
1427                    invariant(cx.windows.get_mut(id), "window id must be registered")
1428                        .replace(Box::new(window));
1429                    Ok(handle)
1430                }
1431                Err(e) => {
1432                    cx.windows.remove(id);
1433                    Err(e)
1434                }
1435            }
1436        })
1437    }
1438
1439    /// 指示平台通过将应用带到前台来激活应用。
1440    pub fn activate(&self, ignoring_other_apps: bool) {
1441        self.platform.activate(ignoring_other_apps);
1442    }
1443
1444    /// 在平台级别隐藏应用。
1445    pub fn hide(&self) {
1446        self.platform.hide();
1447    }
1448
1449    /// 在平台级别隐藏其他应用。
1450    pub fn hide_other_apps(&self) {
1451        self.platform.hide_other_apps();
1452    }
1453
1454    /// 在平台级别取消隐藏其他应用。
1455    pub fn unhide_other_apps(&self) {
1456        self.platform.unhide_other_apps();
1457    }
1458
1459    /// 返回当前活动显示器的列表。
1460    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1461        self.platform.displays()
1462    }
1463
1464    /// 返回将用于新窗口的主显示器。
1465    pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1466        self.platform.primary_display()
1467    }
1468
1469    /// 返回 `screen_capture_sources` 是否可能工作。
1470    pub fn is_screen_capture_supported(&self) -> bool {
1471        self.platform.is_screen_capture_supported()
1472    }
1473
1474    /// 返回可用屏幕捕获源的列表。
1475    pub fn screen_capture_sources(
1476        &self,
1477    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
1478        self.platform.screen_capture_sources()
1479    }
1480
1481    /// 返回具有给定 ID 的显示器(如果存在)。
1482    pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1483        self.displays()
1484            .iter()
1485            .find(|display| display.id() == id)
1486            .cloned()
1487    }
1488
1489    /// 返回系统当前的热状态。
1490    pub fn thermal_state(&self) -> ThermalState {
1491        self.platform.thermal_state()
1492    }
1493
1494    /// 当热状态发生变化时调用处理器
1495    pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
1496    where
1497        F: 'static + FnMut(&mut App),
1498    {
1499        let (subscription, activate) = self.thermal_state_observers.insert(
1500            (),
1501            Box::new(move |cx| {
1502                callback(cx);
1503                true
1504            }),
1505        );
1506        activate();
1507        subscription
1508    }
1509
1510    /// 返回应用窗口的外观。
1511    pub fn window_appearance(&self) -> WindowAppearance {
1512        self.platform.window_appearance()
1513    }
1514
1515    /// 返回受支持时的窗口按钮布局配置。
1516    pub fn button_layout(&self) -> Option<WindowButtonLayout> {
1517        self.platform.button_layout()
1518    }
1519
1520    /// 从平台剪贴板读取数据。
1521    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1522        self.platform.read_from_clipboard()
1523    }
1524
1525    /// 设置应用的文本渲染模式。
1526    pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
1527        self.text_rendering_mode.set(mode);
1528    }
1529
1530    /// 返回应用当前的文本渲染模式。
1531    pub fn text_rendering_mode(&self) -> TextRenderingMode {
1532        self.text_rendering_mode.get()
1533    }
1534
1535    /// 向平台剪贴板写入数据。
1536    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1537        self.platform.write_to_clipboard(item)
1538    }
1539
1540    /// 从主选择缓冲区读取数据。
1541    /// 仅在 Linux 上可用。
1542    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1543    pub fn read_from_primary(&self) -> Option<ClipboardItem> {
1544        self.platform.read_from_primary()
1545    }
1546
1547    /// 向主选择缓冲区写入数据。
1548    /// 仅在 Linux 上可用。
1549    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1550    pub fn write_to_primary(&self, item: ClipboardItem) {
1551        self.platform.write_to_primary(item)
1552    }
1553
1554    /// 从 macOS 的"查找"粘贴板读取数据。
1555    ///
1556    /// 用于在应用之间共享当前搜索字符串。
1557    ///
1558    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1559    #[cfg(target_os = "macos")]
1560    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1561        self.platform.read_from_find_pasteboard()
1562    }
1563
1564    /// 向 macOS 的"查找"粘贴板写入数据。
1565    ///
1566    /// 用于在应用之间共享当前搜索字符串。
1567    ///
1568    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
1569    #[cfg(target_os = "macos")]
1570    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1571        self.platform.write_to_find_pasteboard(item)
1572    }
1573
1574    /// 向平台密钥链写入凭据。
1575    pub fn write_credentials(
1576        &self,
1577        url: &str,
1578        username: &str,
1579        password: &[u8],
1580    ) -> Task<Result<()>> {
1581        self.platform.write_credentials(url, username, password)
1582    }
1583
1584    /// 从平台密钥链读取凭据。
1585    pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1586        self.platform.read_credentials(url)
1587    }
1588
1589    /// 从平台密钥链删除凭据。
1590    pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1591        self.platform.delete_credentials(url)
1592    }
1593
1594    /// 指示平台默认浏览器打开给定的 URL。
1595    pub fn open_url(&self, url: &str) {
1596        self.platform.open_url(url);
1597    }
1598
1599    /// 注册给定的 URL scheme(例如 `rgpui` 用于 `rgpui://` URL)以由当前应用打开。
1600    ///
1601    /// 在某些平台(例如 macOS)上,你可以在应用分发时注册 URL scheme,
1602    /// 但此方法允许你在运行时注册 scheme。
1603    pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
1604        self.platform.register_url_scheme(scheme)
1605    }
1606
1607    /// 返回当前应用 bundle 的完整路径名。
1608    ///
1609    /// 如果应用不是从 bundle 运行的,则返回错误。
1610    pub fn app_path(&self) -> Result<PathBuf> {
1611        self.platform.app_path()
1612    }
1613
1614    /// 在 Linux 上,返回正在使用的合成器名称。
1615    ///
1616    /// 在其他平台上返回空字符串。
1617    pub fn compositor_name(&self) -> &'static str {
1618        self.platform.compositor_name()
1619    }
1620
1621    /// 返回应用 bundle 中指定名称的可执行文件的文件 URL
1622    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
1623        self.platform.path_for_auxiliary_executable(name)
1624    }
1625
1626    /// 显示用于选择路径的平台模态框。
1627    ///
1628    /// 当选择一个或多个路径时,它们将通过返回的 oneshot 通道异步中继。
1629    /// 如果取消,则中继 `None`。
1630    /// 在 Linux 上,如果无法打开文件选择器,可能返回错误。
1631    pub fn prompt_for_paths(
1632        &self,
1633        options: PathPromptOptions,
1634    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
1635        self.platform.prompt_for_paths(options)
1636    }
1637
1638    /// 显示用于选择新路径的平台模态框,文件可以保存到该路径。
1639    ///
1640    /// 提供的目录将用于设置初始位置。
1641    /// 当选择路径时,它将通过返回的 oneshot 通道异步中继。
1642    /// 如果取消,则中继 `None`。
1643    /// 在 Linux 上,如果无法打开文件选择器,可能返回错误。
1644    pub fn prompt_for_new_path(
1645        &self,
1646        directory: &Path,
1647        suggested_name: Option<&str>,
1648    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
1649        self.platform.prompt_for_new_path(directory, suggested_name)
1650    }
1651
1652    /// 防抖执行一次回调:同一 `key` 连续调用只执行最后一次。
1653    ///
1654    /// `Context` 经 Deref 到 `App`,可直接 `cx.debounce("search", duration, callback)`。
1655    /// 不同 key 相互隔离(如搜索框与自动保存各用各的 key)。
1656    /// 回调在后台任务中运行,不得捕获非 `Send` 数据;写回 UI 请经 channel/Atomic
1657    /// 或 `cx.update_entity`。需要独立生命周期的防抖器请直接持有 [`Debouncer`] 结构。
1658    pub fn debounce(
1659        &mut self,
1660        key: impl Into<SharedString>,
1661        duration: Duration,
1662        callback: impl FnOnce() + Send + 'static,
1663    ) {
1664        let executor = self.background_executor.clone();
1665        self.debouncers
1666            .entry(key.into())
1667            .or_default()
1668            .debounce(&executor, duration, callback);
1669    }
1670
1671    /// 在平台级别显示指定路径,例如在 macOS 的 Finder 中。
1672    pub fn reveal_path(&self, path: &Path) {
1673        self.platform.reveal_path(path)
1674    }
1675
1676    /// 使用系统默认应用程序打开指定路径。
1677    pub fn open_with_system(&self, path: &Path) {
1678        self.platform.open_with_system(path)
1679    }
1680
1681    /// 返回用户是否在平台级别配置了滚动条自动隐藏。
1682    pub fn should_auto_hide_scrollbars(&self) -> bool {
1683        self.platform.should_auto_hide_scrollbars()
1684    }
1685
1686    /// 重启应用。
1687    pub fn restart(&mut self) {
1688        self.restart_observers
1689            .clone()
1690            .retain(&(), |observer| observer(self));
1691        self.platform.restart(self.restart_path.take())
1692    }
1693
1694    /// 设置重启应用时使用的路径。
1695    pub fn set_restart_path(&mut self, path: PathBuf) {
1696        self.restart_path = Some(path);
1697    }
1698
1699    /// 返回应用的 HTTP 客户端。
1700    pub fn http_client(&self) -> Arc<dyn HttpClient> {
1701        self.http_client.clone()
1702    }
1703
1704    /// 设置应用的 HTTP 客户端。
1705    pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
1706        self.http_client = new_client;
1707    }
1708
1709    /// 配置应用自动退出的时机。
1710    /// 默认使用 [`QuitMode::Default`]。
1711    pub fn set_quit_mode(&mut self, mode: QuitMode) {
1712        self.quit_mode = mode;
1713    }
1714
1715    /// 返回应用使用的 SVG 渲染器。
1716    pub fn svg_renderer(&self) -> SvgRenderer {
1717        self.svg_renderer.clone()
1718    }
1719
1720    pub(crate) fn push_effect(&mut self, effect: Effect) {
1721        match &effect {
1722            Effect::Notify { emitter } => {
1723                if !self.pending_notifications.insert(*emitter) {
1724                    return;
1725                }
1726            }
1727            Effect::NotifyGlobalObservers { global_type } => {
1728                if !self.pending_global_notifications.insert(*global_type) {
1729                    return;
1730                }
1731            }
1732            _ => {}
1733        };
1734
1735        self.pending_effects.push_back(effect);
1736    }
1737
1738    /// 在 [`App::update`] 结束时调用,以完成所有副作用,
1739    /// 例如通知观察者、发出事件等。副作用本身可以产生副作用,
1740    /// 因此我们持续循环直到所有副作用被处理。
1741    fn flush_effects(&mut self) {
1742        loop {
1743            self.release_dropped_entities();
1744            self.release_dropped_focus_handles();
1745            if let Some(effect) = self.pending_effects.pop_front() {
1746                match effect {
1747                    Effect::Notify { emitter } => {
1748                        self.apply_notify_effect(emitter);
1749                    }
1750
1751                    Effect::Emit {
1752                        emitter,
1753                        event_type,
1754                        event,
1755                    } => self.apply_emit_effect(emitter, event_type, &*event),
1756
1757                    Effect::RefreshWindows => {
1758                        self.apply_refresh_effect();
1759                    }
1760
1761                    Effect::NotifyGlobalObservers { global_type } => {
1762                        self.apply_notify_global_observers_effect(global_type);
1763                    }
1764
1765                    Effect::Defer { callback } => {
1766                        self.apply_defer_effect(callback);
1767                    }
1768                    Effect::EntityCreated {
1769                        entity,
1770                        tid,
1771                        window,
1772                    } => {
1773                        self.apply_entity_created_effect(entity, tid, window);
1774                    }
1775                }
1776            } else {
1777                #[cfg(any(test, feature = "test-support", feature = "bench"))]
1778                for window in self
1779                    .windows
1780                    .values()
1781                    .filter_map(|window| {
1782                        let window = window.as_deref()?;
1783                        window.invalidator.is_dirty().then_some(window.handle)
1784                    })
1785                    .collect::<Vec<_>>()
1786                {
1787                    if let Err(err) =
1788                        self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
1789                    {
1790                        // 窗口已不在栈上(可能已被关闭):跳过重绘,不中断整帧处理。
1791                        log::debug!("[rgpui::app] 重绘窗口失败:{err}");
1792                    }
1793                }
1794
1795                if self.pending_effects.is_empty() {
1796                    self.event_arena.clear();
1797                    break;
1798                }
1799            }
1800        }
1801    }
1802
1803    /// 在 `flush_effects` 期间重复调用,以释放引用计数已变为零的实体。
1804    /// 我们在丢弃每个实体之前调用所有释放观察者。
1805    fn release_dropped_entities(&mut self) {
1806        loop {
1807            let dropped = self.entities.take_dropped();
1808            if dropped.is_empty() {
1809                break;
1810            }
1811
1812            for (entity_id, mut entity) in dropped {
1813                self.observers.remove(&entity_id);
1814                self.event_listeners.remove(&entity_id);
1815                self.window_invalidators_by_entity.remove(&entity_id);
1816                self.current_window_by_entity.remove(&entity_id);
1817                for release_callback in self.release_listeners.remove(&entity_id) {
1818                    release_callback(entity.as_mut(), self);
1819                }
1820            }
1821        }
1822    }
1823
1824    /// 在 `flush_effects` 期间重复调用,以处理被丢弃的焦点句柄。
1825    fn release_dropped_focus_handles(&mut self) {
1826        self.focus_handles
1827            .clone()
1828            .write()
1829            .retain(|handle_id, focus| {
1830                if focus.ref_count.load(SeqCst) == 0 {
1831                    for window_handle in self.windows() {
1832                        if let Err(err) = window_handle.update(self, |_, window, _| {
1833                            if window.focus == Some(handle_id) {
1834                                window.blur();
1835                            }
1836                        }) {
1837                            // 窗口已关闭:无需再取消焦点。
1838                            log::debug!("[rgpui::app] 取消焦点失败:{err}");
1839                        }
1840                    }
1841                    false
1842                } else {
1843                    true
1844                }
1845            });
1846    }
1847
1848    fn apply_notify_effect(&mut self, emitter: EntityId) {
1849        self.pending_notifications.remove(&emitter);
1850
1851        self.observers
1852            .clone()
1853            .retain(&emitter, |handler| handler(self));
1854    }
1855
1856    fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
1857        self.event_listeners
1858            .clone()
1859            .retain(&emitter, |(stored_type, handler)| {
1860                if *stored_type == event_type {
1861                    handler(event, self)
1862                } else {
1863                    true
1864                }
1865            });
1866    }
1867
1868    fn apply_refresh_effect(&mut self) {
1869        for window in self.windows.values_mut() {
1870            if let Some(window) = window.as_deref_mut() {
1871                window.refreshing = true;
1872                window.invalidator.set_dirty(true);
1873            }
1874        }
1875    }
1876
1877    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
1878        self.pending_global_notifications.remove(&type_id);
1879        self.global_observers
1880            .clone()
1881            .retain(&type_id, |observer| observer(self));
1882    }
1883
1884    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
1885        callback(self);
1886    }
1887
1888    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
1889    fn apply_entity_created_effect(
1890        &mut self,
1891        entity: AnyEntity,
1892        tid: TypeId,
1893        window: Option<WindowId>,
1894    ) {
1895        // Seed the entity's current window from its creation context so
1896        // `with_window` resolves correctly before the entity has ever been
1897        // rendered.
1898        if let Some(id) = window {
1899            self.current_window_by_entity.insert(entity.entity_id(), id);
1900        }
1901
1902        self.new_entity_observers.clone().retain(&tid, |observer| {
1903            if let Some(id) = window {
1904                self.update_window_id(id, {
1905                    let entity = entity.clone();
1906                    |_, window, cx| (observer)(entity, &mut Some(window), cx)
1907                })
1908                .unwrap_or_else(|err| {
1909                    panic!("All windows should be off the stack when flushing effects: {err}")
1910                });
1911            } else {
1912                (observer)(entity.clone(), &mut None, self)
1913            }
1914            true
1915        });
1916    }
1917
1918    /// 对实体的*当前*窗口执行 `f`——即最近引用该实体的渲染窗口,
1919    /// 如果尚未渲染则为其创建窗口。如果实体没有当前窗口、
1920    /// 该窗口已关闭或已在更新栈上,则返回 `None`。
1921    pub fn with_window<R>(
1922        &mut self,
1923        entity_id: EntityId,
1924        f: impl FnOnce(&mut Window, &mut App) -> R,
1925    ) -> Option<R> {
1926        let window_id = *self.current_window_by_entity.get(&entity_id)?;
1927        self.update_window_id(window_id, |_, window, cx| f(window, cx))
1928            .ok()
1929    }
1930
1931    fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
1932        self.current_window_by_entity
1933            .entry(entity_id)
1934            .or_insert(window);
1935    }
1936
1937    #[track_caller]
1938    pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
1939    where
1940        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
1941    {
1942        self.update(|cx| {
1943            let mut window = cx.windows.get_mut(id)?.take()?;
1944
1945            let root_view = invariant(window.root.clone(), "window must have a root view");
1946
1947            cx.window_update_stack.push(window.handle.id);
1948            let result = update(root_view, &mut window, cx);
1949            fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
1950                cx.window_update_stack.pop();
1951
1952                if window.removed {
1953                    cx.window_handles.remove(&id);
1954                    cx.windows.remove(id);
1955                    if let Some(tracked) = cx.tracked_entities.remove(&id) {
1956                        for entity_id in tracked {
1957                            if let Some(windows) =
1958                                cx.window_invalidators_by_entity.get_mut(&entity_id)
1959                            {
1960                                windows.remove(&id);
1961                            }
1962                            if cx.current_window_by_entity.get(&entity_id) == Some(&id) {
1963                                cx.current_window_by_entity.remove(&entity_id);
1964                            }
1965                        }
1966                    }
1967
1968                    cx.window_closed_observers.clone().retain(&(), |callback| {
1969                        callback(cx, id);
1970                        true
1971                    });
1972
1973                    // 「没有窗口也要活着」优先于任何自动退出模式,
1974                    // 这是驻留托盘 / 后台服务型应用的典型诉求。
1975                    let quit_on_empty = !cx.keep_alive_without_windows.get()
1976                        && match cx.quit_mode {
1977                            QuitMode::Explicit => false,
1978                            QuitMode::LastWindowClosed => true,
1979                            QuitMode::Default => cfg!(not(target_os = "macos")),
1980                        };
1981
1982                    if quit_on_empty && cx.windows.is_empty() {
1983                        cx.quit();
1984                    }
1985                } else {
1986                    cx.windows.get_mut(id)?.replace(window);
1987                }
1988                Some(())
1989            }
1990            trail(id, window, cx)?;
1991
1992            Some(result)
1993        })
1994        .context("window not found")
1995    }
1996
1997    /// 创建一个 `AsyncApp`,可以克隆且具有静态生命周期,
1998    /// 因此可以跨 `await` 点持有。
1999    pub fn to_async(&self) -> AsyncApp {
2000        AsyncApp {
2001            app: self.this.clone(),
2002            background_executor: self.background_executor.clone(),
2003            foreground_executor: self.foreground_executor.clone(),
2004        }
2005    }
2006
2007    /// 获取执行器的引用,可用于生成 future。
2008    pub fn background_executor(&self) -> &BackgroundExecutor {
2009        &self.background_executor
2010    }
2011
2012    /// 获取执行器的引用,可用于生成 future。
2013    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2014    pub fn foreground_executor(&self) -> &ForegroundExecutor {
2015        if self.quitting {
2016            panic!("Can't spawn on main thread after on_app_quit")
2017        };
2018        &self.foreground_executor
2019    }
2020
2021    /// 在主线程上生成给定函数返回的 future。闭包将使用 [AsyncApp] 调用,
2022    /// 允许跨 await 点访问应用状态。
2023    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2024    #[track_caller]
2025    pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
2026    where
2027        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2028        R: 'static,
2029    {
2030        if self.quitting {
2031            debug_panic!("Can't spawn on main thread after on_app_quit")
2032        };
2033
2034        let mut cx = self.to_async();
2035
2036        self.foreground_executor
2037            .spawn(async move { f(&mut cx).await }.boxed_local())
2038    }
2039
2040    /// 在主线程上以给定优先级生成给定函数返回的 future。
2041    /// 闭包将使用 [AsyncApp] 调用,允许跨 await 点访问应用状态。
2042    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2043    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
2044    where
2045        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
2046        R: 'static,
2047    {
2048        if self.quitting {
2049            debug_panic!("Can't spawn on main thread after on_app_quit")
2050        };
2051
2052        let mut cx = self.to_async();
2053
2054        self.foreground_executor
2055            .spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
2056    }
2057
2058    /// 安排给定函数在当前副作用周期结束时运行,允许当前在栈上的实体
2059    /// 返回到应用。
2060    pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
2061        self.push_effect(Effect::Defer {
2062            callback: Box::new(f),
2063        });
2064    }
2065
2066    /// 应用资源来源的访问器,在构造 `App` 时提供。
2067    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
2068        &self.asset_source
2069    }
2070
2071    /// 文本系统的访问器。
2072    pub fn text_system(&self) -> &Arc<TextSystem> {
2073        &self.text_system
2074    }
2075
2076    /// 检查是否已分配给定类型的全局变量。
2077    pub fn has_global<G: Global>(&self) -> bool {
2078        let present = self.globals_by_type.contains_key(&TypeId::of::<G>());
2079        // Retained 依赖追踪 P1 读 hook:只记录存在性,值写入不影响此记录。
2080        if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2081            recorder.record_global_presence(TypeId::of::<G>(), present);
2082        }
2083        present
2084    }
2085
2086    /// 访问给定类型的全局变量。如果未分配该类型的全局变量则 panic。
2087    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2088    #[track_caller]
2089    pub fn global<G: Global>(&self) -> &G {
2090        // Retained 依赖追踪 P1 读 hook:记录值读取时的版本号。
2091        if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2092            recorder.record_global(TypeId::of::<G>(), self.global_generation_or_initial::<G>());
2093        }
2094        self.globals_by_type
2095            .get(&TypeId::of::<G>())
2096            .map(|any_state| invariant(any_state.downcast_ref::<G>(), "global type must match"))
2097            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2098    }
2099
2100    /// 如果已分配值,则访问给定类型的全局变量。
2101    pub fn try_global<G: Global>(&self) -> Option<&G> {
2102        let global = self
2103            .globals_by_type
2104            .get(&TypeId::of::<G>())
2105            .map(|any_state| invariant(any_state.downcast_ref::<G>(), "global type must match"));
2106        // Retained 依赖追踪 P1 读 hook:有值记版本号,无值记不存在。
2107        if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2108            if global.is_some() {
2109                recorder.record_global(TypeId::of::<G>(), self.global_generation_or_initial::<G>());
2110            } else {
2111                recorder.record_global_presence(TypeId::of::<G>(), false);
2112            }
2113        }
2114        global
2115    }
2116
2117    /// 可变访问给定类型的全局变量。如果未分配该类型的全局变量则 panic。
2118    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2119    #[track_caller]
2120    pub fn global_mut<G: Global>(&mut self) -> &mut G {
2121        let global_type = TypeId::of::<G>();
2122        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2123        self.bump_global_generation(global_type);
2124        self.globals_by_type
2125            .get_mut(&global_type)
2126            .and_then(|any_state| any_state.downcast_mut::<G>())
2127            .unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
2128    }
2129
2130    /// 可变访问给定类型的全局变量。如果尚未分配该类型的全局变量,则分配默认值。
2131    pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
2132        let global_type = TypeId::of::<G>();
2133        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2134        self.bump_global_generation(global_type);
2135        invariant(
2136            self.globals_by_type
2137                .entry(global_type)
2138                .or_insert_with(|| Box::<G>::default())
2139                .downcast_mut::<G>(),
2140            "global type must match",
2141        )
2142    }
2143
2144    /// 设置给定类型全局变量的值。
2145    pub fn set_global<G: Global>(&mut self, global: G) {
2146        let global_type = TypeId::of::<G>();
2147        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2148        self.bump_global_generation(global_type);
2149        self.globals_by_type.insert(global_type, Box::new(global));
2150    }
2151
2152    /// 清除所有存储的全局变量。不通知全局观察者。
2153    #[cfg(any(test, feature = "test-support"))]
2154    pub fn clear_globals(&mut self) {
2155        self.globals_by_type.drain();
2156        // 版本号一并清空:存量快照查不到版本号即按过期处理。
2157        self.global_generations.clear();
2158    }
2159
2160    /// 从应用上下文中移除给定类型的全局变量。不通知全局观察者。
2161    #[allow(clippy::panic)] // 契约违规:调用前提被破坏,必须立刻暴露
2162    pub fn remove_global<G: Global>(&mut self) -> G {
2163        let global_type = TypeId::of::<G>();
2164        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2165        self.bump_global_generation(global_type);
2166        *invariant_result(
2167            self.globals_by_type
2168                .remove(&global_type)
2169                .unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
2170                .downcast(),
2171            "global type must match",
2172        )
2173    }
2174
2175    /// 注册一个回调,当给定类型的全局变量被更新时调用。
2176    pub fn observe_global<G: Global>(
2177        &mut self,
2178        mut f: impl FnMut(&mut Self) + 'static,
2179    ) -> Subscription {
2180        let (subscription, activate) = self.global_observers.insert(
2181            TypeId::of::<G>(),
2182            Box::new(move |cx| {
2183                f(cx);
2184                true
2185            }),
2186        );
2187        self.defer(move |_| activate());
2188        subscription
2189    }
2190
2191    /// 将给定类型的全局变量移动到栈上。
2192    #[track_caller]
2193    pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
2194        GlobalLease::new(invariant_result(
2195            self.globals_by_type
2196                .remove(&TypeId::of::<G>())
2197                .with_context(|| format!("no global registered of type {}", type_name::<G>())),
2198            "global type must match",
2199        ))
2200    }
2201
2202    /// 将全局变量移动到栈后恢复该类型的全局变量。
2203    pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
2204        let global_type = TypeId::of::<G>();
2205
2206        self.push_effect(Effect::NotifyGlobalObservers { global_type });
2207        self.bump_global_generation(global_type);
2208        self.globals_by_type.insert(global_type, lease.global);
2209    }
2210
2211    /// 递增指定全局的版本号(Retained 依赖追踪 P1 写路径 hook)。
2212    fn bump_global_generation(&mut self, global_type: TypeId) {
2213        let bumped = self
2214            .global_generations
2215            .get(&global_type)
2216            .copied()
2217            .unwrap_or_else(crate::fast::dependencies::Generation::initial)
2218            .bumped();
2219        self.global_generations.insert(global_type, bumped);
2220    }
2221
2222    /// 查询全局当前版本号(从未写入返回初始版本;依赖记录打戳用)。
2223    fn global_generation_or_initial<G: Global>(&self) -> crate::fast::dependencies::Generation {
2224        self.global_generation::<G>()
2225            .unwrap_or_else(crate::fast::dependencies::Generation::initial)
2226    }
2227
2228    /// 查询全局当前版本号(从未写入或已移除返回 `None`;快照过期判定用)。
2229    pub(crate) fn global_generation<G: Global>(
2230        &self,
2231    ) -> Option<crate::fast::dependencies::Generation> {
2232        self.global_generations.get(&TypeId::of::<G>()).copied()
2233    }
2234
2235    /// 按类型擦除查询全局版本号(依赖快照过期判定闭包用)。
2236    pub(crate) fn global_generation_by_type(
2237        &self,
2238        global_type: TypeId,
2239    ) -> Option<crate::fast::dependencies::Generation> {
2240        self.global_generations.get(&global_type).copied()
2241    }
2242
2243    /// 查询实体当前版本号(依赖快照过期判定闭包用)。
2244    pub(crate) fn entity_generation(
2245        &self,
2246        id: EntityId,
2247    ) -> Option<crate::fast::dependencies::Generation> {
2248        self.entities.entity_generation(id)
2249    }
2250
2251    /// 开始一次依赖记录(实体 + 全局同步压栈;P2 绘制包装调用)。
2252    pub(crate) fn begin_dependency_recording(&self) {
2253        self.entities.begin_dependency_recording();
2254        self.global_recorders
2255            .borrow_mut()
2256            .push(crate::fast::dependencies::DependencyRecorder::new());
2257    }
2258
2259    /// 结束依赖记录并返回合并快照;栈空时返回空快照。
2260    ///
2261    /// 结束时把子快照并入父记录器:父视图复用判定须包含嵌套视图的读取,
2262    /// 否则后代变化而父复用会吞掉子树更新(P2a 保守重建;splice 优化是 P2b 的事)。
2263    pub(crate) fn end_dependency_recording(&self) -> crate::fast::dependencies::DependencySet {
2264        let mut set = self.entities.end_dependency_recording();
2265        if let Some(recorder) = self.global_recorders.borrow_mut().pop() {
2266            set.merge(recorder.finish());
2267        }
2268        if let Some(parent) = self.global_recorders.borrow_mut().last_mut() {
2269            parent.absorb_shared(&set);
2270        }
2271        self.entities.absorb_entities_into_parent(&set);
2272        set
2273    }
2274
2275    /// 记录一次实体外共享状态读取(滚动句柄、列表状态;打戳到栈顶记录器)。
2276    pub(crate) fn note_state_read(&self, version: &crate::fast::dependencies::StateVersion) {
2277        if let Some(recorder) = self.global_recorders.borrow_mut().last_mut() {
2278            recorder.record_state(version);
2279        }
2280    }
2281
2282    pub(crate) fn new_entity_observer(
2283        &self,
2284        key: TypeId,
2285        value: NewEntityListener,
2286    ) -> Subscription {
2287        let (subscription, activate) = self.new_entity_observers.insert(key, value);
2288        activate();
2289        subscription
2290    }
2291
2292    /// 安排在创建指定类型的视图时调用给定函数。
2293    /// 该函数将接收视图的可变引用和适当的上下文。
2294    pub fn observe_new<T: 'static>(
2295        &self,
2296        on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
2297    ) -> Subscription {
2298        self.new_entity_observer(
2299            TypeId::of::<T>(),
2300            Box::new(
2301                move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
2302                    invariant_result(any_entity.downcast::<T>(), "entity type must match")
2303                        .update(cx, |entity_state, cx| {
2304                            on_new(entity_state, window.as_deref_mut(), cx)
2305                        })
2306                },
2307            ),
2308        )
2309    }
2310
2311    /// 观察实体的释放。回调在实体没有更多强引用后但在丢弃前调用。
2312    pub fn observe_release<T>(
2313        &self,
2314        handle: &Entity<T>,
2315        on_release: impl FnOnce(&mut T, &mut App) + 'static,
2316    ) -> Subscription
2317    where
2318        T: 'static,
2319    {
2320        let (subscription, activate) = self.release_listeners.insert(
2321            handle.entity_id(),
2322            Box::new(move |entity, cx| {
2323                let entity = invariant(entity.downcast_mut(), "invalid entity type");
2324                on_release(entity, cx)
2325            }),
2326        );
2327        activate();
2328        subscription
2329    }
2330
2331    /// 观察实体的释放。回调在实体没有更多强引用后但在丢弃前调用。
2332    pub fn observe_release_in<T>(
2333        &self,
2334        handle: &Entity<T>,
2335        window: &Window,
2336        on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2337    ) -> Subscription
2338    where
2339        T: 'static,
2340    {
2341        let window_handle = window.handle;
2342        self.observe_release(handle, move |entity, cx| {
2343            let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2344        })
2345    }
2346
2347    /// 注册一个回调,当应用在任何窗口中收到按键时调用。
2348    /// 注意,此回调在所有其他动作和事件机制解析后触发,
2349    /// 如果事件的传播被停止,则不会调用此 API。
2350    pub fn observe_keystrokes(
2351        &mut self,
2352        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2353    ) -> Subscription {
2354        fn inner(
2355            keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
2356            handler: KeystrokeObserver,
2357        ) -> Subscription {
2358            let (subscription, activate) = keystroke_observers.insert((), handler);
2359            activate();
2360            subscription
2361        }
2362
2363        inner(
2364            &self.keystroke_observers,
2365            Box::new(move |event, window, cx| {
2366                f(event, window, cx);
2367                true
2368            }),
2369        )
2370    }
2371
2372    /// 注册一个回调,当应用在任何窗口中收到按键时调用。
2373    /// 注意,此回调在所有其他动作和事件机制解析*之前*触发,
2374    /// 与 [`App::observe_keystrokes`] 在之后触发不同。
2375    /// 这意味着拦截器中的 `cx.stop_propagation` 调用将阻止动作分发。
2376    pub fn intercept_keystrokes(
2377        &mut self,
2378        mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
2379    ) -> Subscription {
2380        fn inner(
2381            keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
2382            handler: KeystrokeObserver,
2383        ) -> Subscription {
2384            let (subscription, activate) = keystroke_interceptors.insert((), handler);
2385            activate();
2386            subscription
2387        }
2388
2389        inner(
2390            &self.keystroke_interceptors,
2391            Box::new(move |event, window, cx| {
2392                f(event, window, cx);
2393                true
2394            }),
2395        )
2396    }
2397
2398    /// 注册键绑定。
2399    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
2400        self.keymap.borrow_mut().add_bindings(bindings);
2401        self.pending_effects.push_back(Effect::RefreshWindows);
2402    }
2403
2404    /// 清除应用中所有键绑定。
2405    pub fn clear_key_bindings(&mut self) {
2406        self.keymap.borrow_mut().clear();
2407        self.pending_effects.push_back(Effect::RefreshWindows);
2408    }
2409
2410    /// 获取应用中所有键绑定。
2411    pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
2412        self.keymap.clone()
2413    }
2414
2415    /// 注册通过键盘调用动作的全局处理程序。这些处理程序在动作的
2416    /// 冒泡阶段结束时运行,因此仅在没有其他处理程序或它们调用了
2417    /// `cx.propagate()` 时才会被调用。
2418    pub fn on_action<A: Action>(
2419        &mut self,
2420        listener: impl Fn(&A, &mut Self) + 'static,
2421    ) -> &mut Self {
2422        self.global_action_listeners
2423            .entry(TypeId::of::<A>())
2424            .or_default()
2425            .push(Rc::new(move |action, phase, cx| {
2426                if phase == DispatchPhase::Bubble {
2427                    let action = invariant(action.downcast_ref(), "action type must match");
2428                    listener(action, cx)
2429                }
2430            }));
2431        self
2432    }
2433
2434    /// 注册全局动作:全局绑定 + 打到活动窗口 + spawn 延后更新三件套。
2435    ///
2436    /// 适用“按快捷键对活动窗口做点事”(如 F12 开关检查器):
2437    /// - `keystroke` 为 `Some("f12")` 时加一条无上下文的全局键绑定,
2438    ///   `None` 则只监听不绑定;
2439    /// - 监听只打活动窗口(`active_window`,无窗口时静默跳过);
2440    /// - 监听回调处于动作分发中,此时同步 `update` 活动窗口必失败,
2441    ///   故经 `spawn` 延后执行 `handler`。
2442    ///
2443    /// `handler` 只要求 `'static`(与 [`Self::on_action`] 一致,允许 `Rc` 捕获;
2444    /// 分发经本地 `spawn`,不需要 `Send + Sync`)。
2445    pub fn on_global_action<A: Action>(
2446        &mut self,
2447        action: A,
2448        keystroke: Option<&str>,
2449        handler: impl Fn(&mut Window, &mut App) + 'static,
2450    ) -> &mut Self {
2451        if let Some(keystroke) = keystroke {
2452            self.bind_keys([KeyBinding::new(keystroke, action, None)]);
2453        }
2454        let handler = Arc::new(handler);
2455        self.on_action(move |_: &A, cx: &mut App| {
2456            if let Some(window) = cx.active_window() {
2457                let handler = handler.clone();
2458                cx.spawn(async move |cx| {
2459                    _ = window.update(cx, |_, window, cx| handler(window, cx));
2460                })
2461                .detach();
2462            }
2463        })
2464    }
2465
2466    /// 事件处理程序默认传播事件。调用此方法可停止向 z-index 较低(鼠标)
2467    /// 或树中较高(键盘)的事件处理程序分发。这与 [`Self::propagate`] 相反。
2468    /// 也可以在副作用刷新前调用此方法来取消 [`Self::propagate`] 调用。
2469    pub fn stop_propagation(&mut self) {
2470        self.propagate_event = false;
2471    }
2472
2473    /// 动作处理程序在动作分发的冒泡阶段默认停止传播,
2474    /// 不向元素树中较高的动作处理程序分发。这与
2475    /// [`Self::stop_propagation`] 相反。也可以在副作用刷新前
2476    /// 调用此方法来取消 [`Self::stop_propagation`] 调用。
2477    pub fn propagate(&mut self) {
2478        self.propagate_event = true;
2479    }
2480
2481    /// 从一些任意数据构建动作,通常是键映射条目。
2482    pub fn build_action(
2483        &self,
2484        name: &str,
2485        data: Option<serde_json::Value>,
2486    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
2487        self.actions.build_action(name, data)
2488    }
2489
2490    /// 获取所有已注册的动作名称。注意,注册仅允许动态构建动作,
2491    /// 与在元素树中绑定动作无关。
2492    pub fn all_action_names(&self) -> &[&'static str] {
2493        self.actions.all_action_names()
2494    }
2495
2496    /// 返回在当前焦点元素上调用给定动作的键绑定,不检查上下文。
2497    /// 绑定按添加顺序返回。显示时,最后一个绑定应优先。
2498    pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
2499        RefCell::borrow(&self.keymap).all_bindings_for_input(input)
2500    }
2501
2502    /// 获取所有已注册的非内部动作及其 schema。
2503    pub fn action_schemas(
2504        &self,
2505        generator: &mut schemars::SchemaGenerator,
2506    ) -> Vec<(&'static str, Option<schemars::Schema>)> {
2507        self.actions.action_schemas(generator)
2508    }
2509
2510    /// 按名称获取特定动作的 schema。
2511    /// 如果未找到动作则返回 `None`。
2512    /// 如果动作存在但没有 schema 则返回 `Some(None)`。
2513    /// 如果动作存在且有 schema 则返回 `Some(Some(schema))`。
2514    pub fn action_schema_by_name(
2515        &self,
2516        name: &str,
2517        generator: &mut schemars::SchemaGenerator,
2518    ) -> Option<Option<schemars::Schema>> {
2519        self.actions.action_schema_by_name(name, generator)
2520    }
2521
2522    /// 获取从已弃用动作名称到规范名称的映射。
2523    pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
2524        self.actions.deprecated_aliases()
2525    }
2526
2527    /// 获取从动作名称到弃用消息的映射。
2528    pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
2529        self.actions.deprecation_messages()
2530    }
2531
2532    /// 获取从动作名称到文档的映射。
2533    pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
2534        self.actions.documentation()
2535    }
2536
2537    /// 注册一个回调,当应用即将退出时调用。
2538    /// 此时无法取消退出事件。
2539    pub fn on_app_quit<Fut>(
2540        &self,
2541        mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
2542    ) -> Subscription
2543    where
2544        Fut: 'static + Future<Output = ()>,
2545    {
2546        let (subscription, activate) = self.quit_observers.insert(
2547            (),
2548            Box::new(move |cx| {
2549                let future = on_quit(cx);
2550                future.boxed_local()
2551            }),
2552        );
2553        activate();
2554        subscription
2555    }
2556
2557    /// 注册一个回调,当应用即将重启时调用。
2558    ///
2559    /// 这些回调在任何 `on_app_quit` 回调之前调用。
2560    pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
2561        let (subscription, activate) = self.restart_observers.insert(
2562            (),
2563            Box::new(move |cx| {
2564                on_restart(cx);
2565                true
2566            }),
2567        );
2568        activate();
2569        subscription
2570    }
2571
2572    /// 注册一个回调,当窗口关闭时调用。
2573    /// 在调用此回调时,窗口不再可访问。
2574    pub fn on_window_closed(
2575        &self,
2576        mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
2577    ) -> Subscription {
2578        let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
2579        activate();
2580        subscription
2581    }
2582
2583    pub(crate) fn clear_pending_keystrokes(&mut self) {
2584        for window in self.windows() {
2585            window
2586                .update(self, |_, window, cx| {
2587                    if window.pending_input_keystrokes().is_some() {
2588                        window.clear_pending_keystrokes();
2589                        window.pending_input_changed(cx);
2590                    }
2591                })
2592                .ok();
2593        }
2594    }
2595
2596    /// 检查给定动作是否在当前上下文中被绑定,由应用的当前焦点、
2597    /// 元素树中的绑定和任何全局动作监听器定义。
2598    pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
2599        let mut action_available = false;
2600        if let Some(window) = self.active_window()
2601            && let Ok(window_action_available) =
2602                window.update(self, |_, window, cx| window.is_action_available(action, cx))
2603        {
2604            action_available = window_action_available;
2605        }
2606
2607        action_available
2608            || self
2609                .global_action_listeners
2610                .contains_key(&action.as_any().type_id())
2611    }
2612
2613    /// 设置此应用的菜单栏。这将替换任何现有的菜单栏。
2614    ///
2615    /// 注意:macOS 会把它显示为系统菜单栏;Windows 与 Linux 只保存菜单数据,
2616    /// 不会显示原生菜单栏。Linux 上若要用自绘的 `AppMenuBar`,还需通过
2617    /// `GlobalState::set_app_menus` 同步同一份数据(平台层的存储与自绘组件
2618    /// 的数据源当前互不连通)。
2619    pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
2620        let menus: Vec<Menu> = menus.into_iter().collect();
2621        self.platform.set_menus(menus, &self.keymap.borrow());
2622    }
2623
2624    /// 获取此应用的菜单栏。
2625    pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
2626        self.platform.get_menus()
2627    }
2628
2629    /// 注册菜单项动作的执行回调。
2630    ///
2631    /// 回调由平台在原生命令到达时调用:macOS 是全局菜单项被选中,Windows 是托盘菜单
2632    /// 与任务栏跳转列表项被选中,Linux 是用 `set_tray`(旧 API)随菜单项带过去的动作被点击。
2633    /// 需要「菜单项 → 动作」这条路走通的场景都注册这里;框架自身的
2634    /// `menu::MenuBar` 组件走常规 action 派发,不经过本回调。
2635    pub fn on_app_menu_action(&self, mut callback: impl FnMut(&dyn Action, &mut App) + 'static) {
2636        let this = self.this.clone();
2637        self.platform.on_app_menu_action(Box::new(move |action| {
2638            if let Some(app) = this.upgrade() {
2639                callback(action, &mut app.borrow_mut());
2640            }
2641        }));
2642    }
2643
2644    /// 注册「菜单即将打开」回调,可据此重建菜单内容再让主机取用。
2645    ///
2646    /// 目前只有 macOS 会触发(Windows/Linux 没有对应的原生事件源)。
2647    pub fn on_will_open_app_menu(&self, mut callback: impl FnMut(&mut App) + 'static) {
2648        let this = self.this.clone();
2649        self.platform.on_will_open_app_menu(Box::new(move || {
2650            if let Some(app) = this.upgrade() {
2651                callback(&mut app.borrow_mut());
2652            }
2653        }));
2654    }
2655
2656    /// 注册菜单项可用性校验回调,返回 `false` 会禁用对应菜单项。
2657    ///
2658    /// 目前只有 macOS 会触发(Windows/Linux 没有对应的原生事件源)。
2659    pub fn on_validate_app_menu_command(
2660        &self,
2661        mut callback: impl FnMut(&dyn Action, &mut App) -> bool + 'static,
2662    ) {
2663        let this = self.this.clone();
2664        self.platform
2665            .on_validate_app_menu_command(Box::new(move |action| match this.upgrade() {
2666                Some(app) => callback(action, &mut app.borrow_mut()),
2667                None => true,
2668            }));
2669    }
2670
2671    /// 设置 Dock 中应用图标的右键菜单
2672    pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
2673        self.platform.set_dock_menu(menus, &self.keymap.borrow())
2674    }
2675
2676    /// 执行与给定 Dock 菜单项关联的动作,目前仅在 Windows 上使用。
2677    pub fn perform_dock_menu_action(&self, action: usize) {
2678        self.platform.perform_dock_menu_action(action);
2679    }
2680
2681    /// 将给定路径添加到应用最近路径列表的底部。
2682    /// 该列表通常显示在 Dock 中应用图标的上下文菜单中,
2683    /// 允许通过该上下文菜单打开最近的文件。
2684    /// 如果路径已在列表中,它将被移动到列表底部。
2685    pub fn add_recent_document(&self, path: &Path) {
2686        self.platform.add_recent_document(path);
2687    }
2688
2689    /// 使用更新的最近路径列表更新跳转列表,目前仅在 Windows 上使用。
2690    /// 注意,这也会在 Windows 上设置 Dock 菜单。
2691    pub fn update_jump_list(
2692        &self,
2693        menus: Vec<MenuItem>,
2694        entries: Vec<SmallVec<[PathBuf; 2]>>,
2695    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
2696        self.platform.update_jump_list(menus, entries)
2697    }
2698
2699    /// 设置系统托盘图标和菜单(旧 API,向后兼容)
2700    pub fn set_tray(&self, tray: Tray, menus: Option<Vec<MenuItem>>) {
2701        self.platform.set_tray(tray, menus, &self.keymap.borrow())
2702    }
2703
2704    /// 设置系统托盘图标
2705    pub fn set_tray_icon(&self, icon: Option<&[u8]>) {
2706        self.platform.set_tray_icon(icon);
2707    }
2708
2709    /// 设置系统托盘菜单项
2710    pub fn set_tray_menu(&self, menu: Vec<TrayMenuItem>) {
2711        self.platform.set_tray_menu(menu);
2712    }
2713
2714    /// 设置系统托盘工具提示
2715    pub fn set_tray_tooltip(&self, tooltip: &str) {
2716        self.platform.set_tray_tooltip(tooltip);
2717    }
2718
2719    /// 启用或禁用托盘面板模式
2720    /// 启用时,点击托盘图标会触发 `TrayIconEvent::LeftClick` 而不是显示菜单
2721    pub fn set_tray_panel_mode(&self, enabled: bool) {
2722        self.platform.set_tray_panel_mode(enabled);
2723    }
2724
2725    /// 在操作系统中显示通知
2726    pub fn show_notification(&self, title: &str, body: &str) -> Result<()> {
2727        self.platform.show_notification(title, body)
2728    }
2729
2730    /// 推送通知(便捷方法,触发操作系统级通知)。
2731    ///
2732    /// 等价于 `show_notification`,提供更具语义化的命名。
2733    pub fn push_notification(&self, title: &str, message: &str) -> Result<()> {
2734        self.show_notification(title, message)
2735    }
2736
2737    /// 获取托盘图标的屏幕边界坐标,用于在其下方定位窗口
2738    pub fn tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
2739        self.platform.get_tray_icon_bounds()
2740    }
2741
2742    /// 注册系统托盘图标事件的回调函数
2743    pub fn on_tray_icon_event(&self, mut callback: impl FnMut(TrayIconEvent, &mut App) + 'static) {
2744        let this = self.this.clone();
2745        self.platform.on_tray_icon_event(Box::new(move |event| {
2746            if let Some(app) = this.upgrade() {
2747                callback(event, &mut app.borrow_mut());
2748            }
2749        }));
2750    }
2751
2752    /// 注册托盘菜单项点击事件的回调函数
2753    pub fn on_tray_menu_action(&self, mut callback: impl FnMut(SharedString, &mut App) + 'static) {
2754        let this = self.this.clone();
2755        self.platform.on_tray_menu_action(Box::new(move |id| {
2756            if let Some(app) = this.upgrade() {
2757                callback(id, &mut app.borrow_mut());
2758            }
2759        }));
2760    }
2761
2762    /// 设置应用程序是否应在没有窗口时保持运行
2763    ///
2764    /// 状态存在核心层:窗口全部关闭后的自动退出判据就在 `App` 里,
2765    /// 交给平台保存只会变成一个没人读的标志。
2766    pub fn set_keep_alive_without_windows(&self, keep_alive: bool) {
2767        self.keep_alive_without_windows.set(keep_alive);
2768    }
2769
2770    /// 查询系统权限状态(辅助功能 / 屏幕录制 / 输入监控)。
2771    ///
2772    /// 返回 [`PermissionStatus::Unavailable`] 表示系统根本没有这一类别的授权概念,
2773    /// 或判定通道不可达 —— 与 `Granted` 是两回事,调用方不要按「拿不到就当有」处理。
2774    pub fn check_permission(&self, kind: PermissionType) -> PermissionStatus {
2775        self.platform.check_permission(kind)
2776    }
2777
2778    /// 请求系统权限:有授权弹窗的类别会触发弹窗,其余类别输出可操作的引导日志。
2779    pub fn request_permission(&self, kind: PermissionType) {
2780        self.platform.request_permission(kind);
2781    }
2782
2783    /// 返回操作系统名称与版本号。
2784    pub fn os_info(&self) -> OsInfo {
2785        self.platform.os_info()
2786    }
2787
2788    /// 返回系统空闲时长(自上次用户输入以来),无法判定时为 `None`。
2789    pub fn system_idle_time(&self) -> Option<Duration> {
2790        self.platform.system_idle_time()
2791    }
2792
2793    /// 返回当前网络连接状态。
2794    pub fn network_status(&self) -> NetworkStatus {
2795        self.platform.network_status()
2796    }
2797
2798    /// 注册系统电源事件回调(即将睡眠 / 已唤醒)。
2799    ///
2800    /// 「即将睡眠」是平台给应用的收尾窗口:此刻还在事件循环里,可以落盘或释放资源;
2801    /// 「已唤醒」用来恢复那些在睡眠期间失效的状态(例如计时器、连接)。
2802    /// 与 [`App::on_system_wake`] 的区别是本回调两种事件都能收到。
2803    pub fn on_system_power_event(
2804        &self,
2805        mut callback: impl FnMut(SystemPowerEvent, &mut App) + 'static,
2806    ) {
2807        let this = self.this.clone();
2808        self.platform.on_system_power_event(Box::new(move |event| {
2809            if let Some(app) = this.upgrade() {
2810                callback(event, &mut app.borrow_mut());
2811            }
2812        }));
2813    }
2814
2815    /// 阻止系统休眠或息屏;返回的句柄**持有即生效、`Drop` 即恢复**。
2816    ///
2817    /// 平台不支持或系统服务不可达时返回 `None`。句柄要放在应用能控制生命周期的地方
2818    /// (字段、`Cell<Option<..>>`),不要靠「按 ID 停止」——那样底层资源会一直泄漏。
2819    pub fn start_power_save_blocker(
2820        &self,
2821        kind: PowerSaveBlockerKind,
2822    ) -> Option<Box<dyn PowerSaveBlocker>> {
2823        self.platform.start_power_save_blocker(kind)
2824    }
2825
2826    /// 设置开机自启动,`app_id` 为应用标识。
2827    pub fn set_auto_launch(&self, app_id: &str, enabled: bool) -> Result<()> {
2828        self.platform.set_auto_launch(app_id, enabled)
2829    }
2830
2831    /// 查询开机自启动是否已启用。
2832    pub fn is_auto_launch_enabled(&self, app_id: &str) -> bool {
2833        self.platform.is_auto_launch_enabled(app_id)
2834    }
2835
2836    /// 返回当前系统中获得焦点的窗口信息(跨进程,需系统辅助功能授权)。
2837    pub fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
2838        self.platform.focused_window_info()
2839    }
2840
2841    /// 最小化到托盘 —— 隐藏所有窗口(从任务栏移除)。
2842    ///
2843    /// 常用于点击关闭按钮时将应用最小化到系统托盘而非退出。
2844    pub fn minimize_to_tray(&mut self) {
2845        let windows: Vec<AnyWindowHandle> = self.windows();
2846        for window in windows {
2847            self.update_window(window, |_view, window, _cx| {
2848                window.hide_window();
2849            })
2850            .ok();
2851        }
2852    }
2853
2854    /// 显示所有窗口(将所有窗口带到前台)。
2855    pub fn show_all_windows(&mut self) {
2856        let windows: Vec<AnyWindowHandle> = self.windows();
2857        for window in windows {
2858            self.update_window(window, |_view, window, _cx| {
2859                window.activate_window();
2860            })
2861            .ok();
2862        }
2863    }
2864
2865    /// 隐藏所有窗口(从任务栏和屏幕移除)。
2866    pub fn hide_all_windows(&mut self) {
2867        let windows: Vec<AnyWindowHandle> = self.windows();
2868        for window in windows {
2869            self.update_window(window, |_view, window, _cx| {
2870                window.hide_window();
2871            })
2872            .ok();
2873        }
2874    }
2875
2876    /// 最小化所有窗口。
2877    pub fn minimize_all_windows(&mut self) {
2878        let windows: Vec<AnyWindowHandle> = self.windows();
2879        for window in windows {
2880            self.update_window(window, |_view, window, _cx| {
2881                window.minimize_window();
2882            })
2883            .ok();
2884        }
2885    }
2886
2887    /// 注册全局快捷键
2888    ///
2889    /// # 参数
2890    /// * `id` - 快捷键的唯一标识符
2891    /// * `keystroke` - 快捷键组合(如 "cmd-shift-k")
2892    ///
2893    /// # 返回
2894    /// 成功时返回 `Ok(())`,失败时返回错误
2895    pub fn register_global_hotkey(&self, id: u32, keystroke: &Keystroke) -> Result<()> {
2896        self.platform.register_global_hotkey(id, keystroke)
2897    }
2898
2899    /// 注销全局快捷键
2900    ///
2901    /// # 参数
2902    /// * `id` - 要注销的快捷键 ID
2903    pub fn unregister_global_hotkey(&self, id: u32) {
2904        self.platform.unregister_global_hotkey(id);
2905    }
2906
2907    /// 注册全局快捷键事件的回调函数
2908    pub fn on_global_hotkey(&self, mut callback: impl FnMut(u32, &mut App) + 'static) {
2909        let this = self.this.clone();
2910        self.platform.on_global_hotkey(Box::new(move |id| {
2911            if let Some(app) = this.upgrade() {
2912                callback(id, &mut app.borrow_mut());
2913            }
2914        }));
2915    }
2916
2917    /// 将动作分发到当前活动窗口或全局动作处理程序
2918    /// 参见 [`crate::Action`] 了解动作如何工作的更多信息
2919    pub fn dispatch_action(&mut self, action: &dyn Action) {
2920        // 平台上报的“活动窗口”偶尔为空(窗口刚创建、尚未激活等),
2921        // 此时退回到任意一个仍存活的窗口,避免命令被静默丢弃。
2922        let window = self.active_window().or_else(|| self.first_window_handle());
2923
2924        if let Some(window) = window {
2925            let dispatched = window
2926                .update(self, |_, window, cx| window.dispatch_action_now(action, cx))
2927                .is_ok();
2928
2929            if dispatched {
2930                return;
2931            }
2932
2933            // 同步更新失败通常意味着调用发生在窗口事件/渲染回调内部:
2934            // 该窗口正被借用(`windows` 槽位暂时为空),立即派发必然失败。
2935            // 推迟到本次更新结束后再派发,命令才不会“点了没反应”。
2936            let action = action.boxed_clone();
2937            self.defer(move |cx| {
2938                let window = cx.active_window().or_else(|| cx.first_window_handle());
2939                if let Some(window) = window {
2940                    window
2941                        .update(cx, |_, window, cx| {
2942                            window.dispatch_action_now(action.as_ref(), cx)
2943                        })
2944                        .log_err();
2945                } else {
2946                    cx.dispatch_global_action(action.as_ref());
2947                }
2948            });
2949        } else {
2950            self.dispatch_global_action(action);
2951        }
2952    }
2953
2954    /// 返回任意一个存活窗口的句柄;没有窗口时为 `None`。
2955    fn first_window_handle(&self) -> Option<AnyWindowHandle> {
2956        self.windows
2957            .values()
2958            .flatten()
2959            .next()
2960            .map(|window| window.handle)
2961    }
2962
2963    fn dispatch_global_action(&mut self, action: &dyn Action) {
2964        self.propagate_event = true;
2965
2966        if let Some(mut global_listeners) = self
2967            .global_action_listeners
2968            .remove(&action.as_any().type_id())
2969        {
2970            for listener in &global_listeners {
2971                listener(action.as_any(), DispatchPhase::Capture, self);
2972                if !self.propagate_event {
2973                    break;
2974                }
2975            }
2976
2977            global_listeners.extend(
2978                self.global_action_listeners
2979                    .remove(&action.as_any().type_id())
2980                    .unwrap_or_default(),
2981            );
2982
2983            self.global_action_listeners
2984                .insert(action.as_any().type_id(), global_listeners);
2985        }
2986
2987        if self.propagate_event
2988            && let Some(mut global_listeners) = self
2989                .global_action_listeners
2990                .remove(&action.as_any().type_id())
2991        {
2992            for listener in global_listeners.iter().rev() {
2993                listener(action.as_any(), DispatchPhase::Bubble, self);
2994                if !self.propagate_event {
2995                    break;
2996                }
2997            }
2998
2999            global_listeners.extend(
3000                self.global_action_listeners
3001                    .remove(&action.as_any().type_id())
3002                    .unwrap_or_default(),
3003            );
3004
3005            self.global_action_listeners
3006                .insert(action.as_any().type_id(), global_listeners);
3007        }
3008    }
3009
3010    /// 当前是否有正在拖动的内容?
3011    pub fn has_active_drag(&self) -> bool {
3012        self.active_drag.is_some()
3013    }
3014
3015    /// 获取当前活动拖动操作的光标样式。
3016    pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
3017        self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
3018    }
3019
3020    /// 停止活动拖动并清除任何相关副作用。
3021    pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
3022        if self.active_drag.is_some() {
3023            self.active_drag = None;
3024            window.refresh();
3025            true
3026        } else {
3027            false
3028        }
3029    }
3030
3031    /// 获取活动拖动的值(如果有的话)(用于接收文件拖放)。
3032    pub fn take_active_drag_value(&mut self) -> Option<Arc<dyn std::any::Any>> {
3033        self.active_drag.take().map(|drag| drag.value)
3034    }
3035
3036    /// 设置当前活动拖动操作的光标样式。
3037    pub fn set_active_drag_cursor_style(
3038        &mut self,
3039        cursor_style: CursorStyle,
3040        window: &mut Window,
3041    ) -> bool {
3042        if let Some(ref mut drag) = self.active_drag {
3043            drag.cursor_style = Some(cursor_style);
3044            window.refresh();
3045            true
3046        } else {
3047            false
3048        }
3049    }
3050
3051    /// 设置 RGPUI 的提示渲染器。这将用此自定义实现替换默认或平台特定的提示。
3052    pub fn set_prompt_builder(
3053        &mut self,
3054        renderer: impl Fn(
3055            PromptLevel,
3056            &str,
3057            Option<&str>,
3058            &[PromptButton],
3059            PromptHandle,
3060            &mut Window,
3061            &mut App,
3062        ) -> RenderablePromptHandle
3063        + 'static,
3064    ) {
3065        self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
3066    }
3067
3068    /// 将提示构建器重置为默认实现。
3069    pub fn reset_prompt_builder(&mut self) {
3070        self.prompt_builder = Some(PromptBuilder::Default);
3071    }
3072
3073    /// 从 RGPUI 缓存中移除资源
3074    pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
3075        let asset_id = (TypeId::of::<A>(), hash(source));
3076        self.loading_assets.remove(&asset_id);
3077    }
3078
3079    /// 异步加载资源,如果资源尚未完成加载则返回 None。
3080    ///
3081    /// 注意,多次调用此方法每次只会产生一次 `Asset::load` 调用,
3082    /// 且该调用的结果将被缓存。
3083    pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) {
3084        let asset_id = (TypeId::of::<A>(), hash(source));
3085        let mut is_first = false;
3086        let task = self
3087            .loading_assets
3088            .remove(&asset_id)
3089            .map(|boxed_task| {
3090                *invariant_result(
3091                    boxed_task.downcast::<Shared<Task<A::Output>>>(),
3092                    "asset task type must match",
3093                )
3094            })
3095            .unwrap_or_else(|| {
3096                is_first = true;
3097                let future = A::load(source.clone(), self);
3098
3099                self.background_executor().spawn(future).shared()
3100            });
3101
3102        self.loading_assets.insert(asset_id, Box::new(task.clone()));
3103
3104        (task, is_first)
3105    }
3106
3107    /// 获取一个新的 [`FocusHandle`],允许你跟踪和操作
3108    /// 此窗口中渲染的元素的键盘焦点。
3109    #[track_caller]
3110    pub fn focus_handle(&self) -> FocusHandle {
3111        FocusHandle::new(&self.focus_handles)
3112    }
3113
3114    /// 告诉 RGPUI 实体已更改,应通知其观察者。
3115    pub fn notify(&mut self, entity_id: EntityId) {
3116        let window_invalidators = mem::take(
3117            self.window_invalidators_by_entity
3118                .entry(entity_id)
3119                .or_default(),
3120        );
3121
3122        // `window_invalidators_by_entity` is monotonic, so an entry alone
3123        // doesn't mean the window is currently rendering the entity. Filter
3124        // through `tracked_entities` to keep invalidation tight to windows
3125        // that actually display this entity right now.
3126        let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
3127            .iter()
3128            .filter(|(window_id, _)| {
3129                self.tracked_entities
3130                    .get(window_id)
3131                    .is_some_and(|set| set.contains(&entity_id))
3132            })
3133            .map(|(_, invalidator)| invalidator.clone())
3134            .collect();
3135
3136        if live_invalidators.is_empty() {
3137            if self.pending_notifications.insert(entity_id) {
3138                self.pending_effects
3139                    .push_back(Effect::Notify { emitter: entity_id });
3140            }
3141        } else {
3142            for invalidator in &live_invalidators {
3143                invalidator.invalidate_view(entity_id, self);
3144            }
3145        }
3146
3147        self.window_invalidators_by_entity
3148            .insert(entity_id, window_invalidators);
3149    }
3150
3151    /// 返回此 [`App`] 的名称。
3152    #[cfg(any(test, feature = "test-support", debug_assertions))]
3153    pub fn get_name(&self) -> Option<&'static str> {
3154        self.name
3155    }
3156
3157    /// 如果平台文件选择器支持选择文件和目录的混合,则返回 `true`。
3158    pub fn can_select_mixed_files_and_dirs(&self) -> bool {
3159        self.platform.can_select_mixed_files_and_dirs()
3160    }
3161
3162    /// 从所有窗口的精灵图集中移除图像。
3163    ///
3164    /// 如果当前窗口正在更新,它将从 `App.windows` 中移除,你可以使用 `current_window` 指定当前窗口。
3165    /// 如果图像不在精灵图集中,此操作无效。
3166    pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
3167        // remove the texture from all other windows
3168        for window in self.windows.values_mut().flatten() {
3169            _ = window.drop_image(image.clone());
3170        }
3171
3172        // remove the texture from the current window
3173        if let Some(window) = current_window {
3174            _ = window.drop_image(image);
3175        }
3176    }
3177
3178    /// 设置检查器的渲染器。
3179    #[cfg(any(feature = "inspector", debug_assertions))]
3180    pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
3181        self.inspector_renderer = Some(f);
3182    }
3183
3184    /// 注册特定于检查器状态的渲染器。
3185    #[cfg(any(feature = "inspector", debug_assertions))]
3186    pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
3187        &mut self,
3188        f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
3189    ) {
3190        self.inspector_element_registry.register(f);
3191    }
3192
3193    /// 一键启用默认检查器面板(I3 开箱即用)。
3194    ///
3195    /// 注册默认面板 + `Div` 布局展示;应用入口调用本方法后,
3196    /// 再调 `window.toggle_inspector(cx)` 即出完整面板,共两行。
3197    /// 需自定义时以 `set_inspector_renderer` 整板替换
3198    /// (可复用 `crate::default_inspector_panel` 包裹扩展),
3199    /// 或以 `register_inspector_element` 按状态类型扩展。
3200    #[cfg(any(feature = "inspector", debug_assertions))]
3201    pub fn enable_default_inspector(&mut self) {
3202        self.set_inspector_renderer(Box::new(crate::inspector_panel::default_inspector_panel));
3203        self.register_inspector_element(crate::inspector_panel::render_div_inspector_state);
3204    }
3205
3206    /// 上报一条应用错误(写入有界错误环,最多保留 50 条)。
3207    ///
3208    /// 检查器“报错”卡片与崩溃快照读取此处;这是应用内 Console 的对应物——
3209    /// 框架不拦截 `log`(应用自有 logger),需要进面板的错误请走本方法。
3210    pub fn report_error(&mut self, message: impl Into<SharedString>) {
3211        const CAP: usize = 50;
3212        if self.recent_errors.len() >= CAP {
3213            self.recent_errors.pop_front();
3214        }
3215        let seq = self.error_seq;
3216        self.error_seq += 1;
3217        self.recent_errors.push_back((seq, message.into()));
3218    }
3219
3220    /// 读取错误环(序号升序)。面板与快照用;平时无额外开销(只读)。
3221    pub fn recent_errors(&self) -> Vec<(u64, SharedString)> {
3222        self.recent_errors.iter().cloned().collect()
3223    }
3224
3225    /// 开启崩溃快照滚动记录(`last.json` 约 2 秒一写,原子替换)。
3226    ///
3227    /// 需配合 [`crate::runtime_stats::install_crash_hook`] 的 panic 日志食用:
3228    /// 快照是死前状态,日志是死因。目录不存在会自动创建。
3229    /// 仅检查器打开的窗口写入;关闭记录传空目录或重启应用(字段不持久化)。
3230    pub fn enable_crash_recorder(&mut self, dir: impl Into<std::path::PathBuf>) {
3231        self.crash_recorder_dir = Some(dir.into());
3232    }
3233
3234    /// 设置默认检查器面板插槽(H5:换顶栏/段落外皮,不必整板替换)。
3235    ///
3236    /// 与 [`Self::enable_default_inspector`] 配合:先启用默认面板,再按需覆盖插槽;
3237    /// 未设置的插槽走默认外皮(`default_inspector_header` / `default_inspector_section`)。
3238    #[cfg(any(feature = "inspector", debug_assertions))]
3239    pub fn set_inspector_panel_slots(
3240        &mut self,
3241        slots: crate::inspector_panel::InspectorPanelSlots,
3242    ) {
3243        self.set_global(slots);
3244    }
3245
3246    /// 初始化应用的 rgpui 默认颜色。
3247    ///
3248    /// 这些颜色可以通过 `cx.default_colors()` 访问。
3249    pub fn init_colors(&mut self) {
3250        self.set_global(GlobalColors(Arc::new(Colors::default())));
3251    }
3252}
3253
3254impl AppContext for App {
3255    /// 构建由应用拥有的实体。
3256    ///
3257    /// 给定函数将使用 [`Context`] 调用,必须返回表示实体的对象。
3258    /// 将返回 [`Entity`] 句柄,可用于在上下文中访问实体。
3259    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
3260        self.update(|cx| {
3261            let slot = cx.entities.reserve();
3262            let handle = slot.clone();
3263            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3264
3265            cx.push_effect(Effect::EntityCreated {
3266                entity: handle.into_any(),
3267                tid: TypeId::of::<T>(),
3268                window: cx.window_update_stack.last().cloned(),
3269            });
3270
3271            cx.entities.insert(slot, entity)
3272        })
3273    }
3274
3275    fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
3276        Reservation(self.entities.reserve())
3277    }
3278
3279    fn insert_entity<T: 'static>(
3280        &mut self,
3281        reservation: Reservation<T>,
3282        build_entity: impl FnOnce(&mut Context<T>) -> T,
3283    ) -> Entity<T> {
3284        self.update(|cx| {
3285            let slot = reservation.0;
3286            let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
3287            cx.entities.insert(slot, entity)
3288        })
3289    }
3290
3291    /// 更新给定句柄引用的实体。函数接收实体的可变引用和实体的 `Context`。
3292    fn update_entity<T: 'static, R>(
3293        &mut self,
3294        handle: &Entity<T>,
3295        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
3296    ) -> R {
3297        self.update(|cx| {
3298            let mut entity = cx.entities.lease(handle);
3299            let result = update(
3300                &mut entity,
3301                &mut Context::new_context(cx, handle.downgrade()),
3302            );
3303            cx.entities.end_lease(entity);
3304            result
3305        })
3306    }
3307
3308    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
3309    where
3310        T: 'static,
3311    {
3312        GpuiBorrow::new(handle.clone(), self)
3313    }
3314
3315    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
3316    where
3317        T: 'static,
3318    {
3319        let entity = self.entities.read(handle);
3320        read(entity, self)
3321    }
3322
3323    #[track_caller]
3324    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
3325    where
3326        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
3327    {
3328        self.update_window_id(handle.id, update)
3329    }
3330
3331    fn with_window<R>(
3332        &mut self,
3333        entity_id: EntityId,
3334        f: impl FnOnce(&mut Window, &mut App) -> R,
3335    ) -> Option<R> {
3336        App::with_window(self, entity_id, f)
3337    }
3338
3339    fn read_window<T, R>(
3340        &self,
3341        window: &WindowHandle<T>,
3342        read: impl FnOnce(Entity<T>, &App) -> R,
3343    ) -> Result<R>
3344    where
3345        T: 'static,
3346    {
3347        let window = self
3348            .windows
3349            .get(window.id)
3350            .context("window not found")?
3351            .as_deref();
3352        let window = invariant(
3353            window,
3354            "attempted to read a window that is already on the stack",
3355        );
3356
3357        let root_view = invariant(window.root.clone(), "window must have a root view");
3358        let view = Root::root_view_downcast::<T>(root_view, self)
3359            .map_err(|_| anyhow!("root view's type has changed"))?;
3360
3361        Ok(read(view, self))
3362    }
3363
3364    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
3365    where
3366        R: Send + 'static,
3367    {
3368        self.background_executor.spawn(future)
3369    }
3370
3371    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
3372    where
3373        G: Global,
3374    {
3375        let mut g = self.global::<G>();
3376        callback(g, self)
3377    }
3378}
3379
3380/// 这些副作用在每个应用更新周期结束时处理。
3381pub(crate) enum Effect {
3382    Notify {
3383        emitter: EntityId,
3384    },
3385    Emit {
3386        emitter: EntityId,
3387        event_type: TypeId,
3388        event: ArenaBox<dyn Any>,
3389    },
3390    RefreshWindows,
3391    NotifyGlobalObservers {
3392        global_type: TypeId,
3393    },
3394    Defer {
3395        callback: Box<dyn FnOnce(&mut App) + 'static>,
3396    },
3397    EntityCreated {
3398        entity: AnyEntity,
3399        tid: TypeId,
3400        window: Option<WindowId>,
3401    },
3402}
3403
3404impl std::fmt::Debug for Effect {
3405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3406        match self {
3407            Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
3408            Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
3409            Effect::RefreshWindows => write!(f, "RefreshWindows"),
3410            Effect::NotifyGlobalObservers { global_type } => {
3411                write!(f, "NotifyGlobalObservers({:?})", global_type)
3412            }
3413            Effect::Defer { .. } => write!(f, "Defer(..)"),
3414            Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
3415        }
3416    }
3417}
3418
3419/// 在 `update_global` 期间包装全局变量值,当值已移动到栈上时。
3420pub(crate) struct GlobalLease<G: Global> {
3421    global: Box<dyn Any>,
3422    global_type: PhantomData<G>,
3423}
3424
3425impl<G: Global> GlobalLease<G> {
3426    fn new(global: Box<dyn Any>) -> Self {
3427        GlobalLease {
3428            global,
3429            global_type: PhantomData,
3430        }
3431    }
3432}
3433
3434impl<G: Global> Deref for GlobalLease<G> {
3435    type Target = G;
3436
3437    fn deref(&self) -> &Self::Target {
3438        invariant(self.global.downcast_ref(), "global type must match")
3439    }
3440}
3441
3442impl<G: Global> DerefMut for GlobalLease<G> {
3443    fn deref_mut(&mut self) -> &mut Self::Target {
3444        invariant(self.global.downcast_mut(), "global type must match")
3445    }
3446}
3447
3448/// 包含与活动拖动操作关联的状态,通过在窗口中拖动元素
3449/// 或从底层平台拖入应用来启动。
3450pub struct AnyDrag {
3451    /// 用于渲染此拖动的视图
3452    pub view: AnyView,
3453
3454    /// 被拖动项的值,将被拖放
3455    pub value: Arc<dyn Any>,
3456
3457    /// 用于在发起拖动的原始元素的同一位置渲染被拖动项
3458    pub cursor_offset: Point<Pixels>,
3459
3460    /// 拖动时使用的光标样式
3461    pub cursor_style: Option<CursorStyle>,
3462}
3463
3464/// 包含与工具提示关联的状态。仅当在自定义元素上实现工具提示行为时才需要此结构体。
3465/// 否则,请使用 [Div::tooltip](crate::Interactivity::tooltip)。
3466#[derive(Clone)]
3467pub struct AnyTooltip {
3468    /// 用于显示工具提示的视图
3469    pub view: AnyView,
3470
3471    /// 工具提示展开时鼠标的绝对位置。
3472    pub mouse_position: Point<Pixels>,
3473
3474    /// 根据工具提示的边界检查工具提示是否仍应可见,并相应地更新其状态。
3475    /// 这需要在悬停元素的鼠标移动处理程序之上,以处理元素未被绘制的情况
3476    /// (例如通过使用 `visible_on_hover`)。
3477    pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
3478}
3479
3480/// 按键事件,以及可能关联的动作
3481#[derive(Debug)]
3482pub struct KeystrokeEvent {
3483    /// 发生的按键
3484    pub keystroke: Keystroke,
3485
3486    /// 为按键解析出的动作(如果有)
3487    pub action: Option<Box<dyn Action>>,
3488
3489    /// 事件发生时的上下文栈
3490    pub context_stack: Vec<KeyContext>,
3491}
3492
3493struct NullHttpClient;
3494
3495impl HttpClient for NullHttpClient {
3496    fn send(
3497        &self,
3498        _req: crate::http_client::Request<crate::http_client::AsyncBody>,
3499    ) -> futures::future::BoxFuture<
3500        'static,
3501        anyhow::Result<crate::http_client::Response<crate::http_client::AsyncBody>>,
3502    > {
3503        async move {
3504            anyhow::bail!("No HttpClient available");
3505        }
3506        .boxed()
3507    }
3508
3509    fn user_agent(&self) -> Option<&crate::http_client::http::HeaderValue> {
3510        None
3511    }
3512
3513    fn proxy(&self) -> Option<&Url> {
3514        None
3515    }
3516}
3517
3518/// 对 RGPUI 拥有的实体的可变引用
3519pub struct GpuiBorrow<'a, T> {
3520    inner: Option<Lease<T>>,
3521    app: &'a mut App,
3522}
3523
3524impl<'a, T: 'static> GpuiBorrow<'a, T> {
3525    fn new(inner: Entity<T>, app: &'a mut App) -> Self {
3526        app.start_update();
3527        let lease = app.entities.lease(&inner);
3528        Self {
3529            inner: Some(lease),
3530            app,
3531        }
3532    }
3533}
3534
3535impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
3536    fn borrow(&self) -> &T {
3537        // 借用期内实体必然存在(Lease 借用后由 GpuiBorrow 持有)。
3538        let lease: &Lease<T> = invariant(self.inner.as_ref(), "borrow must be alive");
3539        lease
3540    }
3541}
3542
3543impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
3544    fn borrow_mut(&mut self) -> &mut T {
3545        // 借用期内实体必然存在(Lease 借用后由 GpuiBorrow 持有)。
3546        let lease: &mut Lease<T> = invariant(self.inner.as_mut(), "borrow must be alive");
3547        lease
3548    }
3549}
3550
3551impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
3552    type Target = T;
3553
3554    fn deref(&self) -> &Self::Target {
3555        // 借用期内实体必然存在(Lease 借用后由 GpuiBorrow 持有)。
3556        let lease: &Lease<T> = invariant(self.inner.as_ref(), "borrow must be alive");
3557        lease
3558    }
3559}
3560
3561impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
3562    fn deref_mut(&mut self) -> &mut T {
3563        // 借用期内实体必然存在(Lease 借用后由 GpuiBorrow 持有)。
3564        let lease: &mut Lease<T> = invariant(self.inner.as_mut(), "borrow must be alive");
3565        lease
3566    }
3567}
3568
3569impl<'a, T> Drop for GpuiBorrow<'a, T> {
3570    fn drop(&mut self) {
3571        let lease = invariant(self.inner.take(), "borrow must be alive");
3572        self.app.notify(lease.id);
3573        self.app.entities.end_lease(lease);
3574        self.app.finish_update();
3575    }
3576}
3577
3578#[cfg(test)]
3579mod test {
3580    use std::{cell::RefCell, rc::Rc};
3581
3582    use crate::{AppContext, TestAppContext};
3583
3584    #[test]
3585    fn test_gpui_borrow() {
3586        let cx = TestAppContext::single();
3587        let observation_count = Rc::new(RefCell::new(0));
3588
3589        let state = cx.update(|cx| {
3590            let state = cx.new(|_| false);
3591            cx.observe(&state, {
3592                let observation_count = observation_count.clone();
3593                move |_, _| {
3594                    let mut count = observation_count.borrow_mut();
3595                    *count += 1;
3596                }
3597            })
3598            .detach();
3599
3600            state
3601        });
3602
3603        cx.update(|cx| {
3604            // Calling this like this so that we don't clobber the borrow_mut above
3605            *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
3606        });
3607
3608        cx.update(|cx| {
3609            state.write(cx, false);
3610        });
3611
3612        assert_eq!(*observation_count.borrow(), 2);
3613    }
3614}