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