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