app.rs

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