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