app.rs

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