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