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}
3249pub struct WeakViewHandle<T> {
3250    window_id: usize,
3251    view_id: usize,
3252    view_type: PhantomData<T>,
3253}
3254
3255impl<T: View> WeakViewHandle<T> {
3256    fn new(window_id: usize, view_id: usize) -> Self {
3257        Self {
3258            window_id,
3259            view_id,
3260            view_type: PhantomData,
3261        }
3262    }
3263
3264    pub fn id(&self) -> usize {
3265        self.view_id
3266    }
3267
3268    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
3269        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
3270            Some(ViewHandle::new(
3271                self.window_id,
3272                self.view_id,
3273                &cx.ref_counts,
3274            ))
3275        } else {
3276            None
3277        }
3278    }
3279}
3280
3281impl<T> Clone for WeakViewHandle<T> {
3282    fn clone(&self) -> Self {
3283        Self {
3284            window_id: self.window_id,
3285            view_id: self.view_id,
3286            view_type: PhantomData,
3287        }
3288    }
3289}
3290
3291#[derive(Clone, Copy, PartialEq, Eq, Hash)]
3292pub struct ElementStateId(usize, usize);
3293
3294impl From<usize> for ElementStateId {
3295    fn from(id: usize) -> Self {
3296        Self(id, 0)
3297    }
3298}
3299
3300impl From<(usize, usize)> for ElementStateId {
3301    fn from(id: (usize, usize)) -> Self {
3302        Self(id.0, id.1)
3303    }
3304}
3305
3306pub struct ElementStateHandle<T> {
3307    value_type: PhantomData<T>,
3308    tag_type_id: TypeId,
3309    id: ElementStateId,
3310    ref_counts: Weak<Mutex<RefCounts>>,
3311}
3312
3313impl<T: 'static> ElementStateHandle<T> {
3314    fn new(tag_type_id: TypeId, id: ElementStateId, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3315        ref_counts.lock().inc_element_state(tag_type_id, id);
3316        Self {
3317            value_type: PhantomData,
3318            tag_type_id,
3319            id,
3320            ref_counts: Arc::downgrade(ref_counts),
3321        }
3322    }
3323
3324    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3325        cx.element_states
3326            .get(&(self.tag_type_id, self.id))
3327            .unwrap()
3328            .downcast_ref()
3329            .unwrap()
3330    }
3331
3332    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3333    where
3334        C: DerefMut<Target = MutableAppContext>,
3335    {
3336        let mut element_state = cx
3337            .deref_mut()
3338            .cx
3339            .element_states
3340            .remove(&(self.tag_type_id, self.id))
3341            .unwrap();
3342        let result = f(element_state.downcast_mut().unwrap(), cx);
3343        cx.deref_mut()
3344            .cx
3345            .element_states
3346            .insert((self.tag_type_id, self.id), element_state);
3347        result
3348    }
3349}
3350
3351impl<T> Drop for ElementStateHandle<T> {
3352    fn drop(&mut self) {
3353        if let Some(ref_counts) = self.ref_counts.upgrade() {
3354            ref_counts
3355                .lock()
3356                .dec_element_state(self.tag_type_id, self.id);
3357        }
3358    }
3359}
3360
3361pub struct CursorStyleHandle {
3362    id: usize,
3363    next_cursor_style_handle_id: Arc<AtomicUsize>,
3364    platform: Arc<dyn Platform>,
3365}
3366
3367impl Drop for CursorStyleHandle {
3368    fn drop(&mut self) {
3369        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3370            self.platform.set_cursor_style(CursorStyle::Arrow);
3371        }
3372    }
3373}
3374
3375#[must_use]
3376pub enum Subscription {
3377    Subscription {
3378        id: usize,
3379        entity_id: usize,
3380        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3381    },
3382    Observation {
3383        id: usize,
3384        entity_id: usize,
3385        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3386    },
3387    ReleaseObservation {
3388        id: usize,
3389        entity_id: usize,
3390        observations:
3391            Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ReleaseObservationCallback>>>>>,
3392    },
3393}
3394
3395impl Subscription {
3396    pub fn detach(&mut self) {
3397        match self {
3398            Subscription::Subscription { subscriptions, .. } => {
3399                subscriptions.take();
3400            }
3401            Subscription::Observation { observations, .. } => {
3402                observations.take();
3403            }
3404            Subscription::ReleaseObservation { observations, .. } => {
3405                observations.take();
3406            }
3407        }
3408    }
3409}
3410
3411impl Drop for Subscription {
3412    fn drop(&mut self) {
3413        match self {
3414            Subscription::Observation {
3415                id,
3416                entity_id,
3417                observations,
3418            } => {
3419                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3420                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3421                        observations.remove(id);
3422                    }
3423                }
3424            }
3425            Subscription::ReleaseObservation {
3426                id,
3427                entity_id,
3428                observations,
3429            } => {
3430                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3431                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3432                        observations.remove(id);
3433                    }
3434                }
3435            }
3436            Subscription::Subscription {
3437                id,
3438                entity_id,
3439                subscriptions,
3440            } => {
3441                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3442                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3443                        subscriptions.remove(id);
3444                    }
3445                }
3446            }
3447        }
3448    }
3449}
3450
3451#[derive(Default)]
3452struct RefCounts {
3453    entity_counts: HashMap<usize, usize>,
3454    element_state_counts: HashMap<(TypeId, ElementStateId), usize>,
3455    dropped_models: HashSet<usize>,
3456    dropped_views: HashSet<(usize, usize)>,
3457    dropped_element_states: HashSet<(TypeId, ElementStateId)>,
3458}
3459
3460impl RefCounts {
3461    fn inc_model(&mut self, model_id: usize) {
3462        match self.entity_counts.entry(model_id) {
3463            Entry::Occupied(mut entry) => {
3464                *entry.get_mut() += 1;
3465            }
3466            Entry::Vacant(entry) => {
3467                entry.insert(1);
3468                self.dropped_models.remove(&model_id);
3469            }
3470        }
3471    }
3472
3473    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3474        match self.entity_counts.entry(view_id) {
3475            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3476            Entry::Vacant(entry) => {
3477                entry.insert(1);
3478                self.dropped_views.remove(&(window_id, view_id));
3479            }
3480        }
3481    }
3482
3483    fn inc_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3484        match self.element_state_counts.entry((tag_type_id, id)) {
3485            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3486            Entry::Vacant(entry) => {
3487                entry.insert(1);
3488                self.dropped_element_states.remove(&(tag_type_id, id));
3489            }
3490        }
3491    }
3492
3493    fn dec_model(&mut self, model_id: usize) {
3494        let count = self.entity_counts.get_mut(&model_id).unwrap();
3495        *count -= 1;
3496        if *count == 0 {
3497            self.entity_counts.remove(&model_id);
3498            self.dropped_models.insert(model_id);
3499        }
3500    }
3501
3502    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3503        let count = self.entity_counts.get_mut(&view_id).unwrap();
3504        *count -= 1;
3505        if *count == 0 {
3506            self.entity_counts.remove(&view_id);
3507            self.dropped_views.insert((window_id, view_id));
3508        }
3509    }
3510
3511    fn dec_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3512        let key = (tag_type_id, id);
3513        let count = self.element_state_counts.get_mut(&key).unwrap();
3514        *count -= 1;
3515        if *count == 0 {
3516            self.element_state_counts.remove(&key);
3517            self.dropped_element_states.insert(key);
3518        }
3519    }
3520
3521    fn is_entity_alive(&self, entity_id: usize) -> bool {
3522        self.entity_counts.contains_key(&entity_id)
3523    }
3524
3525    fn take_dropped(
3526        &mut self,
3527    ) -> (
3528        HashSet<usize>,
3529        HashSet<(usize, usize)>,
3530        HashSet<(TypeId, ElementStateId)>,
3531    ) {
3532        (
3533            std::mem::take(&mut self.dropped_models),
3534            std::mem::take(&mut self.dropped_views),
3535            std::mem::take(&mut self.dropped_element_states),
3536        )
3537    }
3538}
3539
3540#[cfg(test)]
3541mod tests {
3542    use super::*;
3543    use crate::elements::*;
3544    use smol::future::poll_once;
3545    use std::{
3546        cell::Cell,
3547        sync::atomic::{AtomicUsize, Ordering::SeqCst},
3548    };
3549
3550    #[crate::test(self)]
3551    fn test_model_handles(cx: &mut MutableAppContext) {
3552        struct Model {
3553            other: Option<ModelHandle<Model>>,
3554            events: Vec<String>,
3555        }
3556
3557        impl Entity for Model {
3558            type Event = usize;
3559        }
3560
3561        impl Model {
3562            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3563                if let Some(other) = other.as_ref() {
3564                    cx.observe(other, |me, _, _| {
3565                        me.events.push("notified".into());
3566                    })
3567                    .detach();
3568                    cx.subscribe(other, |me, _, event, _| {
3569                        me.events.push(format!("observed event {}", event));
3570                    })
3571                    .detach();
3572                }
3573
3574                Self {
3575                    other,
3576                    events: Vec::new(),
3577                }
3578            }
3579        }
3580
3581        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3582        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3583        assert_eq!(cx.cx.models.len(), 2);
3584
3585        handle_1.update(cx, |model, cx| {
3586            model.events.push("updated".into());
3587            cx.emit(1);
3588            cx.notify();
3589            cx.emit(2);
3590        });
3591        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3592        assert_eq!(
3593            handle_2.read(cx).events,
3594            vec![
3595                "observed event 1".to_string(),
3596                "notified".to_string(),
3597                "observed event 2".to_string(),
3598            ]
3599        );
3600
3601        handle_2.update(cx, |model, _| {
3602            drop(handle_1);
3603            model.other.take();
3604        });
3605
3606        assert_eq!(cx.cx.models.len(), 1);
3607        assert!(cx.subscriptions.lock().is_empty());
3608        assert!(cx.observations.lock().is_empty());
3609    }
3610
3611    #[crate::test(self)]
3612    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3613        #[derive(Default)]
3614        struct Model {
3615            events: Vec<usize>,
3616        }
3617
3618        impl Entity for Model {
3619            type Event = usize;
3620        }
3621
3622        let handle_1 = cx.add_model(|_| Model::default());
3623        let handle_2 = cx.add_model(|_| Model::default());
3624        let handle_2b = handle_2.clone();
3625
3626        handle_1.update(cx, |_, c| {
3627            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3628                model.events.push(*event);
3629
3630                c.subscribe(&handle_2b, |model, _, event, _| {
3631                    model.events.push(*event * 2);
3632                })
3633                .detach();
3634            })
3635            .detach();
3636        });
3637
3638        handle_2.update(cx, |_, c| c.emit(7));
3639        assert_eq!(handle_1.read(cx).events, vec![7]);
3640
3641        handle_2.update(cx, |_, c| c.emit(5));
3642        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3643    }
3644
3645    #[crate::test(self)]
3646    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3647        #[derive(Default)]
3648        struct Model {
3649            count: usize,
3650            events: Vec<usize>,
3651        }
3652
3653        impl Entity for Model {
3654            type Event = ();
3655        }
3656
3657        let handle_1 = cx.add_model(|_| Model::default());
3658        let handle_2 = cx.add_model(|_| Model::default());
3659        let handle_2b = handle_2.clone();
3660
3661        handle_1.update(cx, |_, c| {
3662            c.observe(&handle_2, move |model, observed, c| {
3663                model.events.push(observed.read(c).count);
3664                c.observe(&handle_2b, |model, observed, c| {
3665                    model.events.push(observed.read(c).count * 2);
3666                })
3667                .detach();
3668            })
3669            .detach();
3670        });
3671
3672        handle_2.update(cx, |model, c| {
3673            model.count = 7;
3674            c.notify()
3675        });
3676        assert_eq!(handle_1.read(cx).events, vec![7]);
3677
3678        handle_2.update(cx, |model, c| {
3679            model.count = 5;
3680            c.notify()
3681        });
3682        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3683    }
3684
3685    #[crate::test(self)]
3686    fn test_view_handles(cx: &mut MutableAppContext) {
3687        struct View {
3688            other: Option<ViewHandle<View>>,
3689            events: Vec<String>,
3690        }
3691
3692        impl Entity for View {
3693            type Event = usize;
3694        }
3695
3696        impl super::View for View {
3697            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3698                Empty::new().boxed()
3699            }
3700
3701            fn ui_name() -> &'static str {
3702                "View"
3703            }
3704        }
3705
3706        impl View {
3707            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3708                if let Some(other) = other.as_ref() {
3709                    cx.subscribe(other, |me, _, event, _| {
3710                        me.events.push(format!("observed event {}", event));
3711                    })
3712                    .detach();
3713                }
3714                Self {
3715                    other,
3716                    events: Vec::new(),
3717                }
3718            }
3719        }
3720
3721        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3722        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3723        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3724        assert_eq!(cx.cx.views.len(), 3);
3725
3726        handle_1.update(cx, |view, cx| {
3727            view.events.push("updated".into());
3728            cx.emit(1);
3729            cx.emit(2);
3730        });
3731        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3732        assert_eq!(
3733            handle_2.read(cx).events,
3734            vec![
3735                "observed event 1".to_string(),
3736                "observed event 2".to_string(),
3737            ]
3738        );
3739
3740        handle_2.update(cx, |view, _| {
3741            drop(handle_1);
3742            view.other.take();
3743        });
3744
3745        assert_eq!(cx.cx.views.len(), 2);
3746        assert!(cx.subscriptions.lock().is_empty());
3747        assert!(cx.observations.lock().is_empty());
3748    }
3749
3750    #[crate::test(self)]
3751    fn test_add_window(cx: &mut MutableAppContext) {
3752        struct View {
3753            mouse_down_count: Arc<AtomicUsize>,
3754        }
3755
3756        impl Entity for View {
3757            type Event = ();
3758        }
3759
3760        impl super::View for View {
3761            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3762                let mouse_down_count = self.mouse_down_count.clone();
3763                EventHandler::new(Empty::new().boxed())
3764                    .on_mouse_down(move |_| {
3765                        mouse_down_count.fetch_add(1, SeqCst);
3766                        true
3767                    })
3768                    .boxed()
3769            }
3770
3771            fn ui_name() -> &'static str {
3772                "View"
3773            }
3774        }
3775
3776        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3777        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3778            mouse_down_count: mouse_down_count.clone(),
3779        });
3780        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3781        // Ensure window's root element is in a valid lifecycle state.
3782        presenter.borrow_mut().dispatch_event(
3783            Event::LeftMouseDown {
3784                position: Default::default(),
3785                ctrl: false,
3786                alt: false,
3787                shift: false,
3788                cmd: false,
3789                click_count: 1,
3790            },
3791            cx,
3792        );
3793        assert_eq!(mouse_down_count.load(SeqCst), 1);
3794    }
3795
3796    #[crate::test(self)]
3797    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3798        struct Model {
3799            released: Rc<Cell<bool>>,
3800        }
3801
3802        struct View {
3803            released: Rc<Cell<bool>>,
3804        }
3805
3806        impl Entity for Model {
3807            type Event = ();
3808
3809            fn release(&mut self, _: &mut MutableAppContext) {
3810                self.released.set(true);
3811            }
3812        }
3813
3814        impl Entity for View {
3815            type Event = ();
3816
3817            fn release(&mut self, _: &mut MutableAppContext) {
3818                self.released.set(true);
3819            }
3820        }
3821
3822        impl super::View for View {
3823            fn ui_name() -> &'static str {
3824                "View"
3825            }
3826
3827            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3828                Empty::new().boxed()
3829            }
3830        }
3831
3832        let model_released = Rc::new(Cell::new(false));
3833        let model_release_observed = Rc::new(Cell::new(false));
3834        let view_released = Rc::new(Cell::new(false));
3835        let view_release_observed = Rc::new(Cell::new(false));
3836
3837        let model = cx.add_model(|_| Model {
3838            released: model_released.clone(),
3839        });
3840        let (window_id, view) = cx.add_window(Default::default(), |_| View {
3841            released: view_released.clone(),
3842        });
3843        assert!(!model_released.get());
3844        assert!(!view_released.get());
3845
3846        cx.observe_release(&model, {
3847            let model_release_observed = model_release_observed.clone();
3848            move |_| model_release_observed.set(true)
3849        })
3850        .detach();
3851        cx.observe_release(&view, {
3852            let view_release_observed = view_release_observed.clone();
3853            move |_| view_release_observed.set(true)
3854        })
3855        .detach();
3856
3857        cx.update(move |_| {
3858            drop(model);
3859        });
3860        assert!(model_released.get());
3861        assert!(model_release_observed.get());
3862
3863        drop(view);
3864        cx.remove_window(window_id);
3865        assert!(view_released.get());
3866        assert!(view_release_observed.get());
3867    }
3868
3869    #[crate::test(self)]
3870    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3871        #[derive(Default)]
3872        struct View {
3873            events: Vec<usize>,
3874        }
3875
3876        impl Entity for View {
3877            type Event = usize;
3878        }
3879
3880        impl super::View for View {
3881            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3882                Empty::new().boxed()
3883            }
3884
3885            fn ui_name() -> &'static str {
3886                "View"
3887            }
3888        }
3889
3890        struct Model;
3891
3892        impl Entity for Model {
3893            type Event = usize;
3894        }
3895
3896        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3897        let handle_2 = cx.add_view(window_id, |_| View::default());
3898        let handle_2b = handle_2.clone();
3899        let handle_3 = cx.add_model(|_| Model);
3900
3901        handle_1.update(cx, |_, c| {
3902            c.subscribe(&handle_2, move |me, _, event, c| {
3903                me.events.push(*event);
3904
3905                c.subscribe(&handle_2b, |me, _, event, _| {
3906                    me.events.push(*event * 2);
3907                })
3908                .detach();
3909            })
3910            .detach();
3911
3912            c.subscribe(&handle_3, |me, _, event, _| {
3913                me.events.push(*event);
3914            })
3915            .detach();
3916        });
3917
3918        handle_2.update(cx, |_, c| c.emit(7));
3919        assert_eq!(handle_1.read(cx).events, vec![7]);
3920
3921        handle_2.update(cx, |_, c| c.emit(5));
3922        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3923
3924        handle_3.update(cx, |_, c| c.emit(9));
3925        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
3926    }
3927
3928    #[crate::test(self)]
3929    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3930        struct View;
3931
3932        impl Entity for View {
3933            type Event = ();
3934        }
3935
3936        impl super::View for View {
3937            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3938                Empty::new().boxed()
3939            }
3940
3941            fn ui_name() -> &'static str {
3942                "View"
3943            }
3944        }
3945
3946        struct Model;
3947
3948        impl Entity for Model {
3949            type Event = ();
3950        }
3951
3952        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3953        let observing_view = cx.add_view(window_id, |_| View);
3954        let emitting_view = cx.add_view(window_id, |_| View);
3955        let observing_model = cx.add_model(|_| Model);
3956        let observed_model = cx.add_model(|_| Model);
3957
3958        observing_view.update(cx, |_, cx| {
3959            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
3960            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3961        });
3962        observing_model.update(cx, |_, cx| {
3963            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3964        });
3965
3966        cx.update(|_| {
3967            drop(observing_view);
3968            drop(observing_model);
3969        });
3970
3971        emitting_view.update(cx, |_, cx| cx.emit(()));
3972        observed_model.update(cx, |_, cx| cx.emit(()));
3973    }
3974
3975    #[crate::test(self)]
3976    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3977        #[derive(Default)]
3978        struct View {
3979            events: Vec<usize>,
3980        }
3981
3982        impl Entity for View {
3983            type Event = usize;
3984        }
3985
3986        impl super::View for View {
3987            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3988                Empty::new().boxed()
3989            }
3990
3991            fn ui_name() -> &'static str {
3992                "View"
3993            }
3994        }
3995
3996        #[derive(Default)]
3997        struct Model {
3998            count: usize,
3999        }
4000
4001        impl Entity for Model {
4002            type Event = ();
4003        }
4004
4005        let (_, view) = cx.add_window(Default::default(), |_| View::default());
4006        let model = cx.add_model(|_| Model::default());
4007
4008        view.update(cx, |_, c| {
4009            c.observe(&model, |me, observed, c| {
4010                me.events.push(observed.read(c).count)
4011            })
4012            .detach();
4013        });
4014
4015        model.update(cx, |model, c| {
4016            model.count = 11;
4017            c.notify();
4018        });
4019        assert_eq!(view.read(cx).events, vec![11]);
4020    }
4021
4022    #[crate::test(self)]
4023    fn test_dropping_observers(cx: &mut MutableAppContext) {
4024        struct View;
4025
4026        impl Entity for View {
4027            type Event = ();
4028        }
4029
4030        impl super::View for View {
4031            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4032                Empty::new().boxed()
4033            }
4034
4035            fn ui_name() -> &'static str {
4036                "View"
4037            }
4038        }
4039
4040        struct Model;
4041
4042        impl Entity for Model {
4043            type Event = ();
4044        }
4045
4046        let (window_id, _) = cx.add_window(Default::default(), |_| View);
4047        let observing_view = cx.add_view(window_id, |_| View);
4048        let observing_model = cx.add_model(|_| Model);
4049        let observed_model = cx.add_model(|_| Model);
4050
4051        observing_view.update(cx, |_, cx| {
4052            cx.observe(&observed_model, |_, _, _| {}).detach();
4053        });
4054        observing_model.update(cx, |_, cx| {
4055            cx.observe(&observed_model, |_, _, _| {}).detach();
4056        });
4057
4058        cx.update(|_| {
4059            drop(observing_view);
4060            drop(observing_model);
4061        });
4062
4063        observed_model.update(cx, |_, cx| cx.notify());
4064    }
4065
4066    #[crate::test(self)]
4067    fn test_focus(cx: &mut MutableAppContext) {
4068        struct View {
4069            name: String,
4070            events: Arc<Mutex<Vec<String>>>,
4071        }
4072
4073        impl Entity for View {
4074            type Event = ();
4075        }
4076
4077        impl super::View for View {
4078            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4079                Empty::new().boxed()
4080            }
4081
4082            fn ui_name() -> &'static str {
4083                "View"
4084            }
4085
4086            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
4087                self.events.lock().push(format!("{} focused", &self.name));
4088            }
4089
4090            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
4091                self.events.lock().push(format!("{} blurred", &self.name));
4092            }
4093        }
4094
4095        let events: Arc<Mutex<Vec<String>>> = Default::default();
4096        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
4097            events: events.clone(),
4098            name: "view 1".to_string(),
4099        });
4100        let view_2 = cx.add_view(window_id, |_| View {
4101            events: events.clone(),
4102            name: "view 2".to_string(),
4103        });
4104
4105        view_1.update(cx, |_, cx| cx.focus(&view_2));
4106        view_1.update(cx, |_, cx| cx.focus(&view_1));
4107        view_1.update(cx, |_, cx| cx.focus(&view_2));
4108        view_1.update(cx, |_, _| drop(view_2));
4109
4110        assert_eq!(
4111            *events.lock(),
4112            [
4113                "view 1 focused".to_string(),
4114                "view 1 blurred".to_string(),
4115                "view 2 focused".to_string(),
4116                "view 2 blurred".to_string(),
4117                "view 1 focused".to_string(),
4118                "view 1 blurred".to_string(),
4119                "view 2 focused".to_string(),
4120                "view 1 focused".to_string(),
4121            ],
4122        );
4123    }
4124
4125    #[crate::test(self)]
4126    fn test_dispatch_action(cx: &mut MutableAppContext) {
4127        struct ViewA {
4128            id: usize,
4129        }
4130
4131        impl Entity for ViewA {
4132            type Event = ();
4133        }
4134
4135        impl View for ViewA {
4136            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4137                Empty::new().boxed()
4138            }
4139
4140            fn ui_name() -> &'static str {
4141                "View"
4142            }
4143        }
4144
4145        struct ViewB {
4146            id: usize,
4147        }
4148
4149        impl Entity for ViewB {
4150            type Event = ();
4151        }
4152
4153        impl View for ViewB {
4154            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4155                Empty::new().boxed()
4156            }
4157
4158            fn ui_name() -> &'static str {
4159                "View"
4160            }
4161        }
4162
4163        action!(Action, &'static str);
4164
4165        let actions = Rc::new(RefCell::new(Vec::new()));
4166
4167        let actions_clone = actions.clone();
4168        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4169            actions_clone.borrow_mut().push("global".to_string());
4170        });
4171
4172        let actions_clone = actions.clone();
4173        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4174            assert_eq!(action.0, "bar");
4175            cx.propagate_action();
4176            actions_clone.borrow_mut().push(format!("{} a", view.id));
4177        });
4178
4179        let actions_clone = actions.clone();
4180        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4181            if view.id != 1 {
4182                cx.propagate_action();
4183            }
4184            actions_clone.borrow_mut().push(format!("{} b", view.id));
4185        });
4186
4187        let actions_clone = actions.clone();
4188        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4189            cx.propagate_action();
4190            actions_clone.borrow_mut().push(format!("{} c", view.id));
4191        });
4192
4193        let actions_clone = actions.clone();
4194        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4195            cx.propagate_action();
4196            actions_clone.borrow_mut().push(format!("{} d", view.id));
4197        });
4198
4199        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4200        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4201        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4202        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4203
4204        cx.dispatch_action(
4205            window_id,
4206            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4207            &Action("bar"),
4208        );
4209
4210        assert_eq!(
4211            *actions.borrow(),
4212            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
4213        );
4214
4215        // Remove view_1, which doesn't propagate the action
4216        actions.borrow_mut().clear();
4217        cx.dispatch_action(
4218            window_id,
4219            vec![view_2.id(), view_3.id(), view_4.id()],
4220            &Action("bar"),
4221        );
4222
4223        assert_eq!(
4224            *actions.borrow(),
4225            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global"]
4226        );
4227    }
4228
4229    #[crate::test(self)]
4230    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4231        use std::cell::Cell;
4232
4233        action!(Action, &'static str);
4234
4235        struct View {
4236            id: usize,
4237            keymap_context: keymap::Context,
4238        }
4239
4240        impl Entity for View {
4241            type Event = ();
4242        }
4243
4244        impl super::View for View {
4245            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4246                Empty::new().boxed()
4247            }
4248
4249            fn ui_name() -> &'static str {
4250                "View"
4251            }
4252
4253            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4254                self.keymap_context.clone()
4255            }
4256        }
4257
4258        impl View {
4259            fn new(id: usize) -> Self {
4260                View {
4261                    id,
4262                    keymap_context: keymap::Context::default(),
4263                }
4264            }
4265        }
4266
4267        let mut view_1 = View::new(1);
4268        let mut view_2 = View::new(2);
4269        let mut view_3 = View::new(3);
4270        view_1.keymap_context.set.insert("a".into());
4271        view_2.keymap_context.set.insert("a".into());
4272        view_2.keymap_context.set.insert("b".into());
4273        view_3.keymap_context.set.insert("a".into());
4274        view_3.keymap_context.set.insert("b".into());
4275        view_3.keymap_context.set.insert("c".into());
4276
4277        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4278        let view_2 = cx.add_view(window_id, |_| view_2);
4279        let view_3 = cx.add_view(window_id, |_| view_3);
4280
4281        // This keymap's only binding dispatches an action on view 2 because that view will have
4282        // "a" and "b" in its context, but not "c".
4283        cx.add_bindings(vec![keymap::Binding::new(
4284            "a",
4285            Action("a"),
4286            Some("a && b && !c"),
4287        )]);
4288
4289        let handled_action = Rc::new(Cell::new(false));
4290        let handled_action_clone = handled_action.clone();
4291        cx.add_action(move |view: &mut View, action: &Action, _| {
4292            handled_action_clone.set(true);
4293            assert_eq!(view.id, 2);
4294            assert_eq!(action.0, "a");
4295        });
4296
4297        cx.dispatch_keystroke(
4298            window_id,
4299            vec![view_1.id(), view_2.id(), view_3.id()],
4300            &Keystroke::parse("a").unwrap(),
4301        )
4302        .unwrap();
4303
4304        assert!(handled_action.get());
4305    }
4306
4307    #[crate::test(self)]
4308    async fn test_model_condition(mut cx: TestAppContext) {
4309        struct Counter(usize);
4310
4311        impl super::Entity for Counter {
4312            type Event = ();
4313        }
4314
4315        impl Counter {
4316            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4317                self.0 += 1;
4318                cx.notify();
4319            }
4320        }
4321
4322        let model = cx.add_model(|_| Counter(0));
4323
4324        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4325        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4326        smol::pin!(condition1, condition2);
4327
4328        model.update(&mut cx, |model, cx| model.inc(cx));
4329        assert_eq!(poll_once(&mut condition1).await, None);
4330        assert_eq!(poll_once(&mut condition2).await, None);
4331
4332        model.update(&mut cx, |model, cx| model.inc(cx));
4333        assert_eq!(poll_once(&mut condition1).await, Some(()));
4334        assert_eq!(poll_once(&mut condition2).await, None);
4335
4336        model.update(&mut cx, |model, cx| model.inc(cx));
4337        assert_eq!(poll_once(&mut condition2).await, Some(()));
4338
4339        model.update(&mut cx, |_, cx| cx.notify());
4340    }
4341
4342    #[crate::test(self)]
4343    #[should_panic]
4344    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4345        struct Model;
4346
4347        impl super::Entity for Model {
4348            type Event = ();
4349        }
4350
4351        let model = cx.add_model(|_| Model);
4352        model.condition(&cx, |_, _| false).await;
4353    }
4354
4355    #[crate::test(self)]
4356    #[should_panic(expected = "model dropped with pending condition")]
4357    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4358        struct Model;
4359
4360        impl super::Entity for Model {
4361            type Event = ();
4362        }
4363
4364        let model = cx.add_model(|_| Model);
4365        let condition = model.condition(&cx, |_, _| false);
4366        cx.update(|_| drop(model));
4367        condition.await;
4368    }
4369
4370    #[crate::test(self)]
4371    async fn test_view_condition(mut cx: TestAppContext) {
4372        struct Counter(usize);
4373
4374        impl super::Entity for Counter {
4375            type Event = ();
4376        }
4377
4378        impl super::View for Counter {
4379            fn ui_name() -> &'static str {
4380                "test view"
4381            }
4382
4383            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4384                Empty::new().boxed()
4385            }
4386        }
4387
4388        impl Counter {
4389            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4390                self.0 += 1;
4391                cx.notify();
4392            }
4393        }
4394
4395        let (_, view) = cx.add_window(|_| Counter(0));
4396
4397        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4398        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4399        smol::pin!(condition1, condition2);
4400
4401        view.update(&mut cx, |view, cx| view.inc(cx));
4402        assert_eq!(poll_once(&mut condition1).await, None);
4403        assert_eq!(poll_once(&mut condition2).await, None);
4404
4405        view.update(&mut cx, |view, cx| view.inc(cx));
4406        assert_eq!(poll_once(&mut condition1).await, Some(()));
4407        assert_eq!(poll_once(&mut condition2).await, None);
4408
4409        view.update(&mut cx, |view, cx| view.inc(cx));
4410        assert_eq!(poll_once(&mut condition2).await, Some(()));
4411        view.update(&mut cx, |_, cx| cx.notify());
4412    }
4413
4414    #[crate::test(self)]
4415    #[should_panic]
4416    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4417        struct View;
4418
4419        impl super::Entity for View {
4420            type Event = ();
4421        }
4422
4423        impl super::View for View {
4424            fn ui_name() -> &'static str {
4425                "test view"
4426            }
4427
4428            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4429                Empty::new().boxed()
4430            }
4431        }
4432
4433        let (_, view) = cx.add_window(|_| View);
4434        view.condition(&cx, |_, _| false).await;
4435    }
4436
4437    #[crate::test(self)]
4438    #[should_panic(expected = "view dropped with pending condition")]
4439    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4440        struct View;
4441
4442        impl super::Entity for View {
4443            type Event = ();
4444        }
4445
4446        impl super::View for View {
4447            fn ui_name() -> &'static str {
4448                "test view"
4449            }
4450
4451            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4452                Empty::new().boxed()
4453            }
4454        }
4455
4456        let window_id = cx.add_window(|_| View).0;
4457        let view = cx.add_view(window_id, |_| View);
4458
4459        let condition = view.condition(&cx, |_, _| false);
4460        cx.update(|_| drop(view));
4461        condition.await;
4462    }
4463}