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