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