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