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