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