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