app.rs

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