Skip to main content

gpui_platform/
gpui_platform.rs

1//! Convenience crate that re-exports GPUI's platform traits and the
2//! `current_platform` constructor so consumers don't need `#[cfg]` gating.
3
4pub use gpui::Platform;
5
6use std::rc::Rc;
7
8/// Returns a background executor for the current platform.
9pub fn background_executor() -> gpui::BackgroundExecutor {
10    current_platform(true).background_executor()
11}
12
13pub fn application() -> gpui::Application {
14    #[cfg(target_family = "wasm")]
15    {
16        application_with_web_backend(gpui_web::WebBackendPreference::Auto)
17    }
18
19    #[cfg(not(target_family = "wasm"))]
20    gpui::Application::with_platform(current_platform(false))
21}
22
23pub fn headless() -> gpui::Application {
24    gpui::Application::with_platform(current_platform(true))
25}
26
27#[cfg(target_family = "wasm")]
28pub use gpui_web::WebBackendPreference;
29
30#[cfg(target_family = "wasm")]
31pub fn application_with_web_backend(backend_preference: WebBackendPreference) -> gpui::Application {
32    let platform = Rc::new(gpui_web::WebPlatform::new_with_backend(
33        true,
34        backend_preference,
35    ));
36    let http_client = std::sync::Arc::new(platform.fetch_http_client());
37    gpui::Application::with_platform(platform).with_http_client(http_client)
38}
39
40/// Unlike `application`, this function returns a single-threaded web application.
41#[cfg(target_family = "wasm")]
42pub fn single_threaded_web() -> gpui::Application {
43    let platform = Rc::new(gpui_web::WebPlatform::new(false));
44    let http_client = std::sync::Arc::new(platform.fetch_http_client());
45    gpui::Application::with_platform(platform).with_http_client(http_client)
46}
47
48/// Initializes panic hooks and logging for the web platform.
49/// Call this before running the application in a wasm_bindgen entrypoint.
50#[cfg(target_family = "wasm")]
51pub fn web_init() {
52    console_error_panic_hook::set_once();
53    gpui_web::init_logging();
54}
55
56/// Returns the default [`Platform`] for the current OS.
57pub fn current_platform(headless: bool) -> Rc<dyn Platform> {
58    #[cfg(target_os = "macos")]
59    {
60        Rc::new(gpui_macos::MacPlatform::new(headless))
61    }
62
63    #[cfg(target_os = "windows")]
64    {
65        Rc::new(
66            gpui_windows::WindowsPlatform::new(headless)
67                .expect("failed to initialize Windows platform"),
68        )
69    }
70
71    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
72    {
73        gpui_linux::current_platform(headless)
74    }
75
76    #[cfg(target_family = "wasm")]
77    {
78        let _ = headless;
79        Rc::new(gpui_web::WebPlatform::new(true))
80    }
81}
82
83/// Returns a new [`HeadlessRenderer`] for the current platform, if available.
84#[cfg(any(feature = "bench-support", feature = "test-support"))]
85pub fn current_headless_renderer() -> Option<Box<dyn gpui::PlatformHeadlessRenderer>> {
86    #[cfg(target_os = "macos")]
87    {
88        Some(Box::new(
89            gpui_macos::metal_renderer::MetalHeadlessRenderer::new(),
90        ))
91    }
92
93    #[cfg(not(target_os = "macos"))]
94    {
95        None
96    }
97}
98
99#[cfg(all(test, target_os = "macos"))]
100mod tests {
101    use super::*;
102    use gpui::{AppContext, Empty, VisualTestAppContext};
103    use std::cell::RefCell;
104    use std::time::Duration;
105
106    // Note: All VisualTestAppContext tests are ignored by default because they require
107    // the macOS main thread. Standard Rust tests run on worker threads, which causes
108    // SIGABRT when interacting with macOS AppKit/Cocoa APIs.
109    //
110    // To run these tests, use:
111    // cargo test -p gpui visual_test_context -- --ignored --test-threads=1
112
113    #[test]
114    #[ignore] // Requires macOS main thread
115    fn test_foreground_tasks_run_with_run_until_parked() {
116        let mut cx = VisualTestAppContext::new(current_platform(false));
117
118        let task_ran = Rc::new(RefCell::new(false));
119
120        // Spawn a foreground task via the App's spawn method
121        // This should use our TestDispatcher, not the MacDispatcher
122        {
123            let task_ran = task_ran.clone();
124            cx.update(|cx| {
125                cx.spawn(async move |_| {
126                    *task_ran.borrow_mut() = true;
127                })
128                .detach();
129            });
130        }
131
132        // The task should not have run yet
133        assert!(!*task_ran.borrow());
134
135        // Run until parked should execute the foreground task
136        cx.run_until_parked();
137
138        // Now the task should have run
139        assert!(*task_ran.borrow());
140    }
141
142    #[test]
143    #[ignore] // Requires macOS main thread
144    fn test_advance_clock_triggers_delayed_tasks() {
145        let mut cx = VisualTestAppContext::new(current_platform(false));
146
147        let task_ran = Rc::new(RefCell::new(false));
148
149        // Spawn a task that waits for a timer
150        {
151            let task_ran = task_ran.clone();
152            let executor = cx.background_executor.clone();
153            cx.update(|cx| {
154                cx.spawn(async move |_| {
155                    executor.timer(Duration::from_millis(500)).await;
156                    *task_ran.borrow_mut() = true;
157                })
158                .detach();
159            });
160        }
161
162        // Run until parked - the task should be waiting on the timer
163        cx.run_until_parked();
164        assert!(!*task_ran.borrow());
165
166        // Advance clock past the timer duration
167        cx.advance_clock(Duration::from_millis(600));
168
169        // Now the task should have completed
170        assert!(*task_ran.borrow());
171    }
172
173    #[test]
174    #[ignore] // Requires macOS main thread - window creation fails on test threads
175    fn test_window_spawn_uses_test_dispatcher() {
176        let mut cx = VisualTestAppContext::new(current_platform(false));
177
178        let task_ran = Rc::new(RefCell::new(false));
179
180        let window = cx
181            .open_offscreen_window_default(|_, cx| cx.new(|_| Empty))
182            .expect("Failed to open window");
183
184        // Spawn a task via window.spawn - this is the critical test case
185        // for tooltip behavior, as tooltips use window.spawn for delayed show
186        {
187            let task_ran = task_ran.clone();
188            cx.update_window(window.into(), |_, window, cx| {
189                window
190                    .spawn(cx, async move |_| {
191                        *task_ran.borrow_mut() = true;
192                    })
193                    .detach();
194            })
195            .ok();
196        }
197
198        // The task should not have run yet
199        assert!(!*task_ran.borrow());
200
201        // Run until parked should execute the foreground task spawned via window
202        cx.run_until_parked();
203
204        // Now the task should have run
205        assert!(*task_ran.borrow());
206    }
207}