test_context.rs

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