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