app.rs

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