| 1 | use crate::{ |
| 2 | Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AsyncApp, AvailableSpace, |
| 3 | BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, DrawPhase, Drawable, |
| 4 | Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, |
| 5 | Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, |
| 6 | Pixels, Platform, PlatformTextSystem, Point, Render, Result, SharedString, Size, |
| 7 | SystemNotification, SystemNotificationResponse, Task, TestDispatcher, TestPlatform, |
| 8 | TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds, |
| 9 | WindowHandle, WindowOptions, WindowVisibility, app::GpuiMode, window::ElementArenaScope, |
| 10 | }; |
| 11 | use anyhow::{anyhow, bail}; |
| 12 | use futures::{Stream, StreamExt, channel::oneshot}; |
| 13 | |
| 14 | use std::{ |
| 15 | cell::RefCell, future::Future, ops::Deref, path::PathBuf, rc::Rc, sync::Arc, time::Duration, |
| 16 | }; |
| 17 | |
| 18 | /// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides |
| 19 | /// an implementation of `Context` with additional methods that are useful in tests. |
| 20 | #[derive(Clone)] |
| 21 | pub struct TestAppContext { |
| 22 | #[doc(hidden)] |
| 23 | pub background_executor: BackgroundExecutor, |
| 24 | #[doc(hidden)] |
| 25 | pub foreground_executor: ForegroundExecutor, |
| 26 | #[doc(hidden)] |
| 27 | pub dispatcher: TestDispatcher, |
| 28 | test_platform: Rc<TestPlatform>, |
| 29 | text_system: Arc<TextSystem>, |
| 30 | fn_name: Option<&'static str>, |
| 31 | on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>, |
| 32 | #[doc(hidden)] |
| 33 | pub app: Rc<AppCell>, |
| 34 | } |
| 35 | |
| 36 | impl AppContext for TestAppContext { |
| 37 | fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> { |
| 38 | let mut app = self.app.borrow_mut(); |
| 39 | app.new(build_entity) |
| 40 | } |
| 41 | |
| 42 | fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> { |
| 43 | let mut app = self.app.borrow_mut(); |
| 44 | app.reserve_entity() |
| 45 | } |
| 46 | |
| 47 | fn insert_entity<T: 'static>( |
| 48 | &mut self, |
| 49 | reservation: crate::Reservation<T>, |
| 50 | build_entity: impl FnOnce(&mut Context<T>) -> T, |
| 51 | ) -> Entity<T> { |
| 52 | let mut app = self.app.borrow_mut(); |
| 53 | app.insert_entity(reservation, build_entity) |
| 54 | } |
| 55 | |
| 56 | fn update_entity<T: 'static, R>( |
| 57 | &mut self, |
| 58 | handle: &Entity<T>, |
| 59 | update: impl FnOnce(&mut T, &mut Context<T>) -> R, |
| 60 | ) -> R { |
| 61 | let mut app = self.app.borrow_mut(); |
| 62 | app.update_entity(handle, update) |
| 63 | } |
| 64 | |
| 65 | fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> super::GpuiBorrow<'a, T> |
| 66 | where |
| 67 | T: 'static, |
| 68 | { |
| 69 | panic!("Cannot use as_mut with a test app context. Try calling update() first") |
| 70 | } |
| 71 | |
| 72 | fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R |
| 73 | where |
| 74 | T: 'static, |
| 75 | { |
| 76 | let app = self.app.borrow(); |
| 77 | app.read_entity(handle, read) |
| 78 | } |
| 79 | |
| 80 | fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T> |
| 81 | where |
| 82 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 83 | { |
| 84 | let mut lock = self.app.borrow_mut(); |
| 85 | lock.update_window(window, f) |
| 86 | } |
| 87 | |
| 88 | fn with_window<R>( |
| 89 | &mut self, |
| 90 | entity_id: EntityId, |
| 91 | f: impl FnOnce(&mut Window, &mut App) -> R, |
| 92 | ) -> Option<R> { |
| 93 | let mut lock = self.app.borrow_mut(); |
| 94 | lock.with_window(entity_id, f) |
| 95 | } |
| 96 | |
| 97 | fn read_window<T, R>( |
| 98 | &self, |
| 99 | window: &WindowHandle<T>, |
| 100 | read: impl FnOnce(Entity<T>, &App) -> R, |
| 101 | ) -> Result<R> |
| 102 | where |
| 103 | T: 'static, |
| 104 | { |
| 105 | let app = self.app.borrow(); |
| 106 | app.read_window(window, read) |
| 107 | } |
| 108 | |
| 109 | fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> |
| 110 | where |
| 111 | R: Send + 'static, |
| 112 | { |
| 113 | self.background_executor.spawn(future) |
| 114 | } |
| 115 | |
| 116 | fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R |
| 117 | where |
| 118 | G: Global, |
| 119 | { |
| 120 | let app = self.app.borrow(); |
| 121 | app.read_global(callback) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | impl TestAppContext { |
| 126 | /// Creates a new `TestAppContext`. Usually you can rely on `#[gpui::test]` to do this for you. |
| 127 | pub fn build(dispatcher: TestDispatcher, fn_name: Option<&'static str>) -> Self { |
| 128 | let arc_dispatcher = Arc::new(dispatcher.clone()); |
| 129 | let background_executor = BackgroundExecutor::new(arc_dispatcher.clone()); |
| 130 | let foreground_executor = ForegroundExecutor::new(arc_dispatcher); |
| 131 | let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone()); |
| 132 | Self::build_with_platform( |
| 133 | dispatcher, |
| 134 | fn_name, |
| 135 | background_executor, |
| 136 | foreground_executor, |
| 137 | platform, |
| 138 | ) |
| 139 | } |
| 140 | |
| 141 | /// Creates a test context backed by the provided platform text system. |
| 142 | pub fn build_with_text_system( |
| 143 | dispatcher: TestDispatcher, |
| 144 | fn_name: Option<&'static str>, |
| 145 | platform_text_system: Arc<dyn PlatformTextSystem>, |
| 146 | ) -> Self { |
| 147 | let arc_dispatcher = Arc::new(dispatcher.clone()); |
| 148 | let background_executor = BackgroundExecutor::new(arc_dispatcher.clone()); |
| 149 | let foreground_executor = ForegroundExecutor::new(arc_dispatcher); |
| 150 | let platform = TestPlatform::with_text_system( |
| 151 | background_executor.clone(), |
| 152 | foreground_executor.clone(), |
| 153 | platform_text_system, |
| 154 | ); |
| 155 | Self::build_with_platform( |
| 156 | dispatcher, |
| 157 | fn_name, |
| 158 | background_executor, |
| 159 | foreground_executor, |
| 160 | platform, |
| 161 | ) |
| 162 | } |
| 163 | |
| 164 | fn build_with_platform( |
| 165 | dispatcher: TestDispatcher, |
| 166 | fn_name: Option<&'static str>, |
| 167 | background_executor: BackgroundExecutor, |
| 168 | foreground_executor: ForegroundExecutor, |
| 169 | platform: Rc<TestPlatform>, |
| 170 | ) -> Self { |
| 171 | let asset_source = Arc::new(()); |
| 172 | let http_client = http_client::FakeHttpClient::with_404_response(); |
| 173 | let text_system = Arc::new(TextSystem::new(platform.text_system())); |
| 174 | |
| 175 | let app = App::new_app(platform.clone(), asset_source, http_client); |
| 176 | app.borrow_mut().mode = GpuiMode::test(); |
| 177 | |
| 178 | Self { |
| 179 | app, |
| 180 | background_executor, |
| 181 | foreground_executor, |
| 182 | dispatcher, |
| 183 | test_platform: platform, |
| 184 | text_system, |
| 185 | fn_name, |
| 186 | on_quit: Rc::new(RefCell::new(Vec::default())), |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// Disables accessibility for subsequently created test windows. |
| 191 | pub fn disable_accessibility(&mut self) { |
| 192 | self.update(|cx| cx.accessibility_force_disabled = true); |
| 193 | } |
| 194 | |
| 195 | /// Skip all drawing operations for the duration of this test. |
| 196 | pub fn skip_drawing(&mut self) { |
| 197 | self.app.borrow_mut().mode = GpuiMode::Test { skip_drawing: true }; |
| 198 | } |
| 199 | |
| 200 | /// Create a single TestAppContext, for non-multi-client tests |
| 201 | pub fn single() -> Self { |
| 202 | let dispatcher = TestDispatcher::new(0); |
| 203 | Self::build(dispatcher, None) |
| 204 | } |
| 205 | |
| 206 | /// The name of the test function that created this `TestAppContext` |
| 207 | pub fn test_function_name(&self) -> Option<&'static str> { |
| 208 | self.fn_name |
| 209 | } |
| 210 | |
| 211 | /// Checks whether there have been any new path prompts received by the platform. |
| 212 | pub fn did_prompt_for_new_path(&self) -> bool { |
| 213 | self.test_platform.did_prompt_for_new_path() |
| 214 | } |
| 215 | |
| 216 | /// Returns the number of active idle sleep prevention tokens. |
| 217 | pub fn active_idle_sleep_preventions(&self) -> usize { |
| 218 | self.test_platform.active_idle_sleep_preventions() |
| 219 | } |
| 220 | |
| 221 | /// Sets the delay for subsequent idle sleep prevention acquisitions. |
| 222 | pub fn set_idle_sleep_prevention_delay(&self, delay: Duration) { |
| 223 | self.test_platform.set_idle_sleep_prevention_delay(delay); |
| 224 | } |
| 225 | |
| 226 | /// Makes subsequent idle sleep prevention acquisitions fail or succeed. |
| 227 | pub fn set_idle_sleep_prevention_fails(&self, fails: bool) { |
| 228 | self.test_platform.set_idle_sleep_prevention_fails(fails); |
| 229 | } |
| 230 | |
| 231 | /// returns a new `TestAppContext` re-using the same executors to interleave tasks. |
| 232 | pub fn new_app(&self) -> TestAppContext { |
| 233 | Self::build(self.dispatcher.clone(), self.fn_name) |
| 234 | } |
| 235 | |
| 236 | /// Called by the test helper to end the test. |
| 237 | /// public so the macro can call it. |
| 238 | pub fn quit(&self) { |
| 239 | self.on_quit.borrow_mut().drain(..).for_each(|f| f()); |
| 240 | self.app.borrow_mut().shutdown(); |
| 241 | } |
| 242 | |
| 243 | /// Register cleanup to run when the test ends. |
| 244 | pub fn on_quit(&mut self, f: impl FnOnce() + 'static) { |
| 245 | self.on_quit.borrow_mut().push(Box::new(f)); |
| 246 | } |
| 247 | |
| 248 | /// Schedules all windows to be redrawn on the next effect cycle. |
| 249 | pub fn refresh(&mut self) -> Result<()> { |
| 250 | let mut app = self.app.borrow_mut(); |
| 251 | app.refresh_windows(); |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | /// Returns an executor (for running tasks in the background) |
| 256 | pub fn executor(&self) -> BackgroundExecutor { |
| 257 | self.background_executor.clone() |
| 258 | } |
| 259 | |
| 260 | /// Returns an executor (for running tasks on the main thread) |
| 261 | pub fn foreground_executor(&self) -> &ForegroundExecutor { |
| 262 | &self.foreground_executor |
| 263 | } |
| 264 | |
| 265 | /// Gives you an `&mut App` for the duration of the closure |
| 266 | pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R { |
| 267 | let mut cx = self.app.borrow_mut(); |
| 268 | cx.update(f) |
| 269 | } |
| 270 | |
| 271 | /// Gives you an `&App` for the duration of the closure |
| 272 | pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R { |
| 273 | let cx = self.app.borrow(); |
| 274 | f(&cx) |
| 275 | } |
| 276 | |
| 277 | /// Adds a new window. The Window will always be backed by a `TestWindow` which |
| 278 | /// can be retrieved with `self.test_window(handle)` |
| 279 | pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V> |
| 280 | where |
| 281 | F: FnOnce(&mut Window, &mut Context<V>) -> V, |
| 282 | V: 'static + Render, |
| 283 | { |
| 284 | let mut cx = self.app.borrow_mut(); |
| 285 | |
| 286 | // Some tests rely on the window size matching the bounds of the test display |
| 287 | let bounds = Bounds::maximized(None, &cx); |
| 288 | cx.open_window( |
| 289 | WindowOptions { |
| 290 | window_bounds: Some(WindowBounds::Windowed(bounds)), |
| 291 | ..Default::default() |
| 292 | }, |
| 293 | |window, cx| cx.new(|cx| build_window(window, cx)), |
| 294 | ) |
| 295 | .unwrap() |
| 296 | } |
| 297 | |
| 298 | /// Opens a new window with a specific size. |
| 299 | /// |
| 300 | /// Unlike `add_window` which uses maximized bounds, this allows controlling |
| 301 | /// the window dimensions, which is important for layout-sensitive tests. |
| 302 | pub fn open_window<F, V>( |
| 303 | &mut self, |
| 304 | window_size: Size<Pixels>, |
| 305 | build_window: F, |
| 306 | ) -> WindowHandle<V> |
| 307 | where |
| 308 | F: FnOnce(&mut Window, &mut Context<V>) -> V, |
| 309 | V: 'static + Render, |
| 310 | { |
| 311 | let mut cx = self.app.borrow_mut(); |
| 312 | cx.open_window( |
| 313 | WindowOptions { |
| 314 | window_bounds: Some(WindowBounds::Windowed(Bounds { |
| 315 | origin: Point::default(), |
| 316 | size: window_size, |
| 317 | })), |
| 318 | ..Default::default() |
| 319 | }, |
| 320 | |window, cx| cx.new(|cx| build_window(window, cx)), |
| 321 | ) |
| 322 | .unwrap() |
| 323 | } |
| 324 | |
| 325 | /// Adds a new window with no content. |
| 326 | pub fn add_empty_window(&mut self) -> &mut VisualTestContext { |
| 327 | let mut cx = self.app.borrow_mut(); |
| 328 | let bounds = Bounds::maximized(None, &cx); |
| 329 | let window = cx |
| 330 | .open_window( |
| 331 | WindowOptions { |
| 332 | window_bounds: Some(WindowBounds::Windowed(bounds)), |
| 333 | ..Default::default() |
| 334 | }, |
| 335 | |_, cx| cx.new(|_| Empty), |
| 336 | ) |
| 337 | .unwrap(); |
| 338 | drop(cx); |
| 339 | let cx = VisualTestContext::from_window(*window.deref(), self).into_mut(); |
| 340 | cx.run_until_parked(); |
| 341 | cx |
| 342 | } |
| 343 | |
| 344 | /// Adds a new window, and returns its root view and a `VisualTestContext` which can be used |
| 345 | /// as a `Window` and `App` for the rest of the test. Typically you would shadow this context with |
| 346 | /// the returned one. `let (view, cx) = cx.add_window_view(...);` |
| 347 | pub fn add_window_view<F, V>( |
| 348 | &mut self, |
| 349 | build_root_view: F, |
| 350 | ) -> (Entity<V>, &mut VisualTestContext) |
| 351 | where |
| 352 | F: FnOnce(&mut Window, &mut Context<V>) -> V, |
| 353 | V: 'static + Render, |
| 354 | { |
| 355 | let mut cx = self.app.borrow_mut(); |
| 356 | let bounds = Bounds::maximized(None, &cx); |
| 357 | let window = cx |
| 358 | .open_window( |
| 359 | WindowOptions { |
| 360 | window_bounds: Some(WindowBounds::Windowed(bounds)), |
| 361 | ..Default::default() |
| 362 | }, |
| 363 | |window, cx| cx.new(|cx| build_root_view(window, cx)), |
| 364 | ) |
| 365 | .unwrap(); |
| 366 | drop(cx); |
| 367 | let view = window.root(self).unwrap(); |
| 368 | let cx = VisualTestContext::from_window(*window.deref(), self).into_mut(); |
| 369 | cx.run_until_parked(); |
| 370 | |
| 371 | // it might be nice to try and cleanup these at the end of each test. |
| 372 | (view, cx) |
| 373 | } |
| 374 | |
| 375 | /// returns the TextSystem |
| 376 | pub fn text_system(&self) -> &Arc<TextSystem> { |
| 377 | &self.text_system |
| 378 | } |
| 379 | |
| 380 | /// Simulates writing to the platform clipboard |
| 381 | pub fn write_to_clipboard(&self, item: ClipboardItem) { |
| 382 | self.test_platform.write_to_clipboard(item) |
| 383 | } |
| 384 | |
| 385 | /// Simulates reading from the platform clipboard. |
| 386 | /// This will return the most recent value from `write_to_clipboard`. |
| 387 | pub fn read_from_clipboard(&self) -> Option<ClipboardItem> { |
| 388 | self.test_platform.read_from_clipboard() |
| 389 | } |
| 390 | |
| 391 | /// Simulates choosing a File in the platform's "Open" dialog. |
| 392 | pub fn simulate_new_path_selection( |
| 393 | &self, |
| 394 | select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>, |
| 395 | ) { |
| 396 | self.test_platform.simulate_new_path_selection(select_path); |
| 397 | } |
| 398 | |
| 399 | /// Simulates responding to a `prompt_for_paths` ("Open") dialog. |
| 400 | pub fn simulate_path_prompt_response( |
| 401 | &self, |
| 402 | select_paths: impl FnOnce(&crate::PathPromptOptions) -> Option<Vec<std::path::PathBuf>>, |
| 403 | ) { |
| 404 | self.test_platform |
| 405 | .simulate_path_prompt_response(select_paths); |
| 406 | } |
| 407 | |
| 408 | /// Returns true if there's a path selection dialog pending. |
| 409 | pub fn did_prompt_for_paths(&self) -> bool { |
| 410 | self.test_platform.did_prompt_for_paths() |
| 411 | } |
| 412 | |
| 413 | /// Simulates clicking a button in an platform-level alert dialog. |
| 414 | #[track_caller] |
| 415 | pub fn simulate_prompt_answer(&self, button: &str) { |
| 416 | self.test_platform.simulate_prompt_answer(button); |
| 417 | } |
| 418 | |
| 419 | /// Returns true if there's an alert dialog open. |
| 420 | pub fn has_pending_prompt(&self) -> bool { |
| 421 | self.test_platform.has_pending_prompt() |
| 422 | } |
| 423 | |
| 424 | /// Returns true if there's an alert dialog open. |
| 425 | pub fn pending_prompt(&self) -> Option<(String, String)> { |
| 426 | self.test_platform.pending_prompt() |
| 427 | } |
| 428 | |
| 429 | /// All the urls that have been opened with cx.open_url() during this test. |
| 430 | pub fn opened_url(&self) -> Option<String> { |
| 431 | self.test_platform.opened_url.borrow().clone() |
| 432 | } |
| 433 | |
| 434 | /// Returns the application identity configured during this test. |
| 435 | pub fn app_identity(&self) -> Option<(SharedString, SharedString)> { |
| 436 | self.test_platform.app_identity() |
| 437 | } |
| 438 | |
| 439 | /// Returns all system notifications shown during this test, in order. |
| 440 | pub fn shown_system_notifications(&self) -> Vec<SystemNotification> { |
| 441 | self.test_platform.shown_system_notifications() |
| 442 | } |
| 443 | |
| 444 | /// Returns the system notifications currently delivered by the test platform. |
| 445 | pub fn delivered_system_notifications(&self) -> Vec<SystemNotification> { |
| 446 | self.test_platform.delivered_system_notifications() |
| 447 | } |
| 448 | |
| 449 | /// Returns the tags of all system notifications dismissed during this test, in order. |
| 450 | pub fn dismissed_system_notifications(&self) -> Vec<SharedString> { |
| 451 | self.test_platform.dismissed_system_notifications() |
| 452 | } |
| 453 | |
| 454 | /// Simulates the user activating a system notification. |
| 455 | pub fn simulate_system_notification_response(&self, response: SystemNotificationResponse) { |
| 456 | self.test_platform |
| 457 | .simulate_system_notification_response(response); |
| 458 | } |
| 459 | |
| 460 | /// Simulates the user resizing the window to the new size. |
| 461 | pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) { |
| 462 | self.test_window(window_handle).simulate_resize(size); |
| 463 | } |
| 464 | |
| 465 | /// Simulates a change in whether the platform is presenting the window. |
| 466 | pub fn simulate_window_visibility_change( |
| 467 | &self, |
| 468 | window_handle: AnyWindowHandle, |
| 469 | visibility: WindowVisibility, |
| 470 | ) { |
| 471 | self.test_window(window_handle) |
| 472 | .simulate_visibility_change(visibility); |
| 473 | } |
| 474 | |
| 475 | /// Simulates visible viewport changes without resizing the window's layout area. |
| 476 | pub fn simulate_window_visual_viewport_change( |
| 477 | &self, |
| 478 | window_handle: AnyWindowHandle, |
| 479 | bounds: Bounds<Pixels>, |
| 480 | ) { |
| 481 | self.test_window(window_handle) |
| 482 | .simulate_visual_viewport_change(bounds); |
| 483 | } |
| 484 | |
| 485 | /// Simulates the window moving to a display with a different scale factor. |
| 486 | pub fn simulate_window_scale_factor_change( |
| 487 | &self, |
| 488 | window_handle: AnyWindowHandle, |
| 489 | scale_factor: f32, |
| 490 | ) { |
| 491 | self.test_window(window_handle) |
| 492 | .simulate_scale_factor_change(scale_factor); |
| 493 | } |
| 494 | |
| 495 | /// Returns true if there's an alert dialog open. |
| 496 | pub fn expect_restart(&self) -> oneshot::Receiver<(Option<PathBuf>, Vec<std::ffi::OsString>)> { |
| 497 | let (tx, rx) = futures::channel::oneshot::channel(); |
| 498 | self.test_platform.expect_restart.borrow_mut().replace(tx); |
| 499 | rx |
| 500 | } |
| 501 | |
| 502 | /// Causes the given sources to be returned if the application queries for screen |
| 503 | /// capture sources. |
| 504 | pub fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) { |
| 505 | self.test_platform.set_screen_capture_sources(sources); |
| 506 | } |
| 507 | |
| 508 | /// Returns all windows open in the test. |
| 509 | pub fn windows(&self) -> Vec<AnyWindowHandle> { |
| 510 | self.app.borrow().windows() |
| 511 | } |
| 512 | |
| 513 | /// Run the given task on the main thread. |
| 514 | #[track_caller] |
| 515 | pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R> |
| 516 | where |
| 517 | Fut: Future<Output = R> + 'static, |
| 518 | R: 'static, |
| 519 | { |
| 520 | self.foreground_executor.spawn(f(self.to_async())) |
| 521 | } |
| 522 | |
| 523 | /// true if the given global is defined |
| 524 | pub fn has_global<G: Global>(&self) -> bool { |
| 525 | let app = self.app.borrow(); |
| 526 | app.has_global::<G>() |
| 527 | } |
| 528 | |
| 529 | /// runs the given closure with a reference to the global |
| 530 | /// panics if `has_global` would return false. |
| 531 | pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R { |
| 532 | let app = self.app.borrow(); |
| 533 | read(app.global(), &app) |
| 534 | } |
| 535 | |
| 536 | /// runs the given closure with a reference to the global (if set) |
| 537 | pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> { |
| 538 | let lock = self.app.borrow(); |
| 539 | Some(read(lock.try_global()?, &lock)) |
| 540 | } |
| 541 | |
| 542 | /// sets the global in this context. |
| 543 | pub fn set_global<G: Global>(&mut self, global: G) { |
| 544 | let mut lock = self.app.borrow_mut(); |
| 545 | lock.update(|cx| cx.set_global(global)) |
| 546 | } |
| 547 | |
| 548 | /// updates the global in this context. (panics if `has_global` would return false) |
| 549 | pub fn update_global<G: Global, R>(&mut self, update: impl FnOnce(&mut G, &mut App) -> R) -> R { |
| 550 | let mut lock = self.app.borrow_mut(); |
| 551 | lock.update(|cx| cx.update_global(update)) |
| 552 | } |
| 553 | |
| 554 | /// Returns an `AsyncApp` which can be used to run tasks that expect to be on a background |
| 555 | /// thread on the current thread in tests. |
| 556 | pub fn to_async(&self) -> AsyncApp { |
| 557 | AsyncApp { |
| 558 | app: Rc::downgrade(&self.app), |
| 559 | background_executor: self.background_executor.clone(), |
| 560 | foreground_executor: self.foreground_executor.clone(), |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | /// Wait until there are no more pending tasks. |
| 565 | pub fn run_until_parked(&self) { |
| 566 | self.dispatcher.run_until_parked(); |
| 567 | } |
| 568 | |
| 569 | /// Simulate dispatching an action to the currently focused node in the window. |
| 570 | pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A) |
| 571 | where |
| 572 | A: Action, |
| 573 | { |
| 574 | window |
| 575 | .update(self, |_, window, cx| { |
| 576 | window.dispatch_action(action.boxed_clone(), cx) |
| 577 | }) |
| 578 | .unwrap(); |
| 579 | |
| 580 | self.background_executor.run_until_parked() |
| 581 | } |
| 582 | |
| 583 | /// simulate_keystrokes takes a space-separated list of keys to type. |
| 584 | /// cx.simulate_keystrokes("cmd-shift-p b k s p enter") |
| 585 | /// in Zed, this will run backspace on the current editor through the command palette. |
| 586 | /// This will also run the background executor until it's parked. |
| 587 | pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) { |
| 588 | for keystroke in keystrokes |
| 589 | .split(' ') |
| 590 | .map(Keystroke::parse) |
| 591 | .map(Result::unwrap) |
| 592 | { |
| 593 | self.dispatch_keystroke(window, keystroke); |
| 594 | } |
| 595 | |
| 596 | self.background_executor.run_until_parked() |
| 597 | } |
| 598 | |
| 599 | /// simulate_input takes a string of text to type. |
| 600 | /// cx.simulate_input("abc") |
| 601 | /// will type abc into your current editor |
| 602 | /// This will also run the background executor until it's parked. |
| 603 | pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) { |
| 604 | for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) { |
| 605 | self.dispatch_keystroke(window, keystroke); |
| 606 | } |
| 607 | |
| 608 | self.background_executor.run_until_parked() |
| 609 | } |
| 610 | |
| 611 | /// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`) |
| 612 | pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) { |
| 613 | self.update_window(window, |_, window, cx| { |
| 614 | window.dispatch_keystroke(keystroke, cx) |
| 615 | }) |
| 616 | .unwrap(); |
| 617 | } |
| 618 | |
| 619 | /// Returns the `TestWindow` backing the given handle. |
| 620 | pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow { |
| 621 | self.app |
| 622 | .borrow_mut() |
| 623 | .windows |
| 624 | .get_mut(window.id) |
| 625 | .unwrap() |
| 626 | .as_deref_mut() |
| 627 | .unwrap() |
| 628 | .platform_window |
| 629 | .as_test() |
| 630 | .unwrap() |
| 631 | .clone() |
| 632 | } |
| 633 | |
| 634 | /// Returns a stream of notifications whenever the Entity is updated. |
| 635 | pub fn notifications<T: 'static>( |
| 636 | &mut self, |
| 637 | entity: &Entity<T>, |
| 638 | ) -> impl Stream<Item = ()> + use<T> { |
| 639 | let (tx, rx) = futures::channel::mpsc::unbounded(); |
| 640 | self.update(|cx| { |
| 641 | cx.observe(entity, { |
| 642 | let tx = tx.clone(); |
| 643 | move |_, _| { |
| 644 | let _ = tx.unbounded_send(()); |
| 645 | } |
| 646 | }) |
| 647 | .detach(); |
| 648 | cx.observe_release(entity, move |_, _| tx.close_channel()) |
| 649 | .detach() |
| 650 | }); |
| 651 | rx |
| 652 | } |
| 653 | |
| 654 | /// Returns a stream of events emitted by the given Entity. |
| 655 | pub fn events<Evt, T: 'static + EventEmitter<Evt>>( |
| 656 | &mut self, |
| 657 | entity: &Entity<T>, |
| 658 | ) -> futures::channel::mpsc::UnboundedReceiver<Evt> |
| 659 | where |
| 660 | Evt: 'static + Clone, |
| 661 | { |
| 662 | let (tx, rx) = futures::channel::mpsc::unbounded(); |
| 663 | entity |
| 664 | .update(self, |_, cx: &mut Context<T>| { |
| 665 | cx.subscribe(entity, move |_entity, _handle, event, _cx| { |
| 666 | let _ = tx.unbounded_send(event.clone()); |
| 667 | }) |
| 668 | }) |
| 669 | .detach(); |
| 670 | rx |
| 671 | } |
| 672 | |
| 673 | /// Runs until the given condition becomes true. (Prefer `run_until_parked` if you |
| 674 | /// don't need to jump in at a specific time). |
| 675 | pub async fn condition<T: 'static>( |
| 676 | &mut self, |
| 677 | entity: &Entity<T>, |
| 678 | mut predicate: impl FnMut(&mut T, &mut Context<T>) -> bool, |
| 679 | ) { |
| 680 | let timer = self.executor().timer(Duration::from_secs(3)); |
| 681 | let mut notifications = self.notifications(entity); |
| 682 | |
| 683 | use futures::FutureExt as _; |
| 684 | use futures_concurrency::future::Race as _; |
| 685 | |
| 686 | ( |
| 687 | async { |
| 688 | loop { |
| 689 | if entity.update(self, &mut predicate) { |
| 690 | return Ok(()); |
| 691 | } |
| 692 | |
| 693 | if notifications.next().await.is_none() { |
| 694 | bail!("entity dropped") |
| 695 | } |
| 696 | } |
| 697 | }, |
| 698 | timer.map(|_| Err(anyhow!("condition timed out"))), |
| 699 | ) |
| 700 | .race() |
| 701 | .await |
| 702 | .unwrap(); |
| 703 | } |
| 704 | |
| 705 | /// Set a name for this App. |
| 706 | #[cfg(any(test, feature = "test-support"))] |
| 707 | pub fn set_name(&mut self, name: &'static str) { |
| 708 | self.update(|cx| cx.name = Some(name)) |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | impl<T: 'static> Entity<T> { |
| 713 | /// Block until the next event is emitted by the entity, then return it. |
| 714 | pub fn next_event<Event>(&self, cx: &mut TestAppContext) -> impl Future<Output = Event> |
| 715 | where |
| 716 | Event: Send + Clone + 'static, |
| 717 | T: EventEmitter<Event>, |
| 718 | { |
| 719 | let (tx, mut rx) = oneshot::channel(); |
| 720 | let mut tx = Some(tx); |
| 721 | let subscription = self.update(cx, |_, cx| { |
| 722 | cx.subscribe(self, move |_, _, event, _| { |
| 723 | if let Some(tx) = tx.take() { |
| 724 | _ = tx.send(event.clone()); |
| 725 | } |
| 726 | }) |
| 727 | }); |
| 728 | |
| 729 | async move { |
| 730 | let event = rx.await.expect("no event emitted"); |
| 731 | drop(subscription); |
| 732 | event |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | impl<V: 'static> Entity<V> { |
| 738 | /// Returns a future that resolves when the view is next updated. |
| 739 | pub fn next_notification( |
| 740 | &self, |
| 741 | advance_clock_by: Duration, |
| 742 | cx: &TestAppContext, |
| 743 | ) -> impl Future<Output = ()> { |
| 744 | use postage::prelude::{Sink as _, Stream as _}; |
| 745 | |
| 746 | let (mut tx, mut rx) = postage::mpsc::channel(1); |
| 747 | let subscription = cx.app.borrow_mut().observe(self, move |_, _| { |
| 748 | tx.try_send(()).ok(); |
| 749 | }); |
| 750 | |
| 751 | cx.executor().advance_clock(advance_clock_by); |
| 752 | |
| 753 | async move { |
| 754 | rx.recv() |
| 755 | .await |
| 756 | .expect("entity dropped while test was waiting for its next notification"); |
| 757 | drop(subscription); |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | impl<V> Entity<V> { |
| 763 | /// Returns a future that resolves when the condition becomes true. |
| 764 | pub fn condition<Evt>( |
| 765 | &self, |
| 766 | cx: &TestAppContext, |
| 767 | mut predicate: impl FnMut(&V, &App) -> bool, |
| 768 | ) -> impl Future<Output = ()> |
| 769 | where |
| 770 | Evt: 'static, |
| 771 | V: EventEmitter<Evt>, |
| 772 | { |
| 773 | use postage::prelude::{Sink as _, Stream as _}; |
| 774 | |
| 775 | let (tx, mut rx) = postage::mpsc::channel(1024); |
| 776 | |
| 777 | let mut cx = cx.app.borrow_mut(); |
| 778 | let subscriptions = ( |
| 779 | cx.observe(self, { |
| 780 | let mut tx = tx.clone(); |
| 781 | move |_, _| { |
| 782 | tx.blocking_send(()).ok(); |
| 783 | } |
| 784 | }), |
| 785 | cx.subscribe(self, { |
| 786 | let mut tx = tx; |
| 787 | move |_, _: &Evt, _| { |
| 788 | tx.blocking_send(()).ok(); |
| 789 | } |
| 790 | }), |
| 791 | ); |
| 792 | |
| 793 | let cx = cx.this.upgrade().unwrap(); |
| 794 | let handle = self.downgrade(); |
| 795 | |
| 796 | async move { |
| 797 | loop { |
| 798 | { |
| 799 | let cx = cx.borrow(); |
| 800 | let cx = &*cx; |
| 801 | if predicate( |
| 802 | handle |
| 803 | .upgrade() |
| 804 | .expect("view dropped with pending condition") |
| 805 | .read(cx), |
| 806 | cx, |
| 807 | ) { |
| 808 | break; |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | rx.recv() |
| 813 | .await |
| 814 | .expect("view dropped with pending condition"); |
| 815 | } |
| 816 | drop(subscriptions); |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | use derive_more::{Deref, DerefMut}; |
| 822 | |
| 823 | use super::{Context, Entity}; |
| 824 | #[derive(Deref, DerefMut, Clone)] |
| 825 | /// A VisualTestContext is the test-equivalent of a `Window` and `App`. It allows you to |
| 826 | /// run window-specific test code. It can be dereferenced to a `TextAppContext`. |
| 827 | pub struct VisualTestContext { |
| 828 | #[deref] |
| 829 | #[deref_mut] |
| 830 | /// cx is the original TestAppContext (you can more easily access this using Deref) |
| 831 | pub cx: TestAppContext, |
| 832 | window: AnyWindowHandle, |
| 833 | } |
| 834 | |
| 835 | impl VisualTestContext { |
| 836 | /// Provides a `Window` and `App` for the duration of the closure. |
| 837 | pub fn update<R>(&mut self, f: impl FnOnce(&mut Window, &mut App) -> R) -> R { |
| 838 | self.cx |
| 839 | .update_window(self.window, |_, window, cx| f(window, cx)) |
| 840 | .unwrap() |
| 841 | } |
| 842 | |
| 843 | /// Creates a new VisualTestContext. You would typically shadow the passed in |
| 844 | /// TestAppContext with this, as this is typically more useful. |
| 845 | /// `let cx = VisualTestContext::from_window(window, cx);` |
| 846 | pub fn from_window(window: AnyWindowHandle, cx: &TestAppContext) -> Self { |
| 847 | Self { |
| 848 | cx: cx.clone(), |
| 849 | window, |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | /// Wait until there are no more pending tasks. |
| 854 | pub fn run_until_parked(&self) { |
| 855 | self.cx.background_executor.run_until_parked(); |
| 856 | } |
| 857 | |
| 858 | /// Dispatch the action to the currently focused node. |
| 859 | pub fn dispatch_action<A>(&mut self, action: A) |
| 860 | where |
| 861 | A: Action, |
| 862 | { |
| 863 | self.cx.dispatch_action(self.window, action) |
| 864 | } |
| 865 | |
| 866 | /// Read the title off the window (set by `Window#set_window_title`) |
| 867 | pub fn window_title(&mut self) -> Option<String> { |
| 868 | self.cx.test_window(self.window).0.lock().title.clone() |
| 869 | } |
| 870 | |
| 871 | /// Read the document path off the window (set by `Window#set_document_path`) |
| 872 | pub fn document_path(&mut self) -> Option<std::path::PathBuf> { |
| 873 | self.cx |
| 874 | .test_window(self.window) |
| 875 | .0 |
| 876 | .lock() |
| 877 | .document_path |
| 878 | .clone() |
| 879 | } |
| 880 | |
| 881 | /// Simulate a sequence of keystrokes `cx.simulate_keystrokes("cmd-p escape")` |
| 882 | /// Automatically runs until parked. |
| 883 | pub fn simulate_keystrokes(&mut self, keystrokes: &str) { |
| 884 | self.cx.simulate_keystrokes(self.window, keystrokes) |
| 885 | } |
| 886 | |
| 887 | /// Simulate typing text `cx.simulate_input("hello")` |
| 888 | /// Automatically runs until parked. |
| 889 | pub fn simulate_input(&mut self, input: &str) { |
| 890 | self.cx.simulate_input(self.window, input) |
| 891 | } |
| 892 | |
| 893 | /// Simulate a mouse move event to the given point |
| 894 | pub fn simulate_mouse_move( |
| 895 | &mut self, |
| 896 | position: Point<Pixels>, |
| 897 | button: impl Into<Option<MouseButton>>, |
| 898 | modifiers: Modifiers, |
| 899 | ) { |
| 900 | self.simulate_event(MouseMoveEvent { |
| 901 | position, |
| 902 | modifiers, |
| 903 | pressed_button: button.into(), |
| 904 | }) |
| 905 | } |
| 906 | |
| 907 | /// Simulate a mouse down event to the given point |
| 908 | pub fn simulate_mouse_down( |
| 909 | &mut self, |
| 910 | position: Point<Pixels>, |
| 911 | button: MouseButton, |
| 912 | modifiers: Modifiers, |
| 913 | ) { |
| 914 | self.simulate_event(MouseDownEvent { |
| 915 | position, |
| 916 | modifiers, |
| 917 | button, |
| 918 | click_count: 1, |
| 919 | first_mouse: false, |
| 920 | }) |
| 921 | } |
| 922 | |
| 923 | /// Simulate a mouse up event to the given point |
| 924 | pub fn simulate_mouse_up( |
| 925 | &mut self, |
| 926 | position: Point<Pixels>, |
| 927 | button: MouseButton, |
| 928 | modifiers: Modifiers, |
| 929 | ) { |
| 930 | self.simulate_event(MouseUpEvent { |
| 931 | position, |
| 932 | modifiers, |
| 933 | button, |
| 934 | click_count: 1, |
| 935 | }) |
| 936 | } |
| 937 | |
| 938 | /// Simulate a primary mouse click at the given point |
| 939 | pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) { |
| 940 | self.simulate_event(MouseDownEvent { |
| 941 | position, |
| 942 | modifiers, |
| 943 | button: MouseButton::Left, |
| 944 | click_count: 1, |
| 945 | first_mouse: false, |
| 946 | }); |
| 947 | self.simulate_event(MouseUpEvent { |
| 948 | position, |
| 949 | modifiers, |
| 950 | button: MouseButton::Left, |
| 951 | click_count: 1, |
| 952 | }); |
| 953 | } |
| 954 | |
| 955 | /// Simulate a modifiers changed event |
| 956 | pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) { |
| 957 | self.simulate_event(ModifiersChangedEvent { |
| 958 | modifiers, |
| 959 | capslock: Capslock { on: false }, |
| 960 | }) |
| 961 | } |
| 962 | |
| 963 | /// Simulate a capslock changed event |
| 964 | pub fn simulate_capslock_change(&mut self, on: bool) { |
| 965 | self.simulate_event(ModifiersChangedEvent { |
| 966 | modifiers: Modifiers::none(), |
| 967 | capslock: Capslock { on }, |
| 968 | }) |
| 969 | } |
| 970 | |
| 971 | /// Simulates the user resizing the window to the new size. |
| 972 | pub fn simulate_resize(&self, size: Size<Pixels>) { |
| 973 | self.simulate_window_resize(self.window, size) |
| 974 | } |
| 975 | |
| 976 | /// Simulates a change in whether the platform is presenting this window. |
| 977 | pub fn simulate_visibility_change(&self, visibility: WindowVisibility) { |
| 978 | self.simulate_window_visibility_change(self.window, visibility); |
| 979 | } |
| 980 | |
| 981 | /// Simulates the window moving to a display with a different scale factor. |
| 982 | pub fn simulate_scale_factor_change(&self, scale_factor: f32) { |
| 983 | self.simulate_window_scale_factor_change(self.window, scale_factor) |
| 984 | } |
| 985 | |
| 986 | /// Returns the bounds of the element with the given debug selector. |
| 987 | /// |
| 988 | /// Returns `None` in builds without `debug_assertions`, which don't record |
| 989 | /// selectors; see [`crate::InteractiveElement::debug_selector`]. |
| 990 | pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> { |
| 991 | self.update(|window, _| window.rendered_frame.debug_bounds.get(selector).copied()) |
| 992 | } |
| 993 | |
| 994 | /// Draw an element to the window. Useful for simulating events or actions |
| 995 | pub fn draw<E>( |
| 996 | &mut self, |
| 997 | origin: Point<Pixels>, |
| 998 | space: impl Into<Size<AvailableSpace>>, |
| 999 | f: impl FnOnce(&mut Window, &mut App) -> E, |
| 1000 | ) -> (E::RequestLayoutState, E::PrepaintState) |
| 1001 | where |
| 1002 | E: Element, |
| 1003 | { |
| 1004 | self.update(|window, cx| { |
| 1005 | let arena_scope = ElementArenaScope::enter(&cx.element_arena); |
| 1006 | |
| 1007 | window.invalidator.set_phase(DrawPhase::Prepaint); |
| 1008 | let mut element = Drawable::new(f(window, cx)); |
| 1009 | element.layout_as_root(space.into(), window, cx); |
| 1010 | window.with_absolute_element_offset(origin, |window| element.prepaint(window, cx)); |
| 1011 | |
| 1012 | window.invalidator.set_phase(DrawPhase::Paint); |
| 1013 | let (request_layout_state, prepaint_state) = element.paint(window, cx); |
| 1014 | |
| 1015 | window.invalidator.set_phase(DrawPhase::None); |
| 1016 | window.refresh(); |
| 1017 | |
| 1018 | drop(element); |
| 1019 | arena_scope.exit(&cx.element_arena).clear(cx); |
| 1020 | |
| 1021 | (request_layout_state, prepaint_state) |
| 1022 | }) |
| 1023 | } |
| 1024 | |
| 1025 | /// Simulate an event from the platform, e.g. a ScrollWheelEvent |
| 1026 | /// Make sure you've called [VisualTestContext::draw] first! |
| 1027 | pub fn simulate_event<E: InputEvent>(&mut self, event: E) { |
| 1028 | self.test_window(self.window) |
| 1029 | .simulate_input(event.to_platform_input()); |
| 1030 | self.background_executor.run_until_parked(); |
| 1031 | } |
| 1032 | |
| 1033 | /// Simulates the user blurring the window. |
| 1034 | pub fn deactivate_window(&mut self) { |
| 1035 | if Some(self.window) == self.test_platform.active_window() { |
| 1036 | self.test_platform.set_active_window(None) |
| 1037 | } |
| 1038 | self.background_executor.run_until_parked(); |
| 1039 | } |
| 1040 | |
| 1041 | /// Simulates the user closing the window. |
| 1042 | /// Returns true if the window was closed. |
| 1043 | pub fn simulate_close(&mut self) -> bool { |
| 1044 | let handler = self |
| 1045 | .cx |
| 1046 | .update_window(self.window, |_, window, _| { |
| 1047 | window |
| 1048 | .platform_window |
| 1049 | .as_test() |
| 1050 | .unwrap() |
| 1051 | .0 |
| 1052 | .lock() |
| 1053 | .should_close_handler |
| 1054 | .take() |
| 1055 | }) |
| 1056 | .unwrap(); |
| 1057 | if let Some(mut handler) = handler { |
| 1058 | let should_close = handler(); |
| 1059 | self.cx |
| 1060 | .update_window(self.window, |_, window, _| { |
| 1061 | window.platform_window.on_should_close(handler); |
| 1062 | }) |
| 1063 | .unwrap(); |
| 1064 | should_close |
| 1065 | } else { |
| 1066 | false |
| 1067 | } |
| 1068 | } |
| 1069 | |
| 1070 | /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods). |
| 1071 | /// This method internally retains the VisualTestContext until the end of the test. |
| 1072 | pub fn into_mut(self) -> &'static mut Self { |
| 1073 | let ptr = Box::into_raw(Box::new(self)); |
| 1074 | // safety: on_quit will be called after the test has finished. |
| 1075 | // the executor will ensure that all tasks related to the test have stopped. |
| 1076 | // so there is no way for cx to be accessed after on_quit is called. |
| 1077 | // todo: This is unsound under stacked borrows (also tree borrows probably?) |
| 1078 | // the mutable reference invalidates `ptr` which is later used in the closure |
| 1079 | let cx = unsafe { &mut *ptr }; |
| 1080 | cx.on_quit(move || unsafe { |
| 1081 | drop(Box::from_raw(ptr)); |
| 1082 | }); |
| 1083 | cx |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | impl AppContext for VisualTestContext { |
| 1088 | fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> { |
| 1089 | self.window |
| 1090 | .update(&mut self.cx, |_, _, cx| cx.new(build_entity)) |
| 1091 | .expect("window was unexpectedly closed") |
| 1092 | } |
| 1093 | |
| 1094 | fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> { |
| 1095 | self.cx.reserve_entity() |
| 1096 | } |
| 1097 | |
| 1098 | fn insert_entity<T: 'static>( |
| 1099 | &mut self, |
| 1100 | reservation: crate::Reservation<T>, |
| 1101 | build_entity: impl FnOnce(&mut Context<T>) -> T, |
| 1102 | ) -> Entity<T> { |
| 1103 | self.window |
| 1104 | .update(&mut self.cx, |_, _, cx| { |
| 1105 | cx.insert_entity(reservation, build_entity) |
| 1106 | }) |
| 1107 | .expect("window was unexpectedly closed") |
| 1108 | } |
| 1109 | |
| 1110 | fn update_entity<T, R>( |
| 1111 | &mut self, |
| 1112 | handle: &Entity<T>, |
| 1113 | update: impl FnOnce(&mut T, &mut Context<T>) -> R, |
| 1114 | ) -> R |
| 1115 | where |
| 1116 | T: 'static, |
| 1117 | { |
| 1118 | self.cx.update_entity(handle, update) |
| 1119 | } |
| 1120 | |
| 1121 | fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> super::GpuiBorrow<'a, T> |
| 1122 | where |
| 1123 | T: 'static, |
| 1124 | { |
| 1125 | self.cx.as_mut(handle) |
| 1126 | } |
| 1127 | |
| 1128 | fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R |
| 1129 | where |
| 1130 | T: 'static, |
| 1131 | { |
| 1132 | self.cx.read_entity(handle, read) |
| 1133 | } |
| 1134 | |
| 1135 | fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T> |
| 1136 | where |
| 1137 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 1138 | { |
| 1139 | self.cx.update_window(window, f) |
| 1140 | } |
| 1141 | |
| 1142 | fn with_window<R>( |
| 1143 | &mut self, |
| 1144 | entity_id: EntityId, |
| 1145 | f: impl FnOnce(&mut Window, &mut App) -> R, |
| 1146 | ) -> Option<R> { |
| 1147 | self.cx.with_window(entity_id, f) |
| 1148 | } |
| 1149 | |
| 1150 | fn read_window<T, R>( |
| 1151 | &self, |
| 1152 | window: &WindowHandle<T>, |
| 1153 | read: impl FnOnce(Entity<T>, &App) -> R, |
| 1154 | ) -> Result<R> |
| 1155 | where |
| 1156 | T: 'static, |
| 1157 | { |
| 1158 | self.cx.read_window(window, read) |
| 1159 | } |
| 1160 | |
| 1161 | fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> |
| 1162 | where |
| 1163 | R: Send + 'static, |
| 1164 | { |
| 1165 | self.cx.background_spawn(future) |
| 1166 | } |
| 1167 | |
| 1168 | fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R |
| 1169 | where |
| 1170 | G: Global, |
| 1171 | { |
| 1172 | self.cx.read_global(callback) |
| 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | impl VisualContext for VisualTestContext { |
| 1177 | type Result<T> = T; |
| 1178 | |
| 1179 | /// Get the underlying window handle underlying this context. |
| 1180 | fn window_handle(&self) -> AnyWindowHandle { |
| 1181 | self.window |
| 1182 | } |
| 1183 | |
| 1184 | fn new_window_entity<T: 'static>( |
| 1185 | &mut self, |
| 1186 | build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T, |
| 1187 | ) -> Entity<T> { |
| 1188 | self.window |
| 1189 | .update(&mut self.cx, |_, window, cx| { |
| 1190 | cx.new(|cx| build_entity(window, cx)) |
| 1191 | }) |
| 1192 | .expect("window was unexpectedly closed") |
| 1193 | } |
| 1194 | |
| 1195 | fn update_window_entity<V: 'static, R>( |
| 1196 | &mut self, |
| 1197 | view: &Entity<V>, |
| 1198 | update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R, |
| 1199 | ) -> R { |
| 1200 | let view = view.clone(); |
| 1201 | self.cx |
| 1202 | .app |
| 1203 | .borrow_mut() |
| 1204 | .with_window(view.entity_id(), |window, app| { |
| 1205 | view.update(app, |v, cx| update(v, window, cx)) |
| 1206 | }) |
| 1207 | .expect("entity has no current window; use `update` instead of `update_in`") |
| 1208 | } |
| 1209 | |
| 1210 | fn replace_root_view<V>( |
| 1211 | &mut self, |
| 1212 | build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V, |
| 1213 | ) -> Entity<V> |
| 1214 | where |
| 1215 | V: 'static + Render, |
| 1216 | { |
| 1217 | self.window |
| 1218 | .update(&mut self.cx, |_, window, cx| { |
| 1219 | window.replace_root(cx, build_view) |
| 1220 | }) |
| 1221 | .expect("window was unexpectedly closed") |
| 1222 | } |
| 1223 | |
| 1224 | fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) { |
| 1225 | self.window |
| 1226 | .update(&mut self.cx, |_, window, cx| { |
| 1227 | view.read(cx).focus_handle(cx).focus(window, cx) |
| 1228 | }) |
| 1229 | .expect("window was unexpectedly closed") |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | impl AnyWindowHandle { |
| 1234 | /// Creates the given view in this window. |
| 1235 | pub fn build_entity<V: Render + 'static>( |
| 1236 | &self, |
| 1237 | cx: &mut TestAppContext, |
| 1238 | build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V, |
| 1239 | ) -> Entity<V> { |
| 1240 | self.update(cx, |_, window, cx| cx.new(|cx| build_view(window, cx))) |
| 1241 | .unwrap() |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | #[cfg(test)] |
| 1246 | mod tests { |
| 1247 | use crate::{ |
| 1248 | PathPromptOptions, SystemNotification, SystemNotificationAction, |
| 1249 | SystemNotificationResponse, TestAppContext, |
| 1250 | }; |
| 1251 | use std::cell::RefCell; |
| 1252 | use std::path::PathBuf; |
| 1253 | use std::rc::Rc; |
| 1254 | |
| 1255 | #[gpui::test] |
| 1256 | async fn test_system_notifications_require_identity_and_replace_matching_tags( |
| 1257 | cx: &mut TestAppContext, |
| 1258 | ) { |
| 1259 | cx.update(|cx| { |
| 1260 | cx.show_system_notification(SystemNotification { |
| 1261 | tag: "thread-1".into(), |
| 1262 | title: "Task started".into(), |
| 1263 | body: "Running tests".into(), |
| 1264 | actions: Vec::new(), |
| 1265 | }); |
| 1266 | }); |
| 1267 | assert!(cx.shown_system_notifications().is_empty()); |
| 1268 | assert!(cx.delivered_system_notifications().is_empty()); |
| 1269 | |
| 1270 | cx.update(|cx| { |
| 1271 | cx.set_app_identity("com.example.tasks", "Tasks"); |
| 1272 | cx.show_system_notification(SystemNotification { |
| 1273 | tag: "thread-1".into(), |
| 1274 | title: "Task started".into(), |
| 1275 | body: "Running tests".into(), |
| 1276 | actions: Vec::new(), |
| 1277 | }); |
| 1278 | cx.show_system_notification(SystemNotification { |
| 1279 | tag: "thread-1".into(), |
| 1280 | title: "Task finished".into(), |
| 1281 | body: "All tests passed".into(), |
| 1282 | actions: vec![SystemNotificationAction { |
| 1283 | id: "open".into(), |
| 1284 | label: "Open".into(), |
| 1285 | }], |
| 1286 | }); |
| 1287 | }); |
| 1288 | |
| 1289 | assert_eq!( |
| 1290 | cx.app_identity(), |
| 1291 | Some(("com.example.tasks".into(), "Tasks".into())) |
| 1292 | ); |
| 1293 | assert_eq!(cx.shown_system_notifications().len(), 2); |
| 1294 | assert_eq!( |
| 1295 | cx.delivered_system_notifications(), |
| 1296 | [SystemNotification { |
| 1297 | tag: "thread-1".into(), |
| 1298 | title: "Task finished".into(), |
| 1299 | body: "All tests passed".into(), |
| 1300 | actions: vec![SystemNotificationAction { |
| 1301 | id: "open".into(), |
| 1302 | label: "Open".into(), |
| 1303 | }], |
| 1304 | }] |
| 1305 | ); |
| 1306 | |
| 1307 | cx.update(|cx| cx.dismiss_system_notification("thread-1")); |
| 1308 | assert!(cx.delivered_system_notifications().is_empty()); |
| 1309 | assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]); |
| 1310 | } |
| 1311 | |
| 1312 | #[gpui::test] |
| 1313 | async fn test_system_notification_body_and_action_responses(cx: &mut TestAppContext) { |
| 1314 | let responses = Rc::new(RefCell::new(Vec::new())); |
| 1315 | cx.update(|cx| { |
| 1316 | cx.on_system_notification_response({ |
| 1317 | let responses = responses.clone(); |
| 1318 | move |response, _cx| responses.borrow_mut().push(response) |
| 1319 | }); |
| 1320 | }); |
| 1321 | |
| 1322 | cx.simulate_system_notification_response(SystemNotificationResponse { |
| 1323 | tag: "thread-1".into(), |
| 1324 | action_id: None, |
| 1325 | }); |
| 1326 | cx.simulate_system_notification_response(SystemNotificationResponse { |
| 1327 | tag: "thread-1".into(), |
| 1328 | action_id: Some("default".into()), |
| 1329 | }); |
| 1330 | |
| 1331 | assert_eq!( |
| 1332 | responses.borrow().as_slice(), |
| 1333 | &[ |
| 1334 | SystemNotificationResponse { |
| 1335 | tag: "thread-1".into(), |
| 1336 | action_id: None, |
| 1337 | }, |
| 1338 | SystemNotificationResponse { |
| 1339 | tag: "thread-1".into(), |
| 1340 | action_id: Some("default".into()), |
| 1341 | }, |
| 1342 | ] |
| 1343 | ); |
| 1344 | } |
| 1345 | |
| 1346 | #[gpui::test] |
| 1347 | async fn test_system_notification_response_handler_can_be_replaced(cx: &mut TestAppContext) { |
| 1348 | let first_responses = Rc::new(RefCell::new(Vec::new())); |
| 1349 | let second_responses = Rc::new(RefCell::new(Vec::new())); |
| 1350 | cx.update(|cx| { |
| 1351 | cx.on_system_notification_response({ |
| 1352 | let first_responses = first_responses.clone(); |
| 1353 | move |response, _cx| first_responses.borrow_mut().push(response) |
| 1354 | }); |
| 1355 | cx.on_system_notification_response({ |
| 1356 | let second_responses = second_responses.clone(); |
| 1357 | move |response, _cx| second_responses.borrow_mut().push(response) |
| 1358 | }); |
| 1359 | }); |
| 1360 | |
| 1361 | let response = SystemNotificationResponse { |
| 1362 | tag: "thread-1".into(), |
| 1363 | action_id: None, |
| 1364 | }; |
| 1365 | cx.simulate_system_notification_response(response.clone()); |
| 1366 | |
| 1367 | assert!(first_responses.borrow().is_empty()); |
| 1368 | assert_eq!(second_responses.borrow().as_slice(), &[response]); |
| 1369 | } |
| 1370 | |
| 1371 | #[gpui::test] |
| 1372 | async fn test_system_notification_response_handler_can_reenter_app(cx: &mut TestAppContext) { |
| 1373 | cx.update(|cx| { |
| 1374 | cx.set_app_identity("com.example.tasks", "Tasks"); |
| 1375 | cx.show_system_notification(SystemNotification { |
| 1376 | tag: "thread-1".into(), |
| 1377 | title: "Task finished".into(), |
| 1378 | body: "All tests passed".into(), |
| 1379 | actions: Vec::new(), |
| 1380 | }); |
| 1381 | cx.on_system_notification_response(|response, cx| { |
| 1382 | cx.dismiss_system_notification(&response.tag); |
| 1383 | }); |
| 1384 | }); |
| 1385 | |
| 1386 | cx.simulate_system_notification_response(SystemNotificationResponse { |
| 1387 | tag: "thread-1".into(), |
| 1388 | action_id: None, |
| 1389 | }); |
| 1390 | |
| 1391 | assert!(cx.delivered_system_notifications().is_empty()); |
| 1392 | assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]); |
| 1393 | } |
| 1394 | |
| 1395 | #[gpui::test] |
| 1396 | async fn test_simulate_path_prompt_response(cx: &mut TestAppContext) { |
| 1397 | assert!(!cx.did_prompt_for_paths()); |
| 1398 | |
| 1399 | let receiver = cx.update(|cx| { |
| 1400 | cx.prompt_for_paths(PathPromptOptions { |
| 1401 | files: false, |
| 1402 | directories: true, |
| 1403 | multiple: true, |
| 1404 | prompt: None, |
| 1405 | }) |
| 1406 | }); |
| 1407 | assert!(cx.did_prompt_for_paths()); |
| 1408 | |
| 1409 | let selected = vec![PathBuf::from("/a"), PathBuf::from("/b")]; |
| 1410 | cx.simulate_path_prompt_response({ |
| 1411 | let selected = selected.clone(); |
| 1412 | move |options| { |
| 1413 | assert!(options.multiple); |
| 1414 | Some(selected) |
| 1415 | } |
| 1416 | }); |
| 1417 | assert!(!cx.did_prompt_for_paths()); |
| 1418 | |
| 1419 | let response = receiver.await.unwrap().unwrap(); |
| 1420 | assert_eq!(response, Some(selected)); |
| 1421 | } |
| 1422 | |
| 1423 | #[gpui::test] |
| 1424 | async fn test_simulate_path_prompt_cancellation(cx: &mut TestAppContext) { |
| 1425 | let receiver = cx.update(|cx| { |
| 1426 | cx.prompt_for_paths(PathPromptOptions { |
| 1427 | files: true, |
| 1428 | directories: false, |
| 1429 | multiple: false, |
| 1430 | prompt: None, |
| 1431 | }) |
| 1432 | }); |
| 1433 | |
| 1434 | cx.simulate_path_prompt_response(|_options| None); |
| 1435 | |
| 1436 | let response = receiver.await.unwrap().unwrap(); |
| 1437 | assert_eq!(response, None); |
| 1438 | } |
| 1439 | } |