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