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 parking_lot::Mutex;
  14use platform::Event;
  15use postage::{mpsc, oneshot, sink::Sink as _, stream::Stream as _};
  16use smol::prelude::*;
  17use std::{
  18    any::{type_name, Any, TypeId},
  19    cell::RefCell,
  20    collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque},
  21    fmt::{self, Debug},
  22    hash::{Hash, Hasher},
  23    marker::PhantomData,
  24    mem,
  25    ops::{Deref, DerefMut},
  26    path::{Path, PathBuf},
  27    pin::Pin,
  28    rc::{self, Rc},
  29    sync::{
  30        atomic::{AtomicUsize, Ordering::SeqCst},
  31        Arc, Weak,
  32    },
  33    time::Duration,
  34};
  35
  36pub trait Entity: 'static {
  37    type Event;
  38
  39    fn release(&mut self, _: &mut MutableAppContext) {}
  40    fn app_will_quit(
  41        &mut self,
  42        _: &mut MutableAppContext,
  43    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  44        None
  45    }
  46}
  47
  48pub trait View: Entity + Sized {
  49    fn ui_name() -> &'static str;
  50    fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox;
  51    fn on_focus(&mut self, _: &mut ViewContext<Self>) {}
  52    fn on_blur(&mut self, _: &mut ViewContext<Self>) {}
  53    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
  54        Self::default_keymap_context()
  55    }
  56    fn default_keymap_context() -> keymap::Context {
  57        let mut cx = keymap::Context::default();
  58        cx.set.insert(Self::ui_name().into());
  59        cx
  60    }
  61}
  62
  63pub trait ReadModel {
  64    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T;
  65}
  66
  67pub trait ReadModelWith {
  68    fn read_model_with<E: Entity, T>(
  69        &self,
  70        handle: &ModelHandle<E>,
  71        read: &mut dyn FnMut(&E, &AppContext) -> T,
  72    ) -> T;
  73}
  74
  75pub trait UpdateModel {
  76    fn update_model<T: Entity, O>(
  77        &mut self,
  78        handle: &ModelHandle<T>,
  79        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
  80    ) -> O;
  81}
  82
  83pub trait UpgradeModelHandle {
  84    fn upgrade_model_handle<T: Entity>(
  85        &self,
  86        handle: &WeakModelHandle<T>,
  87    ) -> Option<ModelHandle<T>>;
  88
  89    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool;
  90
  91    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle>;
  92}
  93
  94pub trait UpgradeViewHandle {
  95    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>>;
  96}
  97
  98pub trait ReadView {
  99    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T;
 100}
 101
 102pub trait ReadViewWith {
 103    fn read_view_with<V, T>(
 104        &self,
 105        handle: &ViewHandle<V>,
 106        read: &mut dyn FnMut(&V, &AppContext) -> T,
 107    ) -> T
 108    where
 109        V: View;
 110}
 111
 112pub trait UpdateView {
 113    fn update_view<T, S>(
 114        &mut self,
 115        handle: &ViewHandle<T>,
 116        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 117    ) -> S
 118    where
 119        T: View;
 120}
 121
 122pub trait ElementStateContext: DerefMut<Target = MutableAppContext> {
 123    fn current_view_id(&self) -> usize;
 124
 125    fn element_state<Tag: 'static, T: 'static + Default>(
 126        &mut self,
 127        element_id: usize,
 128    ) -> ElementStateHandle<T> {
 129        let id = ElementStateId {
 130            view_id: self.current_view_id(),
 131            element_id,
 132            tag: TypeId::of::<Tag>(),
 133        };
 134        self.cx
 135            .element_states
 136            .entry(id)
 137            .or_insert_with(|| Box::new(T::default()));
 138        ElementStateHandle::new(id, self.frame_count, &self.cx.ref_counts)
 139    }
 140}
 141
 142pub trait Action: 'static + AnyAction {
 143    type Argument: 'static + Clone;
 144}
 145
 146pub trait AnyAction {
 147    fn id(&self) -> TypeId;
 148    fn name(&self) -> &'static str;
 149    fn as_any(&self) -> &dyn Any;
 150    fn boxed_clone(&self) -> Box<dyn AnyAction>;
 151    fn boxed_clone_as_any(&self) -> Box<dyn Any>;
 152}
 153
 154#[macro_export]
 155macro_rules! action {
 156    ($name:ident, $arg:ty) => {
 157        #[derive(Clone)]
 158        pub struct $name(pub $arg);
 159
 160        impl $crate::Action for $name {
 161            type Argument = $arg;
 162        }
 163
 164        impl $crate::AnyAction for $name {
 165            fn id(&self) -> std::any::TypeId {
 166                std::any::TypeId::of::<$name>()
 167            }
 168
 169            fn name(&self) -> &'static str {
 170                stringify!($name)
 171            }
 172
 173            fn as_any(&self) -> &dyn std::any::Any {
 174                self
 175            }
 176
 177            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 178                Box::new(self.clone())
 179            }
 180
 181            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 182                Box::new(self.clone())
 183            }
 184        }
 185    };
 186
 187    ($name:ident) => {
 188        #[derive(Clone, Debug, Eq, PartialEq)]
 189        pub struct $name;
 190
 191        impl $crate::Action for $name {
 192            type Argument = ();
 193        }
 194
 195        impl $crate::AnyAction for $name {
 196            fn id(&self) -> std::any::TypeId {
 197                std::any::TypeId::of::<$name>()
 198            }
 199
 200            fn name(&self) -> &'static str {
 201                stringify!($name)
 202            }
 203
 204            fn as_any(&self) -> &dyn std::any::Any {
 205                self
 206            }
 207
 208            fn boxed_clone(&self) -> Box<dyn $crate::AnyAction> {
 209                Box::new(self.clone())
 210            }
 211
 212            fn boxed_clone_as_any(&self) -> Box<dyn std::any::Any> {
 213                Box::new(self.clone())
 214            }
 215        }
 216    };
 217}
 218
 219pub struct Menu<'a> {
 220    pub name: &'a str,
 221    pub items: Vec<MenuItem<'a>>,
 222}
 223
 224pub enum MenuItem<'a> {
 225    Action {
 226        name: &'a str,
 227        keystroke: Option<&'a str>,
 228        action: Box<dyn AnyAction>,
 229    },
 230    Separator,
 231}
 232
 233#[derive(Clone)]
 234pub struct App(Rc<RefCell<MutableAppContext>>);
 235
 236#[derive(Clone)]
 237pub struct AsyncAppContext(Rc<RefCell<MutableAppContext>>);
 238
 239pub struct TestAppContext {
 240    cx: Rc<RefCell<MutableAppContext>>,
 241    foreground_platform: Rc<platform::test::ForegroundPlatform>,
 242}
 243
 244impl App {
 245    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 246        let platform = platform::current::platform();
 247        let foreground_platform = platform::current::foreground_platform();
 248        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 249        let app = Self(Rc::new(RefCell::new(MutableAppContext::new(
 250            foreground,
 251            Arc::new(executor::Background::new()),
 252            platform.clone(),
 253            foreground_platform.clone(),
 254            Arc::new(FontCache::new(platform.fonts())),
 255            Default::default(),
 256            asset_source,
 257        ))));
 258
 259        foreground_platform.on_quit(Box::new({
 260            let cx = app.0.clone();
 261            move || {
 262                cx.borrow_mut().quit();
 263            }
 264        }));
 265        foreground_platform.on_menu_command(Box::new({
 266            let cx = app.0.clone();
 267            move |action| {
 268                let mut cx = cx.borrow_mut();
 269                if let Some(key_window_id) = cx.cx.platform.key_window_id() {
 270                    if let Some((presenter, _)) =
 271                        cx.presenters_and_platform_windows.get(&key_window_id)
 272                    {
 273                        let presenter = presenter.clone();
 274                        let path = presenter.borrow().dispatch_path(cx.as_ref());
 275                        cx.dispatch_action_any(key_window_id, &path, action);
 276                    } else {
 277                        cx.dispatch_global_action_any(action);
 278                    }
 279                } else {
 280                    cx.dispatch_global_action_any(action);
 281                }
 282            }
 283        }));
 284
 285        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 286        Ok(app)
 287    }
 288
 289    pub fn background(&self) -> Arc<executor::Background> {
 290        self.0.borrow().background().clone()
 291    }
 292
 293    pub fn on_become_active<F>(self, mut callback: F) -> Self
 294    where
 295        F: 'static + FnMut(&mut MutableAppContext),
 296    {
 297        let cx = self.0.clone();
 298        self.0
 299            .borrow_mut()
 300            .foreground_platform
 301            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 302        self
 303    }
 304
 305    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 306    where
 307        F: 'static + FnMut(&mut MutableAppContext),
 308    {
 309        let cx = self.0.clone();
 310        self.0
 311            .borrow_mut()
 312            .foreground_platform
 313            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 314        self
 315    }
 316
 317    pub fn on_quit<F>(self, mut callback: F) -> Self
 318    where
 319        F: 'static + FnMut(&mut MutableAppContext),
 320    {
 321        let cx = self.0.clone();
 322        self.0
 323            .borrow_mut()
 324            .foreground_platform
 325            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 326        self
 327    }
 328
 329    pub fn on_event<F>(self, mut callback: F) -> Self
 330    where
 331        F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
 332    {
 333        let cx = self.0.clone();
 334        self.0
 335            .borrow_mut()
 336            .foreground_platform
 337            .on_event(Box::new(move |event| {
 338                callback(event, &mut *cx.borrow_mut())
 339            }));
 340        self
 341    }
 342
 343    pub fn on_open_files<F>(self, mut callback: F) -> Self
 344    where
 345        F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
 346    {
 347        let cx = self.0.clone();
 348        self.0
 349            .borrow_mut()
 350            .foreground_platform
 351            .on_open_files(Box::new(move |paths| {
 352                callback(paths, &mut *cx.borrow_mut())
 353            }));
 354        self
 355    }
 356
 357    pub fn run<F>(self, on_finish_launching: F)
 358    where
 359        F: 'static + FnOnce(&mut MutableAppContext),
 360    {
 361        let platform = self.0.borrow().foreground_platform.clone();
 362        platform.run(Box::new(move || {
 363            let mut cx = self.0.borrow_mut();
 364            let cx = &mut *cx;
 365            crate::views::init(cx);
 366            on_finish_launching(cx);
 367        }))
 368    }
 369
 370    pub fn platform(&self) -> Arc<dyn Platform> {
 371        self.0.borrow().platform()
 372    }
 373
 374    pub fn font_cache(&self) -> Arc<FontCache> {
 375        self.0.borrow().cx.font_cache.clone()
 376    }
 377
 378    fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 379        let mut state = self.0.borrow_mut();
 380        let result = state.update(callback);
 381        state.pending_notifications.clear();
 382        result
 383    }
 384}
 385
 386impl TestAppContext {
 387    pub fn new(
 388        foreground_platform: Rc<platform::test::ForegroundPlatform>,
 389        platform: Arc<dyn Platform>,
 390        foreground: Rc<executor::Foreground>,
 391        background: Arc<executor::Background>,
 392        font_cache: Arc<FontCache>,
 393        leak_detector: Arc<Mutex<LeakDetector>>,
 394        first_entity_id: usize,
 395    ) -> Self {
 396        let mut cx = MutableAppContext::new(
 397            foreground.clone(),
 398            background,
 399            platform,
 400            foreground_platform.clone(),
 401            font_cache,
 402            RefCounts {
 403                #[cfg(feature = "test-support")]
 404                leak_detector,
 405                ..Default::default()
 406            },
 407            (),
 408        );
 409        cx.next_entity_id = first_entity_id;
 410        let cx = TestAppContext {
 411            cx: Rc::new(RefCell::new(cx)),
 412            foreground_platform,
 413        };
 414        cx.cx.borrow_mut().weak_self = Some(Rc::downgrade(&cx.cx));
 415        cx
 416    }
 417
 418    pub fn dispatch_action<A: Action>(
 419        &self,
 420        window_id: usize,
 421        responder_chain: Vec<usize>,
 422        action: A,
 423    ) {
 424        self.cx
 425            .borrow_mut()
 426            .dispatch_action_any(window_id, &responder_chain, &action);
 427    }
 428
 429    pub fn dispatch_global_action<A: Action>(&self, action: A) {
 430        self.cx.borrow_mut().dispatch_global_action(action);
 431    }
 432
 433    pub fn dispatch_keystroke(
 434        &self,
 435        window_id: usize,
 436        responder_chain: Vec<usize>,
 437        keystroke: &Keystroke,
 438    ) -> Result<bool> {
 439        let mut state = self.cx.borrow_mut();
 440        state.dispatch_keystroke(window_id, responder_chain, keystroke)
 441    }
 442
 443    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 444    where
 445        T: Entity,
 446        F: FnOnce(&mut ModelContext<T>) -> T,
 447    {
 448        self.cx.borrow_mut().add_model(build_model)
 449    }
 450
 451    pub fn add_window<T, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<T>)
 452    where
 453        T: View,
 454        F: FnOnce(&mut ViewContext<T>) -> T,
 455    {
 456        self.cx
 457            .borrow_mut()
 458            .add_window(Default::default(), build_root_view)
 459    }
 460
 461    pub fn window_ids(&self) -> Vec<usize> {
 462        self.cx.borrow().window_ids().collect()
 463    }
 464
 465    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 466        self.cx.borrow().root_view(window_id)
 467    }
 468
 469    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
 470    where
 471        T: View,
 472        F: FnOnce(&mut ViewContext<T>) -> T,
 473    {
 474        self.cx.borrow_mut().add_view(window_id, build_view)
 475    }
 476
 477    pub fn add_option_view<T, F>(
 478        &mut self,
 479        window_id: usize,
 480        build_view: F,
 481    ) -> Option<ViewHandle<T>>
 482    where
 483        T: View,
 484        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 485    {
 486        self.cx.borrow_mut().add_option_view(window_id, build_view)
 487    }
 488
 489    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 490        callback(self.cx.borrow().as_ref())
 491    }
 492
 493    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 494        let mut state = self.cx.borrow_mut();
 495        // Don't increment pending flushes in order to effects to be flushed before the callback
 496        // completes, which is helpful in tests.
 497        let result = callback(&mut *state);
 498        // Flush effects after the callback just in case there are any. This can happen in edge
 499        // cases such as the closure dropping handles.
 500        state.flush_effects();
 501        result
 502    }
 503
 504    pub fn to_async(&self) -> AsyncAppContext {
 505        AsyncAppContext(self.cx.clone())
 506    }
 507
 508    pub fn font_cache(&self) -> Arc<FontCache> {
 509        self.cx.borrow().cx.font_cache.clone()
 510    }
 511
 512    pub fn foreground_platform(&self) -> Rc<platform::test::ForegroundPlatform> {
 513        self.foreground_platform.clone()
 514    }
 515
 516    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 517        self.cx.borrow().cx.platform.clone()
 518    }
 519
 520    pub fn foreground(&self) -> Rc<executor::Foreground> {
 521        self.cx.borrow().foreground().clone()
 522    }
 523
 524    pub fn background(&self) -> Arc<executor::Background> {
 525        self.cx.borrow().background().clone()
 526    }
 527
 528    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 529    where
 530        F: FnOnce(AsyncAppContext) -> Fut,
 531        Fut: 'static + Future<Output = T>,
 532        T: 'static,
 533    {
 534        self.cx.borrow_mut().spawn(f)
 535    }
 536
 537    pub fn simulate_new_path_selection(&self, result: impl FnOnce(PathBuf) -> Option<PathBuf>) {
 538        self.foreground_platform.simulate_new_path_selection(result);
 539    }
 540
 541    pub fn did_prompt_for_new_path(&self) -> bool {
 542        self.foreground_platform.as_ref().did_prompt_for_new_path()
 543    }
 544
 545    pub fn simulate_prompt_answer(&self, window_id: usize, answer: usize) {
 546        let mut state = self.cx.borrow_mut();
 547        let (_, window) = state
 548            .presenters_and_platform_windows
 549            .get_mut(&window_id)
 550            .unwrap();
 551        let test_window = window
 552            .as_any_mut()
 553            .downcast_mut::<platform::test::Window>()
 554            .unwrap();
 555        let mut done_tx = test_window
 556            .last_prompt
 557            .take()
 558            .expect("prompt was not called");
 559        let _ = done_tx.try_send(answer);
 560    }
 561
 562    #[cfg(feature = "test-support")]
 563    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
 564        self.cx.borrow().leak_detector()
 565    }
 566}
 567
 568impl Drop for TestAppContext {
 569    fn drop(&mut self) {
 570        self.cx.borrow_mut().flush_effects();
 571    }
 572}
 573
 574impl AsyncAppContext {
 575    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 576    where
 577        F: FnOnce(AsyncAppContext) -> Fut,
 578        Fut: 'static + Future<Output = T>,
 579        T: 'static,
 580    {
 581        self.0.borrow().foreground.spawn(f(self.clone()))
 582    }
 583
 584    pub fn read<T, F: FnOnce(&AppContext) -> T>(&mut self, callback: F) -> T {
 585        callback(self.0.borrow().as_ref())
 586    }
 587
 588    pub fn update<T, F: FnOnce(&mut MutableAppContext) -> T>(&mut self, callback: F) -> T {
 589        self.0.borrow_mut().update(callback)
 590    }
 591
 592    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 593    where
 594        T: Entity,
 595        F: FnOnce(&mut ModelContext<T>) -> T,
 596    {
 597        self.update(|cx| cx.add_model(build_model))
 598    }
 599
 600    pub fn platform(&self) -> Arc<dyn Platform> {
 601        self.0.borrow().platform()
 602    }
 603
 604    pub fn foreground(&self) -> Rc<executor::Foreground> {
 605        self.0.borrow().foreground.clone()
 606    }
 607
 608    pub fn background(&self) -> Arc<executor::Background> {
 609        self.0.borrow().cx.background.clone()
 610    }
 611}
 612
 613impl UpdateModel for AsyncAppContext {
 614    fn update_model<E: Entity, O>(
 615        &mut self,
 616        handle: &ModelHandle<E>,
 617        update: &mut dyn FnMut(&mut E, &mut ModelContext<E>) -> O,
 618    ) -> O {
 619        self.0.borrow_mut().update_model(handle, update)
 620    }
 621}
 622
 623impl UpgradeModelHandle for AsyncAppContext {
 624    fn upgrade_model_handle<T: Entity>(
 625        &self,
 626        handle: &WeakModelHandle<T>,
 627    ) -> Option<ModelHandle<T>> {
 628        self.0.borrow().upgrade_model_handle(handle)
 629    }
 630
 631    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 632        self.0.borrow().model_handle_is_upgradable(handle)
 633    }
 634
 635    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 636        self.0.borrow().upgrade_any_model_handle(handle)
 637    }
 638}
 639
 640impl UpgradeViewHandle for AsyncAppContext {
 641    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 642        self.0.borrow_mut().upgrade_view_handle(handle)
 643    }
 644}
 645
 646impl ReadModelWith for AsyncAppContext {
 647    fn read_model_with<E: Entity, T>(
 648        &self,
 649        handle: &ModelHandle<E>,
 650        read: &mut dyn FnMut(&E, &AppContext) -> T,
 651    ) -> T {
 652        let cx = self.0.borrow();
 653        let cx = cx.as_ref();
 654        read(handle.read(cx), cx)
 655    }
 656}
 657
 658impl UpdateView for AsyncAppContext {
 659    fn update_view<T, S>(
 660        &mut self,
 661        handle: &ViewHandle<T>,
 662        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 663    ) -> S
 664    where
 665        T: View,
 666    {
 667        self.0.borrow_mut().update_view(handle, update)
 668    }
 669}
 670
 671impl ReadViewWith for AsyncAppContext {
 672    fn read_view_with<V, T>(
 673        &self,
 674        handle: &ViewHandle<V>,
 675        read: &mut dyn FnMut(&V, &AppContext) -> T,
 676    ) -> T
 677    where
 678        V: View,
 679    {
 680        let cx = self.0.borrow();
 681        let cx = cx.as_ref();
 682        read(handle.read(cx), cx)
 683    }
 684}
 685
 686impl UpdateModel for TestAppContext {
 687    fn update_model<T: Entity, O>(
 688        &mut self,
 689        handle: &ModelHandle<T>,
 690        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
 691    ) -> O {
 692        self.cx.borrow_mut().update_model(handle, update)
 693    }
 694}
 695
 696impl ReadModelWith for TestAppContext {
 697    fn read_model_with<E: Entity, T>(
 698        &self,
 699        handle: &ModelHandle<E>,
 700        read: &mut dyn FnMut(&E, &AppContext) -> T,
 701    ) -> T {
 702        let cx = self.cx.borrow();
 703        let cx = cx.as_ref();
 704        read(handle.read(cx), cx)
 705    }
 706}
 707
 708impl UpdateView for TestAppContext {
 709    fn update_view<T, S>(
 710        &mut self,
 711        handle: &ViewHandle<T>,
 712        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 713    ) -> S
 714    where
 715        T: View,
 716    {
 717        self.cx.borrow_mut().update_view(handle, update)
 718    }
 719}
 720
 721impl ReadViewWith for TestAppContext {
 722    fn read_view_with<V, T>(
 723        &self,
 724        handle: &ViewHandle<V>,
 725        read: &mut dyn FnMut(&V, &AppContext) -> T,
 726    ) -> T
 727    where
 728        V: View,
 729    {
 730        let cx = self.cx.borrow();
 731        let cx = cx.as_ref();
 732        read(handle.read(cx), cx)
 733    }
 734}
 735
 736type ActionCallback =
 737    dyn FnMut(&mut dyn AnyView, &dyn AnyAction, &mut MutableAppContext, usize, usize);
 738type GlobalActionCallback = dyn FnMut(&dyn AnyAction, &mut MutableAppContext);
 739
 740type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut MutableAppContext) -> bool>;
 741type ObservationCallback = Box<dyn FnMut(&mut MutableAppContext) -> bool>;
 742type ReleaseObservationCallback = Box<dyn FnMut(&mut MutableAppContext)>;
 743
 744pub struct MutableAppContext {
 745    weak_self: Option<rc::Weak<RefCell<Self>>>,
 746    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 747    assets: Arc<AssetCache>,
 748    cx: AppContext,
 749    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 750    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 751    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 752    keystroke_matcher: keymap::Matcher,
 753    next_entity_id: usize,
 754    next_window_id: usize,
 755    next_subscription_id: usize,
 756    frame_count: usize,
 757    subscriptions: Arc<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>,
 758    observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>,
 759    release_observations: Arc<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>,
 760    presenters_and_platform_windows:
 761        HashMap<usize, (Rc<RefCell<Presenter>>, Box<dyn platform::Window>)>,
 762    debug_elements_callbacks: HashMap<usize, Box<dyn Fn(&AppContext) -> crate::json::Value>>,
 763    foreground: Rc<executor::Foreground>,
 764    pending_effects: VecDeque<Effect>,
 765    pending_notifications: HashSet<usize>,
 766    pending_flushes: usize,
 767    flushing_effects: bool,
 768    next_cursor_style_handle_id: Arc<AtomicUsize>,
 769    halt_action_dispatch: bool,
 770}
 771
 772impl MutableAppContext {
 773    fn new(
 774        foreground: Rc<executor::Foreground>,
 775        background: Arc<executor::Background>,
 776        platform: Arc<dyn platform::Platform>,
 777        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 778        font_cache: Arc<FontCache>,
 779        ref_counts: RefCounts,
 780        asset_source: impl AssetSource,
 781    ) -> Self {
 782        Self {
 783            weak_self: None,
 784            foreground_platform,
 785            assets: Arc::new(AssetCache::new(asset_source)),
 786            cx: AppContext {
 787                models: Default::default(),
 788                views: Default::default(),
 789                windows: Default::default(),
 790                app_states: Default::default(),
 791                element_states: Default::default(),
 792                ref_counts: Arc::new(Mutex::new(ref_counts)),
 793                background,
 794                font_cache,
 795                platform,
 796            },
 797            capture_actions: HashMap::new(),
 798            actions: HashMap::new(),
 799            global_actions: HashMap::new(),
 800            keystroke_matcher: keymap::Matcher::default(),
 801            next_entity_id: 0,
 802            next_window_id: 0,
 803            next_subscription_id: 0,
 804            frame_count: 0,
 805            subscriptions: Default::default(),
 806            observations: Default::default(),
 807            release_observations: Default::default(),
 808            presenters_and_platform_windows: HashMap::new(),
 809            debug_elements_callbacks: HashMap::new(),
 810            foreground,
 811            pending_effects: VecDeque::new(),
 812            pending_notifications: HashSet::new(),
 813            pending_flushes: 0,
 814            flushing_effects: false,
 815            next_cursor_style_handle_id: Default::default(),
 816            halt_action_dispatch: false,
 817        }
 818    }
 819
 820    pub fn upgrade(&self) -> App {
 821        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 822    }
 823
 824    pub fn quit(&mut self) {
 825        let mut futures = Vec::new();
 826        for model_id in self.cx.models.keys().copied().collect::<Vec<_>>() {
 827            let mut model = self.cx.models.remove(&model_id).unwrap();
 828            futures.extend(model.app_will_quit(self));
 829            self.cx.models.insert(model_id, model);
 830        }
 831
 832        for view_id in self.cx.views.keys().copied().collect::<Vec<_>>() {
 833            let mut view = self.cx.views.remove(&view_id).unwrap();
 834            futures.extend(view.app_will_quit(self));
 835            self.cx.views.insert(view_id, view);
 836        }
 837
 838        self.remove_all_windows();
 839
 840        let futures = futures::future::join_all(futures);
 841        if self
 842            .background
 843            .block_with_timeout(Duration::from_millis(100), futures)
 844            .is_err()
 845        {
 846            log::error!("timed out waiting on app_will_quit");
 847        }
 848    }
 849
 850    fn remove_all_windows(&mut self) {
 851        for (window_id, _) in self.cx.windows.drain() {
 852            self.presenters_and_platform_windows.remove(&window_id);
 853        }
 854        self.remove_dropped_entities();
 855    }
 856
 857    pub fn platform(&self) -> Arc<dyn platform::Platform> {
 858        self.cx.platform.clone()
 859    }
 860
 861    pub fn font_cache(&self) -> &Arc<FontCache> {
 862        &self.cx.font_cache
 863    }
 864
 865    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 866        &self.foreground
 867    }
 868
 869    pub fn background(&self) -> &Arc<executor::Background> {
 870        &self.cx.background
 871    }
 872
 873    pub fn on_debug_elements<F>(&mut self, window_id: usize, callback: F)
 874    where
 875        F: 'static + Fn(&AppContext) -> crate::json::Value,
 876    {
 877        self.debug_elements_callbacks
 878            .insert(window_id, Box::new(callback));
 879    }
 880
 881    pub fn debug_elements(&self, window_id: usize) -> Option<crate::json::Value> {
 882        self.debug_elements_callbacks
 883            .get(&window_id)
 884            .map(|debug_elements| debug_elements(&self.cx))
 885    }
 886
 887    pub fn add_action<A, V, F>(&mut self, handler: F)
 888    where
 889        A: Action,
 890        V: View,
 891        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 892    {
 893        self.add_action_internal(handler, false)
 894    }
 895
 896    pub fn capture_action<A, V, F>(&mut self, handler: F)
 897    where
 898        A: Action,
 899        V: View,
 900        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 901    {
 902        self.add_action_internal(handler, true)
 903    }
 904
 905    fn add_action_internal<A, V, F>(&mut self, mut handler: F, capture: bool)
 906    where
 907        A: Action,
 908        V: View,
 909        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 910    {
 911        let handler = Box::new(
 912            move |view: &mut dyn AnyView,
 913                  action: &dyn AnyAction,
 914                  cx: &mut MutableAppContext,
 915                  window_id: usize,
 916                  view_id: usize| {
 917                let action = action.as_any().downcast_ref().unwrap();
 918                let mut cx = ViewContext::new(cx, window_id, view_id);
 919                handler(
 920                    view.as_any_mut()
 921                        .downcast_mut()
 922                        .expect("downcast is type safe"),
 923                    action,
 924                    &mut cx,
 925                );
 926            },
 927        );
 928
 929        let actions = if capture {
 930            &mut self.capture_actions
 931        } else {
 932            &mut self.actions
 933        };
 934
 935        actions
 936            .entry(TypeId::of::<V>())
 937            .or_default()
 938            .entry(TypeId::of::<A>())
 939            .or_default()
 940            .push(handler);
 941    }
 942
 943    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 944    where
 945        A: Action,
 946        V: View,
 947        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 948    {
 949        self.add_action(move |view, action, cx| {
 950            handler(view, action, cx).map(|task| task.detach_and_log_err(cx));
 951        })
 952    }
 953
 954    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 955    where
 956        A: Action,
 957        F: 'static + FnMut(&A, &mut MutableAppContext),
 958    {
 959        let handler = Box::new(move |action: &dyn AnyAction, cx: &mut MutableAppContext| {
 960            let action = action.as_any().downcast_ref().unwrap();
 961            handler(action, cx);
 962        });
 963
 964        if self
 965            .global_actions
 966            .insert(TypeId::of::<A>(), handler)
 967            .is_some()
 968        {
 969            panic!("registered multiple global handlers for the same action type");
 970        }
 971    }
 972
 973    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 974        self.cx.windows.keys().cloned()
 975    }
 976
 977    pub fn activate_window(&self, window_id: usize) {
 978        if let Some((_, window)) = self.presenters_and_platform_windows.get(&window_id) {
 979            window.activate()
 980        }
 981    }
 982
 983    pub fn root_view<T: View>(&self, window_id: usize) -> Option<ViewHandle<T>> {
 984        self.cx
 985            .windows
 986            .get(&window_id)
 987            .and_then(|window| window.root_view.clone().downcast::<T>())
 988    }
 989
 990    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
 991        self.cx.root_view_id(window_id)
 992    }
 993
 994    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
 995        self.cx.focused_view_id(window_id)
 996    }
 997
 998    pub fn render_view(
 999        &mut self,
1000        window_id: usize,
1001        view_id: usize,
1002        titlebar_height: f32,
1003        refreshing: bool,
1004    ) -> Result<ElementBox> {
1005        let mut view = self
1006            .cx
1007            .views
1008            .remove(&(window_id, view_id))
1009            .ok_or(anyhow!("view not found"))?;
1010        let element = view.render(window_id, view_id, titlebar_height, refreshing, self);
1011        self.cx.views.insert((window_id, view_id), view);
1012        Ok(element)
1013    }
1014
1015    pub fn render_views(
1016        &mut self,
1017        window_id: usize,
1018        titlebar_height: f32,
1019    ) -> HashMap<usize, ElementBox> {
1020        self.start_frame();
1021        let view_ids = self
1022            .views
1023            .keys()
1024            .filter_map(|(win_id, view_id)| {
1025                if *win_id == window_id {
1026                    Some(*view_id)
1027                } else {
1028                    None
1029                }
1030            })
1031            .collect::<Vec<_>>();
1032        view_ids
1033            .into_iter()
1034            .map(|view_id| {
1035                (
1036                    view_id,
1037                    self.render_view(window_id, view_id, titlebar_height, false)
1038                        .unwrap(),
1039                )
1040            })
1041            .collect()
1042    }
1043
1044    pub(crate) fn start_frame(&mut self) {
1045        self.frame_count += 1;
1046    }
1047
1048    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
1049        self.pending_flushes += 1;
1050        let result = callback(self);
1051        self.flush_effects();
1052        result
1053    }
1054
1055    pub fn set_menus(&mut self, menus: Vec<Menu>) {
1056        self.foreground_platform.set_menus(menus);
1057    }
1058
1059    fn prompt(
1060        &self,
1061        window_id: usize,
1062        level: PromptLevel,
1063        msg: &str,
1064        answers: &[&str],
1065    ) -> oneshot::Receiver<usize> {
1066        let (_, window) = &self.presenters_and_platform_windows[&window_id];
1067        window.prompt(level, msg, answers)
1068    }
1069
1070    pub fn prompt_for_paths(
1071        &self,
1072        options: PathPromptOptions,
1073    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1074        self.foreground_platform.prompt_for_paths(options)
1075    }
1076
1077    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
1078        self.foreground_platform.prompt_for_new_path(directory)
1079    }
1080
1081    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1082    where
1083        E: Entity,
1084        E::Event: 'static,
1085        H: Handle<E>,
1086        F: 'static + FnMut(H, &E::Event, &mut Self),
1087    {
1088        self.subscribe_internal(handle, move |handle, event, cx| {
1089            callback(handle, event, cx);
1090            true
1091        })
1092    }
1093
1094    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1095    where
1096        E: Entity,
1097        E::Event: 'static,
1098        H: Handle<E>,
1099        F: 'static + FnMut(H, &mut Self),
1100    {
1101        self.observe_internal(handle, move |handle, cx| {
1102            callback(handle, cx);
1103            true
1104        })
1105    }
1106
1107    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1108    where
1109        E: Entity,
1110        E::Event: 'static,
1111        H: Handle<E>,
1112        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
1113    {
1114        let id = post_inc(&mut self.next_subscription_id);
1115        let emitter = handle.downgrade();
1116        self.subscriptions
1117            .lock()
1118            .entry(handle.id())
1119            .or_default()
1120            .insert(
1121                id,
1122                Box::new(move |payload, cx| {
1123                    if let Some(emitter) = H::upgrade_from(&emitter, cx.as_ref()) {
1124                        let payload = payload.downcast_ref().expect("downcast is type safe");
1125                        callback(emitter, payload, cx)
1126                    } else {
1127                        false
1128                    }
1129                }),
1130            );
1131        Subscription::Subscription {
1132            id,
1133            entity_id: handle.id(),
1134            subscriptions: Some(Arc::downgrade(&self.subscriptions)),
1135        }
1136    }
1137
1138    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1139    where
1140        E: Entity,
1141        E::Event: 'static,
1142        H: Handle<E>,
1143        F: 'static + FnMut(H, &mut Self) -> bool,
1144    {
1145        let id = post_inc(&mut self.next_subscription_id);
1146        let observed = handle.downgrade();
1147        self.observations
1148            .lock()
1149            .entry(handle.id())
1150            .or_default()
1151            .insert(
1152                id,
1153                Box::new(move |cx| {
1154                    if let Some(observed) = H::upgrade_from(&observed, cx) {
1155                        callback(observed, cx)
1156                    } else {
1157                        false
1158                    }
1159                }),
1160            );
1161        Subscription::Observation {
1162            id,
1163            entity_id: handle.id(),
1164            observations: Some(Arc::downgrade(&self.observations)),
1165        }
1166    }
1167
1168    pub fn observe_release<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
1169    where
1170        E: Entity,
1171        E::Event: 'static,
1172        H: Handle<E>,
1173        F: 'static + FnMut(&mut Self),
1174    {
1175        let id = post_inc(&mut self.next_subscription_id);
1176        self.release_observations
1177            .lock()
1178            .entry(handle.id())
1179            .or_default()
1180            .insert(id, Box::new(move |cx| callback(cx)));
1181        Subscription::ReleaseObservation {
1182            id,
1183            entity_id: handle.id(),
1184            observations: Some(Arc::downgrade(&self.release_observations)),
1185        }
1186    }
1187
1188    fn defer(&mut self, callback: Box<dyn FnOnce(&mut MutableAppContext)>) {
1189        self.pending_effects.push_back(Effect::Deferred(callback))
1190    }
1191
1192    pub(crate) fn notify_model(&mut self, model_id: usize) {
1193        if self.pending_notifications.insert(model_id) {
1194            self.pending_effects
1195                .push_back(Effect::ModelNotification { model_id });
1196        }
1197    }
1198
1199    pub(crate) fn notify_view(&mut self, window_id: usize, view_id: usize) {
1200        if self.pending_notifications.insert(view_id) {
1201            self.pending_effects
1202                .push_back(Effect::ViewNotification { window_id, view_id });
1203        }
1204    }
1205
1206    pub fn dispatch_action<A: Action>(
1207        &mut self,
1208        window_id: usize,
1209        responder_chain: Vec<usize>,
1210        action: &A,
1211    ) {
1212        self.dispatch_action_any(window_id, &responder_chain, action);
1213    }
1214
1215    pub(crate) fn dispatch_action_any(
1216        &mut self,
1217        window_id: usize,
1218        path: &[usize],
1219        action: &dyn AnyAction,
1220    ) -> bool {
1221        self.update(|this| {
1222            this.halt_action_dispatch = false;
1223            for (capture_phase, view_id) in path
1224                .iter()
1225                .map(|view_id| (true, *view_id))
1226                .chain(path.iter().rev().map(|view_id| (false, *view_id)))
1227            {
1228                if let Some(mut view) = this.cx.views.remove(&(window_id, view_id)) {
1229                    let type_id = view.as_any().type_id();
1230
1231                    if let Some((name, mut handlers)) = this
1232                        .actions_mut(capture_phase)
1233                        .get_mut(&type_id)
1234                        .and_then(|h| h.remove_entry(&action.id()))
1235                    {
1236                        for handler in handlers.iter_mut().rev() {
1237                            this.halt_action_dispatch = true;
1238                            handler(view.as_mut(), action, this, window_id, view_id);
1239                            if this.halt_action_dispatch {
1240                                break;
1241                            }
1242                        }
1243                        this.actions_mut(capture_phase)
1244                            .get_mut(&type_id)
1245                            .unwrap()
1246                            .insert(name, handlers);
1247                    }
1248
1249                    this.cx.views.insert((window_id, view_id), view);
1250
1251                    if this.halt_action_dispatch {
1252                        break;
1253                    }
1254                }
1255            }
1256
1257            if !this.halt_action_dispatch {
1258                this.dispatch_global_action_any(action);
1259            }
1260            this.halt_action_dispatch
1261        })
1262    }
1263
1264    fn actions_mut(
1265        &mut self,
1266        capture_phase: bool,
1267    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1268        if capture_phase {
1269            &mut self.capture_actions
1270        } else {
1271            &mut self.actions
1272        }
1273    }
1274
1275    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1276        self.dispatch_global_action_any(&action);
1277    }
1278
1279    fn dispatch_global_action_any(&mut self, action: &dyn AnyAction) -> bool {
1280        self.update(|this| {
1281            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1282                handler(action, this);
1283                this.global_actions.insert(name, handler);
1284                true
1285            } else {
1286                false
1287            }
1288        })
1289    }
1290
1291    pub fn add_bindings<T: IntoIterator<Item = keymap::Binding>>(&mut self, bindings: T) {
1292        self.keystroke_matcher.add_bindings(bindings);
1293    }
1294
1295    pub fn dispatch_keystroke(
1296        &mut self,
1297        window_id: usize,
1298        responder_chain: Vec<usize>,
1299        keystroke: &Keystroke,
1300    ) -> Result<bool> {
1301        let mut context_chain = Vec::new();
1302        for view_id in &responder_chain {
1303            if let Some(view) = self.cx.views.get(&(window_id, *view_id)) {
1304                context_chain.push(view.keymap_context(self.as_ref()));
1305            } else {
1306                return Err(anyhow!(
1307                    "View {} in responder chain does not exist",
1308                    view_id
1309                ));
1310            }
1311        }
1312
1313        let mut pending = false;
1314        for (i, cx) in context_chain.iter().enumerate().rev() {
1315            match self
1316                .keystroke_matcher
1317                .push_keystroke(keystroke.clone(), responder_chain[i], cx)
1318            {
1319                MatchResult::None => {}
1320                MatchResult::Pending => pending = true,
1321                MatchResult::Action(action) => {
1322                    if self.dispatch_action_any(window_id, &responder_chain[0..=i], action.as_ref())
1323                    {
1324                        self.keystroke_matcher.clear_pending();
1325                        return Ok(true);
1326                    }
1327                }
1328            }
1329        }
1330
1331        Ok(pending)
1332    }
1333
1334    pub fn add_app_state<T: 'static>(&mut self, state: T) {
1335        self.cx
1336            .app_states
1337            .insert(TypeId::of::<T>(), Box::new(state));
1338    }
1339
1340    pub fn update_app_state<T: 'static, F, U>(&mut self, update: F) -> U
1341    where
1342        F: FnOnce(&mut T, &mut MutableAppContext) -> U,
1343    {
1344        let type_id = TypeId::of::<T>();
1345        let mut state = self
1346            .cx
1347            .app_states
1348            .remove(&type_id)
1349            .expect("no app state has been added for this type");
1350        let result = update(state.downcast_mut().unwrap(), self);
1351        self.cx.app_states.insert(type_id, state);
1352        result
1353    }
1354
1355    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1356    where
1357        T: Entity,
1358        F: FnOnce(&mut ModelContext<T>) -> T,
1359    {
1360        self.update(|this| {
1361            let model_id = post_inc(&mut this.next_entity_id);
1362            let handle = ModelHandle::new(model_id, &this.cx.ref_counts);
1363            let mut cx = ModelContext::new(this, model_id);
1364            let model = build_model(&mut cx);
1365            this.cx.models.insert(model_id, Box::new(model));
1366            handle
1367        })
1368    }
1369
1370    pub fn add_window<T, F>(
1371        &mut self,
1372        window_options: WindowOptions,
1373        build_root_view: F,
1374    ) -> (usize, ViewHandle<T>)
1375    where
1376        T: View,
1377        F: FnOnce(&mut ViewContext<T>) -> T,
1378    {
1379        self.update(|this| {
1380            let window_id = post_inc(&mut this.next_window_id);
1381            let root_view = this.add_view(window_id, build_root_view);
1382
1383            this.cx.windows.insert(
1384                window_id,
1385                Window {
1386                    root_view: root_view.clone().into(),
1387                    focused_view_id: root_view.id(),
1388                    invalidation: None,
1389                },
1390            );
1391            this.open_platform_window(window_id, window_options);
1392            root_view.update(this, |view, cx| {
1393                view.on_focus(cx);
1394                cx.notify();
1395            });
1396
1397            (window_id, root_view)
1398        })
1399    }
1400
1401    pub fn remove_window(&mut self, window_id: usize) {
1402        self.cx.windows.remove(&window_id);
1403        self.presenters_and_platform_windows.remove(&window_id);
1404        self.remove_dropped_entities();
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}
3153
3154impl<T: View> ViewHandle<T> {
3155    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3156        ref_counts.lock().inc_view(window_id, view_id);
3157        Self {
3158            window_id,
3159            view_id,
3160            view_type: PhantomData,
3161            ref_counts: ref_counts.clone(),
3162        }
3163    }
3164
3165    pub fn downgrade(&self) -> WeakViewHandle<T> {
3166        WeakViewHandle::new(self.window_id, self.view_id)
3167    }
3168
3169    pub fn window_id(&self) -> usize {
3170        self.window_id
3171    }
3172
3173    pub fn id(&self) -> usize {
3174        self.view_id
3175    }
3176
3177    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
3178        cx.read_view(self)
3179    }
3180
3181    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3182    where
3183        C: ReadViewWith,
3184        F: FnOnce(&T, &AppContext) -> S,
3185    {
3186        let mut read = Some(read);
3187        cx.read_view_with(self, &mut |view, cx| {
3188            let read = read.take().unwrap();
3189            read(view, cx)
3190        })
3191    }
3192
3193    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3194    where
3195        C: UpdateView,
3196        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3197    {
3198        let mut update = Some(update);
3199        cx.update_view(self, &mut |view, cx| {
3200            let update = update.take().unwrap();
3201            update(view, cx)
3202        })
3203    }
3204
3205    pub fn defer<C, F>(&self, cx: &mut C, update: F)
3206    where
3207        C: AsMut<MutableAppContext>,
3208        F: 'static + FnOnce(&mut T, &mut ViewContext<T>),
3209    {
3210        let this = self.clone();
3211        cx.as_mut().defer(Box::new(move |cx| {
3212            this.update(cx, |view, cx| update(view, cx));
3213        }));
3214    }
3215
3216    pub fn is_focused(&self, cx: &AppContext) -> bool {
3217        cx.focused_view_id(self.window_id)
3218            .map_or(false, |focused_id| focused_id == self.view_id)
3219    }
3220
3221    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
3222        let (mut tx, mut rx) = mpsc::channel(1);
3223        let mut cx = cx.cx.borrow_mut();
3224        let subscription = cx.observe(self, move |_, _| {
3225            tx.try_send(()).ok();
3226        });
3227
3228        let duration = if std::env::var("CI").is_ok() {
3229            Duration::from_secs(5)
3230        } else {
3231            Duration::from_secs(1)
3232        };
3233
3234        async move {
3235            let notification = timeout(duration, rx.recv())
3236                .await
3237                .expect("next notification timed out");
3238            drop(subscription);
3239            notification.expect("model dropped while test was waiting for its next notification")
3240        }
3241    }
3242
3243    pub fn condition(
3244        &self,
3245        cx: &TestAppContext,
3246        mut predicate: impl FnMut(&T, &AppContext) -> bool,
3247    ) -> impl Future<Output = ()> {
3248        let (tx, mut rx) = mpsc::channel(1024);
3249
3250        let mut cx = cx.cx.borrow_mut();
3251        let subscriptions = self.update(&mut *cx, |_, cx| {
3252            (
3253                cx.observe(self, {
3254                    let mut tx = tx.clone();
3255                    move |_, _, _| {
3256                        tx.blocking_send(()).ok();
3257                    }
3258                }),
3259                cx.subscribe(self, {
3260                    let mut tx = tx.clone();
3261                    move |_, _, _, _| {
3262                        tx.blocking_send(()).ok();
3263                    }
3264                }),
3265            )
3266        });
3267
3268        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
3269        let handle = self.downgrade();
3270        let duration = if std::env::var("CI").is_ok() {
3271            Duration::from_secs(2)
3272        } else {
3273            Duration::from_millis(500)
3274        };
3275
3276        async move {
3277            timeout(duration, async move {
3278                loop {
3279                    {
3280                        let cx = cx.borrow();
3281                        let cx = cx.as_ref();
3282                        if predicate(
3283                            handle
3284                                .upgrade(cx)
3285                                .expect("view dropped with pending condition")
3286                                .read(cx),
3287                            cx,
3288                        ) {
3289                            break;
3290                        }
3291                    }
3292
3293                    cx.borrow().foreground().start_waiting();
3294                    rx.recv()
3295                        .await
3296                        .expect("view dropped with pending condition");
3297                    cx.borrow().foreground().finish_waiting();
3298                }
3299            })
3300            .await
3301            .expect("condition timed out");
3302            drop(subscriptions);
3303        }
3304    }
3305}
3306
3307impl<T> Clone for ViewHandle<T> {
3308    fn clone(&self) -> Self {
3309        self.ref_counts
3310            .lock()
3311            .inc_view(self.window_id, self.view_id);
3312        Self {
3313            window_id: self.window_id,
3314            view_id: self.view_id,
3315            view_type: PhantomData,
3316            ref_counts: self.ref_counts.clone(),
3317        }
3318    }
3319}
3320
3321impl<T> PartialEq for ViewHandle<T> {
3322    fn eq(&self, other: &Self) -> bool {
3323        self.window_id == other.window_id && self.view_id == other.view_id
3324    }
3325}
3326
3327impl<T> Eq for ViewHandle<T> {}
3328
3329impl<T> Debug for ViewHandle<T> {
3330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3331        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3332            .field("window_id", &self.window_id)
3333            .field("view_id", &self.view_id)
3334            .finish()
3335    }
3336}
3337
3338impl<T> Drop for ViewHandle<T> {
3339    fn drop(&mut self) {
3340        self.ref_counts
3341            .lock()
3342            .dec_view(self.window_id, self.view_id);
3343    }
3344}
3345
3346impl<T: View> Handle<T> for ViewHandle<T> {
3347    type Weak = WeakViewHandle<T>;
3348
3349    fn id(&self) -> usize {
3350        self.view_id
3351    }
3352
3353    fn location(&self) -> EntityLocation {
3354        EntityLocation::View(self.window_id, self.view_id)
3355    }
3356
3357    fn downgrade(&self) -> Self::Weak {
3358        self.downgrade()
3359    }
3360
3361    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3362    where
3363        Self: Sized,
3364    {
3365        weak.upgrade(cx)
3366    }
3367}
3368
3369pub struct AnyViewHandle {
3370    window_id: usize,
3371    view_id: usize,
3372    view_type: TypeId,
3373    ref_counts: Arc<Mutex<RefCounts>>,
3374}
3375
3376impl AnyViewHandle {
3377    pub fn id(&self) -> usize {
3378        self.view_id
3379    }
3380
3381    pub fn is<T: 'static>(&self) -> bool {
3382        TypeId::of::<T>() == self.view_type
3383    }
3384
3385    pub fn is_focused(&self, cx: &AppContext) -> bool {
3386        cx.focused_view_id(self.window_id)
3387            .map_or(false, |focused_id| focused_id == self.view_id)
3388    }
3389
3390    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3391        if self.is::<T>() {
3392            let result = Some(ViewHandle {
3393                window_id: self.window_id,
3394                view_id: self.view_id,
3395                ref_counts: self.ref_counts.clone(),
3396                view_type: PhantomData,
3397            });
3398            unsafe {
3399                Arc::decrement_strong_count(&self.ref_counts);
3400            }
3401            std::mem::forget(self);
3402            result
3403        } else {
3404            None
3405        }
3406    }
3407}
3408
3409impl Clone for AnyViewHandle {
3410    fn clone(&self) -> Self {
3411        self.ref_counts
3412            .lock()
3413            .inc_view(self.window_id, self.view_id);
3414        Self {
3415            window_id: self.window_id,
3416            view_id: self.view_id,
3417            view_type: self.view_type,
3418            ref_counts: self.ref_counts.clone(),
3419        }
3420    }
3421}
3422
3423impl From<&AnyViewHandle> for AnyViewHandle {
3424    fn from(handle: &AnyViewHandle) -> Self {
3425        handle.clone()
3426    }
3427}
3428
3429impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3430    fn from(handle: &ViewHandle<T>) -> Self {
3431        handle
3432            .ref_counts
3433            .lock()
3434            .inc_view(handle.window_id, handle.view_id);
3435        AnyViewHandle {
3436            window_id: handle.window_id,
3437            view_id: handle.view_id,
3438            view_type: TypeId::of::<T>(),
3439            ref_counts: handle.ref_counts.clone(),
3440        }
3441    }
3442}
3443
3444impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3445    fn from(handle: ViewHandle<T>) -> Self {
3446        let any_handle = AnyViewHandle {
3447            window_id: handle.window_id,
3448            view_id: handle.view_id,
3449            view_type: TypeId::of::<T>(),
3450            ref_counts: handle.ref_counts.clone(),
3451        };
3452        unsafe {
3453            Arc::decrement_strong_count(&handle.ref_counts);
3454        }
3455        std::mem::forget(handle);
3456        any_handle
3457    }
3458}
3459
3460impl Drop for AnyViewHandle {
3461    fn drop(&mut self) {
3462        self.ref_counts
3463            .lock()
3464            .dec_view(self.window_id, self.view_id);
3465    }
3466}
3467
3468pub struct AnyModelHandle {
3469    model_id: usize,
3470    model_type: TypeId,
3471    ref_counts: Arc<Mutex<RefCounts>>,
3472
3473    #[cfg(feature = "test-support")]
3474    handle_id: usize,
3475}
3476
3477impl AnyModelHandle {
3478    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3479        ref_counts.lock().inc_model(model_id);
3480
3481        #[cfg(feature = "test-support")]
3482        let handle_id = ref_counts
3483            .lock()
3484            .leak_detector
3485            .lock()
3486            .handle_created(None, model_id);
3487
3488        Self {
3489            model_id,
3490            model_type,
3491            ref_counts,
3492
3493            #[cfg(feature = "test-support")]
3494            handle_id,
3495        }
3496    }
3497
3498    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3499        if self.is::<T>() {
3500            let result = Some(ModelHandle {
3501                model_id: self.model_id,
3502                model_type: PhantomData,
3503                ref_counts: self.ref_counts.clone(),
3504
3505                #[cfg(feature = "test-support")]
3506                handle_id: self.handle_id,
3507            });
3508            unsafe {
3509                Arc::decrement_strong_count(&self.ref_counts);
3510            }
3511            std::mem::forget(self);
3512            result
3513        } else {
3514            None
3515        }
3516    }
3517
3518    pub fn downgrade(&self) -> AnyWeakModelHandle {
3519        AnyWeakModelHandle {
3520            model_id: self.model_id,
3521            model_type: self.model_type,
3522        }
3523    }
3524
3525    pub fn is<T: Entity>(&self) -> bool {
3526        self.model_type == TypeId::of::<T>()
3527    }
3528}
3529
3530impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3531    fn from(handle: ModelHandle<T>) -> Self {
3532        Self::new(
3533            handle.model_id,
3534            TypeId::of::<T>(),
3535            handle.ref_counts.clone(),
3536        )
3537    }
3538}
3539
3540impl Clone for AnyModelHandle {
3541    fn clone(&self) -> Self {
3542        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3543    }
3544}
3545
3546impl Drop for AnyModelHandle {
3547    fn drop(&mut self) {
3548        let mut ref_counts = self.ref_counts.lock();
3549        ref_counts.dec_model(self.model_id);
3550
3551        #[cfg(feature = "test-support")]
3552        ref_counts
3553            .leak_detector
3554            .lock()
3555            .handle_dropped(self.model_id, self.handle_id);
3556    }
3557}
3558
3559pub struct AnyWeakModelHandle {
3560    model_id: usize,
3561    model_type: TypeId,
3562}
3563
3564impl AnyWeakModelHandle {
3565    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<AnyModelHandle> {
3566        cx.upgrade_any_model_handle(self)
3567    }
3568}
3569
3570pub struct WeakViewHandle<T> {
3571    window_id: usize,
3572    view_id: usize,
3573    view_type: PhantomData<T>,
3574}
3575
3576impl<T: View> WeakViewHandle<T> {
3577    fn new(window_id: usize, view_id: usize) -> Self {
3578        Self {
3579            window_id,
3580            view_id,
3581            view_type: PhantomData,
3582        }
3583    }
3584
3585    pub fn id(&self) -> usize {
3586        self.view_id
3587    }
3588
3589    pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
3590        cx.upgrade_view_handle(self)
3591    }
3592}
3593
3594impl<T> Clone for WeakViewHandle<T> {
3595    fn clone(&self) -> Self {
3596        Self {
3597            window_id: self.window_id,
3598            view_id: self.view_id,
3599            view_type: PhantomData,
3600        }
3601    }
3602}
3603
3604impl<T> PartialEq for WeakViewHandle<T> {
3605    fn eq(&self, other: &Self) -> bool {
3606        self.window_id == other.window_id && self.view_id == other.view_id
3607    }
3608}
3609
3610impl<T> Eq for WeakViewHandle<T> {}
3611
3612impl<T> Hash for WeakViewHandle<T> {
3613    fn hash<H: Hasher>(&self, state: &mut H) {
3614        self.window_id.hash(state);
3615        self.view_id.hash(state);
3616    }
3617}
3618
3619#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3620pub struct ElementStateId {
3621    view_id: usize,
3622    element_id: usize,
3623    tag: TypeId,
3624}
3625
3626pub struct ElementStateHandle<T> {
3627    value_type: PhantomData<T>,
3628    id: ElementStateId,
3629    ref_counts: Weak<Mutex<RefCounts>>,
3630}
3631
3632impl<T: 'static> ElementStateHandle<T> {
3633    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3634        ref_counts.lock().inc_element_state(id, frame_id);
3635        Self {
3636            value_type: PhantomData,
3637            id,
3638            ref_counts: Arc::downgrade(ref_counts),
3639        }
3640    }
3641
3642    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3643        cx.element_states
3644            .get(&self.id)
3645            .unwrap()
3646            .downcast_ref()
3647            .unwrap()
3648    }
3649
3650    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3651    where
3652        C: DerefMut<Target = MutableAppContext>,
3653    {
3654        let mut element_state = cx.deref_mut().cx.element_states.remove(&self.id).unwrap();
3655        let result = f(element_state.downcast_mut().unwrap(), cx);
3656        cx.deref_mut()
3657            .cx
3658            .element_states
3659            .insert(self.id, element_state);
3660        result
3661    }
3662}
3663
3664impl<T> Drop for ElementStateHandle<T> {
3665    fn drop(&mut self) {
3666        if let Some(ref_counts) = self.ref_counts.upgrade() {
3667            ref_counts.lock().dec_element_state(self.id);
3668        }
3669    }
3670}
3671
3672pub struct CursorStyleHandle {
3673    id: usize,
3674    next_cursor_style_handle_id: Arc<AtomicUsize>,
3675    platform: Arc<dyn Platform>,
3676}
3677
3678impl Drop for CursorStyleHandle {
3679    fn drop(&mut self) {
3680        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3681            self.platform.set_cursor_style(CursorStyle::Arrow);
3682        }
3683    }
3684}
3685
3686#[must_use]
3687pub enum Subscription {
3688    Subscription {
3689        id: usize,
3690        entity_id: usize,
3691        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3692    },
3693    Observation {
3694        id: usize,
3695        entity_id: usize,
3696        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3697    },
3698    ReleaseObservation {
3699        id: usize,
3700        entity_id: usize,
3701        observations:
3702            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3703    },
3704}
3705
3706impl Subscription {
3707    pub fn detach(&mut self) {
3708        match self {
3709            Subscription::Subscription { subscriptions, .. } => {
3710                subscriptions.take();
3711            }
3712            Subscription::Observation { observations, .. } => {
3713                observations.take();
3714            }
3715            Subscription::ReleaseObservation { observations, .. } => {
3716                observations.take();
3717            }
3718        }
3719    }
3720}
3721
3722impl Drop for Subscription {
3723    fn drop(&mut self) {
3724        match self {
3725            Subscription::Observation {
3726                id,
3727                entity_id,
3728                observations,
3729            } => {
3730                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3731                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3732                        observations.remove(id);
3733                    }
3734                }
3735            }
3736            Subscription::ReleaseObservation {
3737                id,
3738                entity_id,
3739                observations,
3740            } => {
3741                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3742                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3743                        observations.remove(id);
3744                    }
3745                }
3746            }
3747            Subscription::Subscription {
3748                id,
3749                entity_id,
3750                subscriptions,
3751            } => {
3752                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3753                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3754                        subscriptions.remove(id);
3755                    }
3756                }
3757            }
3758        }
3759    }
3760}
3761
3762#[derive(Default)]
3763pub struct LeakDetector {
3764    next_handle_id: usize,
3765    handle_backtraces: HashMap<usize, (Option<&'static str>, HashMap<usize, Backtrace>)>,
3766}
3767
3768impl LeakDetector {
3769    fn handle_created(&mut self, type_name: Option<&'static str>, entity_id: usize) -> usize {
3770        let handle_id = post_inc(&mut self.next_handle_id);
3771        let entry = self.handle_backtraces.entry(entity_id).or_default();
3772        if let Some(type_name) = type_name {
3773            entry.0.get_or_insert(type_name);
3774        }
3775        entry.1.insert(handle_id, Backtrace::new_unresolved());
3776        handle_id
3777    }
3778
3779    fn handle_dropped(&mut self, entity_id: usize, handle_id: usize) {
3780        if let Some((_, backtraces)) = self.handle_backtraces.get_mut(&entity_id) {
3781            assert!(backtraces.remove(&handle_id).is_some());
3782            if backtraces.is_empty() {
3783                self.handle_backtraces.remove(&entity_id);
3784            }
3785        }
3786    }
3787
3788    pub fn detect(&mut self) {
3789        let mut found_leaks = false;
3790        for (id, (type_name, backtraces)) in self.handle_backtraces.iter_mut() {
3791            eprintln!(
3792                "leaked {} handles to {:?} {}",
3793                backtraces.len(),
3794                type_name.unwrap_or("entity"),
3795                id
3796            );
3797            for trace in backtraces.values_mut() {
3798                trace.resolve();
3799                eprintln!("{:?}", CwdBacktrace(trace));
3800            }
3801            found_leaks = true;
3802        }
3803        assert!(!found_leaks, "detected leaked handles");
3804    }
3805}
3806
3807#[derive(Default)]
3808struct RefCounts {
3809    entity_counts: HashMap<usize, usize>,
3810    element_state_counts: HashMap<ElementStateId, ElementStateRefCount>,
3811    dropped_models: HashSet<usize>,
3812    dropped_views: HashSet<(usize, usize)>,
3813    dropped_element_states: HashSet<ElementStateId>,
3814
3815    #[cfg(feature = "test-support")]
3816    leak_detector: Arc<Mutex<LeakDetector>>,
3817}
3818
3819struct ElementStateRefCount {
3820    ref_count: usize,
3821    frame_id: usize,
3822}
3823
3824impl RefCounts {
3825    fn inc_model(&mut self, model_id: usize) {
3826        match self.entity_counts.entry(model_id) {
3827            Entry::Occupied(mut entry) => {
3828                *entry.get_mut() += 1;
3829            }
3830            Entry::Vacant(entry) => {
3831                entry.insert(1);
3832                self.dropped_models.remove(&model_id);
3833            }
3834        }
3835    }
3836
3837    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3838        match self.entity_counts.entry(view_id) {
3839            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3840            Entry::Vacant(entry) => {
3841                entry.insert(1);
3842                self.dropped_views.remove(&(window_id, view_id));
3843            }
3844        }
3845    }
3846
3847    fn inc_element_state(&mut self, id: ElementStateId, frame_id: usize) {
3848        match self.element_state_counts.entry(id) {
3849            Entry::Occupied(mut entry) => {
3850                let entry = entry.get_mut();
3851                if entry.frame_id == frame_id || entry.ref_count >= 2 {
3852                    panic!("used the same element state more than once in the same frame");
3853                }
3854                entry.ref_count += 1;
3855                entry.frame_id = frame_id;
3856            }
3857            Entry::Vacant(entry) => {
3858                entry.insert(ElementStateRefCount {
3859                    ref_count: 1,
3860                    frame_id,
3861                });
3862                self.dropped_element_states.remove(&id);
3863            }
3864        }
3865    }
3866
3867    fn dec_model(&mut self, model_id: usize) {
3868        let count = self.entity_counts.get_mut(&model_id).unwrap();
3869        *count -= 1;
3870        if *count == 0 {
3871            self.entity_counts.remove(&model_id);
3872            self.dropped_models.insert(model_id);
3873        }
3874    }
3875
3876    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3877        let count = self.entity_counts.get_mut(&view_id).unwrap();
3878        *count -= 1;
3879        if *count == 0 {
3880            self.entity_counts.remove(&view_id);
3881            self.dropped_views.insert((window_id, view_id));
3882        }
3883    }
3884
3885    fn dec_element_state(&mut self, id: ElementStateId) {
3886        let entry = self.element_state_counts.get_mut(&id).unwrap();
3887        entry.ref_count -= 1;
3888        if entry.ref_count == 0 {
3889            self.element_state_counts.remove(&id);
3890            self.dropped_element_states.insert(id);
3891        }
3892    }
3893
3894    fn is_entity_alive(&self, entity_id: usize) -> bool {
3895        self.entity_counts.contains_key(&entity_id)
3896    }
3897
3898    fn take_dropped(
3899        &mut self,
3900    ) -> (
3901        HashSet<usize>,
3902        HashSet<(usize, usize)>,
3903        HashSet<ElementStateId>,
3904    ) {
3905        (
3906            std::mem::take(&mut self.dropped_models),
3907            std::mem::take(&mut self.dropped_views),
3908            std::mem::take(&mut self.dropped_element_states),
3909        )
3910    }
3911}
3912
3913#[cfg(test)]
3914mod tests {
3915    use super::*;
3916    use crate::elements::*;
3917    use smol::future::poll_once;
3918    use std::{
3919        cell::Cell,
3920        sync::atomic::{AtomicUsize, Ordering::SeqCst},
3921    };
3922
3923    #[crate::test(self)]
3924    fn test_model_handles(cx: &mut MutableAppContext) {
3925        struct Model {
3926            other: Option<ModelHandle<Model>>,
3927            events: Vec<String>,
3928        }
3929
3930        impl Entity for Model {
3931            type Event = usize;
3932        }
3933
3934        impl Model {
3935            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3936                if let Some(other) = other.as_ref() {
3937                    cx.observe(other, |me, _, _| {
3938                        me.events.push("notified".into());
3939                    })
3940                    .detach();
3941                    cx.subscribe(other, |me, _, event, _| {
3942                        me.events.push(format!("observed event {}", event));
3943                    })
3944                    .detach();
3945                }
3946
3947                Self {
3948                    other,
3949                    events: Vec::new(),
3950                }
3951            }
3952        }
3953
3954        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3955        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3956        assert_eq!(cx.cx.models.len(), 2);
3957
3958        handle_1.update(cx, |model, cx| {
3959            model.events.push("updated".into());
3960            cx.emit(1);
3961            cx.notify();
3962            cx.emit(2);
3963        });
3964        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3965        assert_eq!(
3966            handle_2.read(cx).events,
3967            vec![
3968                "observed event 1".to_string(),
3969                "notified".to_string(),
3970                "observed event 2".to_string(),
3971            ]
3972        );
3973
3974        handle_2.update(cx, |model, _| {
3975            drop(handle_1);
3976            model.other.take();
3977        });
3978
3979        assert_eq!(cx.cx.models.len(), 1);
3980        assert!(cx.subscriptions.lock().is_empty());
3981        assert!(cx.observations.lock().is_empty());
3982    }
3983
3984    #[crate::test(self)]
3985    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3986        #[derive(Default)]
3987        struct Model {
3988            events: Vec<usize>,
3989        }
3990
3991        impl Entity for Model {
3992            type Event = usize;
3993        }
3994
3995        let handle_1 = cx.add_model(|_| Model::default());
3996        let handle_2 = cx.add_model(|_| Model::default());
3997        let handle_2b = handle_2.clone();
3998
3999        handle_1.update(cx, |_, c| {
4000            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
4001                model.events.push(*event);
4002
4003                c.subscribe(&handle_2b, |model, _, event, _| {
4004                    model.events.push(*event * 2);
4005                })
4006                .detach();
4007            })
4008            .detach();
4009        });
4010
4011        handle_2.update(cx, |_, c| c.emit(7));
4012        assert_eq!(handle_1.read(cx).events, vec![7]);
4013
4014        handle_2.update(cx, |_, c| c.emit(5));
4015        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4016    }
4017
4018    #[crate::test(self)]
4019    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
4020        #[derive(Default)]
4021        struct Model {
4022            count: usize,
4023            events: Vec<usize>,
4024        }
4025
4026        impl Entity for Model {
4027            type Event = ();
4028        }
4029
4030        let handle_1 = cx.add_model(|_| Model::default());
4031        let handle_2 = cx.add_model(|_| Model::default());
4032        let handle_2b = handle_2.clone();
4033
4034        handle_1.update(cx, |_, c| {
4035            c.observe(&handle_2, move |model, observed, c| {
4036                model.events.push(observed.read(c).count);
4037                c.observe(&handle_2b, |model, observed, c| {
4038                    model.events.push(observed.read(c).count * 2);
4039                })
4040                .detach();
4041            })
4042            .detach();
4043        });
4044
4045        handle_2.update(cx, |model, c| {
4046            model.count = 7;
4047            c.notify()
4048        });
4049        assert_eq!(handle_1.read(cx).events, vec![7]);
4050
4051        handle_2.update(cx, |model, c| {
4052            model.count = 5;
4053            c.notify()
4054        });
4055        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4056    }
4057
4058    #[crate::test(self)]
4059    fn test_view_handles(cx: &mut MutableAppContext) {
4060        struct View {
4061            other: Option<ViewHandle<View>>,
4062            events: Vec<String>,
4063        }
4064
4065        impl Entity for View {
4066            type Event = usize;
4067        }
4068
4069        impl super::View for View {
4070            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4071                Empty::new().boxed()
4072            }
4073
4074            fn ui_name() -> &'static str {
4075                "View"
4076            }
4077        }
4078
4079        impl View {
4080            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4081                if let Some(other) = other.as_ref() {
4082                    cx.subscribe(other, |me, _, event, _| {
4083                        me.events.push(format!("observed event {}", event));
4084                    })
4085                    .detach();
4086                }
4087                Self {
4088                    other,
4089                    events: Vec::new(),
4090                }
4091            }
4092        }
4093
4094        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
4095        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
4096        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
4097        assert_eq!(cx.cx.views.len(), 3);
4098
4099        handle_1.update(cx, |view, cx| {
4100            view.events.push("updated".into());
4101            cx.emit(1);
4102            cx.emit(2);
4103        });
4104        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4105        assert_eq!(
4106            handle_2.read(cx).events,
4107            vec![
4108                "observed event 1".to_string(),
4109                "observed event 2".to_string(),
4110            ]
4111        );
4112
4113        handle_2.update(cx, |view, _| {
4114            drop(handle_1);
4115            view.other.take();
4116        });
4117
4118        assert_eq!(cx.cx.views.len(), 2);
4119        assert!(cx.subscriptions.lock().is_empty());
4120        assert!(cx.observations.lock().is_empty());
4121    }
4122
4123    #[crate::test(self)]
4124    fn test_add_window(cx: &mut MutableAppContext) {
4125        struct View {
4126            mouse_down_count: Arc<AtomicUsize>,
4127        }
4128
4129        impl Entity for View {
4130            type Event = ();
4131        }
4132
4133        impl super::View for View {
4134            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4135                let mouse_down_count = self.mouse_down_count.clone();
4136                EventHandler::new(Empty::new().boxed())
4137                    .on_mouse_down(move |_| {
4138                        mouse_down_count.fetch_add(1, SeqCst);
4139                        true
4140                    })
4141                    .boxed()
4142            }
4143
4144            fn ui_name() -> &'static str {
4145                "View"
4146            }
4147        }
4148
4149        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4150        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4151            mouse_down_count: mouse_down_count.clone(),
4152        });
4153        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
4154        // Ensure window's root element is in a valid lifecycle state.
4155        presenter.borrow_mut().dispatch_event(
4156            Event::LeftMouseDown {
4157                position: Default::default(),
4158                ctrl: false,
4159                alt: false,
4160                shift: false,
4161                cmd: false,
4162                click_count: 1,
4163            },
4164            cx,
4165        );
4166        assert_eq!(mouse_down_count.load(SeqCst), 1);
4167    }
4168
4169    #[crate::test(self)]
4170    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
4171        struct Model {
4172            released: Rc<Cell<bool>>,
4173        }
4174
4175        struct View {
4176            released: Rc<Cell<bool>>,
4177        }
4178
4179        impl Entity for Model {
4180            type Event = ();
4181
4182            fn release(&mut self, _: &mut MutableAppContext) {
4183                self.released.set(true);
4184            }
4185        }
4186
4187        impl Entity for View {
4188            type Event = ();
4189
4190            fn release(&mut self, _: &mut MutableAppContext) {
4191                self.released.set(true);
4192            }
4193        }
4194
4195        impl super::View for View {
4196            fn ui_name() -> &'static str {
4197                "View"
4198            }
4199
4200            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4201                Empty::new().boxed()
4202            }
4203        }
4204
4205        let model_released = Rc::new(Cell::new(false));
4206        let model_release_observed = Rc::new(Cell::new(false));
4207        let view_released = Rc::new(Cell::new(false));
4208        let view_release_observed = Rc::new(Cell::new(false));
4209
4210        let model = cx.add_model(|_| Model {
4211            released: model_released.clone(),
4212        });
4213        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4214            released: view_released.clone(),
4215        });
4216        assert!(!model_released.get());
4217        assert!(!view_released.get());
4218
4219        cx.observe_release(&model, {
4220            let model_release_observed = model_release_observed.clone();
4221            move |_| model_release_observed.set(true)
4222        })
4223        .detach();
4224        cx.observe_release(&view, {
4225            let view_release_observed = view_release_observed.clone();
4226            move |_| view_release_observed.set(true)
4227        })
4228        .detach();
4229
4230        cx.update(move |_| {
4231            drop(model);
4232        });
4233        assert!(model_released.get());
4234        assert!(model_release_observed.get());
4235
4236        drop(view);
4237        cx.remove_window(window_id);
4238        assert!(view_released.get());
4239        assert!(view_release_observed.get());
4240    }
4241
4242    #[crate::test(self)]
4243    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
4244        #[derive(Default)]
4245        struct View {
4246            events: Vec<usize>,
4247        }
4248
4249        impl Entity for View {
4250            type Event = usize;
4251        }
4252
4253        impl super::View for View {
4254            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4255                Empty::new().boxed()
4256            }
4257
4258            fn ui_name() -> &'static str {
4259                "View"
4260            }
4261        }
4262
4263        struct Model;
4264
4265        impl Entity for Model {
4266            type Event = usize;
4267        }
4268
4269        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
4270        let handle_2 = cx.add_view(window_id, |_| View::default());
4271        let handle_2b = handle_2.clone();
4272        let handle_3 = cx.add_model(|_| Model);
4273
4274        handle_1.update(cx, |_, c| {
4275            c.subscribe(&handle_2, move |me, _, event, c| {
4276                me.events.push(*event);
4277
4278                c.subscribe(&handle_2b, |me, _, event, _| {
4279                    me.events.push(*event * 2);
4280                })
4281                .detach();
4282            })
4283            .detach();
4284
4285            c.subscribe(&handle_3, |me, _, event, _| {
4286                me.events.push(*event);
4287            })
4288            .detach();
4289        });
4290
4291        handle_2.update(cx, |_, c| c.emit(7));
4292        assert_eq!(handle_1.read(cx).events, vec![7]);
4293
4294        handle_2.update(cx, |_, c| c.emit(5));
4295        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4296
4297        handle_3.update(cx, |_, c| c.emit(9));
4298        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
4299    }
4300
4301    #[crate::test(self)]
4302    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
4303        struct View;
4304
4305        impl Entity for View {
4306            type Event = ();
4307        }
4308
4309        impl super::View for View {
4310            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4311                Empty::new().boxed()
4312            }
4313
4314            fn ui_name() -> &'static str {
4315                "View"
4316            }
4317        }
4318
4319        struct Model;
4320
4321        impl Entity for Model {
4322            type Event = ();
4323        }
4324
4325        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4326        let observing_view = cx.add_view(window_id, |_| View);
4327        let emitting_view = cx.add_view(window_id, |_| View);
4328        let observing_model = cx.add_model(|_| Model);
4329        let observed_model = cx.add_model(|_| Model);
4330
4331        observing_view.update(cx, |_, cx| {
4332            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4333            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4334        });
4335        observing_model.update(cx, |_, cx| {
4336            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4337        });
4338
4339        cx.update(|_| {
4340            drop(observing_view);
4341            drop(observing_model);
4342        });
4343
4344        emitting_view.update(cx, |_, cx| cx.emit(()));
4345        observed_model.update(cx, |_, cx| cx.emit(()));
4346    }
4347
4348    #[crate::test(self)]
4349    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
4350        #[derive(Default)]
4351        struct View {
4352            events: Vec<usize>,
4353        }
4354
4355        impl Entity for View {
4356            type Event = usize;
4357        }
4358
4359        impl super::View for View {
4360            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4361                Empty::new().boxed()
4362            }
4363
4364            fn ui_name() -> &'static str {
4365                "View"
4366            }
4367        }
4368
4369        #[derive(Default)]
4370        struct Model {
4371            count: usize,
4372        }
4373
4374        impl Entity for Model {
4375            type Event = ();
4376        }
4377
4378        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4379        let model = cx.add_model(|_| Model::default());
4380
4381        view.update(cx, |_, c| {
4382            c.observe(&model, |me, observed, c| {
4383                me.events.push(observed.read(c).count)
4384            })
4385            .detach();
4386        });
4387
4388        model.update(cx, |model, c| {
4389            model.count = 11;
4390            c.notify();
4391        });
4392        assert_eq!(view.read(cx).events, vec![11]);
4393    }
4394
4395    #[crate::test(self)]
4396    fn test_dropping_observers(cx: &mut MutableAppContext) {
4397        struct View;
4398
4399        impl Entity for View {
4400            type Event = ();
4401        }
4402
4403        impl super::View for View {
4404            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4405                Empty::new().boxed()
4406            }
4407
4408            fn ui_name() -> &'static str {
4409                "View"
4410            }
4411        }
4412
4413        struct Model;
4414
4415        impl Entity for Model {
4416            type Event = ();
4417        }
4418
4419        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4420        let observing_view = cx.add_view(window_id, |_| View);
4421        let observing_model = cx.add_model(|_| Model);
4422        let observed_model = cx.add_model(|_| Model);
4423
4424        observing_view.update(cx, |_, cx| {
4425            cx.observe(&observed_model, |_, _, _| {}).detach();
4426        });
4427        observing_model.update(cx, |_, cx| {
4428            cx.observe(&observed_model, |_, _, _| {}).detach();
4429        });
4430
4431        cx.update(|_| {
4432            drop(observing_view);
4433            drop(observing_model);
4434        });
4435
4436        observed_model.update(cx, |_, cx| cx.notify());
4437    }
4438
4439    #[crate::test(self)]
4440    fn test_focus(cx: &mut MutableAppContext) {
4441        struct View {
4442            name: String,
4443            events: Arc<Mutex<Vec<String>>>,
4444        }
4445
4446        impl Entity for View {
4447            type Event = ();
4448        }
4449
4450        impl super::View for View {
4451            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4452                Empty::new().boxed()
4453            }
4454
4455            fn ui_name() -> &'static str {
4456                "View"
4457            }
4458
4459            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4460                self.events.lock().push(format!("{} focused", &self.name));
4461            }
4462
4463            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4464                self.events.lock().push(format!("{} blurred", &self.name));
4465            }
4466        }
4467
4468        let events: Arc<Mutex<Vec<String>>> = Default::default();
4469        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4470            events: events.clone(),
4471            name: "view 1".to_string(),
4472        });
4473        let view_2 = cx.add_view(window_id, |_| View {
4474            events: events.clone(),
4475            name: "view 2".to_string(),
4476        });
4477
4478        view_1.update(cx, |_, cx| cx.focus(&view_2));
4479        view_1.update(cx, |_, cx| cx.focus(&view_1));
4480        view_1.update(cx, |_, cx| cx.focus(&view_2));
4481        view_1.update(cx, |_, _| drop(view_2));
4482
4483        assert_eq!(
4484            *events.lock(),
4485            [
4486                "view 1 focused".to_string(),
4487                "view 1 blurred".to_string(),
4488                "view 2 focused".to_string(),
4489                "view 2 blurred".to_string(),
4490                "view 1 focused".to_string(),
4491                "view 1 blurred".to_string(),
4492                "view 2 focused".to_string(),
4493                "view 1 focused".to_string(),
4494            ],
4495        );
4496    }
4497
4498    #[crate::test(self)]
4499    fn test_dispatch_action(cx: &mut MutableAppContext) {
4500        struct ViewA {
4501            id: usize,
4502        }
4503
4504        impl Entity for ViewA {
4505            type Event = ();
4506        }
4507
4508        impl View for ViewA {
4509            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4510                Empty::new().boxed()
4511            }
4512
4513            fn ui_name() -> &'static str {
4514                "View"
4515            }
4516        }
4517
4518        struct ViewB {
4519            id: usize,
4520        }
4521
4522        impl Entity for ViewB {
4523            type Event = ();
4524        }
4525
4526        impl View for ViewB {
4527            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4528                Empty::new().boxed()
4529            }
4530
4531            fn ui_name() -> &'static str {
4532                "View"
4533            }
4534        }
4535
4536        action!(Action, &'static str);
4537
4538        let actions = Rc::new(RefCell::new(Vec::new()));
4539
4540        {
4541            let actions = actions.clone();
4542            cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4543                actions.borrow_mut().push("global".to_string());
4544            });
4545        }
4546
4547        {
4548            let actions = actions.clone();
4549            cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4550                assert_eq!(action.0, "bar");
4551                cx.propagate_action();
4552                actions.borrow_mut().push(format!("{} a", view.id));
4553            });
4554        }
4555
4556        {
4557            let actions = actions.clone();
4558            cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4559                if view.id != 1 {
4560                    cx.add_view(|cx| {
4561                        cx.propagate_action(); // Still works on a nested ViewContext
4562                        ViewB { id: 5 }
4563                    });
4564                }
4565                actions.borrow_mut().push(format!("{} b", view.id));
4566            });
4567        }
4568
4569        {
4570            let actions = actions.clone();
4571            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4572                cx.propagate_action();
4573                actions.borrow_mut().push(format!("{} c", view.id));
4574            });
4575        }
4576
4577        {
4578            let actions = actions.clone();
4579            cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4580                cx.propagate_action();
4581                actions.borrow_mut().push(format!("{} d", view.id));
4582            });
4583        }
4584
4585        {
4586            let actions = actions.clone();
4587            cx.capture_action(move |view: &mut ViewA, _: &Action, cx| {
4588                cx.propagate_action();
4589                actions.borrow_mut().push(format!("{} capture", view.id));
4590            });
4591        }
4592
4593        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4594        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4595        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4596        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4597
4598        cx.dispatch_action(
4599            window_id,
4600            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4601            &Action("bar"),
4602        );
4603
4604        assert_eq!(
4605            *actions.borrow(),
4606            vec![
4607                "1 capture",
4608                "3 capture",
4609                "4 d",
4610                "4 c",
4611                "3 b",
4612                "3 a",
4613                "2 d",
4614                "2 c",
4615                "1 b"
4616            ]
4617        );
4618
4619        // Remove view_1, which doesn't propagate the action
4620        actions.borrow_mut().clear();
4621        cx.dispatch_action(
4622            window_id,
4623            vec![view_2.id(), view_3.id(), view_4.id()],
4624            &Action("bar"),
4625        );
4626
4627        assert_eq!(
4628            *actions.borrow(),
4629            vec![
4630                "3 capture",
4631                "4 d",
4632                "4 c",
4633                "3 b",
4634                "3 a",
4635                "2 d",
4636                "2 c",
4637                "global"
4638            ]
4639        );
4640    }
4641
4642    #[crate::test(self)]
4643    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4644        use std::cell::Cell;
4645
4646        action!(Action, &'static str);
4647
4648        struct View {
4649            id: usize,
4650            keymap_context: keymap::Context,
4651        }
4652
4653        impl Entity for View {
4654            type Event = ();
4655        }
4656
4657        impl super::View for View {
4658            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4659                Empty::new().boxed()
4660            }
4661
4662            fn ui_name() -> &'static str {
4663                "View"
4664            }
4665
4666            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4667                self.keymap_context.clone()
4668            }
4669        }
4670
4671        impl View {
4672            fn new(id: usize) -> Self {
4673                View {
4674                    id,
4675                    keymap_context: keymap::Context::default(),
4676                }
4677            }
4678        }
4679
4680        let mut view_1 = View::new(1);
4681        let mut view_2 = View::new(2);
4682        let mut view_3 = View::new(3);
4683        view_1.keymap_context.set.insert("a".into());
4684        view_2.keymap_context.set.insert("a".into());
4685        view_2.keymap_context.set.insert("b".into());
4686        view_3.keymap_context.set.insert("a".into());
4687        view_3.keymap_context.set.insert("b".into());
4688        view_3.keymap_context.set.insert("c".into());
4689
4690        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4691        let view_2 = cx.add_view(window_id, |_| view_2);
4692        let view_3 = cx.add_view(window_id, |_| view_3);
4693
4694        // This keymap's only binding dispatches an action on view 2 because that view will have
4695        // "a" and "b" in its context, but not "c".
4696        cx.add_bindings(vec![keymap::Binding::new(
4697            "a",
4698            Action("a"),
4699            Some("a && b && !c"),
4700        )]);
4701
4702        let handled_action = Rc::new(Cell::new(false));
4703        let handled_action_clone = handled_action.clone();
4704        cx.add_action(move |view: &mut View, action: &Action, _| {
4705            handled_action_clone.set(true);
4706            assert_eq!(view.id, 2);
4707            assert_eq!(action.0, "a");
4708        });
4709
4710        cx.dispatch_keystroke(
4711            window_id,
4712            vec![view_1.id(), view_2.id(), view_3.id()],
4713            &Keystroke::parse("a").unwrap(),
4714        )
4715        .unwrap();
4716
4717        assert!(handled_action.get());
4718    }
4719
4720    #[crate::test(self)]
4721    async fn test_model_condition(mut cx: TestAppContext) {
4722        struct Counter(usize);
4723
4724        impl super::Entity for Counter {
4725            type Event = ();
4726        }
4727
4728        impl Counter {
4729            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4730                self.0 += 1;
4731                cx.notify();
4732            }
4733        }
4734
4735        let model = cx.add_model(|_| Counter(0));
4736
4737        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4738        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4739        smol::pin!(condition1, condition2);
4740
4741        model.update(&mut cx, |model, cx| model.inc(cx));
4742        assert_eq!(poll_once(&mut condition1).await, None);
4743        assert_eq!(poll_once(&mut condition2).await, None);
4744
4745        model.update(&mut cx, |model, cx| model.inc(cx));
4746        assert_eq!(poll_once(&mut condition1).await, Some(()));
4747        assert_eq!(poll_once(&mut condition2).await, None);
4748
4749        model.update(&mut cx, |model, cx| model.inc(cx));
4750        assert_eq!(poll_once(&mut condition2).await, Some(()));
4751
4752        model.update(&mut cx, |_, cx| cx.notify());
4753    }
4754
4755    #[crate::test(self)]
4756    #[should_panic]
4757    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4758        struct Model;
4759
4760        impl super::Entity for Model {
4761            type Event = ();
4762        }
4763
4764        let model = cx.add_model(|_| Model);
4765        model.condition(&cx, |_, _| false).await;
4766    }
4767
4768    #[crate::test(self)]
4769    #[should_panic(expected = "model dropped with pending condition")]
4770    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4771        struct Model;
4772
4773        impl super::Entity for Model {
4774            type Event = ();
4775        }
4776
4777        let model = cx.add_model(|_| Model);
4778        let condition = model.condition(&cx, |_, _| false);
4779        cx.update(|_| drop(model));
4780        condition.await;
4781    }
4782
4783    #[crate::test(self)]
4784    async fn test_view_condition(mut cx: TestAppContext) {
4785        struct Counter(usize);
4786
4787        impl super::Entity for Counter {
4788            type Event = ();
4789        }
4790
4791        impl super::View for Counter {
4792            fn ui_name() -> &'static str {
4793                "test view"
4794            }
4795
4796            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4797                Empty::new().boxed()
4798            }
4799        }
4800
4801        impl Counter {
4802            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4803                self.0 += 1;
4804                cx.notify();
4805            }
4806        }
4807
4808        let (_, view) = cx.add_window(|_| Counter(0));
4809
4810        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4811        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4812        smol::pin!(condition1, condition2);
4813
4814        view.update(&mut cx, |view, cx| view.inc(cx));
4815        assert_eq!(poll_once(&mut condition1).await, None);
4816        assert_eq!(poll_once(&mut condition2).await, None);
4817
4818        view.update(&mut cx, |view, cx| view.inc(cx));
4819        assert_eq!(poll_once(&mut condition1).await, Some(()));
4820        assert_eq!(poll_once(&mut condition2).await, None);
4821
4822        view.update(&mut cx, |view, cx| view.inc(cx));
4823        assert_eq!(poll_once(&mut condition2).await, Some(()));
4824        view.update(&mut cx, |_, cx| cx.notify());
4825    }
4826
4827    #[crate::test(self)]
4828    #[should_panic]
4829    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4830        struct View;
4831
4832        impl super::Entity for View {
4833            type Event = ();
4834        }
4835
4836        impl super::View for View {
4837            fn ui_name() -> &'static str {
4838                "test view"
4839            }
4840
4841            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4842                Empty::new().boxed()
4843            }
4844        }
4845
4846        let (_, view) = cx.add_window(|_| View);
4847        view.condition(&cx, |_, _| false).await;
4848    }
4849
4850    #[crate::test(self)]
4851    #[should_panic(expected = "view dropped with pending condition")]
4852    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4853        struct View;
4854
4855        impl super::Entity for View {
4856            type Event = ();
4857        }
4858
4859        impl super::View for View {
4860            fn ui_name() -> &'static str {
4861                "test view"
4862            }
4863
4864            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4865                Empty::new().boxed()
4866            }
4867        }
4868
4869        let window_id = cx.add_window(|_| View).0;
4870        let view = cx.add_view(window_id, |_| View);
4871
4872        let condition = view.condition(&cx, |_, _| false);
4873        cx.update(|_| drop(view));
4874        condition.await;
4875    }
4876}