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