app.rs

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