test_context.rs

   1use crate::{
   2    Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AsyncApp, AvailableSpace,
   3    BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, DrawPhase, Drawable,
   4    Element, Empty, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke, Modifiers,
   5    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
   6    Platform, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform,
   7    TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds,
   8    WindowHandle, WindowOptions, app::GpuiMode,
   9};
  10use anyhow::{anyhow, bail};
  11use futures::{Stream, StreamExt, channel::oneshot};
  12use rand::{SeedableRng, rngs::StdRng};
  13use std::{
  14    cell::RefCell, future::Future, ops::Deref, path::PathBuf, rc::Rc, sync::Arc, time::Duration,
  15};
  16
  17/// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides
  18/// an implementation of `Context` with additional methods that are useful in tests.
  19#[derive(Clone)]
  20pub struct TestAppContext {
  21    #[doc(hidden)]
  22    pub app: Rc<AppCell>,
  23    #[doc(hidden)]
  24    pub background_executor: BackgroundExecutor,
  25    #[doc(hidden)]
  26    pub foreground_executor: ForegroundExecutor,
  27    #[doc(hidden)]
  28    pub dispatcher: TestDispatcher,
  29    test_platform: Rc<TestPlatform>,
  30    text_system: Arc<TextSystem>,
  31    fn_name: Option<&'static str>,
  32    on_quit: Rc<RefCell<Vec<Box<dyn FnOnce() + 'static>>>>,
  33}
  34
  35impl AppContext for TestAppContext {
  36    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
  37        let mut app = self.app.borrow_mut();
  38        app.new(build_entity)
  39    }
  40
  41    fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> {
  42        let mut app = self.app.borrow_mut();
  43        app.reserve_entity()
  44    }
  45
  46    fn insert_entity<T: 'static>(
  47        &mut self,
  48        reservation: crate::Reservation<T>,
  49        build_entity: impl FnOnce(&mut Context<T>) -> T,
  50    ) -> Entity<T> {
  51        let mut app = self.app.borrow_mut();
  52        app.insert_entity(reservation, build_entity)
  53    }
  54
  55    fn update_entity<T: 'static, R>(
  56        &mut self,
  57        handle: &Entity<T>,
  58        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
  59    ) -> R {
  60        let mut app = self.app.borrow_mut();
  61        app.update_entity(handle, update)
  62    }
  63
  64    fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> super::GpuiBorrow<'a, T>
  65    where
  66        T: 'static,
  67    {
  68        panic!("Cannot use as_mut with a test app context. Try calling update() first")
  69    }
  70
  71    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
  72    where
  73        T: 'static,
  74    {
  75        let app = self.app.borrow();
  76        app.read_entity(handle, read)
  77    }
  78
  79    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
  80    where
  81        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
  82    {
  83        let mut lock = self.app.borrow_mut();
  84        lock.update_window(window, f)
  85    }
  86
  87    fn read_window<T, R>(
  88        &self,
  89        window: &WindowHandle<T>,
  90        read: impl FnOnce(Entity<T>, &App) -> R,
  91    ) -> Result<R>
  92    where
  93        T: 'static,
  94    {
  95        let app = self.app.borrow();
  96        app.read_window(window, read)
  97    }
  98
  99    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
 100    where
 101        R: Send + 'static,
 102    {
 103        self.background_executor.spawn(future)
 104    }
 105
 106    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
 107    where
 108        G: Global,
 109    {
 110        let app = self.app.borrow();
 111        app.read_global(callback)
 112    }
 113}
 114
 115impl TestAppContext {
 116    /// Creates a new `TestAppContext`. Usually you can rely on `#[gpui::test]` to do this for you.
 117    pub fn build(dispatcher: TestDispatcher, fn_name: Option<&'static str>) -> Self {
 118        let arc_dispatcher = Arc::new(dispatcher.clone());
 119        let liveness = std::sync::Arc::new(());
 120        let background_executor = BackgroundExecutor::new(arc_dispatcher.clone());
 121        let foreground_executor =
 122            ForegroundExecutor::new(arc_dispatcher, Arc::downgrade(&liveness));
 123        let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
 124        let asset_source = Arc::new(());
 125        let http_client = http_client::FakeHttpClient::with_404_response();
 126        let text_system = Arc::new(TextSystem::new(platform.text_system()));
 127
 128        let app = App::new_app(platform.clone(), liveness, asset_source, http_client);
 129        app.borrow_mut().mode = GpuiMode::test();
 130
 131        Self {
 132            app,
 133            background_executor,
 134            foreground_executor,
 135            dispatcher,
 136            test_platform: platform,
 137            text_system,
 138            fn_name,
 139            on_quit: Rc::new(RefCell::new(Vec::default())),
 140        }
 141    }
 142
 143    /// Skip all drawing operations for the duration of this test.
 144    pub fn skip_drawing(&mut self) {
 145        self.app.borrow_mut().mode = GpuiMode::Test { skip_drawing: true };
 146    }
 147
 148    /// Create a single TestAppContext, for non-multi-client tests
 149    pub fn single() -> Self {
 150        let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
 151        Self::build(dispatcher, None)
 152    }
 153
 154    /// The name of the test function that created this `TestAppContext`
 155    pub fn test_function_name(&self) -> Option<&'static str> {
 156        self.fn_name
 157    }
 158
 159    /// Checks whether there have been any new path prompts received by the platform.
 160    pub fn did_prompt_for_new_path(&self) -> bool {
 161        self.test_platform.did_prompt_for_new_path()
 162    }
 163
 164    /// returns a new `TestAppContext` re-using the same executors to interleave tasks.
 165    pub fn new_app(&self) -> TestAppContext {
 166        Self::build(self.dispatcher.clone(), self.fn_name)
 167    }
 168
 169    /// Called by the test helper to end the test.
 170    /// public so the macro can call it.
 171    pub fn quit(&self) {
 172        self.on_quit.borrow_mut().drain(..).for_each(|f| f());
 173        self.app.borrow_mut().shutdown();
 174    }
 175
 176    /// Register cleanup to run when the test ends.
 177    pub fn on_quit(&mut self, f: impl FnOnce() + 'static) {
 178        self.on_quit.borrow_mut().push(Box::new(f));
 179    }
 180
 181    /// Schedules all windows to be redrawn on the next effect cycle.
 182    pub fn refresh(&mut self) -> Result<()> {
 183        let mut app = self.app.borrow_mut();
 184        app.refresh_windows();
 185        Ok(())
 186    }
 187
 188    /// Returns an executor (for running tasks in the background)
 189    pub fn executor(&self) -> BackgroundExecutor {
 190        self.background_executor.clone()
 191    }
 192
 193    /// Returns an executor (for running tasks on the main thread)
 194    pub fn foreground_executor(&self) -> &ForegroundExecutor {
 195        &self.foreground_executor
 196    }
 197
 198    #[expect(clippy::wrong_self_convention)]
 199    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
 200        let mut cx = self.app.borrow_mut();
 201        cx.new(build_entity)
 202    }
 203
 204    /// Gives you an `&mut App` for the duration of the closure
 205    pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
 206        let mut cx = self.app.borrow_mut();
 207        cx.update(f)
 208    }
 209
 210    /// Gives you an `&App` for the duration of the closure
 211    pub fn read<R>(&self, f: impl FnOnce(&App) -> R) -> R {
 212        let cx = self.app.borrow();
 213        f(&cx)
 214    }
 215
 216    /// Adds a new window. The Window will always be backed by a `TestWindow` which
 217    /// can be retrieved with `self.test_window(handle)`
 218    pub fn add_window<F, V>(&mut self, build_window: F) -> WindowHandle<V>
 219    where
 220        F: FnOnce(&mut Window, &mut Context<V>) -> V,
 221        V: 'static + Render,
 222    {
 223        let mut cx = self.app.borrow_mut();
 224
 225        // Some tests rely on the window size matching the bounds of the test display
 226        let bounds = Bounds::maximized(None, &cx);
 227        cx.open_window(
 228            WindowOptions {
 229                window_bounds: Some(WindowBounds::Windowed(bounds)),
 230                ..Default::default()
 231            },
 232            |window, cx| cx.new(|cx| build_window(window, cx)),
 233        )
 234        .unwrap()
 235    }
 236
 237    /// Adds a new window with no content.
 238    pub fn add_empty_window(&mut self) -> &mut VisualTestContext {
 239        let mut cx = self.app.borrow_mut();
 240        let bounds = Bounds::maximized(None, &cx);
 241        let window = cx
 242            .open_window(
 243                WindowOptions {
 244                    window_bounds: Some(WindowBounds::Windowed(bounds)),
 245                    ..Default::default()
 246                },
 247                |_, cx| cx.new(|_| Empty),
 248            )
 249            .unwrap();
 250        drop(cx);
 251        let cx = VisualTestContext::from_window(*window.deref(), self).into_mut();
 252        cx.run_until_parked();
 253        cx
 254    }
 255
 256    /// Adds a new window, and returns its root view and a `VisualTestContext` which can be used
 257    /// as a `Window` and `App` for the rest of the test. Typically you would shadow this context with
 258    /// the returned one. `let (view, cx) = cx.add_window_view(...);`
 259    pub fn add_window_view<F, V>(
 260        &mut self,
 261        build_root_view: F,
 262    ) -> (Entity<V>, &mut VisualTestContext)
 263    where
 264        F: FnOnce(&mut Window, &mut Context<V>) -> V,
 265        V: 'static + Render,
 266    {
 267        let mut cx = self.app.borrow_mut();
 268        let bounds = Bounds::maximized(None, &cx);
 269        let window = cx
 270            .open_window(
 271                WindowOptions {
 272                    window_bounds: Some(WindowBounds::Windowed(bounds)),
 273                    ..Default::default()
 274                },
 275                |window, cx| cx.new(|cx| build_root_view(window, cx)),
 276            )
 277            .unwrap();
 278        drop(cx);
 279        let view = window.root(self).unwrap();
 280        let cx = VisualTestContext::from_window(*window.deref(), self).into_mut();
 281        cx.run_until_parked();
 282
 283        // it might be nice to try and cleanup these at the end of each test.
 284        (view, cx)
 285    }
 286
 287    /// returns the TextSystem
 288    pub fn text_system(&self) -> &Arc<TextSystem> {
 289        &self.text_system
 290    }
 291
 292    /// Simulates writing to the platform clipboard
 293    pub fn write_to_clipboard(&self, item: ClipboardItem) {
 294        self.test_platform.write_to_clipboard(item)
 295    }
 296
 297    /// Simulates reading from the platform clipboard.
 298    /// This will return the most recent value from `write_to_clipboard`.
 299    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 300        self.test_platform.read_from_clipboard()
 301    }
 302
 303    /// Simulates choosing a File in the platform's "Open" dialog.
 304    pub fn simulate_new_path_selection(
 305        &self,
 306        select_path: impl FnOnce(&std::path::Path) -> Option<std::path::PathBuf>,
 307    ) {
 308        self.test_platform.simulate_new_path_selection(select_path);
 309    }
 310
 311    /// Simulates clicking a button in an platform-level alert dialog.
 312    #[track_caller]
 313    pub fn simulate_prompt_answer(&self, button: &str) {
 314        self.test_platform.simulate_prompt_answer(button);
 315    }
 316
 317    /// Returns true if there's an alert dialog open.
 318    pub fn has_pending_prompt(&self) -> bool {
 319        self.test_platform.has_pending_prompt()
 320    }
 321
 322    /// Returns true if there's an alert dialog open.
 323    pub fn pending_prompt(&self) -> Option<(String, String)> {
 324        self.test_platform.pending_prompt()
 325    }
 326
 327    /// All the urls that have been opened with cx.open_url() during this test.
 328    pub fn opened_url(&self) -> Option<String> {
 329        self.test_platform.opened_url.borrow().clone()
 330    }
 331
 332    /// Simulates the user resizing the window to the new size.
 333    pub fn simulate_window_resize(&self, window_handle: AnyWindowHandle, size: Size<Pixels>) {
 334        self.test_window(window_handle).simulate_resize(size);
 335    }
 336
 337    /// Returns true if there's an alert dialog open.
 338    pub fn expect_restart(&self) -> oneshot::Receiver<Option<PathBuf>> {
 339        let (tx, rx) = futures::channel::oneshot::channel();
 340        self.test_platform.expect_restart.borrow_mut().replace(tx);
 341        rx
 342    }
 343
 344    /// Causes the given sources to be returned if the application queries for screen
 345    /// capture sources.
 346    pub fn set_screen_capture_sources(&self, sources: Vec<TestScreenCaptureSource>) {
 347        self.test_platform.set_screen_capture_sources(sources);
 348    }
 349
 350    /// Returns all windows open in the test.
 351    pub fn windows(&self) -> Vec<AnyWindowHandle> {
 352        self.app.borrow().windows()
 353    }
 354
 355    /// Run the given task on the main thread.
 356    #[track_caller]
 357    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncApp) -> Fut) -> Task<R>
 358    where
 359        Fut: Future<Output = R> + 'static,
 360        R: 'static,
 361    {
 362        self.foreground_executor.spawn(f(self.to_async()))
 363    }
 364
 365    /// true if the given global is defined
 366    pub fn has_global<G: Global>(&self) -> bool {
 367        let app = self.app.borrow();
 368        app.has_global::<G>()
 369    }
 370
 371    /// runs the given closure with a reference to the global
 372    /// panics if `has_global` would return false.
 373    pub fn read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> R {
 374        let app = self.app.borrow();
 375        read(app.global(), &app)
 376    }
 377
 378    /// runs the given closure with a reference to the global (if set)
 379    pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
 380        let lock = self.app.borrow();
 381        Some(read(lock.try_global()?, &lock))
 382    }
 383
 384    /// sets the global in this context.
 385    pub fn set_global<G: Global>(&mut self, global: G) {
 386        let mut lock = self.app.borrow_mut();
 387        lock.update(|cx| cx.set_global(global))
 388    }
 389
 390    /// updates the global in this context. (panics if `has_global` would return false)
 391    pub fn update_global<G: Global, R>(&mut self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
 392        let mut lock = self.app.borrow_mut();
 393        lock.update(|cx| cx.update_global(update))
 394    }
 395
 396    /// Returns an `AsyncApp` which can be used to run tasks that expect to be on a background
 397    /// thread on the current thread in tests.
 398    pub fn to_async(&self) -> AsyncApp {
 399        AsyncApp {
 400            app: Rc::downgrade(&self.app),
 401            background_executor: self.background_executor.clone(),
 402            foreground_executor: self.foreground_executor.clone(),
 403        }
 404    }
 405
 406    /// Wait until there are no more pending tasks.
 407    pub fn run_until_parked(&mut self) {
 408        self.background_executor.run_until_parked()
 409    }
 410
 411    /// Simulate dispatching an action to the currently focused node in the window.
 412    pub fn dispatch_action<A>(&mut self, window: AnyWindowHandle, action: A)
 413    where
 414        A: Action,
 415    {
 416        window
 417            .update(self, |_, window, cx| {
 418                window.dispatch_action(action.boxed_clone(), cx)
 419            })
 420            .unwrap();
 421
 422        self.background_executor.run_until_parked()
 423    }
 424
 425    /// simulate_keystrokes takes a space-separated list of keys to type.
 426    /// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
 427    /// in Zed, this will run backspace on the current editor through the command palette.
 428    /// This will also run the background executor until it's parked.
 429    pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
 430        for keystroke in keystrokes
 431            .split(' ')
 432            .map(Keystroke::parse)
 433            .map(Result::unwrap)
 434        {
 435            self.dispatch_keystroke(window, keystroke);
 436        }
 437
 438        self.background_executor.run_until_parked()
 439    }
 440
 441    /// simulate_input takes a string of text to type.
 442    /// cx.simulate_input("abc")
 443    /// will type abc into your current editor
 444    /// This will also run the background executor until it's parked.
 445    pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
 446        for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
 447            self.dispatch_keystroke(window, keystroke);
 448        }
 449
 450        self.background_executor.run_until_parked()
 451    }
 452
 453    /// dispatches a single Keystroke (see also `simulate_keystrokes` and `simulate_input`)
 454    pub fn dispatch_keystroke(&mut self, window: AnyWindowHandle, keystroke: Keystroke) {
 455        self.update_window(window, |_, window, cx| {
 456            window.dispatch_keystroke(keystroke, cx)
 457        })
 458        .unwrap();
 459    }
 460
 461    /// Returns the `TestWindow` backing the given handle.
 462    pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow {
 463        self.app
 464            .borrow_mut()
 465            .windows
 466            .get_mut(window.id)
 467            .unwrap()
 468            .as_deref_mut()
 469            .unwrap()
 470            .platform_window
 471            .as_test()
 472            .unwrap()
 473            .clone()
 474    }
 475
 476    /// Returns a stream of notifications whenever the Entity is updated.
 477    pub fn notifications<T: 'static>(
 478        &mut self,
 479        entity: &Entity<T>,
 480    ) -> impl Stream<Item = ()> + use<T> {
 481        let (tx, rx) = futures::channel::mpsc::unbounded();
 482        self.update(|cx| {
 483            cx.observe(entity, {
 484                let tx = tx.clone();
 485                move |_, _| {
 486                    let _ = tx.unbounded_send(());
 487                }
 488            })
 489            .detach();
 490            cx.observe_release(entity, move |_, _| tx.close_channel())
 491                .detach()
 492        });
 493        rx
 494    }
 495
 496    /// Returns a stream of events emitted by the given Entity.
 497    pub fn events<Evt, T: 'static + EventEmitter<Evt>>(
 498        &mut self,
 499        entity: &Entity<T>,
 500    ) -> futures::channel::mpsc::UnboundedReceiver<Evt>
 501    where
 502        Evt: 'static + Clone,
 503    {
 504        let (tx, rx) = futures::channel::mpsc::unbounded();
 505        entity
 506            .update(self, |_, cx: &mut Context<T>| {
 507                cx.subscribe(entity, move |_entity, _handle, event, _cx| {
 508                    let _ = tx.unbounded_send(event.clone());
 509                })
 510            })
 511            .detach();
 512        rx
 513    }
 514
 515    /// Runs until the given condition becomes true. (Prefer `run_until_parked` if you
 516    /// don't need to jump in at a specific time).
 517    pub async fn condition<T: 'static>(
 518        &mut self,
 519        entity: &Entity<T>,
 520        mut predicate: impl FnMut(&mut T, &mut Context<T>) -> bool,
 521    ) {
 522        let timer = self.executor().timer(Duration::from_secs(3));
 523        let mut notifications = self.notifications(entity);
 524
 525        use futures::FutureExt as _;
 526        use smol::future::FutureExt as _;
 527
 528        async {
 529            loop {
 530                if entity.update(self, &mut predicate) {
 531                    return Ok(());
 532                }
 533
 534                if notifications.next().await.is_none() {
 535                    bail!("entity dropped")
 536                }
 537            }
 538        }
 539        .race(timer.map(|_| Err(anyhow!("condition timed out"))))
 540        .await
 541        .unwrap();
 542    }
 543
 544    /// Set a name for this App.
 545    #[cfg(any(test, feature = "test-support"))]
 546    pub fn set_name(&mut self, name: &'static str) {
 547        self.update(|cx| cx.name = Some(name))
 548    }
 549}
 550
 551impl<T: 'static> Entity<T> {
 552    /// Block until the next event is emitted by the entity, then return it.
 553    pub fn next_event<Event>(&self, cx: &mut TestAppContext) -> impl Future<Output = Event>
 554    where
 555        Event: Send + Clone + 'static,
 556        T: EventEmitter<Event>,
 557    {
 558        let (tx, mut rx) = oneshot::channel();
 559        let mut tx = Some(tx);
 560        let subscription = self.update(cx, |_, cx| {
 561            cx.subscribe(self, move |_, _, event, _| {
 562                if let Some(tx) = tx.take() {
 563                    _ = tx.send(event.clone());
 564                }
 565            })
 566        });
 567
 568        async move {
 569            let event = rx.await.expect("no event emitted");
 570            drop(subscription);
 571            event
 572        }
 573    }
 574}
 575
 576impl<V: 'static> Entity<V> {
 577    /// Returns a future that resolves when the view is next updated.
 578    pub fn next_notification(
 579        &self,
 580        advance_clock_by: Duration,
 581        cx: &TestAppContext,
 582    ) -> impl Future<Output = ()> {
 583        use postage::prelude::{Sink as _, Stream as _};
 584
 585        let (mut tx, mut rx) = postage::mpsc::channel(1);
 586        let subscription = cx.app.borrow_mut().observe(self, move |_, _| {
 587            tx.try_send(()).ok();
 588        });
 589
 590        let duration = if std::env::var("CI").is_ok() {
 591            Duration::from_secs(5)
 592        } else {
 593            Duration::from_secs(1)
 594        };
 595
 596        cx.executor().advance_clock(advance_clock_by);
 597
 598        async move {
 599            let notification = crate::util::smol_timeout(duration, rx.recv())
 600                .await
 601                .expect("next notification timed out");
 602            drop(subscription);
 603            notification.expect("entity dropped while test was waiting for its next notification")
 604        }
 605    }
 606}
 607
 608impl<V> Entity<V> {
 609    /// Returns a future that resolves when the condition becomes true.
 610    pub fn condition<Evt>(
 611        &self,
 612        cx: &TestAppContext,
 613        mut predicate: impl FnMut(&V, &App) -> bool,
 614    ) -> impl Future<Output = ()>
 615    where
 616        Evt: 'static,
 617        V: EventEmitter<Evt>,
 618    {
 619        use postage::prelude::{Sink as _, Stream as _};
 620
 621        let (tx, mut rx) = postage::mpsc::channel(1024);
 622
 623        let mut cx = cx.app.borrow_mut();
 624        let subscriptions = (
 625            cx.observe(self, {
 626                let mut tx = tx.clone();
 627                move |_, _| {
 628                    tx.blocking_send(()).ok();
 629                }
 630            }),
 631            cx.subscribe(self, {
 632                let mut tx = tx;
 633                move |_, _: &Evt, _| {
 634                    tx.blocking_send(()).ok();
 635                }
 636            }),
 637        );
 638
 639        let cx = cx.this.upgrade().unwrap();
 640        let handle = self.downgrade();
 641
 642        async move {
 643            crate::util::smol_timeout(Duration::from_secs(1), async move {
 644                loop {
 645                    {
 646                        let cx = cx.borrow();
 647                        let cx = &*cx;
 648                        if predicate(
 649                            handle
 650                                .upgrade()
 651                                .expect("view dropped with pending condition")
 652                                .read(cx),
 653                            cx,
 654                        ) {
 655                            break;
 656                        }
 657                    }
 658
 659                    cx.borrow().background_executor().start_waiting();
 660                    rx.recv()
 661                        .await
 662                        .expect("view dropped with pending condition");
 663                    cx.borrow().background_executor().finish_waiting();
 664                }
 665            })
 666            .await
 667            .expect("condition timed out");
 668            drop(subscriptions);
 669        }
 670    }
 671}
 672
 673use derive_more::{Deref, DerefMut};
 674
 675use super::{Context, Entity};
 676#[derive(Deref, DerefMut, Clone)]
 677/// A VisualTestContext is the test-equivalent of a `Window` and `App`. It allows you to
 678/// run window-specific test code. It can be dereferenced to a `TextAppContext`.
 679pub struct VisualTestContext {
 680    #[deref]
 681    #[deref_mut]
 682    /// cx is the original TestAppContext (you can more easily access this using Deref)
 683    pub cx: TestAppContext,
 684    window: AnyWindowHandle,
 685}
 686
 687impl VisualTestContext {
 688    /// Provides a `Window` and `App` for the duration of the closure.
 689    pub fn update<R>(&mut self, f: impl FnOnce(&mut Window, &mut App) -> R) -> R {
 690        self.cx
 691            .update_window(self.window, |_, window, cx| f(window, cx))
 692            .unwrap()
 693    }
 694
 695    /// Creates a new VisualTestContext. You would typically shadow the passed in
 696    /// TestAppContext with this, as this is typically more useful.
 697    /// `let cx = VisualTestContext::from_window(window, cx);`
 698    pub fn from_window(window: AnyWindowHandle, cx: &TestAppContext) -> Self {
 699        Self {
 700            cx: cx.clone(),
 701            window,
 702        }
 703    }
 704
 705    /// Wait until there are no more pending tasks.
 706    pub fn run_until_parked(&self) {
 707        self.cx.background_executor.run_until_parked();
 708    }
 709
 710    /// Dispatch the action to the currently focused node.
 711    pub fn dispatch_action<A>(&mut self, action: A)
 712    where
 713        A: Action,
 714    {
 715        self.cx.dispatch_action(self.window, action)
 716    }
 717
 718    /// Read the title off the window (set by `Window#set_window_title`)
 719    pub fn window_title(&mut self) -> Option<String> {
 720        self.cx.test_window(self.window).0.lock().title.clone()
 721    }
 722
 723    /// Simulate a sequence of keystrokes `cx.simulate_keystrokes("cmd-p escape")`
 724    /// Automatically runs until parked.
 725    pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
 726        self.cx.simulate_keystrokes(self.window, keystrokes)
 727    }
 728
 729    /// Simulate typing text `cx.simulate_input("hello")`
 730    /// Automatically runs until parked.
 731    pub fn simulate_input(&mut self, input: &str) {
 732        self.cx.simulate_input(self.window, input)
 733    }
 734
 735    /// Simulate a mouse move event to the given point
 736    pub fn simulate_mouse_move(
 737        &mut self,
 738        position: Point<Pixels>,
 739        button: impl Into<Option<MouseButton>>,
 740        modifiers: Modifiers,
 741    ) {
 742        self.simulate_event(MouseMoveEvent {
 743            position,
 744            modifiers,
 745            pressed_button: button.into(),
 746        })
 747    }
 748
 749    /// Simulate a mouse down event to the given point
 750    pub fn simulate_mouse_down(
 751        &mut self,
 752        position: Point<Pixels>,
 753        button: MouseButton,
 754        modifiers: Modifiers,
 755    ) {
 756        self.simulate_event(MouseDownEvent {
 757            position,
 758            modifiers,
 759            button,
 760            click_count: 1,
 761            first_mouse: false,
 762        })
 763    }
 764
 765    /// Simulate a mouse up event to the given point
 766    pub fn simulate_mouse_up(
 767        &mut self,
 768        position: Point<Pixels>,
 769        button: MouseButton,
 770        modifiers: Modifiers,
 771    ) {
 772        self.simulate_event(MouseUpEvent {
 773            position,
 774            modifiers,
 775            button,
 776            click_count: 1,
 777        })
 778    }
 779
 780    /// Simulate a primary mouse click at the given point
 781    pub fn simulate_click(&mut self, position: Point<Pixels>, modifiers: Modifiers) {
 782        self.simulate_event(MouseDownEvent {
 783            position,
 784            modifiers,
 785            button: MouseButton::Left,
 786            click_count: 1,
 787            first_mouse: false,
 788        });
 789        self.simulate_event(MouseUpEvent {
 790            position,
 791            modifiers,
 792            button: MouseButton::Left,
 793            click_count: 1,
 794        });
 795    }
 796
 797    /// Simulate a modifiers changed event
 798    pub fn simulate_modifiers_change(&mut self, modifiers: Modifiers) {
 799        self.simulate_event(ModifiersChangedEvent {
 800            modifiers,
 801            capslock: Capslock { on: false },
 802        })
 803    }
 804
 805    /// Simulate a capslock changed event
 806    pub fn simulate_capslock_change(&mut self, on: bool) {
 807        self.simulate_event(ModifiersChangedEvent {
 808            modifiers: Modifiers::none(),
 809            capslock: Capslock { on },
 810        })
 811    }
 812
 813    /// Simulates the user resizing the window to the new size.
 814    pub fn simulate_resize(&self, size: Size<Pixels>) {
 815        self.simulate_window_resize(self.window, size)
 816    }
 817
 818    /// debug_bounds returns the bounds of the element with the given selector.
 819    pub fn debug_bounds(&mut self, selector: &'static str) -> Option<Bounds<Pixels>> {
 820        self.update(|window, _| window.rendered_frame.debug_bounds.get(selector).copied())
 821    }
 822
 823    /// Draw an element to the window. Useful for simulating events or actions
 824    pub fn draw<E>(
 825        &mut self,
 826        origin: Point<Pixels>,
 827        space: impl Into<Size<AvailableSpace>>,
 828        f: impl FnOnce(&mut Window, &mut App) -> E,
 829    ) -> (E::RequestLayoutState, E::PrepaintState)
 830    where
 831        E: Element,
 832    {
 833        self.update(|window, cx| {
 834            window.invalidator.set_phase(DrawPhase::Prepaint);
 835            let mut element = Drawable::new(f(window, cx));
 836            element.layout_as_root(space.into(), window, cx);
 837            window.with_absolute_element_offset(origin, |window| element.prepaint(window, cx));
 838
 839            window.invalidator.set_phase(DrawPhase::Paint);
 840            let (request_layout_state, prepaint_state) = element.paint(window, cx);
 841
 842            window.invalidator.set_phase(DrawPhase::None);
 843            window.refresh();
 844
 845            (request_layout_state, prepaint_state)
 846        })
 847    }
 848
 849    /// Simulate an event from the platform, e.g. a ScrollWheelEvent
 850    /// Make sure you've called [VisualTestContext::draw] first!
 851    pub fn simulate_event<E: InputEvent>(&mut self, event: E) {
 852        self.test_window(self.window)
 853            .simulate_input(event.to_platform_input());
 854        self.background_executor.run_until_parked();
 855    }
 856
 857    /// Simulates the user blurring the window.
 858    pub fn deactivate_window(&mut self) {
 859        if Some(self.window) == self.test_platform.active_window() {
 860            self.test_platform.set_active_window(None)
 861        }
 862        self.background_executor.run_until_parked();
 863    }
 864
 865    /// Simulates the user closing the window.
 866    /// Returns true if the window was closed.
 867    pub fn simulate_close(&mut self) -> bool {
 868        let handler = self
 869            .cx
 870            .update_window(self.window, |_, window, _| {
 871                window
 872                    .platform_window
 873                    .as_test()
 874                    .unwrap()
 875                    .0
 876                    .lock()
 877                    .should_close_handler
 878                    .take()
 879            })
 880            .unwrap();
 881        if let Some(mut handler) = handler {
 882            let should_close = handler();
 883            self.cx
 884                .update_window(self.window, |_, window, _| {
 885                    window.platform_window.on_should_close(handler);
 886                })
 887                .unwrap();
 888            should_close
 889        } else {
 890            false
 891        }
 892    }
 893
 894    /// Get an &mut VisualTestContext (which is mostly what you need to pass to other methods).
 895    /// This method internally retains the VisualTestContext until the end of the test.
 896    pub fn into_mut(self) -> &'static mut Self {
 897        let ptr = Box::into_raw(Box::new(self));
 898        // safety: on_quit will be called after the test has finished.
 899        // the executor will ensure that all tasks related to the test have stopped.
 900        // so there is no way for cx to be accessed after on_quit is called.
 901        // todo: This is unsound under stacked borrows (also tree borrows probably?)
 902        // the mutable reference invalidates `ptr` which is later used in the closure
 903        let cx = unsafe { &mut *ptr };
 904        cx.on_quit(move || unsafe {
 905            drop(Box::from_raw(ptr));
 906        });
 907        cx
 908    }
 909}
 910
 911impl AppContext for VisualTestContext {
 912    fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
 913        self.cx.new(build_entity)
 914    }
 915
 916    fn reserve_entity<T: 'static>(&mut self) -> crate::Reservation<T> {
 917        self.cx.reserve_entity()
 918    }
 919
 920    fn insert_entity<T: 'static>(
 921        &mut self,
 922        reservation: crate::Reservation<T>,
 923        build_entity: impl FnOnce(&mut Context<T>) -> T,
 924    ) -> Entity<T> {
 925        self.cx.insert_entity(reservation, build_entity)
 926    }
 927
 928    fn update_entity<T, R>(
 929        &mut self,
 930        handle: &Entity<T>,
 931        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
 932    ) -> R
 933    where
 934        T: 'static,
 935    {
 936        self.cx.update_entity(handle, update)
 937    }
 938
 939    fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> super::GpuiBorrow<'a, T>
 940    where
 941        T: 'static,
 942    {
 943        self.cx.as_mut(handle)
 944    }
 945
 946    fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
 947    where
 948        T: 'static,
 949    {
 950        self.cx.read_entity(handle, read)
 951    }
 952
 953    fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
 954    where
 955        F: FnOnce(AnyView, &mut Window, &mut App) -> T,
 956    {
 957        self.cx.update_window(window, f)
 958    }
 959
 960    fn read_window<T, R>(
 961        &self,
 962        window: &WindowHandle<T>,
 963        read: impl FnOnce(Entity<T>, &App) -> R,
 964    ) -> Result<R>
 965    where
 966        T: 'static,
 967    {
 968        self.cx.read_window(window, read)
 969    }
 970
 971    fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
 972    where
 973        R: Send + 'static,
 974    {
 975        self.cx.background_spawn(future)
 976    }
 977
 978    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
 979    where
 980        G: Global,
 981    {
 982        self.cx.read_global(callback)
 983    }
 984}
 985
 986impl VisualContext for VisualTestContext {
 987    type Result<T> = T;
 988
 989    /// Get the underlying window handle underlying this context.
 990    fn window_handle(&self) -> AnyWindowHandle {
 991        self.window
 992    }
 993
 994    fn new_window_entity<T: 'static>(
 995        &mut self,
 996        build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
 997    ) -> Entity<T> {
 998        self.window
 999            .update(&mut self.cx, |_, window, cx| {
1000                cx.new(|cx| build_entity(window, cx))
1001            })
1002            .expect("window was unexpectedly closed")
1003    }
1004
1005    fn update_window_entity<V: 'static, R>(
1006        &mut self,
1007        view: &Entity<V>,
1008        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
1009    ) -> R {
1010        self.window
1011            .update(&mut self.cx, |_, window, cx| {
1012                view.update(cx, |v, cx| update(v, window, cx))
1013            })
1014            .expect("window was unexpectedly closed")
1015    }
1016
1017    fn replace_root_view<V>(
1018        &mut self,
1019        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
1020    ) -> Entity<V>
1021    where
1022        V: 'static + Render,
1023    {
1024        self.window
1025            .update(&mut self.cx, |_, window, cx| {
1026                window.replace_root(cx, build_view)
1027            })
1028            .expect("window was unexpectedly closed")
1029    }
1030
1031    fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) {
1032        self.window
1033            .update(&mut self.cx, |_, window, cx| {
1034                view.read(cx).focus_handle(cx).focus(window, cx)
1035            })
1036            .expect("window was unexpectedly closed")
1037    }
1038}
1039
1040impl AnyWindowHandle {
1041    /// Creates the given view in this window.
1042    pub fn build_entity<V: Render + 'static>(
1043        &self,
1044        cx: &mut TestAppContext,
1045        build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
1046    ) -> Entity<V> {
1047        self.update(cx, |_, window, cx| cx.new(|cx| build_view(window, cx)))
1048            .unwrap()
1049    }
1050}