app.rs

   1use crate::{
   2    elements::ElementBox,
   3    executor::{self, Task},
   4    keymap::{self, Keystroke},
   5    platform::{self, CursorStyle, Platform, PromptLevel, WindowOptions},
   6    presenter::Presenter,
   7    util::{post_inc, timeout, CwdBacktrace},
   8    AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
   9};
  10use anyhow::{anyhow, Result};
  11use backtrace::Backtrace;
  12use keymap::MatchResult;
  13use lazy_static::lazy_static;
  14use parking_lot::Mutex;
  15use platform::Event;
  16use postage::{mpsc, oneshot, sink::Sink as _, stream::Stream as _};
  17use smol::prelude::*;
  18use std::{
  19    any::{self, type_name, Any, TypeId},
  20    cell::RefCell,
  21    collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
  22    fmt::{self, Debug},
  23    hash::{Hash, Hasher},
  24    marker::PhantomData,
  25    mem,
  26    ops::{Deref, DerefMut},
  27    path::{Path, PathBuf},
  28    pin::Pin,
  29    rc::{self, Rc},
  30    sync::{
  31        atomic::{AtomicUsize, Ordering::SeqCst},
  32        Arc, Weak,
  33    },
  34    time::Duration,
  35};
  36
  37pub trait Entity: 'static {
  38    type Event;
  39
  40    fn release(&mut self, _: &mut MutableAppContext) {}
  41    fn app_will_quit(
  42        &mut self,
  43        _: &mut MutableAppContext,
  44    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  45        None
  46    }
  47}
  48
  49pub trait View: Entity + Sized {
  50    fn ui_name() -> &'static str;
  51    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  52    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  53    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  54    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  55        Self::default_keymap_context()
  56    }
  57    fn default_keymap_context() -> keymap::Context {
  58        let mut cx = keymap::Context::default();
  59        cx.set.insert(Self::ui_name().into());
  60        cx
  61    }
  62}
  63
  64pub trait ReadModel {
  65    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  66}
  67
  68pub trait ReadModelWith {
  69    fn read_model_with<E: Entity, T>(
  70        &self,
  71        handle: &ModelHandle<E>,
  72        read: &mut dyn FnMut(&E, &AppContext) -> T,
  73    ) -> T;
  74}
  75
  76pub trait UpdateModel {
  77    fn update_model<T: Entity, O>(
  78        &mut self,
  79        handle: &ModelHandle<T>,
  80        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
  81    ) -> O;
  82}
  83
  84pub trait UpgradeModelHandle {
  85    fn upgrade_model_handle<T: Entity>(
  86        &self,
  87        handle: &WeakModelHandle<T>,
  88    ) -> Option<ModelHandle<T>>;
  89
  90    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
  91
  92    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
  93}
  94
  95pub trait UpgradeViewHandle {
  96    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
  97}
  98
  99pub trait ReadView {
 100    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 101}
 102
 103pub trait ReadViewWith {
 104    fn read_view_with<V, T>(
 105        &self,
 106        handle: &ViewHandle<V>,
 107        read: &mut dyn FnMut(&V, &AppContext) -> T,
 108    ) -> T
 109    where
 110        V: View;
 111}
 112
 113pub trait UpdateView {
 114    fn update_view<T, S>(
 115        &mut self,
 116        handle: &ViewHandle<T>,
 117        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 118    ) -> S
 119    where
 120        T: View;
 121}
 122
 123pub trait ElementStateContext: DerefMut<Target = MutableAppContext> {
 124    fn current_view_id(&self) -> usize;
 125
 126    fn element_state<Tag: 'static, T: 'static + Default>(
 127        &mut self,
 128        element_id: usize,
 129    ) -> ElementStateHandle<T> {
 130        let id = ElementStateId {
 131            view_id: self.current_view_id(),
 132            element_id,
 133            tag: TypeId::of::<Tag>(),
 134        };
 135        self.cx
 136            .element_states
 137            .entry(id)
 138            .or_insert_with(|| Box::new(T::default()));
 139        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
 140    }
 141}
 142
 143pub trait Action: 'static + AnyAction {
 144    type Argument: 'static + Clone;
 145}
 146
 147pub trait AnyAction {
 148    fn id(&self) -> TypeId;
 149    fn name(&self) -> &'static str;
 150    fn as_any(&self) -> &dyn Any;
 151    fn boxed_clone(&self) -> Box<dyn AnyAction>;
 152    fn boxed_clone_as_any(&self) -> Box<dyn Any>;
 153}
 154
 155#[macro_export]
 156macro_rules! action {
 157    ($name:ident, $arg:ty) => {
 158        #[derive(Clone)]
 159        pub struct $name(pub $arg);
 160
 161        impl $crate::Action for $name {
 162            type Argument = $arg;
 163        }
 164
 165        impl $crate::AnyAction for $name {
 166            fn id(&self) -> std::any::TypeId {
 167                std::any::TypeId::of::<$name>()
 168            }
 169
 170            fn name(&self) -> &'static str {
 171                stringify!($name)
 172            }
 173
 174            fn as_any(&self) -> &dyn std::any::Any {
 175                self
 176            }
 177
 178            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 179                Box::new(self.clone())
 180            }
 181
 182            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 183                Box::new(self.clone())
 184            }
 185        }
 186    };
 187
 188    ($name:ident) => {
 189        #[derive(Clone, Debug, Eq, PartialEq)]
 190        pub struct $name;
 191
 192        impl $crate::Action for $name {
 193            type Argument = ();
 194        }
 195
 196        impl $crate::AnyAction for $name {
 197            fn id(&self) -> std::any::TypeId {
 198                std::any::TypeId::of::<$name>()
 199            }
 200
 201            fn name(&self) -> &'static str {
 202                stringify!($name)
 203            }
 204
 205            fn as_any(&self) -> &dyn std::any::Any {
 206                self
 207            }
 208
 209            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 210                Box::new(self.clone())
 211            }
 212
 213            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 214                Box::new(self.clone())
 215            }
 216        }
 217    };
 218}
 219
 220pub struct Menu<'a> {
 221    pub name: &'a str,
 222    pub items: Vec<MenuItem<'a>>,
 223}
 224
 225pub enum MenuItem<'a> {
 226    Action {
 227        name: &'a str,
 228        keystroke: Option<&'a str>,
 229        action: Box<dyn AnyAction>,
 230    },
 231    Separator,
 232}
 233
 234#[derive(Clone)]
 235pub struct App(Rc<RefCell<MutableAppContext>>);
 236
 237#[derive(Clone)]
 238pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 239
 240pub struct TestAppContext {
 241    cx: Rc<RefCell<MutableAppContext>>,
 242    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 243}
 244
 245impl App {
 246    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 247        let platform = platform::current::platform();
 248        let foreground_platform = platform::current::foreground_platform();
 249        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 250        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 251            foreground,
 252            Arc::new(executor::Background::new()),
 253            platform.clone(),
 254            foreground_platform.clone(),
 255            Arc::new(FontCache::new(platform.fonts())),
 256            Default::default(),
 257            asset_source,
 258        ))));
 259
 260        foreground_platform.on_quit(Box::new({
 261            let cx = app.0.clone();
 262            move || {
 263                cx.borrow_mut().quit();
 264            }
 265        }));
 266        foreground_platform.on_menu_command(Box::new({
 267            let cx = app.0.clone();
 268            move |action| {
 269                let mut cx = cx.borrow_mut();
 270                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 271                    if let Some((presenter, _)) =
 272                        cx.presenters_and_platform_windows.get(&key_window_id)
 273                    {
 274                        let presenter = presenter.clone();
 275                        let path = presenter.borrow().dispatch_path(cx.as_ref());
 276                        cx.dispatch_action_any(key_window_id, &path, action);
 277                    } else {
 278                        cx.dispatch_global_action_any(action);
 279                    }
 280                } else {
 281                    cx.dispatch_global_action_any(action);
 282                }
 283            }
 284        }));
 285
 286        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 287        Ok(app)
 288    }
 289
 290    pub fn background(&self) -> Arc<executor::Background> {
 291        self.0.borrow().background().clone()
 292    }
 293
 294    pub fn on_become_active<F>(self, mut callback: F) -> Self
 295    where
 296        F: 'static + FnMut(&mut MutableAppContext),
 297    {
 298        let cx = self.0.clone();
 299        self.0
 300            .borrow_mut()
 301            .foreground_platform
 302            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 303        self
 304    }
 305
 306    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 307    where
 308        F: 'static + FnMut(&mut MutableAppContext),
 309    {
 310        let cx = self.0.clone();
 311        self.0
 312            .borrow_mut()
 313            .foreground_platform
 314            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 315        self
 316    }
 317
 318    pub fn on_quit<F>(self, mut callback: F) -> Self
 319    where
 320        F: 'static + FnMut(&mut MutableAppContext),
 321    {
 322        let cx = self.0.clone();
 323        self.0
 324            .borrow_mut()
 325            .foreground_platform
 326            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 327        self
 328    }
 329
 330    pub fn on_event<F>(self, mut callback: F) -> Self
 331    where
 332        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 333    {
 334        let cx = self.0.clone();
 335        self.0
 336            .borrow_mut()
 337            .foreground_platform
 338            .on_event(Box::new(move |event| {
 339                callback(event, &mut *cx.borrow_mut())
 340            }));
 341        self
 342    }
 343
 344    pub fn on_open_files<F>(self, mut callback: F) -> Self
 345    where
 346        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 347    {
 348        let cx = self.0.clone();
 349        self.0
 350            .borrow_mut()
 351            .foreground_platform
 352            .on_open_files(Box::new(move |paths| {
 353                callback(paths, &mut *cx.borrow_mut())
 354            }));
 355        self
 356    }
 357
 358    pub fn run<F>(self, on_finish_launching: F)
 359    where
 360        F: 'static + FnOnce(&mut MutableAppContext),
 361    {
 362        let platform = self.0.borrow().foreground_platform.clone();
 363        platform.run(Box::new(move || {
 364            let mut cx = self.0.borrow_mut();
 365            let cx = &mut *cx;
 366            crate::views::init(cx);
 367            on_finish_launching(cx);
 368        }))
 369    }
 370
 371    pub fn platform(&self) -> Arc<dyn Platform> {
 372        self.0.borrow().platform()
 373    }
 374
 375    pub fn font_cache(&self) -> Arc<FontCache> {
 376        self.0.borrow().cx.font_cache.clone()
 377    }
 378
 379    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 380        let mut state = self.0.borrow_mut();
 381        let result = state.update(callback);
 382        state.pending_notifications.clear();
 383        result
 384    }
 385}
 386
 387impl TestAppContext {
 388    pub fn new(
 389        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 390        platform: Arc<dyn Platform>,
 391        foreground: Rc<executor::Foreground>,
 392        background: Arc<executor::Background>,
 393        font_cache: Arc<FontCache>,
 394        leak_detector: Arc<Mutex<LeakDetector>>,
 395        first_entity_id: usize,
 396    ) -> Self {
 397        let mut cx = MutableAppContext::new(
 398            foreground.clone(),
 399            background,
 400            platform,
 401            foreground_platform.clone(),
 402            font_cache,
 403            RefCounts {
 404                #[cfg(feature = "test-support")]
 405                leak_detector,
 406                ..Default::default()
 407            },
 408            (),
 409        );
 410        cx.next_entity_id = first_entity_id;
 411        let cx = TestAppContext {
 412            cx: Rc::new(RefCell::new(cx)),
 413            foreground_platform,
 414        };
 415        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 416        cx
 417    }
 418
 419    pub fn dispatch_action<A: Action>(
 420        &self,
 421        window_id: usize,
 422        responder_chain: Vec<usize>,
 423        action: A,
 424    ) {
 425        self.cx
 426            .borrow_mut()
 427            .dispatch_action_any(window_id, &responder_chain, &action);
 428    }
 429
 430    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 431        self.cx.borrow_mut().dispatch_global_action(action);
 432    }
 433
 434    pub fn dispatch_keystroke(
 435        &self,
 436        window_id: usize,
 437        responder_chain: Vec<usize>,
 438        keystroke: &Keystroke,
 439    ) -> Result<bool> {
 440        let mut state = self.cx.borrow_mut();
 441        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 442    }
 443
 444    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 445    where
 446        T: Entity,
 447        F: FnOnce(&mut ModelContext<T>) -> T,
 448    {
 449        self.cx.borrow_mut().add_model(build_model)
 450    }
 451
 452    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 453    where
 454        T: View,
 455        F: FnOnce(&mut ViewContext<T>) -> T,
 456    {
 457        self.cx
 458            .borrow_mut()
 459            .add_window(Default::default(), build_root_view)
 460    }
 461
 462    pub fn window_ids(&self) -> Vec<usize> {
 463        self.cx.borrow().window_ids().collect()
 464    }
 465
 466    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 467        self.cx.borrow().root_view(window_id)
 468    }
 469
 470    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 471    where
 472        T: View,
 473        F: FnOnce(&mut ViewContext<T>) -> T,
 474    {
 475        self.cx.borrow_mut().add_view(window_id, build_view)
 476    }
 477
 478    pub fn add_option_view<T, F>(
 479        &mut self,
 480        window_id: usize,
 481        build_view: F,
 482    ) -> Option<ViewHandle<T>>
 483    where
 484        T: View,
 485        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 486    {
 487        self.cx.borrow_mut().add_option_view(window_id, build_view)
 488    }
 489
 490    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 491        callback(self.cx.borrow().as_ref())
 492    }
 493
 494    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 495        let mut state = self.cx.borrow_mut();
 496        // Don't increment pending flushes in order to effects to be flushed before the callback
 497        // completes, which is helpful in tests.
 498        let result = callback(&mut *state);
 499        // Flush effects after the callback just in case there are any. This can happen in edge
 500        // cases such as the closure dropping handles.
 501        state.flush_effects();
 502        result
 503    }
 504
 505    pub fn to_async(&self) -> AsyncAppContext {
 506        AsyncAppContext(self.cx.clone())
 507    }
 508
 509    pub fn font_cache(&self) -> Arc<FontCache> {
 510        self.cx.borrow().cx.font_cache.clone()
 511    }
 512
 513    pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
 514        self.foreground_platform.clone()
 515    }
 516
 517    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 518        self.cx.borrow().cx.platform.clone()
 519    }
 520
 521    pub fn foreground(&self) -> Rc<executor::Foreground> {
 522        self.cx.borrow().foreground().clone()
 523    }
 524
 525    pub fn background(&self) -> Arc<executor::Background> {
 526        self.cx.borrow().background().clone()
 527    }
 528
 529    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 530    where
 531        F: FnOnce(AsyncAppContext) -> Fut,
 532        Fut: 'static + Future<Output = T>,
 533        T: 'static,
 534    {
 535        self.cx.borrow_mut().spawn(f)
 536    }
 537
 538    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 539        self.foreground_platform.simulate_new_path_selection(result);
 540    }
 541
 542    pub fn did_prompt_for_new_path(&self) -> bool {
 543        self.foreground_platform.as_ref().did_prompt_for_new_path()
 544    }
 545
 546    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 547        let mut state = self.cx.borrow_mut();
 548        let (_, window) = state
 549            .presenters_and_platform_windows
 550            .get_mut(&window_id)
 551            .unwrap();
 552        let test_window = window
 553            .as_any_mut()
 554            .downcast_mut::<platform::test::Window>()
 555            .unwrap();
 556        let mut done_tx = test_window
 557            .last_prompt
 558            .take()
 559            .expect("prompt was not called");
 560        let _ = done_tx.try_send(answer);
 561    }
 562
 563    #[cfg(feature = "test-support")]
 564    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
 565        self.cx.borrow().leak_detector()
 566    }
 567}
 568
 569impl Drop for TestAppContext {
 570    fn drop(&mut self) {
 571        self.cx.borrow_mut().remove_all_windows();
 572    }
 573}
 574
 575impl AsyncAppContext {
 576    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 577    where
 578        F: FnOnce(AsyncAppContext) -> Fut,
 579        Fut: 'static + Future<Output = T>,
 580        T: 'static,
 581    {
 582        self.0.borrow().foreground.spawn(f(self.clone()))
 583    }
 584
 585    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 586        callback(self.0.borrow().as_ref())
 587    }
 588
 589    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 590        self.0.borrow_mut().update(callback)
 591    }
 592
 593    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 594    where
 595        T: Entity,
 596        F: FnOnce(&mut ModelContext<T>) -> T,
 597    {
 598        self.update(|cx| cx.add_model(build_model))
 599    }
 600
 601    pub fn platform(&self) -> Arc<dyn Platform> {
 602        self.0.borrow().platform()
 603    }
 604
 605    pub fn foreground(&self) -> Rc<executor::Foreground> {
 606        self.0.borrow().foreground.clone()
 607    }
 608
 609    pub fn background(&self) -> Arc<executor::Background> {
 610        self.0.borrow().cx.background.clone()
 611    }
 612}
 613
 614impl UpdateModel for AsyncAppContext {
 615    fn update_model<E: Entity, O>(
 616        &mut self,
 617        handle: &ModelHandle<E>,
 618        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 619    ) -> O {
 620        self.0.borrow_mut().update_model(handle, update)
 621    }
 622}
 623
 624impl UpgradeModelHandle for AsyncAppContext {
 625    fn upgrade_model_handle<T: Entity>(
 626        &self,
 627        handle: &WeakModelHandle<T>,
 628    ) -> Option<ModelHandle<T>> {
 629        self.0.borrow().upgrade_model_handle(handle)
 630    }
 631
 632    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 633        self.0.borrow().model_handle_is_upgradable(handle)
 634    }
 635
 636    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 637        self.0.borrow().upgrade_any_model_handle(handle)
 638    }
 639}
 640
 641impl UpgradeViewHandle for AsyncAppContext {
 642    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 643        self.0.borrow_mut().upgrade_view_handle(handle)
 644    }
 645}
 646
 647impl ReadModelWith for AsyncAppContext {
 648    fn read_model_with<E: Entity, T>(
 649        &self,
 650        handle: &ModelHandle<E>,
 651        read: &mut dyn FnMut(&E, &AppContext) -> T,
 652    ) -> T {
 653        let cx = self.0.borrow();
 654        let cx = cx.as_ref();
 655        read(handle.read(cx), cx)
 656    }
 657}
 658
 659impl UpdateView for AsyncAppContext {
 660    fn update_view<T, S>(
 661        &mut self,
 662        handle: &ViewHandle<T>,
 663        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 664    ) -> S
 665    where
 666        T: View,
 667    {
 668        self.0.borrow_mut().update_view(handle, update)
 669    }
 670}
 671
 672impl ReadViewWith for AsyncAppContext {
 673    fn read_view_with<V, T>(
 674        &self,
 675        handle: &ViewHandle<V>,
 676        read: &mut dyn FnMut(&V, &AppContext) -> T,
 677    ) -> T
 678    where
 679        V: View,
 680    {
 681        let cx = self.0.borrow();
 682        let cx = cx.as_ref();
 683        read(handle.read(cx), cx)
 684    }
 685}
 686
 687impl UpdateModel for TestAppContext {
 688    fn update_model<T: Entity, O>(
 689        &mut self,
 690        handle: &ModelHandle<T>,
 691        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 692    ) -> O {
 693        self.cx.borrow_mut().update_model(handle, update)
 694    }
 695}
 696
 697impl ReadModelWith for TestAppContext {
 698    fn read_model_with<E: Entity, T>(
 699        &self,
 700        handle: &ModelHandle<E>,
 701        read: &mut dyn FnMut(&E, &AppContext) -> T,
 702    ) -> T {
 703        let cx = self.cx.borrow();
 704        let cx = cx.as_ref();
 705        read(handle.read(cx), cx)
 706    }
 707}
 708
 709impl UpdateView for TestAppContext {
 710    fn update_view<T, S>(
 711        &mut self,
 712        handle: &ViewHandle<T>,
 713        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 714    ) -> S
 715    where
 716        T: View,
 717    {
 718        self.cx.borrow_mut().update_view(handle, update)
 719    }
 720}
 721
 722impl ReadViewWith for TestAppContext {
 723    fn read_view_with<V, T>(
 724        &self,
 725        handle: &ViewHandle<V>,
 726        read: &mut dyn FnMut(&V, &AppContext) -> T,
 727    ) -> T
 728    where
 729        V: View,
 730    {
 731        let cx = self.cx.borrow();
 732        let cx = cx.as_ref();
 733        read(handle.read(cx), cx)
 734    }
 735}
 736
 737type ActionCallback =
 738    dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize);
 739type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
 740
 741type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 742type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 743type ReleaseObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 744
 745pub struct MutableAppContext {
 746    weak_self: Option<rc::Weak<RefCell<Self>>>,
 747    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 748    assets: Arc<AssetCache>,
 749    cx: AppContext,
 750    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 751    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 752    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 753    keystroke_matcher: keymap::Matcher,
 754    next_entity_id: usize,
 755    next_window_id: usize,
 756    next_subscription_id: usize,
 757    frame_count: usize,
 758    subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
 759    observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
 760    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 761    presenters_and_platform_windows:
 762        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 763    debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
 764    foreground: Rc<executor::Foreground>,
 765    pending_effects: VecDeque<Effect>,
 766    pending_notifications: HashSet<usize>,
 767    pending_flushes: usize,
 768    flushing_effects: bool,
 769    next_cursor_style_handle_id: Arc<AtomicUsize>,
 770    halt_action_dispatch: bool,
 771}
 772
 773impl MutableAppContext {
 774    fn new(
 775        foreground: Rc<executor::Foreground>,
 776        background: Arc<executor::Background>,
 777        platform: Arc<dyn platform::Platform>,
 778        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 779        font_cache: Arc<FontCache>,
 780        ref_counts: RefCounts,
 781        asset_source: impl AssetSource,
 782    ) -> Self {
 783        Self {
 784            weak_self: None,
 785            foreground_platform,
 786            assets: Arc::new(AssetCache::new(asset_source)),
 787            cx: AppContext {
 788                models: Default::default(),
 789                views: Default::default(),
 790                windows: Default::default(),
 791                app_states: Default::default(),
 792                element_states: Default::default(),
 793                ref_counts: Arc::new(Mutex::new(ref_counts)),
 794                background,
 795                font_cache,
 796                platform,
 797            },
 798            capture_actions: HashMap::new(),
 799            actions: HashMap::new(),
 800            global_actions: HashMap::new(),
 801            keystroke_matcher: keymap::Matcher::default(),
 802            next_entity_id: 0,
 803            next_window_id: 0,
 804            next_subscription_id: 0,
 805            frame_count: 0,
 806            subscriptions: Default::default(),
 807            observations: Default::default(),
 808            release_observations: Default::default(),
 809            presenters_and_platform_windows: HashMap::new(),
 810            debug_elements_callbacks: HashMap::new(),
 811            foreground,
 812            pending_effects: VecDeque::new(),
 813            pending_notifications: HashSet::new(),
 814            pending_flushes: 0,
 815            flushing_effects: false,
 816            next_cursor_style_handle_id: Default::default(),
 817            halt_action_dispatch: false,
 818        }
 819    }
 820
 821    pub fn upgrade(&self) -> App {
 822        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 823    }
 824
 825    pub fn quit(&mut self) {
 826        let mut futures = Vec::new();
 827        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
 828            let mut model = self.cx.models.remove(&model_id).unwrap();
 829            futures.extend(model.app_will_quit(self));
 830            self.cx.models.insert(model_id, model);
 831        }
 832
 833        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
 834            let mut view = self.cx.views.remove(&view_id).unwrap();
 835            futures.extend(view.app_will_quit(self));
 836            self.cx.views.insert(view_id, view);
 837        }
 838
 839        self.remove_all_windows();
 840
 841        let futures = futures::future::join_all(futures);
 842        if self
 843            .background
 844            .block_with_timeout(Duration::from_millis(100), futures)
 845            .is_err()
 846        {
 847            log::error!("timed out waiting on app_will_quit");
 848        }
 849    }
 850
 851    fn remove_all_windows(&mut self) {
 852        for (window_id, _) in self.cx.windows.drain() {
 853            self.presenters_and_platform_windows.remove(&window_id);
 854        }
 855        self.flush_effects();
 856    }
 857
 858    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 859        self.cx.platform.clone()
 860    }
 861
 862    pub fn font_cache(&self) -> &Arc<FontCache> {
 863        &self.cx.font_cache
 864    }
 865
 866    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 867        &self.foreground
 868    }
 869
 870    pub fn background(&self) -> &Arc<executor::Background> {
 871        &self.cx.background
 872    }
 873
 874    pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
 875    where
 876        F: 'static + Fn(&AppContext) -> crate::json::Value,
 877    {
 878        self.debug_elements_callbacks
 879            .insert(window_id, Box::new(callback));
 880    }
 881
 882    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 883        self.debug_elements_callbacks
 884            .get(&window_id)
 885            .map(|debug_elements| debug_elements(&self.cx))
 886    }
 887
 888    pub fn add_action<A, V, F>(&mut self, handler: F)
 889    where
 890        A: Action,
 891        V: View,
 892        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 893    {
 894        self.add_action_internal(handler, false)
 895    }
 896
 897    pub fn capture_action<A, V, F>(&mut self, handler: F)
 898    where
 899        A: Action,
 900        V: View,
 901        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 902    {
 903        self.add_action_internal(handler, true)
 904    }
 905
 906    fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
 907    where
 908        A: Action,
 909        V: View,
 910        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 911    {
 912        let handler = Box::new(
 913            move |view: &mut dyn AnyView,
 914                  action: &dyn AnyAction,
 915                  cx: &mut MutableAppContext,
 916                  window_id: usize,
 917                  view_id: usize| {
 918                let action = action.as_any().downcast_ref().unwrap();
 919                let mut cx = ViewContext::new(cx, window_id, view_id);
 920                handler(
 921                    view.as_any_mut()
 922                        .downcast_mut()
 923                        .expect("downcast is type safe"),
 924                    action,
 925                    &mut cx,
 926                );
 927            },
 928        );
 929
 930        let actions = if capture {
 931            &mut self.capture_actions
 932        } else {
 933            &mut self.actions
 934        };
 935
 936        actions
 937            .entry(TypeId::of::<V>())
 938            .or_default()
 939            .entry(TypeId::of::<A>())
 940            .or_default()
 941            .push(handler);
 942    }
 943
 944    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 945    where
 946        A: Action,
 947        V: View,
 948        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 949    {
 950        self.add_action(move |view, action, cx| {
 951            handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
 952        })
 953    }
 954
 955    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 956    where
 957        A: Action,
 958        F: 'static + FnMut(&A, &mut MutableAppContext),
 959    {
 960        let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
 961            let action = action.as_any().downcast_ref().unwrap();
 962            handler(action, cx);
 963        });
 964
 965        if self
 966            .global_actions
 967            .insert(TypeId::of::<A>(), handler)
 968            .is_some()
 969        {
 970            panic!("registered multiple global handlers for the same action type");
 971        }
 972    }
 973
 974    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 975        self.cx.windows.keys().cloned()
 976    }
 977
 978    pub fn activate_window(&self, window_id: usize) {
 979        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 980            window.activate()
 981        }
 982    }
 983
 984    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 985        self.cx
 986            .windows
 987            .get(&window_id)
 988            .and_then(|window| window.root_view.clone().downcast::<T>())
 989    }
 990
 991    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 992        self.cx.root_view_id(window_id)
 993    }
 994
 995    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 996        self.cx.focused_view_id(window_id)
 997    }
 998
 999    pub fn render_view(
1000        &mut self,
1001        window_id: usize,
1002        view_id: usize,
1003        titlebar_height: f32,
1004        refreshing: bool,
1005    ) -> Result<ElementBox> {
1006        let mut view = self
1007            .cx
1008            .views
1009            .remove(&(window_id, view_id))
1010            .ok_or(anyhow!("view not found"))?;
1011        let element = view.render(window_id, view_id, titlebar_height, refreshing, self);
1012        self.cx.views.insert((window_id, view_id), view);
1013        Ok(element)
1014    }
1015
1016    pub fn render_views(
1017        &mut self,
1018        window_id: usize,
1019        titlebar_height: f32,
1020    ) -> HashMap<usize, ElementBox> {
1021        self.start_frame();
1022        let view_ids = self
1023            .views
1024            .keys()
1025            .filter_map(|(win_id, view_id)| {
1026                if *win_id == window_id {
1027                    Some(*view_id)
1028                } else {
1029                    None
1030                }
1031            })
1032            .collect::<Vec<_>>();
1033        view_ids
1034            .into_iter()
1035            .map(|view_id| {
1036                (
1037                    view_id,
1038                    self.render_view(window_id, view_id, titlebar_height, false)
1039                        .unwrap(),
1040                )
1041            })
1042            .collect()
1043    }
1044
1045    pub(crate) fn start_frame(&mut self) {
1046        self.frame_count += 1;
1047    }
1048
1049    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1050        self.pending_flushes += 1;
1051        let result = callback(self);
1052        self.flush_effects();
1053        result
1054    }
1055
1056    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1057        self.foreground_platform.set_menus(menus);
1058    }
1059
1060    fn prompt(
1061        &self,
1062        window_id: usize,
1063        level: PromptLevel,
1064        msg: &str,
1065        answers: &[&str],
1066    ) -> oneshot::Receiver<usize> {
1067        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1068        window.prompt(level, msg, answers)
1069    }
1070
1071    pub fn prompt_for_paths(
1072        &self,
1073        options: PathPromptOptions,
1074    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1075        self.foreground_platform.prompt_for_paths(options)
1076    }
1077
1078    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1079        self.foreground_platform.prompt_for_new_path(directory)
1080    }
1081
1082    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1083    where
1084        E: Entity,
1085        E::Event: 'static,
1086        H: Handle<E>,
1087        F: 'static + FnMut(H, &E::Event, &mut Self),
1088    {
1089        self.subscribe_internal(handle, move |handle, event, cx| {
1090            callback(handle, event, cx);
1091            true
1092        })
1093    }
1094
1095    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1096    where
1097        E: Entity,
1098        E::Event: 'static,
1099        H: Handle<E>,
1100        F: 'static + FnMut(H, &mut Self),
1101    {
1102        self.observe_internal(handle, move |handle, cx| {
1103            callback(handle, cx);
1104            true
1105        })
1106    }
1107
1108    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1109    where
1110        E: Entity,
1111        E::Event: 'static,
1112        H: Handle<E>,
1113        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1114    {
1115        let id = post_inc(&mut self.next_subscription_id);
1116        let emitter = handle.downgrade();
1117        self.subscriptions
1118            .lock()
1119            .entry(handle.id())
1120            .or_default()
1121            .insert(
1122                id,
1123                Box::new(move |payload, cx| {
1124                    if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1125                        let payload = payload.downcast_ref().expect("downcast is type safe");
1126                        callback(emitter, payload, cx)
1127                    } else {
1128                        false
1129                    }
1130                }),
1131            );
1132        Subscription::Subscription {
1133            id,
1134            entity_id: handle.id(),
1135            subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1136        }
1137    }
1138
1139    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1140    where
1141        E: Entity,
1142        E::Event: 'static,
1143        H: Handle<E>,
1144        F: 'static + FnMut(H, &mut Self) -> bool,
1145    {
1146        let id = post_inc(&mut self.next_subscription_id);
1147        let observed = handle.downgrade();
1148        self.observations
1149            .lock()
1150            .entry(handle.id())
1151            .or_default()
1152            .insert(
1153                id,
1154                Box::new(move |cx| {
1155                    if let Some(observed) = H::upgrade_from(&observed, cx) {
1156                        callback(observed, cx)
1157                    } else {
1158                        false
1159                    }
1160                }),
1161            );
1162        Subscription::Observation {
1163            id,
1164            entity_id: handle.id(),
1165            observations: Some(Arc::downgrade(&self.observations)),
1166        }
1167    }
1168
1169    pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1170    where
1171        E: Entity,
1172        E::Event: 'static,
1173        H: Handle<E>,
1174        F: 'static + FnMut(&mut Self),
1175    {
1176        let id = post_inc(&mut self.next_subscription_id);
1177        self.release_observations
1178            .lock()
1179            .entry(handle.id())
1180            .or_default()
1181            .insert(id, Box::new(move |cx| callback(cx)));
1182        Subscription::ReleaseObservation {
1183            id,
1184            entity_id: handle.id(),
1185            observations: Some(Arc::downgrade(&self.release_observations)),
1186        }
1187    }
1188
1189    fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1190        self.pending_effects.push_back(Effect::Deferred(callback))
1191    }
1192
1193    pub(crate) fn notify_model(&mut self, model_id: usize) {
1194        if self.pending_notifications.insert(model_id) {
1195            self.pending_effects
1196                .push_back(Effect::ModelNotification { model_id });
1197        }
1198    }
1199
1200    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1201        if self.pending_notifications.insert(view_id) {
1202            self.pending_effects
1203                .push_back(Effect::ViewNotification { window_id, view_id });
1204        }
1205    }
1206
1207    pub fn dispatch_action<A: Action>(
1208        &mut self,
1209        window_id: usize,
1210        responder_chain: Vec<usize>,
1211        action: &A,
1212    ) {
1213        self.dispatch_action_any(window_id, &responder_chain, action);
1214    }
1215
1216    pub(crate) fn dispatch_action_any(
1217        &mut self,
1218        window_id: usize,
1219        path: &[usize],
1220        action: &dyn AnyAction,
1221    ) -> bool {
1222        self.update(|this| {
1223            this.halt_action_dispatch = false;
1224            for (capture_phase, view_id) in path
1225                .iter()
1226                .map(|view_id| (true, *view_id))
1227                .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1228            {
1229                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1230                    let type_id = view.as_any().type_id();
1231
1232                    if let Some((name, mut handlers)) = this
1233                        .actions_mut(capture_phase)
1234                        .get_mut(&type_id)
1235                        .and_then(|h| h.remove_entry(&action.id()))
1236                    {
1237                        for handler in handlers.iter_mut().rev() {
1238                            this.halt_action_dispatch = true;
1239                            handler(view.as_mut(), action, this, window_id, view_id);
1240                            if this.halt_action_dispatch {
1241                                break;
1242                            }
1243                        }
1244                        this.actions_mut(capture_phase)
1245                            .get_mut(&type_id)
1246                            .unwrap()
1247                            .insert(name, handlers);
1248                    }
1249
1250                    this.cx.views.insert((window_id, view_id), view);
1251
1252                    if this.halt_action_dispatch {
1253                        break;
1254                    }
1255                }
1256            }
1257
1258            if !this.halt_action_dispatch {
1259                this.dispatch_global_action_any(action);
1260            }
1261            this.halt_action_dispatch
1262        })
1263    }
1264
1265    fn actions_mut(
1266        &mut self,
1267        capture_phase: bool,
1268    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1269        if capture_phase {
1270            &mut self.capture_actions
1271        } else {
1272            &mut self.actions
1273        }
1274    }
1275
1276    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1277        self.dispatch_global_action_any(&action);
1278    }
1279
1280    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1281        self.update(|this| {
1282            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1283                handler(action, this);
1284                this.global_actions.insert(name, handler);
1285                true
1286            } else {
1287                false
1288            }
1289        })
1290    }
1291
1292    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1293        self.keystroke_matcher.add_bindings(bindings);
1294    }
1295
1296    pub fn dispatch_keystroke(
1297        &mut self,
1298        window_id: usize,
1299        responder_chain: Vec<usize>,
1300        keystroke: &Keystroke,
1301    ) -> Result<bool> {
1302        let mut context_chain = Vec::new();
1303        for view_id in &responder_chain {
1304            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1305                context_chain.push(view.keymap_context(self.as_ref()));
1306            } else {
1307                return Err(anyhow!(
1308                    "View {} in responder chain does not exist",
1309                    view_id
1310                ));
1311            }
1312        }
1313
1314        let mut pending = false;
1315        for (i, cx) in context_chain.iter().enumerate().rev() {
1316            match self
1317                .keystroke_matcher
1318                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1319            {
1320                MatchResult::None => {}
1321                MatchResult::Pending => pending = true,
1322                MatchResult::Action(action) => {
1323                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1324                    {
1325                        self.keystroke_matcher.clear_pending();
1326                        return Ok(true);
1327                    }
1328                }
1329            }
1330        }
1331
1332        Ok(pending)
1333    }
1334
1335    pub fn add_app_state<T: 'static>(&mut self, state: T) {
1336        self.cx
1337            .app_states
1338            .insert(TypeId::of::<T>(), Box::new(state));
1339    }
1340
1341    pub fn update_app_state<T: 'static, F, U>(&mut self, update: F) -> U
1342    where
1343        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1344    {
1345        let type_id = TypeId::of::<T>();
1346        let mut state = self
1347            .cx
1348            .app_states
1349            .remove(&type_id)
1350            .expect("no app state has been added for this type");
1351        let result = update(state.downcast_mut().unwrap(), self);
1352        self.cx.app_states.insert(type_id, state);
1353        result
1354    }
1355
1356    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1357    where
1358        T: Entity,
1359        F: FnOnce(&mut ModelContext<T>) -> T,
1360    {
1361        self.update(|this| {
1362            let model_id = post_inc(&mut this.next_entity_id);
1363            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1364            let mut cx = ModelContext::new(this, model_id);
1365            let model = build_model(&mut cx);
1366            this.cx.models.insert(model_id, Box::new(model));
1367            handle
1368        })
1369    }
1370
1371    pub fn add_window<T, F>(
1372        &mut self,
1373        window_options: WindowOptions,
1374        build_root_view: F,
1375    ) -> (usize, ViewHandle<T>)
1376    where
1377        T: View,
1378        F: FnOnce(&mut ViewContext<T>) -> T,
1379    {
1380        self.update(|this| {
1381            let window_id = post_inc(&mut this.next_window_id);
1382            let root_view = this.add_view(window_id, build_root_view);
1383
1384            this.cx.windows.insert(
1385                window_id,
1386                Window {
1387                    root_view: root_view.clone().into(),
1388                    focused_view_id: root_view.id(),
1389                    invalidation: None,
1390                },
1391            );
1392            this.open_platform_window(window_id, window_options);
1393            root_view.update(this, |view, cx| {
1394                view.on_focus(cx);
1395                cx.notify();
1396            });
1397
1398            (window_id, root_view)
1399        })
1400    }
1401
1402    pub fn remove_window(&mut self, window_id: usize) {
1403        self.cx.windows.remove(&window_id);
1404        self.presenters_and_platform_windows.remove(&window_id);
1405        self.flush_effects();
1406    }
1407
1408    fn open_platform_window(&mut self, window_id: usize, window_options: WindowOptions) {
1409        let mut window =
1410            self.cx
1411                .platform
1412                .open_window(window_id, window_options, self.foreground.clone());
1413        let presenter = Rc::new(RefCell::new(
1414            self.build_presenter(window_id, window.titlebar_height()),
1415        ));
1416
1417        {
1418            let mut app = self.upgrade();
1419            let presenter = presenter.clone();
1420            window.on_event(Box::new(move |event| {
1421                app.update(|cx| {
1422                    if let Event::KeyDown { keystroke, .. } = &event {
1423                        if cx
1424                            .dispatch_keystroke(
1425                                window_id,
1426                                presenter.borrow().dispatch_path(cx.as_ref()),
1427                                keystroke,
1428                            )
1429                            .unwrap()
1430                        {
1431                            return;
1432                        }
1433                    }
1434
1435                    presenter.borrow_mut().dispatch_event(event, cx);
1436                })
1437            }));
1438        }
1439
1440        {
1441            let mut app = self.upgrade();
1442            window.on_resize(Box::new(move || {
1443                app.update(|cx| cx.resize_window(window_id))
1444            }));
1445        }
1446
1447        {
1448            let mut app = self.upgrade();
1449            window.on_close(Box::new(move || {
1450                app.update(|cx| cx.remove_window(window_id));
1451            }));
1452        }
1453
1454        self.presenters_and_platform_windows
1455            .insert(window_id, (presenter.clone(), window));
1456
1457        self.on_debug_elements(window_id, move |cx| {
1458            presenter.borrow().debug_elements(cx).unwrap()
1459        });
1460    }
1461
1462    pub fn build_presenter(&mut self, window_id: usize, titlebar_height: f32) -> Presenter {
1463        Presenter::new(
1464            window_id,
1465            titlebar_height,
1466            self.cx.font_cache.clone(),
1467            TextLayoutCache::new(self.cx.platform.fonts()),
1468            self.assets.clone(),
1469            self,
1470        )
1471    }
1472
1473    pub fn build_render_context<V: View>(
1474        &mut self,
1475        window_id: usize,
1476        view_id: usize,
1477        titlebar_height: f32,
1478        refreshing: bool,
1479    ) -> RenderContext<V> {
1480        RenderContext {
1481            app: self,
1482            titlebar_height,
1483            refreshing,
1484            window_id,
1485            view_id,
1486            view_type: PhantomData,
1487        }
1488    }
1489
1490    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1491    where
1492        T: View,
1493        F: FnOnce(&mut ViewContext<T>) -> T,
1494    {
1495        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1496            .unwrap()
1497    }
1498
1499    pub fn add_option_view<T, F>(
1500        &mut self,
1501        window_id: usize,
1502        build_view: F,
1503    ) -> Option<ViewHandle<T>>
1504    where
1505        T: View,
1506        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1507    {
1508        self.update(|this| {
1509            let view_id = post_inc(&mut this.next_entity_id);
1510            let mut cx = ViewContext::new(this, window_id, view_id);
1511            let handle = if let Some(view) = build_view(&mut cx) {
1512                this.cx.views.insert((window_id, view_id), Box::new(view));
1513                if let Some(window) = this.cx.windows.get_mut(&window_id) {
1514                    window
1515                        .invalidation
1516                        .get_or_insert_with(Default::default)
1517                        .updated
1518                        .insert(view_id);
1519                }
1520                Some(ViewHandle::new(window_id, view_id, &this.cx.ref_counts))
1521            } else {
1522                None
1523            };
1524            handle
1525        })
1526    }
1527
1528    fn remove_dropped_entities(&mut self) {
1529        loop {
1530            let (dropped_models, dropped_views, dropped_element_states) =
1531                self.cx.ref_counts.lock().take_dropped();
1532            if dropped_models.is_empty()
1533                && dropped_views.is_empty()
1534                && dropped_element_states.is_empty()
1535            {
1536                break;
1537            }
1538
1539            for model_id in dropped_models {
1540                self.subscriptions.lock().remove(&model_id);
1541                self.observations.lock().remove(&model_id);
1542                let mut model = self.cx.models.remove(&model_id).unwrap();
1543                model.release(self);
1544                self.pending_effects.push_back(Effect::Release {
1545                    entity_id: model_id,
1546                });
1547            }
1548
1549            for (window_id, view_id) in dropped_views {
1550                self.subscriptions.lock().remove(&view_id);
1551                self.observations.lock().remove(&view_id);
1552                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1553                view.release(self);
1554                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1555                    window
1556                        .invalidation
1557                        .get_or_insert_with(Default::default)
1558                        .removed
1559                        .push(view_id);
1560                    if window.focused_view_id == view_id {
1561                        Some(window.root_view.id())
1562                    } else {
1563                        None
1564                    }
1565                });
1566
1567                if let Some(view_id) = change_focus_to {
1568                    self.focus(window_id, view_id);
1569                }
1570
1571                self.pending_effects
1572                    .push_back(Effect::Release { entity_id: view_id });
1573            }
1574
1575            for key in dropped_element_states {
1576                self.cx.element_states.remove(&key);
1577            }
1578        }
1579    }
1580
1581    fn flush_effects(&mut self) {
1582        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1583
1584        if !self.flushing_effects && self.pending_flushes == 0 {
1585            self.flushing_effects = true;
1586
1587            let mut refreshing = false;
1588            loop {
1589                if let Some(effect) = self.pending_effects.pop_front() {
1590                    match effect {
1591                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1592                        Effect::ModelNotification { model_id } => {
1593                            self.notify_model_observers(model_id)
1594                        }
1595                        Effect::ViewNotification { window_id, view_id } => {
1596                            self.notify_view_observers(window_id, view_id)
1597                        }
1598                        Effect::Deferred(callback) => callback(self),
1599                        Effect::Release { entity_id } => self.notify_release_observers(entity_id),
1600                        Effect::Focus { window_id, view_id } => {
1601                            self.focus(window_id, view_id);
1602                        }
1603                        Effect::ResizeWindow { window_id } => {
1604                            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1605                                window
1606                                    .invalidation
1607                                    .get_or_insert(WindowInvalidation::default());
1608                            }
1609                        }
1610                        Effect::RefreshWindows => {
1611                            refreshing = true;
1612                        }
1613                    }
1614                    self.pending_notifications.clear();
1615                    self.remove_dropped_entities();
1616                } else {
1617                    self.remove_dropped_entities();
1618                    if refreshing {
1619                        self.perform_window_refresh();
1620                    } else {
1621                        self.update_windows();
1622                    }
1623
1624                    if self.pending_effects.is_empty() {
1625                        self.flushing_effects = false;
1626                        self.pending_notifications.clear();
1627                        break;
1628                    } else {
1629                        refreshing = false;
1630                    }
1631                }
1632            }
1633        }
1634    }
1635
1636    fn update_windows(&mut self) {
1637        let mut invalidations = HashMap::new();
1638        for (window_id, window) in &mut self.cx.windows {
1639            if let Some(invalidation) = window.invalidation.take() {
1640                invalidations.insert(*window_id, invalidation);
1641            }
1642        }
1643
1644        for (window_id, invalidation) in invalidations {
1645            if let Some((presenter, mut window)) =
1646                self.presenters_and_platform_windows.remove(&window_id)
1647            {
1648                {
1649                    let mut presenter = presenter.borrow_mut();
1650                    presenter.invalidate(invalidation, self);
1651                    let scene =
1652                        presenter.build_scene(window.size(), window.scale_factor(), false, self);
1653                    window.present_scene(scene);
1654                }
1655                self.presenters_and_platform_windows
1656                    .insert(window_id, (presenter, window));
1657            }
1658        }
1659    }
1660
1661    fn resize_window(&mut self, window_id: usize) {
1662        self.pending_effects
1663            .push_back(Effect::ResizeWindow { window_id });
1664    }
1665
1666    pub fn refresh_windows(&mut self) {
1667        self.pending_effects.push_back(Effect::RefreshWindows);
1668    }
1669
1670    fn perform_window_refresh(&mut self) {
1671        let mut presenters = mem::take(&mut self.presenters_and_platform_windows);
1672        for (window_id, (presenter, window)) in &mut presenters {
1673            let invalidation = self
1674                .cx
1675                .windows
1676                .get_mut(&window_id)
1677                .unwrap()
1678                .invalidation
1679                .take();
1680            let mut presenter = presenter.borrow_mut();
1681            presenter.refresh(invalidation, self);
1682            let scene = presenter.build_scene(window.size(), window.scale_factor(), true, self);
1683            window.present_scene(scene);
1684        }
1685        self.presenters_and_platform_windows = presenters;
1686    }
1687
1688    pub fn set_cursor_style(&mut self, style: CursorStyle) -> CursorStyleHandle {
1689        self.platform.set_cursor_style(style);
1690        let id = self.next_cursor_style_handle_id.fetch_add(1, SeqCst);
1691        CursorStyleHandle {
1692            id,
1693            next_cursor_style_handle_id: self.next_cursor_style_handle_id.clone(),
1694            platform: self.platform(),
1695        }
1696    }
1697
1698    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1699        let callbacks = self.subscriptions.lock().remove(&entity_id);
1700        if let Some(callbacks) = callbacks {
1701            for (id, mut callback) in callbacks {
1702                let alive = callback(payload.as_ref(), self);
1703                if alive {
1704                    self.subscriptions
1705                        .lock()
1706                        .entry(entity_id)
1707                        .or_default()
1708                        .insert(id, callback);
1709                }
1710            }
1711        }
1712    }
1713
1714    fn notify_model_observers(&mut self, observed_id: usize) {
1715        let callbacks = self.observations.lock().remove(&observed_id);
1716        if let Some(callbacks) = callbacks {
1717            if self.cx.models.contains_key(&observed_id) {
1718                for (id, mut callback) in callbacks {
1719                    let alive = callback(self);
1720                    if alive {
1721                        self.observations
1722                            .lock()
1723                            .entry(observed_id)
1724                            .or_default()
1725                            .insert(id, callback);
1726                    }
1727                }
1728            }
1729        }
1730    }
1731
1732    fn notify_view_observers(&mut self, observed_window_id: usize, observed_view_id: usize) {
1733        if let Some(window) = self.cx.windows.get_mut(&observed_window_id) {
1734            window
1735                .invalidation
1736                .get_or_insert_with(Default::default)
1737                .updated
1738                .insert(observed_view_id);
1739        }
1740
1741        let callbacks = self.observations.lock().remove(&observed_view_id);
1742        if let Some(callbacks) = callbacks {
1743            if self
1744                .cx
1745                .views
1746                .contains_key(&(observed_window_id, observed_view_id))
1747            {
1748                for (id, mut callback) in callbacks {
1749                    let alive = callback(self);
1750                    if alive {
1751                        self.observations
1752                            .lock()
1753                            .entry(observed_view_id)
1754                            .or_default()
1755                            .insert(id, callback);
1756                    }
1757                }
1758            }
1759        }
1760    }
1761
1762    fn notify_release_observers(&mut self, entity_id: usize) {
1763        let callbacks = self.release_observations.lock().remove(&entity_id);
1764        if let Some(callbacks) = callbacks {
1765            for (_, mut callback) in callbacks {
1766                callback(self);
1767            }
1768        }
1769    }
1770
1771    fn focus(&mut self, window_id: usize, focused_id: usize) {
1772        if self
1773            .cx
1774            .windows
1775            .get(&window_id)
1776            .map(|w| w.focused_view_id)
1777            .map_or(false, |cur_focused| cur_focused == focused_id)
1778        {
1779            return;
1780        }
1781
1782        self.update(|this| {
1783            let blurred_id = this.cx.windows.get_mut(&window_id).map(|window| {
1784                let blurred_id = window.focused_view_id;
1785                window.focused_view_id = focused_id;
1786                blurred_id
1787            });
1788
1789            if let Some(blurred_id) = blurred_id {
1790                if let Some(mut blurred_view) = this.cx.views.remove(&(window_id, blurred_id)) {
1791                    blurred_view.on_blur(this, window_id, blurred_id);
1792                    this.cx.views.insert((window_id, blurred_id), blurred_view);
1793                }
1794            }
1795
1796            if let Some(mut focused_view) = this.cx.views.remove(&(window_id, focused_id)) {
1797                focused_view.on_focus(this, window_id, focused_id);
1798                this.cx.views.insert((window_id, focused_id), focused_view);
1799            }
1800        })
1801    }
1802
1803    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1804    where
1805        F: FnOnce(AsyncAppContext) -> Fut,
1806        Fut: 'static + Future<Output = T>,
1807        T: 'static,
1808    {
1809        let future = f(self.to_async());
1810        let cx = self.to_async();
1811        self.foreground.spawn(async move {
1812            let result = future.await;
1813            cx.0.borrow_mut().flush_effects();
1814            result
1815        })
1816    }
1817
1818    pub fn to_async(&self) -> AsyncAppContext {
1819        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1820    }
1821
1822    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1823        self.cx.platform.write_to_clipboard(item);
1824    }
1825
1826    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1827        self.cx.platform.read_from_clipboard()
1828    }
1829
1830    #[cfg(feature = "test-support")]
1831    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
1832        self.cx.ref_counts.lock().leak_detector.clone()
1833    }
1834}
1835
1836impl ReadModel for MutableAppContext {
1837    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1838        if let Some(model) = self.cx.models.get(&handle.model_id) {
1839            model
1840                .as_any()
1841                .downcast_ref()
1842                .expect("downcast is type safe")
1843        } else {
1844            panic!("circular model reference");
1845        }
1846    }
1847}
1848
1849impl UpdateModel for MutableAppContext {
1850    fn update_model<T: Entity, V>(
1851        &mut self,
1852        handle: &ModelHandle<T>,
1853        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1854    ) -> V {
1855        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1856            self.update(|this| {
1857                let mut cx = ModelContext::new(this, handle.model_id);
1858                let result = update(
1859                    model
1860                        .as_any_mut()
1861                        .downcast_mut()
1862                        .expect("downcast is type safe"),
1863                    &mut cx,
1864                );
1865                this.cx.models.insert(handle.model_id, model);
1866                result
1867            })
1868        } else {
1869            panic!("circular model update");
1870        }
1871    }
1872}
1873
1874impl UpgradeModelHandle for MutableAppContext {
1875    fn upgrade_model_handle<T: Entity>(
1876        &self,
1877        handle: &WeakModelHandle<T>,
1878    ) -> Option<ModelHandle<T>> {
1879        self.cx.upgrade_model_handle(handle)
1880    }
1881
1882    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1883        self.cx.model_handle_is_upgradable(handle)
1884    }
1885
1886    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1887        self.cx.upgrade_any_model_handle(handle)
1888    }
1889}
1890
1891impl UpgradeViewHandle for MutableAppContext {
1892    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1893        self.cx.upgrade_view_handle(handle)
1894    }
1895}
1896
1897impl ReadView for MutableAppContext {
1898    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1899        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1900            view.as_any().downcast_ref().expect("downcast is type safe")
1901        } else {
1902            panic!("circular view reference");
1903        }
1904    }
1905}
1906
1907impl UpdateView for MutableAppContext {
1908    fn update_view<T, S>(
1909        &mut self,
1910        handle: &ViewHandle<T>,
1911        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
1912    ) -> S
1913    where
1914        T: View,
1915    {
1916        self.update(|this| {
1917            let mut view = this
1918                .cx
1919                .views
1920                .remove(&(handle.window_id, handle.view_id))
1921                .expect("circular view update");
1922
1923            let mut cx = ViewContext::new(this, handle.window_id, handle.view_id);
1924            let result = update(
1925                view.as_any_mut()
1926                    .downcast_mut()
1927                    .expect("downcast is type safe"),
1928                &mut cx,
1929            );
1930            this.cx
1931                .views
1932                .insert((handle.window_id, handle.view_id), view);
1933            result
1934        })
1935    }
1936}
1937
1938impl AsRef<AppContext> for MutableAppContext {
1939    fn as_ref(&self) -> &AppContext {
1940        &self.cx
1941    }
1942}
1943
1944impl Deref for MutableAppContext {
1945    type Target = AppContext;
1946
1947    fn deref(&self) -> &Self::Target {
1948        &self.cx
1949    }
1950}
1951
1952pub struct AppContext {
1953    models: HashMap<usize, Box<dyn AnyModel>>,
1954    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1955    windows: HashMap<usize, Window>,
1956    app_states: HashMap<TypeId, Box<dyn Any>>,
1957    element_states: HashMap<ElementStateId, Box<dyn Any>>,
1958    background: Arc<executor::Background>,
1959    ref_counts: Arc<Mutex<RefCounts>>,
1960    font_cache: Arc<FontCache>,
1961    platform: Arc<dyn Platform>,
1962}
1963
1964impl AppContext {
1965    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1966        self.windows
1967            .get(&window_id)
1968            .map(|window| window.root_view.id())
1969    }
1970
1971    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1972        self.windows
1973            .get(&window_id)
1974            .map(|window| window.focused_view_id)
1975    }
1976
1977    pub fn background(&self) -> &Arc<executor::Background> {
1978        &self.background
1979    }
1980
1981    pub fn font_cache(&self) -> &Arc<FontCache> {
1982        &self.font_cache
1983    }
1984
1985    pub fn platform(&self) -> &Arc<dyn Platform> {
1986        &self.platform
1987    }
1988
1989    pub fn app_state<T: 'static>(&self) -> &T {
1990        self.app_states
1991            .get(&TypeId::of::<T>())
1992            .expect("no app state has been added for this type")
1993            .downcast_ref()
1994            .unwrap()
1995    }
1996}
1997
1998impl ReadModel for AppContext {
1999    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2000        if let Some(model) = self.models.get(&handle.model_id) {
2001            model
2002                .as_any()
2003                .downcast_ref()
2004                .expect("downcast should be type safe")
2005        } else {
2006            panic!("circular model reference");
2007        }
2008    }
2009}
2010
2011impl UpgradeModelHandle for AppContext {
2012    fn upgrade_model_handle<T: Entity>(
2013        &self,
2014        handle: &WeakModelHandle<T>,
2015    ) -> Option<ModelHandle<T>> {
2016        if self.models.contains_key(&handle.model_id) {
2017            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
2018        } else {
2019            None
2020        }
2021    }
2022
2023    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2024        self.models.contains_key(&handle.model_id)
2025    }
2026
2027    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2028        if self.models.contains_key(&handle.model_id) {
2029            Some(AnyModelHandle::new(
2030                handle.model_id,
2031                handle.model_type,
2032                self.ref_counts.clone(),
2033            ))
2034        } else {
2035            None
2036        }
2037    }
2038}
2039
2040impl UpgradeViewHandle for AppContext {
2041    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2042        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
2043            Some(ViewHandle::new(
2044                handle.window_id,
2045                handle.view_id,
2046                &self.ref_counts,
2047            ))
2048        } else {
2049            None
2050        }
2051    }
2052}
2053
2054impl ReadView for AppContext {
2055    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2056        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
2057            view.as_any()
2058                .downcast_ref()
2059                .expect("downcast should be type safe")
2060        } else {
2061            panic!("circular view reference");
2062        }
2063    }
2064}
2065
2066struct Window {
2067    root_view: AnyViewHandle,
2068    focused_view_id: usize,
2069    invalidation: Option<WindowInvalidation>,
2070}
2071
2072#[derive(Default, Clone)]
2073pub struct WindowInvalidation {
2074    pub updated: HashSet<usize>,
2075    pub removed: Vec<usize>,
2076}
2077
2078pub enum Effect {
2079    Event {
2080        entity_id: usize,
2081        payload: Box<dyn Any>,
2082    },
2083    ModelNotification {
2084        model_id: usize,
2085    },
2086    ViewNotification {
2087        window_id: usize,
2088        view_id: usize,
2089    },
2090    Deferred(Box<dyn FnOnce(&mut MutableAppContext)>),
2091    Release {
2092        entity_id: usize,
2093    },
2094    Focus {
2095        window_id: usize,
2096        view_id: usize,
2097    },
2098    ResizeWindow {
2099        window_id: usize,
2100    },
2101    RefreshWindows,
2102}
2103
2104impl Debug for Effect {
2105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2106        match self {
2107            Effect::Event { entity_id, .. } => f
2108                .debug_struct("Effect::Event")
2109                .field("entity_id", entity_id)
2110                .finish(),
2111            Effect::ModelNotification { model_id } => f
2112                .debug_struct("Effect::ModelNotification")
2113                .field("model_id", model_id)
2114                .finish(),
2115            Effect::ViewNotification { window_id, view_id } => f
2116                .debug_struct("Effect::ViewNotification")
2117                .field("window_id", window_id)
2118                .field("view_id", view_id)
2119                .finish(),
2120            Effect::Deferred(_) => f.debug_struct("Effect::Deferred").finish(),
2121            Effect::Release { entity_id } => f
2122                .debug_struct("Effect::Release")
2123                .field("entity_id", entity_id)
2124                .finish(),
2125            Effect::Focus { window_id, view_id } => f
2126                .debug_struct("Effect::Focus")
2127                .field("window_id", window_id)
2128                .field("view_id", view_id)
2129                .finish(),
2130            Effect::ResizeWindow { window_id } => f
2131                .debug_struct("Effect::RefreshWindow")
2132                .field("window_id", window_id)
2133                .finish(),
2134            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2135        }
2136    }
2137}
2138
2139pub trait AnyModel {
2140    fn as_any(&self) -> &dyn Any;
2141    fn as_any_mut(&mut self) -> &mut dyn Any;
2142    fn release(&mut self, cx: &mut MutableAppContext);
2143    fn app_will_quit(
2144        &mut self,
2145        cx: &mut MutableAppContext,
2146    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2147}
2148
2149impl<T> AnyModel for T
2150where
2151    T: Entity,
2152{
2153    fn as_any(&self) -> &dyn Any {
2154        self
2155    }
2156
2157    fn as_any_mut(&mut self) -> &mut dyn Any {
2158        self
2159    }
2160
2161    fn release(&mut self, cx: &mut MutableAppContext) {
2162        self.release(cx);
2163    }
2164
2165    fn app_will_quit(
2166        &mut self,
2167        cx: &mut MutableAppContext,
2168    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2169        self.app_will_quit(cx)
2170    }
2171}
2172
2173pub trait AnyView {
2174    fn as_any(&self) -> &dyn Any;
2175    fn as_any_mut(&mut self) -> &mut dyn Any;
2176    fn release(&mut self, cx: &mut MutableAppContext);
2177    fn app_will_quit(
2178        &mut self,
2179        cx: &mut MutableAppContext,
2180    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2181    fn ui_name(&self) -> &'static str;
2182    fn render<'a>(
2183        &mut self,
2184        window_id: usize,
2185        view_id: usize,
2186        titlebar_height: f32,
2187        refreshing: bool,
2188        cx: &mut MutableAppContext,
2189    ) -> ElementBox;
2190    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2191    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
2192    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
2193}
2194
2195impl<T> AnyView for T
2196where
2197    T: View,
2198{
2199    fn as_any(&self) -> &dyn Any {
2200        self
2201    }
2202
2203    fn as_any_mut(&mut self) -> &mut dyn Any {
2204        self
2205    }
2206
2207    fn release(&mut self, cx: &mut MutableAppContext) {
2208        self.release(cx);
2209    }
2210
2211    fn app_will_quit(
2212        &mut self,
2213        cx: &mut MutableAppContext,
2214    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2215        self.app_will_quit(cx)
2216    }
2217
2218    fn ui_name(&self) -> &'static str {
2219        T::ui_name()
2220    }
2221
2222    fn render<'a>(
2223        &mut self,
2224        window_id: usize,
2225        view_id: usize,
2226        titlebar_height: f32,
2227        refreshing: bool,
2228        cx: &mut MutableAppContext,
2229    ) -> ElementBox {
2230        View::render(
2231            self,
2232            &mut RenderContext {
2233                window_id,
2234                view_id,
2235                app: cx,
2236                view_type: PhantomData::<T>,
2237                titlebar_height,
2238                refreshing,
2239            },
2240        )
2241    }
2242
2243    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2244        let mut cx = ViewContext::new(cx, window_id, view_id);
2245        View::on_focus(self, &mut cx);
2246    }
2247
2248    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
2249        let mut cx = ViewContext::new(cx, window_id, view_id);
2250        View::on_blur(self, &mut cx);
2251    }
2252
2253    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
2254        View::keymap_context(self, cx)
2255    }
2256}
2257
2258pub struct ModelContext<'a, T: ?Sized> {
2259    app: &'a mut MutableAppContext,
2260    model_id: usize,
2261    model_type: PhantomData<T>,
2262    halt_stream: bool,
2263}
2264
2265impl<'a, T: Entity> ModelContext<'a, T> {
2266    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
2267        Self {
2268            app,
2269            model_id,
2270            model_type: PhantomData,
2271            halt_stream: false,
2272        }
2273    }
2274
2275    pub fn background(&self) -> &Arc<executor::Background> {
2276        &self.app.cx.background
2277    }
2278
2279    pub fn halt_stream(&mut self) {
2280        self.halt_stream = true;
2281    }
2282
2283    pub fn model_id(&self) -> usize {
2284        self.model_id
2285    }
2286
2287    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2288    where
2289        S: Entity,
2290        F: FnOnce(&mut ModelContext<S>) -> S,
2291    {
2292        self.app.add_model(build_model)
2293    }
2294
2295    pub fn emit(&mut self, payload: T::Event) {
2296        self.app.pending_effects.push_back(Effect::Event {
2297            entity_id: self.model_id,
2298            payload: Box::new(payload),
2299        });
2300    }
2301
2302    pub fn notify(&mut self) {
2303        self.app.notify_model(self.model_id);
2304    }
2305
2306    pub fn subscribe<S: Entity, F>(
2307        &mut self,
2308        handle: &ModelHandle<S>,
2309        mut callback: F,
2310    ) -> Subscription
2311    where
2312        S::Event: 'static,
2313        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2314    {
2315        let subscriber = self.weak_handle();
2316        self.app
2317            .subscribe_internal(handle, move |emitter, event, cx| {
2318                if let Some(subscriber) = subscriber.upgrade(cx) {
2319                    subscriber.update(cx, |subscriber, cx| {
2320                        callback(subscriber, emitter, event, cx);
2321                    });
2322                    true
2323                } else {
2324                    false
2325                }
2326            })
2327    }
2328
2329    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2330    where
2331        S: Entity,
2332        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2333    {
2334        let observer = self.weak_handle();
2335        self.app.observe_internal(handle, move |observed, cx| {
2336            if let Some(observer) = observer.upgrade(cx) {
2337                observer.update(cx, |observer, cx| {
2338                    callback(observer, observed, cx);
2339                });
2340                true
2341            } else {
2342                false
2343            }
2344        })
2345    }
2346
2347    pub fn observe_release<S, F>(
2348        &mut self,
2349        handle: &ModelHandle<S>,
2350        mut callback: F,
2351    ) -> Subscription
2352    where
2353        S: Entity,
2354        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2355    {
2356        let observer = self.weak_handle();
2357        self.app.observe_release(handle, move |cx| {
2358            if let Some(observer) = observer.upgrade(cx) {
2359                observer.update(cx, |observer, cx| {
2360                    callback(observer, cx);
2361                });
2362            }
2363        })
2364    }
2365
2366    pub fn handle(&self) -> ModelHandle<T> {
2367        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
2368    }
2369
2370    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2371        WeakModelHandle::new(self.model_id)
2372    }
2373
2374    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2375    where
2376        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2377        Fut: 'static + Future<Output = S>,
2378        S: 'static,
2379    {
2380        let handle = self.handle();
2381        self.app.spawn(|cx| f(handle, cx))
2382    }
2383
2384    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2385    where
2386        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2387        Fut: 'static + Future<Output = S>,
2388        S: 'static,
2389    {
2390        let handle = self.weak_handle();
2391        self.app.spawn(|cx| f(handle, cx))
2392    }
2393}
2394
2395impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2396    fn as_ref(&self) -> &AppContext {
2397        &self.app.cx
2398    }
2399}
2400
2401impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
2402    fn as_mut(&mut self) -> &mut MutableAppContext {
2403        self.app
2404    }
2405}
2406
2407impl<M> ReadModel for ModelContext<'_, M> {
2408    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2409        self.app.read_model(handle)
2410    }
2411}
2412
2413impl<M> UpdateModel for ModelContext<'_, M> {
2414    fn update_model<T: Entity, V>(
2415        &mut self,
2416        handle: &ModelHandle<T>,
2417        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
2418    ) -> V {
2419        self.app.update_model(handle, update)
2420    }
2421}
2422
2423impl<M> UpgradeModelHandle for ModelContext<'_, M> {
2424    fn upgrade_model_handle<T: Entity>(
2425        &self,
2426        handle: &WeakModelHandle<T>,
2427    ) -> Option<ModelHandle<T>> {
2428        self.cx.upgrade_model_handle(handle)
2429    }
2430
2431    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2432        self.cx.model_handle_is_upgradable(handle)
2433    }
2434
2435    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2436        self.cx.upgrade_any_model_handle(handle)
2437    }
2438}
2439
2440impl<M> Deref for ModelContext<'_, M> {
2441    type Target = MutableAppContext;
2442
2443    fn deref(&self) -> &Self::Target {
2444        &self.app
2445    }
2446}
2447
2448impl<M> DerefMut for ModelContext<'_, M> {
2449    fn deref_mut(&mut self) -> &mut Self::Target {
2450        &mut self.app
2451    }
2452}
2453
2454pub struct ViewContext<'a, T: ?Sized> {
2455    app: &'a mut MutableAppContext,
2456    window_id: usize,
2457    view_id: usize,
2458    view_type: PhantomData<T>,
2459}
2460
2461impl<'a, T: View> ViewContext<'a, T> {
2462    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
2463        Self {
2464            app,
2465            window_id,
2466            view_id,
2467            view_type: PhantomData,
2468        }
2469    }
2470
2471    pub fn handle(&self) -> ViewHandle<T> {
2472        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
2473    }
2474
2475    pub fn weak_handle(&self) -> WeakViewHandle<T> {
2476        WeakViewHandle::new(self.window_id, self.view_id)
2477    }
2478
2479    pub fn window_id(&self) -> usize {
2480        self.window_id
2481    }
2482
2483    pub fn view_id(&self) -> usize {
2484        self.view_id
2485    }
2486
2487    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2488        self.app.foreground()
2489    }
2490
2491    pub fn background_executor(&self) -> &Arc<executor::Background> {
2492        &self.app.cx.background
2493    }
2494
2495    pub fn platform(&self) -> Arc<dyn Platform> {
2496        self.app.platform()
2497    }
2498
2499    pub fn prompt(
2500        &self,
2501        level: PromptLevel,
2502        msg: &str,
2503        answers: &[&str],
2504    ) -> oneshot::Receiver<usize> {
2505        self.app.prompt(self.window_id, level, msg, answers)
2506    }
2507
2508    pub fn prompt_for_paths(
2509        &self,
2510        options: PathPromptOptions,
2511    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2512        self.app.prompt_for_paths(options)
2513    }
2514
2515    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2516        self.app.prompt_for_new_path(directory)
2517    }
2518
2519    pub fn debug_elements(&self) -> crate::json::Value {
2520        self.app.debug_elements(self.window_id).unwrap()
2521    }
2522
2523    pub fn focus<S>(&mut self, handle: S)
2524    where
2525        S: Into<AnyViewHandle>,
2526    {
2527        let handle = handle.into();
2528        self.app.pending_effects.push_back(Effect::Focus {
2529            window_id: handle.window_id,
2530            view_id: handle.view_id,
2531        });
2532    }
2533
2534    pub fn focus_self(&mut self) {
2535        self.app.pending_effects.push_back(Effect::Focus {
2536            window_id: self.window_id,
2537            view_id: self.view_id,
2538        });
2539    }
2540
2541    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2542    where
2543        S: Entity,
2544        F: FnOnce(&mut ModelContext<S>) -> S,
2545    {
2546        self.app.add_model(build_model)
2547    }
2548
2549    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2550    where
2551        S: View,
2552        F: FnOnce(&mut ViewContext<S>) -> S,
2553    {
2554        self.app.add_view(self.window_id, build_view)
2555    }
2556
2557    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2558    where
2559        S: View,
2560        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2561    {
2562        self.app.add_option_view(self.window_id, build_view)
2563    }
2564
2565    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2566    where
2567        E: Entity,
2568        E::Event: 'static,
2569        H: Handle<E>,
2570        F: 'static + FnMut(&mut T, H, &E::Event, &mut ViewContext<T>),
2571    {
2572        let subscriber = self.weak_handle();
2573        self.app
2574            .subscribe_internal(handle, move |emitter, event, cx| {
2575                if let Some(subscriber) = subscriber.upgrade(cx) {
2576                    subscriber.update(cx, |subscriber, cx| {
2577                        callback(subscriber, emitter, event, cx);
2578                    });
2579                    true
2580                } else {
2581                    false
2582                }
2583            })
2584    }
2585
2586    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2587    where
2588        E: Entity,
2589        H: Handle<E>,
2590        F: 'static + FnMut(&mut T, H, &mut ViewContext<T>),
2591    {
2592        let observer = self.weak_handle();
2593        self.app.observe_internal(handle, move |observed, cx| {
2594            if let Some(observer) = observer.upgrade(cx) {
2595                observer.update(cx, |observer, cx| {
2596                    callback(observer, observed, cx);
2597                });
2598                true
2599            } else {
2600                false
2601            }
2602        })
2603    }
2604
2605    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
2606    where
2607        E: Entity,
2608        H: Handle<E>,
2609        F: 'static + FnMut(&mut T, &mut ViewContext<T>),
2610    {
2611        let observer = self.weak_handle();
2612        self.app.observe_release(handle, move |cx| {
2613            if let Some(observer) = observer.upgrade(cx) {
2614                observer.update(cx, |observer, cx| {
2615                    callback(observer, cx);
2616                });
2617            }
2618        })
2619    }
2620
2621    pub fn emit(&mut self, payload: T::Event) {
2622        self.app.pending_effects.push_back(Effect::Event {
2623            entity_id: self.view_id,
2624            payload: Box::new(payload),
2625        });
2626    }
2627
2628    pub fn notify(&mut self) {
2629        self.app.notify_view(self.window_id, self.view_id);
2630    }
2631
2632    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut T, &mut ViewContext<T>)) {
2633        let handle = self.handle();
2634        self.app.defer(Box::new(move |cx| {
2635            handle.update(cx, |view, cx| {
2636                callback(view, cx);
2637            })
2638        }))
2639    }
2640
2641    pub fn propagate_action(&mut self) {
2642        self.app.halt_action_dispatch = false;
2643    }
2644
2645    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2646    where
2647        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2648        Fut: 'static + Future<Output = S>,
2649        S: 'static,
2650    {
2651        let handle = self.handle();
2652        self.app.spawn(|cx| f(handle, cx))
2653    }
2654
2655    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2656    where
2657        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2658        Fut: 'static + Future<Output = S>,
2659        S: 'static,
2660    {
2661        let handle = self.weak_handle();
2662        self.app.spawn(|cx| f(handle, cx))
2663    }
2664}
2665
2666pub struct RenderContext<'a, T: View> {
2667    pub app: &'a mut MutableAppContext,
2668    pub titlebar_height: f32,
2669    pub refreshing: bool,
2670    window_id: usize,
2671    view_id: usize,
2672    view_type: PhantomData<T>,
2673}
2674
2675impl<'a, T: View> RenderContext<'a, T> {
2676    pub fn handle(&self) -> WeakViewHandle<T> {
2677        WeakViewHandle::new(self.window_id, self.view_id)
2678    }
2679
2680    pub fn view_id(&self) -> usize {
2681        self.view_id
2682    }
2683}
2684
2685impl AsRef<AppContext> for &AppContext {
2686    fn as_ref(&self) -> &AppContext {
2687        self
2688    }
2689}
2690
2691impl<V: View> Deref for RenderContext<'_, V> {
2692    type Target = MutableAppContext;
2693
2694    fn deref(&self) -> &Self::Target {
2695        self.app
2696    }
2697}
2698
2699impl<V: View> DerefMut for RenderContext<'_, V> {
2700    fn deref_mut(&mut self) -> &mut Self::Target {
2701        self.app
2702    }
2703}
2704
2705impl<V: View> ReadModel for RenderContext<'_, V> {
2706    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2707        self.app.read_model(handle)
2708    }
2709}
2710
2711impl<V: View> UpdateModel for RenderContext<'_, V> {
2712    fn update_model<T: Entity, O>(
2713        &mut self,
2714        handle: &ModelHandle<T>,
2715        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2716    ) -> O {
2717        self.app.update_model(handle, update)
2718    }
2719}
2720
2721impl<V: View> ReadView for RenderContext<'_, V> {
2722    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2723        self.app.read_view(handle)
2724    }
2725}
2726
2727impl<V: View> ElementStateContext for RenderContext<'_, V> {
2728    fn current_view_id(&self) -> usize {
2729        self.view_id
2730    }
2731}
2732
2733impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2734    fn as_ref(&self) -> &AppContext {
2735        &self.app.cx
2736    }
2737}
2738
2739impl<M> Deref for ViewContext<'_, M> {
2740    type Target = MutableAppContext;
2741
2742    fn deref(&self) -> &Self::Target {
2743        &self.app
2744    }
2745}
2746
2747impl<M> DerefMut for ViewContext<'_, M> {
2748    fn deref_mut(&mut self) -> &mut Self::Target {
2749        &mut self.app
2750    }
2751}
2752
2753impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2754    fn as_mut(&mut self) -> &mut MutableAppContext {
2755        self.app
2756    }
2757}
2758
2759impl<V> ReadModel for ViewContext<'_, V> {
2760    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2761        self.app.read_model(handle)
2762    }
2763}
2764
2765impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2766    fn upgrade_model_handle<T: Entity>(
2767        &self,
2768        handle: &WeakModelHandle<T>,
2769    ) -> Option<ModelHandle<T>> {
2770        self.cx.upgrade_model_handle(handle)
2771    }
2772
2773    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
2774        self.cx.model_handle_is_upgradable(handle)
2775    }
2776
2777    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
2778        self.cx.upgrade_any_model_handle(handle)
2779    }
2780}
2781
2782impl<V> UpgradeViewHandle for ViewContext<'_, V> {
2783    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
2784        self.cx.upgrade_view_handle(handle)
2785    }
2786}
2787
2788impl<V: View> UpdateModel for ViewContext<'_, V> {
2789    fn update_model<T: Entity, O>(
2790        &mut self,
2791        handle: &ModelHandle<T>,
2792        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2793    ) -> O {
2794        self.app.update_model(handle, update)
2795    }
2796}
2797
2798impl<V: View> ReadView for ViewContext<'_, V> {
2799    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2800        self.app.read_view(handle)
2801    }
2802}
2803
2804impl<V: View> UpdateView for ViewContext<'_, V> {
2805    fn update_view<T, S>(
2806        &mut self,
2807        handle: &ViewHandle<T>,
2808        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2809    ) -> S
2810    where
2811        T: View,
2812    {
2813        self.app.update_view(handle, update)
2814    }
2815}
2816
2817impl<V: View> ElementStateContext for ViewContext<'_, V> {
2818    fn current_view_id(&self) -> usize {
2819        self.view_id
2820    }
2821}
2822
2823pub trait Handle<T> {
2824    type Weak: 'static;
2825    fn id(&self) -> usize;
2826    fn location(&self) -> EntityLocation;
2827    fn downgrade(&self) -> Self::Weak;
2828    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2829    where
2830        Self: Sized;
2831}
2832
2833#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2834pub enum EntityLocation {
2835    Model(usize),
2836    View(usize, usize),
2837}
2838
2839pub struct ModelHandle<T: Entity> {
2840    model_id: usize,
2841    model_type: PhantomData<T>,
2842    ref_counts: Arc<Mutex<RefCounts>>,
2843
2844    #[cfg(feature = "test-support")]
2845    handle_id: usize,
2846}
2847
2848impl<T: Entity> ModelHandle<T> {
2849    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2850        ref_counts.lock().inc_model(model_id);
2851
2852        #[cfg(feature = "test-support")]
2853        let handle_id = ref_counts
2854            .lock()
2855            .leak_detector
2856            .lock()
2857            .handle_created(Some(type_name::<T>()), model_id);
2858
2859        Self {
2860            model_id,
2861            model_type: PhantomData,
2862            ref_counts: ref_counts.clone(),
2863
2864            #[cfg(feature = "test-support")]
2865            handle_id,
2866        }
2867    }
2868
2869    pub fn downgrade(&self) -> WeakModelHandle<T> {
2870        WeakModelHandle::new(self.model_id)
2871    }
2872
2873    pub fn id(&self) -> usize {
2874        self.model_id
2875    }
2876
2877    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2878        cx.read_model(self)
2879    }
2880
2881    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2882    where
2883        C: ReadModelWith,
2884        F: FnOnce(&T, &AppContext) -> S,
2885    {
2886        let mut read = Some(read);
2887        cx.read_model_with(self, &mut |model, cx| {
2888            let read = read.take().unwrap();
2889            read(model, cx)
2890        })
2891    }
2892
2893    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2894    where
2895        C: UpdateModel,
2896        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2897    {
2898        let mut update = Some(update);
2899        cx.update_model(self, &mut |model, cx| {
2900            let update = update.take().unwrap();
2901            update(model, cx)
2902        })
2903    }
2904
2905    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2906        let (mut tx, mut rx) = mpsc::channel(1);
2907        let mut cx = cx.cx.borrow_mut();
2908        let subscription = cx.observe(self, move |_, _| {
2909            tx.try_send(()).ok();
2910        });
2911
2912        let duration = if std::env::var("CI").is_ok() {
2913            Duration::from_secs(5)
2914        } else {
2915            Duration::from_secs(1)
2916        };
2917
2918        async move {
2919            let notification = timeout(duration, rx.recv())
2920                .await
2921                .expect("next notification timed out");
2922            drop(subscription);
2923            notification.expect("model dropped while test was waiting for its next notification")
2924        }
2925    }
2926
2927    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2928    where
2929        T::Event: Clone,
2930    {
2931        let (mut tx, mut rx) = mpsc::channel(1);
2932        let mut cx = cx.cx.borrow_mut();
2933        let subscription = cx.subscribe(self, move |_, event, _| {
2934            tx.blocking_send(event.clone()).ok();
2935        });
2936
2937        let duration = if std::env::var("CI").is_ok() {
2938            Duration::from_secs(5)
2939        } else {
2940            Duration::from_secs(1)
2941        };
2942
2943        async move {
2944            let event = timeout(duration, rx.recv())
2945                .await
2946                .expect("next event timed out");
2947            drop(subscription);
2948            event.expect("model dropped while test was waiting for its next event")
2949        }
2950    }
2951
2952    pub fn condition(
2953        &self,
2954        cx: &TestAppContext,
2955        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2956    ) -> impl Future<Output = ()> {
2957        let (tx, mut rx) = mpsc::channel(1024);
2958
2959        let mut cx = cx.cx.borrow_mut();
2960        let subscriptions = (
2961            cx.observe(self, {
2962                let mut tx = tx.clone();
2963                move |_, _| {
2964                    tx.blocking_send(()).ok();
2965                }
2966            }),
2967            cx.subscribe(self, {
2968                let mut tx = tx.clone();
2969                move |_, _, _| {
2970                    tx.blocking_send(()).ok();
2971                }
2972            }),
2973        );
2974
2975        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2976        let handle = self.downgrade();
2977        let duration = if std::env::var("CI").is_ok() {
2978            Duration::from_secs(5)
2979        } else {
2980            Duration::from_secs(1)
2981        };
2982
2983        async move {
2984            timeout(duration, async move {
2985                loop {
2986                    {
2987                        let cx = cx.borrow();
2988                        let cx = cx.as_ref();
2989                        if predicate(
2990                            handle
2991                                .upgrade(cx)
2992                                .expect("model dropped with pending condition")
2993                                .read(cx),
2994                            cx,
2995                        ) {
2996                            break;
2997                        }
2998                    }
2999
3000                    cx.borrow().foreground().start_waiting();
3001                    rx.recv()
3002                        .await
3003                        .expect("model dropped with pending condition");
3004                    cx.borrow().foreground().finish_waiting();
3005                }
3006            })
3007            .await
3008            .expect("condition timed out");
3009            drop(subscriptions);
3010        }
3011    }
3012}
3013
3014impl<T: Entity> Clone for ModelHandle<T> {
3015    fn clone(&self) -> Self {
3016        Self::new(self.model_id, &self.ref_counts)
3017    }
3018}
3019
3020impl<T: Entity> PartialEq for ModelHandle<T> {
3021    fn eq(&self, other: &Self) -> bool {
3022        self.model_id == other.model_id
3023    }
3024}
3025
3026impl<T: Entity> Eq for ModelHandle<T> {}
3027
3028impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3029    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3030        self.model_id == other.model_id
3031    }
3032}
3033
3034impl<T: Entity> Hash for ModelHandle<T> {
3035    fn hash<H: Hasher>(&self, state: &mut H) {
3036        self.model_id.hash(state);
3037    }
3038}
3039
3040impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3041    fn borrow(&self) -> &usize {
3042        &self.model_id
3043    }
3044}
3045
3046impl<T: Entity> Debug for ModelHandle<T> {
3047    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3048        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3049            .field(&self.model_id)
3050            .finish()
3051    }
3052}
3053
3054unsafe impl<T: Entity> Send for ModelHandle<T> {}
3055unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3056
3057impl<T: Entity> Drop for ModelHandle<T> {
3058    fn drop(&mut self) {
3059        let mut ref_counts = self.ref_counts.lock();
3060        ref_counts.dec_model(self.model_id);
3061
3062        #[cfg(feature = "test-support")]
3063        ref_counts
3064            .leak_detector
3065            .lock()
3066            .handle_dropped(self.model_id, self.handle_id);
3067    }
3068}
3069
3070impl<T: Entity> Handle<T> for ModelHandle<T> {
3071    type Weak = WeakModelHandle<T>;
3072
3073    fn id(&self) -> usize {
3074        self.model_id
3075    }
3076
3077    fn location(&self) -> EntityLocation {
3078        EntityLocation::Model(self.model_id)
3079    }
3080
3081    fn downgrade(&self) -> Self::Weak {
3082        self.downgrade()
3083    }
3084
3085    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3086    where
3087        Self: Sized,
3088    {
3089        weak.upgrade(cx)
3090    }
3091}
3092
3093pub struct WeakModelHandle<T> {
3094    model_id: usize,
3095    model_type: PhantomData<T>,
3096}
3097
3098unsafe impl<T> Send for WeakModelHandle<T> {}
3099unsafe impl<T> Sync for WeakModelHandle<T> {}
3100
3101impl<T: Entity> WeakModelHandle<T> {
3102    fn new(model_id: usize) -> Self {
3103        Self {
3104            model_id,
3105            model_type: PhantomData,
3106        }
3107    }
3108
3109    pub fn id(&self) -> usize {
3110        self.model_id
3111    }
3112
3113    pub fn is_upgradable(&self, cx: &impl UpgradeModelHandle) -> bool {
3114        cx.model_handle_is_upgradable(self)
3115    }
3116
3117    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
3118        cx.upgrade_model_handle(self)
3119    }
3120}
3121
3122impl<T> Hash for WeakModelHandle<T> {
3123    fn hash<H: Hasher>(&self, state: &mut H) {
3124        self.model_id.hash(state)
3125    }
3126}
3127
3128impl<T> PartialEq for WeakModelHandle<T> {
3129    fn eq(&self, other: &Self) -> bool {
3130        self.model_id == other.model_id
3131    }
3132}
3133
3134impl<T> Eq for WeakModelHandle<T> {}
3135
3136impl<T> Clone for WeakModelHandle<T> {
3137    fn clone(&self) -> Self {
3138        Self {
3139            model_id: self.model_id,
3140            model_type: PhantomData,
3141        }
3142    }
3143}
3144
3145impl<T> Copy for WeakModelHandle<T> {}
3146
3147pub struct ViewHandle<T> {
3148    window_id: usize,
3149    view_id: usize,
3150    view_type: PhantomData<T>,
3151    ref_counts: Arc<Mutex<RefCounts>>,
3152    #[cfg(feature = "test-support")]
3153    handle_id: usize,
3154}
3155
3156impl<T: View> ViewHandle<T> {
3157    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3158        ref_counts.lock().inc_view(window_id, view_id);
3159        #[cfg(feature = "test-support")]
3160        let handle_id = ref_counts
3161            .lock()
3162            .leak_detector
3163            .lock()
3164            .handle_created(Some(type_name::<T>()), view_id);
3165
3166        Self {
3167            window_id,
3168            view_id,
3169            view_type: PhantomData,
3170            ref_counts: ref_counts.clone(),
3171
3172            #[cfg(feature = "test-support")]
3173            handle_id,
3174        }
3175    }
3176
3177    pub fn downgrade(&self) -> WeakViewHandle<T> {
3178        WeakViewHandle::new(self.window_id, self.view_id)
3179    }
3180
3181    pub fn window_id(&self) -> usize {
3182        self.window_id
3183    }
3184
3185    pub fn id(&self) -> usize {
3186        self.view_id
3187    }
3188
3189    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3190        cx.read_view(self)
3191    }
3192
3193    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3194    where
3195        C: ReadViewWith,
3196        F: FnOnce(&T, &AppContext) -> S,
3197    {
3198        let mut read = Some(read);
3199        cx.read_view_with(self, &mut |view, cx| {
3200            let read = read.take().unwrap();
3201            read(view, cx)
3202        })
3203    }
3204
3205    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3206    where
3207        C: UpdateView,
3208        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3209    {
3210        let mut update = Some(update);
3211        cx.update_view(self, &mut |view, cx| {
3212            let update = update.take().unwrap();
3213            update(view, cx)
3214        })
3215    }
3216
3217    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3218    where
3219        C: AsMut<MutableAppContext>,
3220        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3221    {
3222        let this = self.clone();
3223        cx.as_mut().defer(Box::new(move |cx| {
3224            this.update(cx, |view, cx| update(view, cx));
3225        }));
3226    }
3227
3228    pub fn is_focused(&self, cx: &AppContext) -> bool {
3229        cx.focused_view_id(self.window_id)
3230            .map_or(false, |focused_id| focused_id == self.view_id)
3231    }
3232
3233    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3234        let (mut tx, mut rx) = mpsc::channel(1);
3235        let mut cx = cx.cx.borrow_mut();
3236        let subscription = cx.observe(self, move |_, _| {
3237            tx.try_send(()).ok();
3238        });
3239
3240        let duration = if std::env::var("CI").is_ok() {
3241            Duration::from_secs(5)
3242        } else {
3243            Duration::from_secs(1)
3244        };
3245
3246        async move {
3247            let notification = timeout(duration, rx.recv())
3248                .await
3249                .expect("next notification timed out");
3250            drop(subscription);
3251            notification.expect("model dropped while test was waiting for its next notification")
3252        }
3253    }
3254
3255    pub fn condition(
3256        &self,
3257        cx: &TestAppContext,
3258        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3259    ) -> impl Future<Output = ()> {
3260        let (tx, mut rx) = mpsc::channel(1024);
3261
3262        let mut cx = cx.cx.borrow_mut();
3263        let subscriptions = self.update(&mut *cx, |_, cx| {
3264            (
3265                cx.observe(self, {
3266                    let mut tx = tx.clone();
3267                    move |_, _, _| {
3268                        tx.blocking_send(()).ok();
3269                    }
3270                }),
3271                cx.subscribe(self, {
3272                    let mut tx = tx.clone();
3273                    move |_, _, _, _| {
3274                        tx.blocking_send(()).ok();
3275                    }
3276                }),
3277            )
3278        });
3279
3280        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3281        let handle = self.downgrade();
3282        let duration = if std::env::var("CI").is_ok() {
3283            Duration::from_secs(2)
3284        } else {
3285            Duration::from_millis(500)
3286        };
3287
3288        async move {
3289            timeout(duration, async move {
3290                loop {
3291                    {
3292                        let cx = cx.borrow();
3293                        let cx = cx.as_ref();
3294                        if predicate(
3295                            handle
3296                                .upgrade(cx)
3297                                .expect("view dropped with pending condition")
3298                                .read(cx),
3299                            cx,
3300                        ) {
3301                            break;
3302                        }
3303                    }
3304
3305                    cx.borrow().foreground().start_waiting();
3306                    rx.recv()
3307                        .await
3308                        .expect("view dropped with pending condition");
3309                    cx.borrow().foreground().finish_waiting();
3310                }
3311            })
3312            .await
3313            .expect("condition timed out");
3314            drop(subscriptions);
3315        }
3316    }
3317}
3318
3319impl<T: View> Clone for ViewHandle<T> {
3320    fn clone(&self) -> Self {
3321        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3322    }
3323}
3324
3325impl<T> PartialEq for ViewHandle<T> {
3326    fn eq(&self, other: &Self) -> bool {
3327        self.window_id == other.window_id && self.view_id == other.view_id
3328    }
3329}
3330
3331impl<T> Eq for ViewHandle<T> {}
3332
3333impl<T> Debug for ViewHandle<T> {
3334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3335        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3336            .field("window_id", &self.window_id)
3337            .field("view_id", &self.view_id)
3338            .finish()
3339    }
3340}
3341
3342impl<T> Drop for ViewHandle<T> {
3343    fn drop(&mut self) {
3344        self.ref_counts
3345            .lock()
3346            .dec_view(self.window_id, self.view_id);
3347        #[cfg(feature = "test-support")]
3348        self.ref_counts
3349            .lock()
3350            .leak_detector
3351            .lock()
3352            .handle_dropped(self.view_id, self.handle_id);
3353    }
3354}
3355
3356impl<T: View> Handle<T> for ViewHandle<T> {
3357    type Weak = WeakViewHandle<T>;
3358
3359    fn id(&self) -> usize {
3360        self.view_id
3361    }
3362
3363    fn location(&self) -> EntityLocation {
3364        EntityLocation::View(self.window_id, self.view_id)
3365    }
3366
3367    fn downgrade(&self) -> Self::Weak {
3368        self.downgrade()
3369    }
3370
3371    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3372    where
3373        Self: Sized,
3374    {
3375        weak.upgrade(cx)
3376    }
3377}
3378
3379pub struct AnyViewHandle {
3380    window_id: usize,
3381    view_id: usize,
3382    view_type: TypeId,
3383    type_name: &'static str,
3384    ref_counts: Arc<Mutex<RefCounts>>,
3385    #[cfg(feature = "test-support")]
3386    handle_id: usize,
3387}
3388
3389impl AnyViewHandle {
3390    fn new(
3391        window_id: usize,
3392        view_id: usize,
3393        view_type: TypeId,
3394        type_name: &'static str,
3395        ref_counts: Arc<Mutex<RefCounts>>,
3396    ) -> Self {
3397        ref_counts.lock().inc_view(window_id, view_id);
3398
3399        #[cfg(feature = "test-support")]
3400        let handle_id = ref_counts
3401            .lock()
3402            .leak_detector
3403            .lock()
3404            .handle_created(Some(type_name), view_id);
3405
3406        Self {
3407            window_id,
3408            view_id,
3409            view_type,
3410            type_name,
3411            ref_counts,
3412            #[cfg(feature = "test-support")]
3413            handle_id,
3414        }
3415    }
3416
3417    pub fn id(&self) -> usize {
3418        self.view_id
3419    }
3420
3421    pub fn is<T: 'static>(&self) -> bool {
3422        TypeId::of::<T>() == self.view_type
3423    }
3424
3425    pub fn is_focused(&self, cx: &AppContext) -> bool {
3426        cx.focused_view_id(self.window_id)
3427            .map_or(false, |focused_id| focused_id == self.view_id)
3428    }
3429
3430    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3431        if self.is::<T>() {
3432            let result = Some(ViewHandle {
3433                window_id: self.window_id,
3434                view_id: self.view_id,
3435                ref_counts: self.ref_counts.clone(),
3436                view_type: PhantomData,
3437                #[cfg(feature = "test-support")]
3438                handle_id: self.handle_id,
3439            });
3440            unsafe {
3441                Arc::decrement_strong_count(&self.ref_counts);
3442            }
3443            std::mem::forget(self);
3444            result
3445        } else {
3446            None
3447        }
3448    }
3449}
3450
3451impl Clone for AnyViewHandle {
3452    fn clone(&self) -> Self {
3453        Self::new(
3454            self.window_id,
3455            self.view_id,
3456            self.view_type,
3457            self.type_name,
3458            self.ref_counts.clone(),
3459        )
3460    }
3461}
3462
3463impl From<&AnyViewHandle> for AnyViewHandle {
3464    fn from(handle: &AnyViewHandle) -> Self {
3465        handle.clone()
3466    }
3467}
3468
3469impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3470    fn from(handle: &ViewHandle<T>) -> Self {
3471        Self::new(
3472            handle.window_id,
3473            handle.view_id,
3474            TypeId::of::<T>(),
3475            any::type_name::<T>(),
3476            handle.ref_counts.clone(),
3477        )
3478    }
3479}
3480
3481impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3482    fn from(handle: ViewHandle<T>) -> Self {
3483        let any_handle = AnyViewHandle {
3484            window_id: handle.window_id,
3485            view_id: handle.view_id,
3486            view_type: TypeId::of::<T>(),
3487            type_name: any::type_name::<T>(),
3488            ref_counts: handle.ref_counts.clone(),
3489            #[cfg(feature = "test-support")]
3490            handle_id: handle.handle_id,
3491        };
3492        unsafe {
3493            Arc::decrement_strong_count(&handle.ref_counts);
3494        }
3495        std::mem::forget(handle);
3496        any_handle
3497    }
3498}
3499
3500impl Drop for AnyViewHandle {
3501    fn drop(&mut self) {
3502        self.ref_counts
3503            .lock()
3504            .dec_view(self.window_id, self.view_id);
3505        #[cfg(feature = "test-support")]
3506        self.ref_counts
3507            .lock()
3508            .leak_detector
3509            .lock()
3510            .handle_dropped(self.view_id, self.handle_id);
3511    }
3512}
3513
3514pub struct AnyModelHandle {
3515    model_id: usize,
3516    model_type: TypeId,
3517    ref_counts: Arc<Mutex<RefCounts>>,
3518
3519    #[cfg(feature = "test-support")]
3520    handle_id: usize,
3521}
3522
3523impl AnyModelHandle {
3524    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3525        ref_counts.lock().inc_model(model_id);
3526
3527        #[cfg(feature = "test-support")]
3528        let handle_id = ref_counts
3529            .lock()
3530            .leak_detector
3531            .lock()
3532            .handle_created(None, model_id);
3533
3534        Self {
3535            model_id,
3536            model_type,
3537            ref_counts,
3538
3539            #[cfg(feature = "test-support")]
3540            handle_id,
3541        }
3542    }
3543
3544    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3545        if self.is::<T>() {
3546            let result = Some(ModelHandle {
3547                model_id: self.model_id,
3548                model_type: PhantomData,
3549                ref_counts: self.ref_counts.clone(),
3550
3551                #[cfg(feature = "test-support")]
3552                handle_id: self.handle_id,
3553            });
3554            unsafe {
3555                Arc::decrement_strong_count(&self.ref_counts);
3556            }
3557            std::mem::forget(self);
3558            result
3559        } else {
3560            None
3561        }
3562    }
3563
3564    pub fn downgrade(&self) -> AnyWeakModelHandle {
3565        AnyWeakModelHandle {
3566            model_id: self.model_id,
3567            model_type: self.model_type,
3568        }
3569    }
3570
3571    pub fn is<T: Entity>(&self) -> bool {
3572        self.model_type == TypeId::of::<T>()
3573    }
3574}
3575
3576impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3577    fn from(handle: ModelHandle<T>) -> Self {
3578        Self::new(
3579            handle.model_id,
3580            TypeId::of::<T>(),
3581            handle.ref_counts.clone(),
3582        )
3583    }
3584}
3585
3586impl Clone for AnyModelHandle {
3587    fn clone(&self) -> Self {
3588        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3589    }
3590}
3591
3592impl Drop for AnyModelHandle {
3593    fn drop(&mut self) {
3594        let mut ref_counts = self.ref_counts.lock();
3595        ref_counts.dec_model(self.model_id);
3596
3597        #[cfg(feature = "test-support")]
3598        ref_counts
3599            .leak_detector
3600            .lock()
3601            .handle_dropped(self.model_id, self.handle_id);
3602    }
3603}
3604
3605pub struct AnyWeakModelHandle {
3606    model_id: usize,
3607    model_type: TypeId,
3608}
3609
3610impl AnyWeakModelHandle {
3611    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3612        cx.upgrade_any_model_handle(self)
3613    }
3614}
3615
3616impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
3617    fn from(handle: WeakModelHandle<T>) -> Self {
3618        AnyWeakModelHandle {
3619            model_id: handle.model_id,
3620            model_type: TypeId::of::<T>(),
3621        }
3622    }
3623}
3624
3625pub struct WeakViewHandle<T> {
3626    window_id: usize,
3627    view_id: usize,
3628    view_type: PhantomData<T>,
3629}
3630
3631impl<T: View> WeakViewHandle<T> {
3632    fn new(window_id: usize, view_id: usize) -> Self {
3633        Self {
3634            window_id,
3635            view_id,
3636            view_type: PhantomData,
3637        }
3638    }
3639
3640    pub fn id(&self) -> usize {
3641        self.view_id
3642    }
3643
3644    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3645        cx.upgrade_view_handle(self)
3646    }
3647}
3648
3649impl<T> Clone for WeakViewHandle<T> {
3650    fn clone(&self) -> Self {
3651        Self {
3652            window_id: self.window_id,
3653            view_id: self.view_id,
3654            view_type: PhantomData,
3655        }
3656    }
3657}
3658
3659impl<T> PartialEq for WeakViewHandle<T> {
3660    fn eq(&self, other: &Self) -> bool {
3661        self.window_id == other.window_id && self.view_id == other.view_id
3662    }
3663}
3664
3665impl<T> Eq for WeakViewHandle<T> {}
3666
3667impl<T> Hash for WeakViewHandle<T> {
3668    fn hash<H: Hasher>(&self, state: &mut H) {
3669        self.window_id.hash(state);
3670        self.view_id.hash(state);
3671    }
3672}
3673
3674#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3675pub struct ElementStateId {
3676    view_id: usize,
3677    element_id: usize,
3678    tag: TypeId,
3679}
3680
3681pub struct ElementStateHandle<T> {
3682    value_type: PhantomData<T>,
3683    id: ElementStateId,
3684    ref_counts: Weak<Mutex<RefCounts>>,
3685}
3686
3687impl<T: 'static> ElementStateHandle<T> {
3688    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3689        ref_counts.lock().inc_element_state(id, frame_id);
3690        Self {
3691            value_type: PhantomData,
3692            id,
3693            ref_counts: Arc::downgrade(ref_counts),
3694        }
3695    }
3696
3697    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3698        cx.element_states
3699            .get(&self.id)
3700            .unwrap()
3701            .downcast_ref()
3702            .unwrap()
3703    }
3704
3705    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3706    where
3707        C: DerefMut<Target = MutableAppContext>,
3708    {
3709        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3710        let result = f(element_state.downcast_mut().unwrap(), cx);
3711        cx.deref_mut()
3712            .cx
3713            .element_states
3714            .insert(self.id, element_state);
3715        result
3716    }
3717}
3718
3719impl<T> Drop for ElementStateHandle<T> {
3720    fn drop(&mut self) {
3721        if let Some(ref_counts) = self.ref_counts.upgrade() {
3722            ref_counts.lock().dec_element_state(self.id);
3723        }
3724    }
3725}
3726
3727pub struct CursorStyleHandle {
3728    id: usize,
3729    next_cursor_style_handle_id: Arc<AtomicUsize>,
3730    platform: Arc<dyn Platform>,
3731}
3732
3733impl Drop for CursorStyleHandle {
3734    fn drop(&mut self) {
3735        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3736            self.platform.set_cursor_style(CursorStyle::Arrow);
3737        }
3738    }
3739}
3740
3741#[must_use]
3742pub enum Subscription {
3743    Subscription {
3744        id: usize,
3745        entity_id: usize,
3746        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3747    },
3748    Observation {
3749        id: usize,
3750        entity_id: usize,
3751        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3752    },
3753    ReleaseObservation {
3754        id: usize,
3755        entity_id: usize,
3756        observations:
3757            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3758    },
3759}
3760
3761impl Subscription {
3762    pub fn detach(&mut self) {
3763        match self {
3764            Subscription::Subscription { subscriptions, .. } => {
3765                subscriptions.take();
3766            }
3767            Subscription::Observation { observations, .. } => {
3768                observations.take();
3769            }
3770            Subscription::ReleaseObservation { observations, .. } => {
3771                observations.take();
3772            }
3773        }
3774    }
3775}
3776
3777impl Drop for Subscription {
3778    fn drop(&mut self) {
3779        match self {
3780            Subscription::Observation {
3781                id,
3782                entity_id,
3783                observations,
3784            } => {
3785                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3786                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3787                        observations.remove(id);
3788                    }
3789                }
3790            }
3791            Subscription::ReleaseObservation {
3792                id,
3793                entity_id,
3794                observations,
3795            } => {
3796                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3797                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3798                        observations.remove(id);
3799                    }
3800                }
3801            }
3802            Subscription::Subscription {
3803                id,
3804                entity_id,
3805                subscriptions,
3806            } => {
3807                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3808                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3809                        subscriptions.remove(id);
3810                    }
3811                }
3812            }
3813        }
3814    }
3815}
3816
3817lazy_static! {
3818    static ref LEAK_BACKTRACE: bool =
3819        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
3820}
3821
3822#[derive(Default)]
3823pub struct LeakDetector {
3824    next_handle_id: usize,
3825    handle_backtraces: HashMap<usize, (Option<&'static str>, HashMap<usize, Option<Backtrace>>)>,
3826}
3827
3828impl LeakDetector {
3829    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
3830        let handle_id = post_inc(&mut self.next_handle_id);
3831        let entry = self.handle_backtraces.entry(entity_id).or_default();
3832        let backtrace = if *LEAK_BACKTRACE {
3833            Some(Backtrace::new_unresolved())
3834        } else {
3835            None
3836        };
3837        if let Some(type_name) = type_name {
3838            entry.0.get_or_insert(type_name);
3839        }
3840        entry.1.insert(handle_id, backtrace);
3841        handle_id
3842    }
3843
3844    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
3845        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
3846            assert!(backtraces.remove(&handle_id).is_some());
3847            if backtraces.is_empty() {
3848                self.handle_backtraces.remove(&entity_id);
3849            }
3850        }
3851    }
3852
3853    pub fn detect(&mut self) {
3854        let mut found_leaks = false;
3855        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
3856            eprintln!(
3857                "leaked {} handles to {:?} {}",
3858                backtraces.len(),
3859                type_name.unwrap_or("entity"),
3860                id
3861            );
3862            for trace in backtraces.values_mut() {
3863                if let Some(trace) = trace {
3864                    trace.resolve();
3865                    eprintln!("{:?}", CwdBacktrace(trace));
3866                }
3867            }
3868            found_leaks = true;
3869        }
3870
3871        let hint = if *LEAK_BACKTRACE {
3872            ""
3873        } else {
3874            " – set LEAK_BACKTRACE=1 for more information"
3875        };
3876        assert!(!found_leaks, "detected leaked handles{}", hint);
3877    }
3878}
3879
3880#[derive(Default)]
3881struct RefCounts {
3882    entity_counts: HashMap<usize, usize>,
3883    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
3884    dropped_models: HashSet<usize>,
3885    dropped_views: HashSet<(usize, usize)>,
3886    dropped_element_states: HashSet<ElementStateId>,
3887
3888    #[cfg(feature = "test-support")]
3889    leak_detector: Arc<Mutex<LeakDetector>>,
3890}
3891
3892struct ElementStateRefCount {
3893    ref_count: usize,
3894    frame_id: usize,
3895}
3896
3897impl RefCounts {
3898    fn inc_model(&mut self, model_id: usize) {
3899        match self.entity_counts.entry(model_id) {
3900            Entry::Occupied(mut entry) => {
3901                *entry.get_mut() += 1;
3902            }
3903            Entry::Vacant(entry) => {
3904                entry.insert(1);
3905                self.dropped_models.remove(&model_id);
3906            }
3907        }
3908    }
3909
3910    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3911        match self.entity_counts.entry(view_id) {
3912            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3913            Entry::Vacant(entry) => {
3914                entry.insert(1);
3915                self.dropped_views.remove(&(window_id, view_id));
3916            }
3917        }
3918    }
3919
3920    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
3921        match self.element_state_counts.entry(id) {
3922            Entry::Occupied(mut entry) => {
3923                let entry = entry.get_mut();
3924                if entry.frame_id == frame_id || entry.ref_count >= 2 {
3925                    panic!("used the same element state more than once in the same frame");
3926                }
3927                entry.ref_count += 1;
3928                entry.frame_id = frame_id;
3929            }
3930            Entry::Vacant(entry) => {
3931                entry.insert(ElementStateRefCount {
3932                    ref_count: 1,
3933                    frame_id,
3934                });
3935                self.dropped_element_states.remove(&id);
3936            }
3937        }
3938    }
3939
3940    fn dec_model(&mut self, model_id: usize) {
3941        let count = self.entity_counts.get_mut(&model_id).unwrap();
3942        *count -= 1;
3943        if *count == 0 {
3944            self.entity_counts.remove(&model_id);
3945            self.dropped_models.insert(model_id);
3946        }
3947    }
3948
3949    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3950        let count = self.entity_counts.get_mut(&view_id).unwrap();
3951        *count -= 1;
3952        if *count == 0 {
3953            self.entity_counts.remove(&view_id);
3954            self.dropped_views.insert((window_id, view_id));
3955        }
3956    }
3957
3958    fn dec_element_state(&mut self, id: ElementStateId) {
3959        let entry = self.element_state_counts.get_mut(&id).unwrap();
3960        entry.ref_count -= 1;
3961        if entry.ref_count == 0 {
3962            self.element_state_counts.remove(&id);
3963            self.dropped_element_states.insert(id);
3964        }
3965    }
3966
3967    fn is_entity_alive(&self, entity_id: usize) -> bool {
3968        self.entity_counts.contains_key(&entity_id)
3969    }
3970
3971    fn take_dropped(
3972        &mut self,
3973    ) -> (
3974        HashSet<usize>,
3975        HashSet<(usize, usize)>,
3976        HashSet<ElementStateId>,
3977    ) {
3978        (
3979            std::mem::take(&mut self.dropped_models),
3980            std::mem::take(&mut self.dropped_views),
3981            std::mem::take(&mut self.dropped_element_states),
3982        )
3983    }
3984}
3985
3986#[cfg(test)]
3987mod tests {
3988    use super::*;
3989    use crate::elements::*;
3990    use smol::future::poll_once;
3991    use std::{
3992        cell::Cell,
3993        sync::atomic::{AtomicUsize, Ordering::SeqCst},
3994    };
3995
3996    #[crate::test(self)]
3997    fn test_model_handles(cx: &mut MutableAppContext) {
3998        struct Model {
3999            other: Option<ModelHandle<Model>>,
4000            events: Vec<String>,
4001        }
4002
4003        impl Entity for Model {
4004            type Event = usize;
4005        }
4006
4007        impl Model {
4008            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4009                if let Some(other) = other.as_ref() {
4010                    cx.observe(other, |me, _, _| {
4011                        me.events.push("notified".into());
4012                    })
4013                    .detach();
4014                    cx.subscribe(other, |me, _, event, _| {
4015                        me.events.push(format!("observed event {}", event));
4016                    })
4017                    .detach();
4018                }
4019
4020                Self {
4021                    other,
4022                    events: Vec::new(),
4023                }
4024            }
4025        }
4026
4027        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4028        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4029        assert_eq!(cx.cx.models.len(), 2);
4030
4031        handle_1.update(cx, |model, cx| {
4032            model.events.push("updated".into());
4033            cx.emit(1);
4034            cx.notify();
4035            cx.emit(2);
4036        });
4037        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4038        assert_eq!(
4039            handle_2.read(cx).events,
4040            vec![
4041                "observed event 1".to_string(),
4042                "notified".to_string(),
4043                "observed event 2".to_string(),
4044            ]
4045        );
4046
4047        handle_2.update(cx, |model, _| {
4048            drop(handle_1);
4049            model.other.take();
4050        });
4051
4052        assert_eq!(cx.cx.models.len(), 1);
4053        assert!(cx.subscriptions.lock().is_empty());
4054        assert!(cx.observations.lock().is_empty());
4055    }
4056
4057    #[crate::test(self)]
4058    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
4059        #[derive(Default)]
4060        struct Model {
4061            events: Vec<usize>,
4062        }
4063
4064        impl Entity for Model {
4065            type Event = usize;
4066        }
4067
4068        let handle_1 = cx.add_model(|_| Model::default());
4069        let handle_2 = cx.add_model(|_| Model::default());
4070        let handle_2b = handle_2.clone();
4071
4072        handle_1.update(cx, |_, c| {
4073            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
4074                model.events.push(*event);
4075
4076                c.subscribe(&handle_2b, |model, _, event, _| {
4077                    model.events.push(*event * 2);
4078                })
4079                .detach();
4080            })
4081            .detach();
4082        });
4083
4084        handle_2.update(cx, |_, c| c.emit(7));
4085        assert_eq!(handle_1.read(cx).events, vec![7]);
4086
4087        handle_2.update(cx, |_, c| c.emit(5));
4088        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4089    }
4090
4091    #[crate::test(self)]
4092    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4093        #[derive(Default)]
4094        struct Model {
4095            count: usize,
4096            events: Vec<usize>,
4097        }
4098
4099        impl Entity for Model {
4100            type Event = ();
4101        }
4102
4103        let handle_1 = cx.add_model(|_| Model::default());
4104        let handle_2 = cx.add_model(|_| Model::default());
4105        let handle_2b = handle_2.clone();
4106
4107        handle_1.update(cx, |_, c| {
4108            c.observe(&handle_2, move |model, observed, c| {
4109                model.events.push(observed.read(c).count);
4110                c.observe(&handle_2b, |model, observed, c| {
4111                    model.events.push(observed.read(c).count * 2);
4112                })
4113                .detach();
4114            })
4115            .detach();
4116        });
4117
4118        handle_2.update(cx, |model, c| {
4119            model.count = 7;
4120            c.notify()
4121        });
4122        assert_eq!(handle_1.read(cx).events, vec![7]);
4123
4124        handle_2.update(cx, |model, c| {
4125            model.count = 5;
4126            c.notify()
4127        });
4128        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4129    }
4130
4131    #[crate::test(self)]
4132    fn test_view_handles(cx: &mut MutableAppContext) {
4133        struct View {
4134            other: Option<ViewHandle<View>>,
4135            events: Vec<String>,
4136        }
4137
4138        impl Entity for View {
4139            type Event = usize;
4140        }
4141
4142        impl super::View for View {
4143            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4144                Empty::new().boxed()
4145            }
4146
4147            fn ui_name() -> &'static str {
4148                "View"
4149            }
4150        }
4151
4152        impl View {
4153            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4154                if let Some(other) = other.as_ref() {
4155                    cx.subscribe(other, |me, _, event, _| {
4156                        me.events.push(format!("observed event {}", event));
4157                    })
4158                    .detach();
4159                }
4160                Self {
4161                    other,
4162                    events: Vec::new(),
4163                }
4164            }
4165        }
4166
4167        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4168        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4169        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4170        assert_eq!(cx.cx.views.len(), 3);
4171
4172        handle_1.update(cx, |view, cx| {
4173            view.events.push("updated".into());
4174            cx.emit(1);
4175            cx.emit(2);
4176        });
4177        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4178        assert_eq!(
4179            handle_2.read(cx).events,
4180            vec![
4181                "observed event 1".to_string(),
4182                "observed event 2".to_string(),
4183            ]
4184        );
4185
4186        handle_2.update(cx, |view, _| {
4187            drop(handle_1);
4188            view.other.take();
4189        });
4190
4191        assert_eq!(cx.cx.views.len(), 2);
4192        assert!(cx.subscriptions.lock().is_empty());
4193        assert!(cx.observations.lock().is_empty());
4194    }
4195
4196    #[crate::test(self)]
4197    fn test_add_window(cx: &mut MutableAppContext) {
4198        struct View {
4199            mouse_down_count: Arc<AtomicUsize>,
4200        }
4201
4202        impl Entity for View {
4203            type Event = ();
4204        }
4205
4206        impl super::View for View {
4207            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4208                let mouse_down_count = self.mouse_down_count.clone();
4209                EventHandler::new(Empty::new().boxed())
4210                    .on_mouse_down(move |_| {
4211                        mouse_down_count.fetch_add(1, SeqCst);
4212                        true
4213                    })
4214                    .boxed()
4215            }
4216
4217            fn ui_name() -> &'static str {
4218                "View"
4219            }
4220        }
4221
4222        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4223        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4224            mouse_down_count: mouse_down_count.clone(),
4225        });
4226        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4227        // Ensure window's root element is in a valid lifecycle state.
4228        presenter.borrow_mut().dispatch_event(
4229            Event::LeftMouseDown {
4230                position: Default::default(),
4231                ctrl: false,
4232                alt: false,
4233                shift: false,
4234                cmd: false,
4235                click_count: 1,
4236            },
4237            cx,
4238        );
4239        assert_eq!(mouse_down_count.load(SeqCst), 1);
4240    }
4241
4242    #[crate::test(self)]
4243    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4244        struct Model {
4245            released: Rc<Cell<bool>>,
4246        }
4247
4248        struct View {
4249            released: Rc<Cell<bool>>,
4250        }
4251
4252        impl Entity for Model {
4253            type Event = ();
4254
4255            fn release(&mut self, _: &mut MutableAppContext) {
4256                self.released.set(true);
4257            }
4258        }
4259
4260        impl Entity for View {
4261            type Event = ();
4262
4263            fn release(&mut self, _: &mut MutableAppContext) {
4264                self.released.set(true);
4265            }
4266        }
4267
4268        impl super::View for View {
4269            fn ui_name() -> &'static str {
4270                "View"
4271            }
4272
4273            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4274                Empty::new().boxed()
4275            }
4276        }
4277
4278        let model_released = Rc::new(Cell::new(false));
4279        let model_release_observed = Rc::new(Cell::new(false));
4280        let view_released = Rc::new(Cell::new(false));
4281        let view_release_observed = Rc::new(Cell::new(false));
4282
4283        let model = cx.add_model(|_| Model {
4284            released: model_released.clone(),
4285        });
4286        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4287            released: view_released.clone(),
4288        });
4289        assert!(!model_released.get());
4290        assert!(!view_released.get());
4291
4292        cx.observe_release(&model, {
4293            let model_release_observed = model_release_observed.clone();
4294            move |_| model_release_observed.set(true)
4295        })
4296        .detach();
4297        cx.observe_release(&view, {
4298            let view_release_observed = view_release_observed.clone();
4299            move |_| view_release_observed.set(true)
4300        })
4301        .detach();
4302
4303        cx.update(move |_| {
4304            drop(model);
4305        });
4306        assert!(model_released.get());
4307        assert!(model_release_observed.get());
4308
4309        drop(view);
4310        cx.remove_window(window_id);
4311        assert!(view_released.get());
4312        assert!(view_release_observed.get());
4313    }
4314
4315    #[crate::test(self)]
4316    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
4317        #[derive(Default)]
4318        struct View {
4319            events: Vec<usize>,
4320        }
4321
4322        impl Entity for View {
4323            type Event = usize;
4324        }
4325
4326        impl super::View for View {
4327            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4328                Empty::new().boxed()
4329            }
4330
4331            fn ui_name() -> &'static str {
4332                "View"
4333            }
4334        }
4335
4336        struct Model;
4337
4338        impl Entity for Model {
4339            type Event = usize;
4340        }
4341
4342        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4343        let handle_2 = cx.add_view(window_id, |_| View::default());
4344        let handle_2b = handle_2.clone();
4345        let handle_3 = cx.add_model(|_| Model);
4346
4347        handle_1.update(cx, |_, c| {
4348            c.subscribe(&handle_2, move |me, _, event, c| {
4349                me.events.push(*event);
4350
4351                c.subscribe(&handle_2b, |me, _, event, _| {
4352                    me.events.push(*event * 2);
4353                })
4354                .detach();
4355            })
4356            .detach();
4357
4358            c.subscribe(&handle_3, |me, _, event, _| {
4359                me.events.push(*event);
4360            })
4361            .detach();
4362        });
4363
4364        handle_2.update(cx, |_, c| c.emit(7));
4365        assert_eq!(handle_1.read(cx).events, vec![7]);
4366
4367        handle_2.update(cx, |_, c| c.emit(5));
4368        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4369
4370        handle_3.update(cx, |_, c| c.emit(9));
4371        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4372    }
4373
4374    #[crate::test(self)]
4375    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4376        struct View;
4377
4378        impl Entity for View {
4379            type Event = ();
4380        }
4381
4382        impl super::View for View {
4383            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4384                Empty::new().boxed()
4385            }
4386
4387            fn ui_name() -> &'static str {
4388                "View"
4389            }
4390        }
4391
4392        struct Model;
4393
4394        impl Entity for Model {
4395            type Event = ();
4396        }
4397
4398        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4399        let observing_view = cx.add_view(window_id, |_| View);
4400        let emitting_view = cx.add_view(window_id, |_| View);
4401        let observing_model = cx.add_model(|_| Model);
4402        let observed_model = cx.add_model(|_| Model);
4403
4404        observing_view.update(cx, |_, cx| {
4405            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4406            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4407        });
4408        observing_model.update(cx, |_, cx| {
4409            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4410        });
4411
4412        cx.update(|_| {
4413            drop(observing_view);
4414            drop(observing_model);
4415        });
4416
4417        emitting_view.update(cx, |_, cx| cx.emit(()));
4418        observed_model.update(cx, |_, cx| cx.emit(()));
4419    }
4420
4421    #[crate::test(self)]
4422    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4423        #[derive(Default)]
4424        struct View {
4425            events: Vec<usize>,
4426        }
4427
4428        impl Entity for View {
4429            type Event = usize;
4430        }
4431
4432        impl super::View for View {
4433            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4434                Empty::new().boxed()
4435            }
4436
4437            fn ui_name() -> &'static str {
4438                "View"
4439            }
4440        }
4441
4442        #[derive(Default)]
4443        struct Model {
4444            count: usize,
4445        }
4446
4447        impl Entity for Model {
4448            type Event = ();
4449        }
4450
4451        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4452        let model = cx.add_model(|_| Model::default());
4453
4454        view.update(cx, |_, c| {
4455            c.observe(&model, |me, observed, c| {
4456                me.events.push(observed.read(c).count)
4457            })
4458            .detach();
4459        });
4460
4461        model.update(cx, |model, c| {
4462            model.count = 11;
4463            c.notify();
4464        });
4465        assert_eq!(view.read(cx).events, vec![11]);
4466    }
4467
4468    #[crate::test(self)]
4469    fn test_dropping_observers(cx: &mut MutableAppContext) {
4470        struct View;
4471
4472        impl Entity for View {
4473            type Event = ();
4474        }
4475
4476        impl super::View for View {
4477            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4478                Empty::new().boxed()
4479            }
4480
4481            fn ui_name() -> &'static str {
4482                "View"
4483            }
4484        }
4485
4486        struct Model;
4487
4488        impl Entity for Model {
4489            type Event = ();
4490        }
4491
4492        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4493        let observing_view = cx.add_view(window_id, |_| View);
4494        let observing_model = cx.add_model(|_| Model);
4495        let observed_model = cx.add_model(|_| Model);
4496
4497        observing_view.update(cx, |_, cx| {
4498            cx.observe(&observed_model, |_, _, _| {}).detach();
4499        });
4500        observing_model.update(cx, |_, cx| {
4501            cx.observe(&observed_model, |_, _, _| {}).detach();
4502        });
4503
4504        cx.update(|_| {
4505            drop(observing_view);
4506            drop(observing_model);
4507        });
4508
4509        observed_model.update(cx, |_, cx| cx.notify());
4510    }
4511
4512    #[crate::test(self)]
4513    fn test_focus(cx: &mut MutableAppContext) {
4514        struct View {
4515            name: String,
4516            events: Arc<Mutex<Vec<String>>>,
4517        }
4518
4519        impl Entity for View {
4520            type Event = ();
4521        }
4522
4523        impl super::View for View {
4524            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4525                Empty::new().boxed()
4526            }
4527
4528            fn ui_name() -> &'static str {
4529                "View"
4530            }
4531
4532            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4533                self.events.lock().push(format!("{} focused", &self.name));
4534            }
4535
4536            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4537                self.events.lock().push(format!("{} blurred", &self.name));
4538            }
4539        }
4540
4541        let events: Arc<Mutex<Vec<String>>> = Default::default();
4542        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4543            events: events.clone(),
4544            name: "view 1".to_string(),
4545        });
4546        let view_2 = cx.add_view(window_id, |_| View {
4547            events: events.clone(),
4548            name: "view 2".to_string(),
4549        });
4550
4551        view_1.update(cx, |_, cx| cx.focus(&view_2));
4552        view_1.update(cx, |_, cx| cx.focus(&view_1));
4553        view_1.update(cx, |_, cx| cx.focus(&view_2));
4554        view_1.update(cx, |_, _| drop(view_2));
4555
4556        assert_eq!(
4557            *events.lock(),
4558            [
4559                "view 1 focused".to_string(),
4560                "view 1 blurred".to_string(),
4561                "view 2 focused".to_string(),
4562                "view 2 blurred".to_string(),
4563                "view 1 focused".to_string(),
4564                "view 1 blurred".to_string(),
4565                "view 2 focused".to_string(),
4566                "view 1 focused".to_string(),
4567            ],
4568        );
4569    }
4570
4571    #[crate::test(self)]
4572    fn test_dispatch_action(cx: &mut MutableAppContext) {
4573        struct ViewA {
4574            id: usize,
4575        }
4576
4577        impl Entity for ViewA {
4578            type Event = ();
4579        }
4580
4581        impl View for ViewA {
4582            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4583                Empty::new().boxed()
4584            }
4585
4586            fn ui_name() -> &'static str {
4587                "View"
4588            }
4589        }
4590
4591        struct ViewB {
4592            id: usize,
4593        }
4594
4595        impl Entity for ViewB {
4596            type Event = ();
4597        }
4598
4599        impl View for ViewB {
4600            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4601                Empty::new().boxed()
4602            }
4603
4604            fn ui_name() -> &'static str {
4605                "View"
4606            }
4607        }
4608
4609        action!(Action, &'static str);
4610
4611        let actions = Rc::new(RefCell::new(Vec::new()));
4612
4613        {
4614            let actions = actions.clone();
4615            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4616                actions.borrow_mut().push("global".to_string());
4617            });
4618        }
4619
4620        {
4621            let actions = actions.clone();
4622            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4623                assert_eq!(action.0, "bar");
4624                cx.propagate_action();
4625                actions.borrow_mut().push(format!("{} a", view.id));
4626            });
4627        }
4628
4629        {
4630            let actions = actions.clone();
4631            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4632                if view.id != 1 {
4633                    cx.add_view(|cx| {
4634                        cx.propagate_action(); // Still works on a nested ViewContext
4635                        ViewB { id: 5 }
4636                    });
4637                }
4638                actions.borrow_mut().push(format!("{} b", view.id));
4639            });
4640        }
4641
4642        {
4643            let actions = actions.clone();
4644            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4645                cx.propagate_action();
4646                actions.borrow_mut().push(format!("{} c", view.id));
4647            });
4648        }
4649
4650        {
4651            let actions = actions.clone();
4652            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4653                cx.propagate_action();
4654                actions.borrow_mut().push(format!("{} d", view.id));
4655            });
4656        }
4657
4658        {
4659            let actions = actions.clone();
4660            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
4661                cx.propagate_action();
4662                actions.borrow_mut().push(format!("{} capture", view.id));
4663            });
4664        }
4665
4666        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4667        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4668        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4669        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4670
4671        cx.dispatch_action(
4672            window_id,
4673            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4674            &Action("bar"),
4675        );
4676
4677        assert_eq!(
4678            *actions.borrow(),
4679            vec![
4680                "1 capture",
4681                "3 capture",
4682                "4 d",
4683                "4 c",
4684                "3 b",
4685                "3 a",
4686                "2 d",
4687                "2 c",
4688                "1 b"
4689            ]
4690        );
4691
4692        // Remove view_1, which doesn't propagate the action
4693        actions.borrow_mut().clear();
4694        cx.dispatch_action(
4695            window_id,
4696            vec![view_2.id(), view_3.id(), view_4.id()],
4697            &Action("bar"),
4698        );
4699
4700        assert_eq!(
4701            *actions.borrow(),
4702            vec![
4703                "3 capture",
4704                "4 d",
4705                "4 c",
4706                "3 b",
4707                "3 a",
4708                "2 d",
4709                "2 c",
4710                "global"
4711            ]
4712        );
4713    }
4714
4715    #[crate::test(self)]
4716    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4717        use std::cell::Cell;
4718
4719        action!(Action, &'static str);
4720
4721        struct View {
4722            id: usize,
4723            keymap_context: keymap::Context,
4724        }
4725
4726        impl Entity for View {
4727            type Event = ();
4728        }
4729
4730        impl super::View for View {
4731            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4732                Empty::new().boxed()
4733            }
4734
4735            fn ui_name() -> &'static str {
4736                "View"
4737            }
4738
4739            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4740                self.keymap_context.clone()
4741            }
4742        }
4743
4744        impl View {
4745            fn new(id: usize) -> Self {
4746                View {
4747                    id,
4748                    keymap_context: keymap::Context::default(),
4749                }
4750            }
4751        }
4752
4753        let mut view_1 = View::new(1);
4754        let mut view_2 = View::new(2);
4755        let mut view_3 = View::new(3);
4756        view_1.keymap_context.set.insert("a".into());
4757        view_2.keymap_context.set.insert("a".into());
4758        view_2.keymap_context.set.insert("b".into());
4759        view_3.keymap_context.set.insert("a".into());
4760        view_3.keymap_context.set.insert("b".into());
4761        view_3.keymap_context.set.insert("c".into());
4762
4763        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4764        let view_2 = cx.add_view(window_id, |_| view_2);
4765        let view_3 = cx.add_view(window_id, |_| view_3);
4766
4767        // This keymap's only binding dispatches an action on view 2 because that view will have
4768        // "a" and "b" in its context, but not "c".
4769        cx.add_bindings(vec![keymap::Binding::new(
4770            "a",
4771            Action("a"),
4772            Some("a && b && !c"),
4773        )]);
4774
4775        let handled_action = Rc::new(Cell::new(false));
4776        let handled_action_clone = handled_action.clone();
4777        cx.add_action(move |view: &mut View, action: &Action, _| {
4778            handled_action_clone.set(true);
4779            assert_eq!(view.id, 2);
4780            assert_eq!(action.0, "a");
4781        });
4782
4783        cx.dispatch_keystroke(
4784            window_id,
4785            vec![view_1.id(), view_2.id(), view_3.id()],
4786            &Keystroke::parse("a").unwrap(),
4787        )
4788        .unwrap();
4789
4790        assert!(handled_action.get());
4791    }
4792
4793    #[crate::test(self)]
4794    async fn test_model_condition(cx: &mut TestAppContext) {
4795        struct Counter(usize);
4796
4797        impl super::Entity for Counter {
4798            type Event = ();
4799        }
4800
4801        impl Counter {
4802            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4803                self.0 += 1;
4804                cx.notify();
4805            }
4806        }
4807
4808        let model = cx.add_model(|_| Counter(0));
4809
4810        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4811        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4812        smol::pin!(condition1, condition2);
4813
4814        model.update(cx, |model, cx| model.inc(cx));
4815        assert_eq!(poll_once(&mut condition1).await, None);
4816        assert_eq!(poll_once(&mut condition2).await, None);
4817
4818        model.update(cx, |model, cx| model.inc(cx));
4819        assert_eq!(poll_once(&mut condition1).await, Some(()));
4820        assert_eq!(poll_once(&mut condition2).await, None);
4821
4822        model.update(cx, |model, cx| model.inc(cx));
4823        assert_eq!(poll_once(&mut condition2).await, Some(()));
4824
4825        model.update(cx, |_, cx| cx.notify());
4826    }
4827
4828    #[crate::test(self)]
4829    #[should_panic]
4830    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
4831        struct Model;
4832
4833        impl super::Entity for Model {
4834            type Event = ();
4835        }
4836
4837        let model = cx.add_model(|_| Model);
4838        model.condition(&cx, |_, _| false).await;
4839    }
4840
4841    #[crate::test(self)]
4842    #[should_panic(expected = "model dropped with pending condition")]
4843    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
4844        struct Model;
4845
4846        impl super::Entity for Model {
4847            type Event = ();
4848        }
4849
4850        let model = cx.add_model(|_| Model);
4851        let condition = model.condition(&cx, |_, _| false);
4852        cx.update(|_| drop(model));
4853        condition.await;
4854    }
4855
4856    #[crate::test(self)]
4857    async fn test_view_condition(cx: &mut TestAppContext) {
4858        struct Counter(usize);
4859
4860        impl super::Entity for Counter {
4861            type Event = ();
4862        }
4863
4864        impl super::View for Counter {
4865            fn ui_name() -> &'static str {
4866                "test view"
4867            }
4868
4869            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4870                Empty::new().boxed()
4871            }
4872        }
4873
4874        impl Counter {
4875            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4876                self.0 += 1;
4877                cx.notify();
4878            }
4879        }
4880
4881        let (_, view) = cx.add_window(|_| Counter(0));
4882
4883        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4884        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4885        smol::pin!(condition1, condition2);
4886
4887        view.update(cx, |view, cx| view.inc(cx));
4888        assert_eq!(poll_once(&mut condition1).await, None);
4889        assert_eq!(poll_once(&mut condition2).await, None);
4890
4891        view.update(cx, |view, cx| view.inc(cx));
4892        assert_eq!(poll_once(&mut condition1).await, Some(()));
4893        assert_eq!(poll_once(&mut condition2).await, None);
4894
4895        view.update(cx, |view, cx| view.inc(cx));
4896        assert_eq!(poll_once(&mut condition2).await, Some(()));
4897        view.update(cx, |_, cx| cx.notify());
4898    }
4899
4900    #[crate::test(self)]
4901    #[should_panic]
4902    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
4903        struct View;
4904
4905        impl super::Entity for View {
4906            type Event = ();
4907        }
4908
4909        impl super::View for View {
4910            fn ui_name() -> &'static str {
4911                "test view"
4912            }
4913
4914            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4915                Empty::new().boxed()
4916            }
4917        }
4918
4919        let (_, view) = cx.add_window(|_| View);
4920        view.condition(&cx, |_, _| false).await;
4921    }
4922
4923    #[crate::test(self)]
4924    #[should_panic(expected = "view dropped with pending condition")]
4925    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
4926        struct View;
4927
4928        impl super::Entity for View {
4929            type Event = ();
4930        }
4931
4932        impl super::View for View {
4933            fn ui_name() -> &'static str {
4934                "test view"
4935            }
4936
4937            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4938                Empty::new().boxed()
4939            }
4940        }
4941
4942        let window_id = cx.add_window(|_| View).0;
4943        let view = cx.add_view(window_id, |_| View);
4944
4945        let condition = view.condition(&cx, |_, _| false);
4946        cx.update(|_| drop(view));
4947        condition.await;
4948    }
4949}