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    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
2287    where
2288        F: FnOnce(WeakViewHandle<T>, AsyncAppContext) -> Fut,
2289        Fut: 'static + Future<Output = S>,
2290        S: 'static,
2291    {
2292        let handle = self.handle().downgrade();
2293        self.app.spawn(|cx| f(handle, cx))
2294    }
2295}
2296
2297pub struct RenderContext<'a, T: View> {
2298    pub app: &'a mut MutableAppContext,
2299    pub titlebar_height: f32,
2300    pub refreshing: bool,
2301    window_id: usize,
2302    view_id: usize,
2303    view_type: PhantomData<T>,
2304}
2305
2306impl<'a, T: View> RenderContext<'a, T> {
2307    pub fn handle(&self) -> WeakViewHandle<T> {
2308        WeakViewHandle::new(self.window_id, self.view_id)
2309    }
2310}
2311
2312impl AsRef<AppContext> for &AppContext {
2313    fn as_ref(&self) -> &AppContext {
2314        self
2315    }
2316}
2317
2318impl<V: View> Deref for RenderContext<'_, V> {
2319    type Target = MutableAppContext;
2320
2321    fn deref(&self) -> &Self::Target {
2322        self.app
2323    }
2324}
2325
2326impl<V: View> DerefMut for RenderContext<'_, V> {
2327    fn deref_mut(&mut self) -> &mut Self::Target {
2328        self.app
2329    }
2330}
2331
2332impl<V: View> ReadModel for RenderContext<'_, V> {
2333    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2334        self.app.read_model(handle)
2335    }
2336}
2337
2338impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2339    fn as_ref(&self) -> &AppContext {
2340        &self.app.cx
2341    }
2342}
2343
2344impl<M> Deref for ViewContext<'_, M> {
2345    type Target = MutableAppContext;
2346
2347    fn deref(&self) -> &Self::Target {
2348        &self.app
2349    }
2350}
2351
2352impl<M> DerefMut for ViewContext<'_, M> {
2353    fn deref_mut(&mut self) -> &mut Self::Target {
2354        &mut self.app
2355    }
2356}
2357
2358impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2359    fn as_mut(&mut self) -> &mut MutableAppContext {
2360        self.app
2361    }
2362}
2363
2364impl<V> ReadModel for ViewContext<'_, V> {
2365    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2366        self.app.read_model(handle)
2367    }
2368}
2369
2370impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2371    fn upgrade_model_handle<T: Entity>(
2372        &self,
2373        handle: WeakModelHandle<T>,
2374    ) -> Option<ModelHandle<T>> {
2375        self.cx.upgrade_model_handle(handle)
2376    }
2377}
2378
2379impl<V: View> UpdateModel for ViewContext<'_, V> {
2380    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2381    where
2382        T: Entity,
2383        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2384    {
2385        self.app.update_model(handle, update)
2386    }
2387}
2388
2389impl<V: View> ReadView for ViewContext<'_, V> {
2390    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2391        self.app.read_view(handle)
2392    }
2393}
2394
2395impl<V: View> UpdateView for ViewContext<'_, V> {
2396    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2397    where
2398        T: View,
2399        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2400    {
2401        self.app.update_view(handle, update)
2402    }
2403}
2404
2405pub trait Handle<T> {
2406    type Weak: 'static;
2407    fn id(&self) -> usize;
2408    fn location(&self) -> EntityLocation;
2409    fn downgrade(&self) -> Self::Weak;
2410    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2411    where
2412        Self: Sized;
2413}
2414
2415#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2416pub enum EntityLocation {
2417    Model(usize),
2418    View(usize, usize),
2419}
2420
2421pub struct ModelHandle<T> {
2422    model_id: usize,
2423    model_type: PhantomData<T>,
2424    ref_counts: Arc<Mutex<RefCounts>>,
2425}
2426
2427impl<T: Entity> ModelHandle<T> {
2428    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2429        ref_counts.lock().inc_model(model_id);
2430        Self {
2431            model_id,
2432            model_type: PhantomData,
2433            ref_counts: ref_counts.clone(),
2434        }
2435    }
2436
2437    pub fn downgrade(&self) -> WeakModelHandle<T> {
2438        WeakModelHandle::new(self.model_id)
2439    }
2440
2441    pub fn id(&self) -> usize {
2442        self.model_id
2443    }
2444
2445    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2446        cx.read_model(self)
2447    }
2448
2449    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2450    where
2451        C: ReadModelWith,
2452        F: FnOnce(&T, &AppContext) -> S,
2453    {
2454        cx.read_model_with(self, read)
2455    }
2456
2457    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2458    where
2459        C: UpdateModel,
2460        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2461    {
2462        cx.update_model(self, update)
2463    }
2464
2465    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2466        let (mut tx, mut rx) = mpsc::channel(1);
2467        let mut cx = cx.cx.borrow_mut();
2468        let subscription = cx.observe(self, move |_, _| {
2469            tx.blocking_send(()).ok();
2470        });
2471
2472        let duration = if std::env::var("CI").is_ok() {
2473            Duration::from_secs(5)
2474        } else {
2475            Duration::from_secs(1)
2476        };
2477
2478        async move {
2479            let notification = timeout(duration, rx.recv())
2480                .await
2481                .expect("next notification timed out");
2482            drop(subscription);
2483            notification.expect("model dropped while test was waiting for its next notification")
2484        }
2485    }
2486
2487    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2488    where
2489        T::Event: Clone,
2490    {
2491        let (mut tx, mut rx) = mpsc::channel(1);
2492        let mut cx = cx.cx.borrow_mut();
2493        let subscription = cx.subscribe(self, move |_, event, _| {
2494            tx.blocking_send(event.clone()).ok();
2495        });
2496
2497        let duration = if std::env::var("CI").is_ok() {
2498            Duration::from_secs(5)
2499        } else {
2500            Duration::from_secs(1)
2501        };
2502
2503        async move {
2504            let event = timeout(duration, rx.recv())
2505                .await
2506                .expect("next event timed out");
2507            drop(subscription);
2508            event.expect("model dropped while test was waiting for its next event")
2509        }
2510    }
2511
2512    pub fn condition(
2513        &self,
2514        cx: &TestAppContext,
2515        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2516    ) -> impl Future<Output = ()> {
2517        let (tx, mut rx) = mpsc::channel(1024);
2518
2519        let mut cx = cx.cx.borrow_mut();
2520        let subscriptions = (
2521            cx.observe(self, {
2522                let mut tx = tx.clone();
2523                move |_, _| {
2524                    tx.blocking_send(()).ok();
2525                }
2526            }),
2527            cx.subscribe(self, {
2528                let mut tx = tx.clone();
2529                move |_, _, _| {
2530                    tx.blocking_send(()).ok();
2531                }
2532            }),
2533        );
2534
2535        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2536        let handle = self.downgrade();
2537        let duration = if std::env::var("CI").is_ok() {
2538            Duration::from_secs(5)
2539        } else {
2540            Duration::from_secs(1)
2541        };
2542
2543        async move {
2544            timeout(duration, async move {
2545                loop {
2546                    {
2547                        let cx = cx.borrow();
2548                        let cx = cx.as_ref();
2549                        if predicate(
2550                            handle
2551                                .upgrade(cx)
2552                                .expect("model dropped with pending condition")
2553                                .read(cx),
2554                            cx,
2555                        ) {
2556                            break;
2557                        }
2558                    }
2559
2560                    rx.recv()
2561                        .await
2562                        .expect("model dropped with pending condition");
2563                }
2564            })
2565            .await
2566            .expect("condition timed out");
2567            drop(subscriptions);
2568        }
2569    }
2570}
2571
2572impl<T> Clone for ModelHandle<T> {
2573    fn clone(&self) -> Self {
2574        self.ref_counts.lock().inc_model(self.model_id);
2575        Self {
2576            model_id: self.model_id,
2577            model_type: PhantomData,
2578            ref_counts: self.ref_counts.clone(),
2579        }
2580    }
2581}
2582
2583impl<T> PartialEq for ModelHandle<T> {
2584    fn eq(&self, other: &Self) -> bool {
2585        self.model_id == other.model_id
2586    }
2587}
2588
2589impl<T> Eq for ModelHandle<T> {}
2590
2591impl<T> Hash for ModelHandle<T> {
2592    fn hash<H: Hasher>(&self, state: &mut H) {
2593        self.model_id.hash(state);
2594    }
2595}
2596
2597impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2598    fn borrow(&self) -> &usize {
2599        &self.model_id
2600    }
2601}
2602
2603impl<T> Debug for ModelHandle<T> {
2604    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2605        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2606            .field(&self.model_id)
2607            .finish()
2608    }
2609}
2610
2611unsafe impl<T> Send for ModelHandle<T> {}
2612unsafe impl<T> Sync for ModelHandle<T> {}
2613
2614impl<T> Drop for ModelHandle<T> {
2615    fn drop(&mut self) {
2616        self.ref_counts.lock().dec_model(self.model_id);
2617    }
2618}
2619
2620impl<T: Entity> Handle<T> for ModelHandle<T> {
2621    type Weak = WeakModelHandle<T>;
2622
2623    fn id(&self) -> usize {
2624        self.model_id
2625    }
2626
2627    fn location(&self) -> EntityLocation {
2628        EntityLocation::Model(self.model_id)
2629    }
2630
2631    fn downgrade(&self) -> Self::Weak {
2632        self.downgrade()
2633    }
2634
2635    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2636    where
2637        Self: Sized,
2638    {
2639        weak.upgrade(cx)
2640    }
2641}
2642
2643pub struct WeakModelHandle<T> {
2644    model_id: usize,
2645    model_type: PhantomData<T>,
2646}
2647
2648unsafe impl<T> Send for WeakModelHandle<T> {}
2649unsafe impl<T> Sync for WeakModelHandle<T> {}
2650
2651impl<T: Entity> WeakModelHandle<T> {
2652    fn new(model_id: usize) -> Self {
2653        Self {
2654            model_id,
2655            model_type: PhantomData,
2656        }
2657    }
2658
2659    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2660        cx.upgrade_model_handle(self)
2661    }
2662}
2663
2664impl<T> Hash for WeakModelHandle<T> {
2665    fn hash<H: Hasher>(&self, state: &mut H) {
2666        self.model_id.hash(state)
2667    }
2668}
2669
2670impl<T> PartialEq for WeakModelHandle<T> {
2671    fn eq(&self, other: &Self) -> bool {
2672        self.model_id == other.model_id
2673    }
2674}
2675
2676impl<T> Eq for WeakModelHandle<T> {}
2677
2678impl<T> Clone for WeakModelHandle<T> {
2679    fn clone(&self) -> Self {
2680        Self {
2681            model_id: self.model_id,
2682            model_type: PhantomData,
2683        }
2684    }
2685}
2686
2687impl<T> Copy for WeakModelHandle<T> {}
2688
2689pub struct ViewHandle<T> {
2690    window_id: usize,
2691    view_id: usize,
2692    view_type: PhantomData<T>,
2693    ref_counts: Arc<Mutex<RefCounts>>,
2694}
2695
2696impl<T: View> ViewHandle<T> {
2697    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2698        ref_counts.lock().inc_view(window_id, view_id);
2699        Self {
2700            window_id,
2701            view_id,
2702            view_type: PhantomData,
2703            ref_counts: ref_counts.clone(),
2704        }
2705    }
2706
2707    pub fn downgrade(&self) -> WeakViewHandle<T> {
2708        WeakViewHandle::new(self.window_id, self.view_id)
2709    }
2710
2711    pub fn window_id(&self) -> usize {
2712        self.window_id
2713    }
2714
2715    pub fn id(&self) -> usize {
2716        self.view_id
2717    }
2718
2719    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2720        cx.read_view(self)
2721    }
2722
2723    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2724    where
2725        C: ReadViewWith,
2726        F: FnOnce(&T, &AppContext) -> S,
2727    {
2728        cx.read_view_with(self, read)
2729    }
2730
2731    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2732    where
2733        C: UpdateView,
2734        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2735    {
2736        cx.update_view(self, update)
2737    }
2738
2739    pub fn is_focused(&self, cx: &AppContext) -> bool {
2740        cx.focused_view_id(self.window_id)
2741            .map_or(false, |focused_id| focused_id == self.view_id)
2742    }
2743
2744    pub fn condition(
2745        &self,
2746        cx: &TestAppContext,
2747        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2748    ) -> impl Future<Output = ()> {
2749        let (tx, mut rx) = mpsc::channel(1024);
2750
2751        let mut cx = cx.cx.borrow_mut();
2752        let subscriptions = self.update(&mut *cx, |_, cx| {
2753            (
2754                cx.observe(self, {
2755                    let mut tx = tx.clone();
2756                    move |_, _, _| {
2757                        tx.blocking_send(()).ok();
2758                    }
2759                }),
2760                cx.subscribe(self, {
2761                    let mut tx = tx.clone();
2762                    move |_, _, _, _| {
2763                        tx.blocking_send(()).ok();
2764                    }
2765                }),
2766            )
2767        });
2768
2769        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2770        let handle = self.downgrade();
2771        let duration = if std::env::var("CI").is_ok() {
2772            Duration::from_secs(2)
2773        } else {
2774            Duration::from_millis(500)
2775        };
2776
2777        async move {
2778            timeout(duration, async move {
2779                loop {
2780                    {
2781                        let cx = cx.borrow();
2782                        let cx = cx.as_ref();
2783                        if predicate(
2784                            handle
2785                                .upgrade(cx)
2786                                .expect("view dropped with pending condition")
2787                                .read(cx),
2788                            cx,
2789                        ) {
2790                            break;
2791                        }
2792                    }
2793
2794                    rx.recv()
2795                        .await
2796                        .expect("view dropped with pending condition");
2797                }
2798            })
2799            .await
2800            .expect("condition timed out");
2801            drop(subscriptions);
2802        }
2803    }
2804}
2805
2806impl<T> Clone for ViewHandle<T> {
2807    fn clone(&self) -> Self {
2808        self.ref_counts
2809            .lock()
2810            .inc_view(self.window_id, self.view_id);
2811        Self {
2812            window_id: self.window_id,
2813            view_id: self.view_id,
2814            view_type: PhantomData,
2815            ref_counts: self.ref_counts.clone(),
2816        }
2817    }
2818}
2819
2820impl<T> PartialEq for ViewHandle<T> {
2821    fn eq(&self, other: &Self) -> bool {
2822        self.window_id == other.window_id && self.view_id == other.view_id
2823    }
2824}
2825
2826impl<T> Eq for ViewHandle<T> {}
2827
2828impl<T> Debug for ViewHandle<T> {
2829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2830        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2831            .field("window_id", &self.window_id)
2832            .field("view_id", &self.view_id)
2833            .finish()
2834    }
2835}
2836
2837impl<T> Drop for ViewHandle<T> {
2838    fn drop(&mut self) {
2839        self.ref_counts
2840            .lock()
2841            .dec_view(self.window_id, self.view_id);
2842    }
2843}
2844
2845impl<T: View> Handle<T> for ViewHandle<T> {
2846    type Weak = WeakViewHandle<T>;
2847
2848    fn id(&self) -> usize {
2849        self.view_id
2850    }
2851
2852    fn location(&self) -> EntityLocation {
2853        EntityLocation::View(self.window_id, self.view_id)
2854    }
2855
2856    fn downgrade(&self) -> Self::Weak {
2857        self.downgrade()
2858    }
2859
2860    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2861    where
2862        Self: Sized,
2863    {
2864        weak.upgrade(cx)
2865    }
2866}
2867
2868pub struct AnyViewHandle {
2869    window_id: usize,
2870    view_id: usize,
2871    view_type: TypeId,
2872    ref_counts: Arc<Mutex<RefCounts>>,
2873}
2874
2875impl AnyViewHandle {
2876    pub fn id(&self) -> usize {
2877        self.view_id
2878    }
2879
2880    pub fn is<T: 'static>(&self) -> bool {
2881        TypeId::of::<T>() == self.view_type
2882    }
2883
2884    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2885        if self.is::<T>() {
2886            let result = Some(ViewHandle {
2887                window_id: self.window_id,
2888                view_id: self.view_id,
2889                ref_counts: self.ref_counts.clone(),
2890                view_type: PhantomData,
2891            });
2892            unsafe {
2893                Arc::decrement_strong_count(&self.ref_counts);
2894            }
2895            std::mem::forget(self);
2896            result
2897        } else {
2898            None
2899        }
2900    }
2901}
2902
2903impl Clone for AnyViewHandle {
2904    fn clone(&self) -> Self {
2905        self.ref_counts
2906            .lock()
2907            .inc_view(self.window_id, self.view_id);
2908        Self {
2909            window_id: self.window_id,
2910            view_id: self.view_id,
2911            view_type: self.view_type,
2912            ref_counts: self.ref_counts.clone(),
2913        }
2914    }
2915}
2916
2917impl From<&AnyViewHandle> for AnyViewHandle {
2918    fn from(handle: &AnyViewHandle) -> Self {
2919        handle.clone()
2920    }
2921}
2922
2923impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2924    fn from(handle: &ViewHandle<T>) -> Self {
2925        handle
2926            .ref_counts
2927            .lock()
2928            .inc_view(handle.window_id, handle.view_id);
2929        AnyViewHandle {
2930            window_id: handle.window_id,
2931            view_id: handle.view_id,
2932            view_type: TypeId::of::<T>(),
2933            ref_counts: handle.ref_counts.clone(),
2934        }
2935    }
2936}
2937
2938impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2939    fn from(handle: ViewHandle<T>) -> Self {
2940        let any_handle = AnyViewHandle {
2941            window_id: handle.window_id,
2942            view_id: handle.view_id,
2943            view_type: TypeId::of::<T>(),
2944            ref_counts: handle.ref_counts.clone(),
2945        };
2946        unsafe {
2947            Arc::decrement_strong_count(&handle.ref_counts);
2948        }
2949        std::mem::forget(handle);
2950        any_handle
2951    }
2952}
2953
2954impl Drop for AnyViewHandle {
2955    fn drop(&mut self) {
2956        self.ref_counts
2957            .lock()
2958            .dec_view(self.window_id, self.view_id);
2959    }
2960}
2961
2962pub struct AnyModelHandle {
2963    model_id: usize,
2964    ref_counts: Arc<Mutex<RefCounts>>,
2965}
2966
2967impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2968    fn from(handle: ModelHandle<T>) -> Self {
2969        handle.ref_counts.lock().inc_model(handle.model_id);
2970        Self {
2971            model_id: handle.model_id,
2972            ref_counts: handle.ref_counts.clone(),
2973        }
2974    }
2975}
2976
2977impl Drop for AnyModelHandle {
2978    fn drop(&mut self) {
2979        self.ref_counts.lock().dec_model(self.model_id);
2980    }
2981}
2982pub struct WeakViewHandle<T> {
2983    window_id: usize,
2984    view_id: usize,
2985    view_type: PhantomData<T>,
2986}
2987
2988impl<T: View> WeakViewHandle<T> {
2989    fn new(window_id: usize, view_id: usize) -> Self {
2990        Self {
2991            window_id,
2992            view_id,
2993            view_type: PhantomData,
2994        }
2995    }
2996
2997    pub fn id(&self) -> usize {
2998        self.view_id
2999    }
3000
3001    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
3002        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
3003            Some(ViewHandle::new(
3004                self.window_id,
3005                self.view_id,
3006                &cx.ref_counts,
3007            ))
3008        } else {
3009            None
3010        }
3011    }
3012}
3013
3014impl<T> Clone for WeakViewHandle<T> {
3015    fn clone(&self) -> Self {
3016        Self {
3017            window_id: self.window_id,
3018            view_id: self.view_id,
3019            view_type: PhantomData,
3020        }
3021    }
3022}
3023
3024#[derive(Clone, Copy, PartialEq, Eq, Hash)]
3025pub struct ElementStateId(usize, usize);
3026
3027impl From<usize> for ElementStateId {
3028    fn from(id: usize) -> Self {
3029        Self(id, 0)
3030    }
3031}
3032
3033impl From<(usize, usize)> for ElementStateId {
3034    fn from(id: (usize, usize)) -> Self {
3035        Self(id.0, id.1)
3036    }
3037}
3038
3039pub struct ElementStateHandle<T> {
3040    value_type: PhantomData<T>,
3041    tag_type_id: TypeId,
3042    id: ElementStateId,
3043    ref_counts: Weak<Mutex<RefCounts>>,
3044}
3045
3046impl<T: 'static> ElementStateHandle<T> {
3047    fn new(tag_type_id: TypeId, id: ElementStateId, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3048        ref_counts.lock().inc_element_state(tag_type_id, id);
3049        Self {
3050            value_type: PhantomData,
3051            tag_type_id,
3052            id,
3053            ref_counts: Arc::downgrade(ref_counts),
3054        }
3055    }
3056
3057    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3058        cx.element_states
3059            .get(&(self.tag_type_id, self.id))
3060            .unwrap()
3061            .downcast_ref()
3062            .unwrap()
3063    }
3064
3065    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3066    where
3067        C: DerefMut<Target = MutableAppContext>,
3068    {
3069        let mut element_state = cx
3070            .deref_mut()
3071            .cx
3072            .element_states
3073            .remove(&(self.tag_type_id, self.id))
3074            .unwrap();
3075        let result = f(element_state.downcast_mut().unwrap(), cx);
3076        cx.deref_mut()
3077            .cx
3078            .element_states
3079            .insert((self.tag_type_id, self.id), element_state);
3080        result
3081    }
3082}
3083
3084impl<T> Drop for ElementStateHandle<T> {
3085    fn drop(&mut self) {
3086        if let Some(ref_counts) = self.ref_counts.upgrade() {
3087            ref_counts
3088                .lock()
3089                .dec_element_state(self.tag_type_id, self.id);
3090        }
3091    }
3092}
3093
3094pub struct CursorStyleHandle {
3095    id: usize,
3096    next_cursor_style_handle_id: Arc<AtomicUsize>,
3097    platform: Arc<dyn Platform>,
3098}
3099
3100impl Drop for CursorStyleHandle {
3101    fn drop(&mut self) {
3102        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3103            self.platform.set_cursor_style(CursorStyle::Arrow);
3104        }
3105    }
3106}
3107
3108#[must_use]
3109pub enum Subscription {
3110    Subscription {
3111        id: usize,
3112        entity_id: usize,
3113        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3114    },
3115    Observation {
3116        id: usize,
3117        entity_id: usize,
3118        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3119    },
3120}
3121
3122impl Subscription {
3123    pub fn detach(&mut self) {
3124        match self {
3125            Subscription::Subscription { subscriptions, .. } => {
3126                subscriptions.take();
3127            }
3128            Subscription::Observation { observations, .. } => {
3129                observations.take();
3130            }
3131        }
3132    }
3133}
3134
3135impl Drop for Subscription {
3136    fn drop(&mut self) {
3137        match self {
3138            Subscription::Observation {
3139                id,
3140                entity_id,
3141                observations,
3142            } => {
3143                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3144                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3145                        observations.remove(id);
3146                    }
3147                }
3148            }
3149            Subscription::Subscription {
3150                id,
3151                entity_id,
3152                subscriptions,
3153            } => {
3154                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3155                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3156                        subscriptions.remove(id);
3157                    }
3158                }
3159            }
3160        }
3161    }
3162}
3163
3164#[derive(Default)]
3165struct RefCounts {
3166    entity_counts: HashMap<usize, usize>,
3167    element_state_counts: HashMap<(TypeId, ElementStateId), usize>,
3168    dropped_models: HashSet<usize>,
3169    dropped_views: HashSet<(usize, usize)>,
3170    dropped_element_states: HashSet<(TypeId, ElementStateId)>,
3171}
3172
3173impl RefCounts {
3174    fn inc_model(&mut self, model_id: usize) {
3175        match self.entity_counts.entry(model_id) {
3176            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3177            Entry::Vacant(entry) => {
3178                entry.insert(1);
3179                self.dropped_models.remove(&model_id);
3180            }
3181        }
3182    }
3183
3184    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3185        match self.entity_counts.entry(view_id) {
3186            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3187            Entry::Vacant(entry) => {
3188                entry.insert(1);
3189                self.dropped_views.remove(&(window_id, view_id));
3190            }
3191        }
3192    }
3193
3194    fn inc_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3195        match self.element_state_counts.entry((tag_type_id, id)) {
3196            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3197            Entry::Vacant(entry) => {
3198                entry.insert(1);
3199                self.dropped_element_states.remove(&(tag_type_id, id));
3200            }
3201        }
3202    }
3203
3204    fn dec_model(&mut self, model_id: usize) {
3205        let count = self.entity_counts.get_mut(&model_id).unwrap();
3206        *count -= 1;
3207        if *count == 0 {
3208            self.entity_counts.remove(&model_id);
3209            self.dropped_models.insert(model_id);
3210        }
3211    }
3212
3213    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3214        let count = self.entity_counts.get_mut(&view_id).unwrap();
3215        *count -= 1;
3216        if *count == 0 {
3217            self.entity_counts.remove(&view_id);
3218            self.dropped_views.insert((window_id, view_id));
3219        }
3220    }
3221
3222    fn dec_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3223        let key = (tag_type_id, id);
3224        let count = self.element_state_counts.get_mut(&key).unwrap();
3225        *count -= 1;
3226        if *count == 0 {
3227            self.element_state_counts.remove(&key);
3228            self.dropped_element_states.insert(key);
3229        }
3230    }
3231
3232    fn is_entity_alive(&self, entity_id: usize) -> bool {
3233        self.entity_counts.contains_key(&entity_id)
3234    }
3235
3236    fn take_dropped(
3237        &mut self,
3238    ) -> (
3239        HashSet<usize>,
3240        HashSet<(usize, usize)>,
3241        HashSet<(TypeId, ElementStateId)>,
3242    ) {
3243        let mut dropped_models = HashSet::new();
3244        let mut dropped_views = HashSet::new();
3245        let mut dropped_element_states = HashSet::new();
3246        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
3247        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
3248        std::mem::swap(
3249            &mut self.dropped_element_states,
3250            &mut dropped_element_states,
3251        );
3252        (dropped_models, dropped_views, dropped_element_states)
3253    }
3254}
3255
3256#[cfg(test)]
3257mod tests {
3258    use super::*;
3259    use crate::elements::*;
3260    use smol::future::poll_once;
3261    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3262
3263    #[crate::test(self)]
3264    fn test_model_handles(cx: &mut MutableAppContext) {
3265        struct Model {
3266            other: Option<ModelHandle<Model>>,
3267            events: Vec<String>,
3268        }
3269
3270        impl Entity for Model {
3271            type Event = usize;
3272        }
3273
3274        impl Model {
3275            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3276                if let Some(other) = other.as_ref() {
3277                    cx.observe(other, |me, _, _| {
3278                        me.events.push("notified".into());
3279                    })
3280                    .detach();
3281                    cx.subscribe(other, |me, _, event, _| {
3282                        me.events.push(format!("observed event {}", event));
3283                    })
3284                    .detach();
3285                }
3286
3287                Self {
3288                    other,
3289                    events: Vec::new(),
3290                }
3291            }
3292        }
3293
3294        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3295        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3296        assert_eq!(cx.cx.models.len(), 2);
3297
3298        handle_1.update(cx, |model, cx| {
3299            model.events.push("updated".into());
3300            cx.emit(1);
3301            cx.notify();
3302            cx.emit(2);
3303        });
3304        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3305        assert_eq!(
3306            handle_2.read(cx).events,
3307            vec![
3308                "observed event 1".to_string(),
3309                "notified".to_string(),
3310                "observed event 2".to_string(),
3311            ]
3312        );
3313
3314        handle_2.update(cx, |model, _| {
3315            drop(handle_1);
3316            model.other.take();
3317        });
3318
3319        assert_eq!(cx.cx.models.len(), 1);
3320        assert!(cx.subscriptions.lock().is_empty());
3321        assert!(cx.observations.lock().is_empty());
3322    }
3323
3324    #[crate::test(self)]
3325    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3326        #[derive(Default)]
3327        struct Model {
3328            events: Vec<usize>,
3329        }
3330
3331        impl Entity for Model {
3332            type Event = usize;
3333        }
3334
3335        let handle_1 = cx.add_model(|_| Model::default());
3336        let handle_2 = cx.add_model(|_| Model::default());
3337        let handle_2b = handle_2.clone();
3338
3339        handle_1.update(cx, |_, c| {
3340            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3341                model.events.push(*event);
3342
3343                c.subscribe(&handle_2b, |model, _, event, _| {
3344                    model.events.push(*event * 2);
3345                })
3346                .detach();
3347            })
3348            .detach();
3349        });
3350
3351        handle_2.update(cx, |_, c| c.emit(7));
3352        assert_eq!(handle_1.read(cx).events, vec![7]);
3353
3354        handle_2.update(cx, |_, c| c.emit(5));
3355        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3356    }
3357
3358    #[crate::test(self)]
3359    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3360        #[derive(Default)]
3361        struct Model {
3362            count: usize,
3363            events: Vec<usize>,
3364        }
3365
3366        impl Entity for Model {
3367            type Event = ();
3368        }
3369
3370        let handle_1 = cx.add_model(|_| Model::default());
3371        let handle_2 = cx.add_model(|_| Model::default());
3372        let handle_2b = handle_2.clone();
3373
3374        handle_1.update(cx, |_, c| {
3375            c.observe(&handle_2, move |model, observed, c| {
3376                model.events.push(observed.read(c).count);
3377                c.observe(&handle_2b, |model, observed, c| {
3378                    model.events.push(observed.read(c).count * 2);
3379                })
3380                .detach();
3381            })
3382            .detach();
3383        });
3384
3385        handle_2.update(cx, |model, c| {
3386            model.count = 7;
3387            c.notify()
3388        });
3389        assert_eq!(handle_1.read(cx).events, vec![7]);
3390
3391        handle_2.update(cx, |model, c| {
3392            model.count = 5;
3393            c.notify()
3394        });
3395        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3396    }
3397
3398    #[crate::test(self)]
3399    fn test_view_handles(cx: &mut MutableAppContext) {
3400        struct View {
3401            other: Option<ViewHandle<View>>,
3402            events: Vec<String>,
3403        }
3404
3405        impl Entity for View {
3406            type Event = usize;
3407        }
3408
3409        impl super::View for View {
3410            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3411                Empty::new().boxed()
3412            }
3413
3414            fn ui_name() -> &'static str {
3415                "View"
3416            }
3417        }
3418
3419        impl View {
3420            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3421                if let Some(other) = other.as_ref() {
3422                    cx.subscribe(other, |me, _, event, _| {
3423                        me.events.push(format!("observed event {}", event));
3424                    })
3425                    .detach();
3426                }
3427                Self {
3428                    other,
3429                    events: Vec::new(),
3430                }
3431            }
3432        }
3433
3434        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3435        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3436        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3437        assert_eq!(cx.cx.views.len(), 3);
3438
3439        handle_1.update(cx, |view, cx| {
3440            view.events.push("updated".into());
3441            cx.emit(1);
3442            cx.emit(2);
3443        });
3444        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3445        assert_eq!(
3446            handle_2.read(cx).events,
3447            vec![
3448                "observed event 1".to_string(),
3449                "observed event 2".to_string(),
3450            ]
3451        );
3452
3453        handle_2.update(cx, |view, _| {
3454            drop(handle_1);
3455            view.other.take();
3456        });
3457
3458        assert_eq!(cx.cx.views.len(), 2);
3459        assert!(cx.subscriptions.lock().is_empty());
3460        assert!(cx.observations.lock().is_empty());
3461    }
3462
3463    #[crate::test(self)]
3464    fn test_add_window(cx: &mut MutableAppContext) {
3465        struct View {
3466            mouse_down_count: Arc<AtomicUsize>,
3467        }
3468
3469        impl Entity for View {
3470            type Event = ();
3471        }
3472
3473        impl super::View for View {
3474            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3475                let mouse_down_count = self.mouse_down_count.clone();
3476                EventHandler::new(Empty::new().boxed())
3477                    .on_mouse_down(move |_| {
3478                        mouse_down_count.fetch_add(1, SeqCst);
3479                        true
3480                    })
3481                    .boxed()
3482            }
3483
3484            fn ui_name() -> &'static str {
3485                "View"
3486            }
3487        }
3488
3489        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3490        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3491            mouse_down_count: mouse_down_count.clone(),
3492        });
3493        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3494        // Ensure window's root element is in a valid lifecycle state.
3495        presenter.borrow_mut().dispatch_event(
3496            Event::LeftMouseDown {
3497                position: Default::default(),
3498                cmd: false,
3499            },
3500            cx,
3501        );
3502        assert_eq!(mouse_down_count.load(SeqCst), 1);
3503    }
3504
3505    #[crate::test(self)]
3506    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3507        struct Model {
3508            released: Arc<Mutex<bool>>,
3509        }
3510
3511        struct View {
3512            released: Arc<Mutex<bool>>,
3513        }
3514
3515        impl Entity for Model {
3516            type Event = ();
3517
3518            fn release(&mut self, _: &mut MutableAppContext) {
3519                *self.released.lock() = true;
3520            }
3521        }
3522
3523        impl Entity for View {
3524            type Event = ();
3525
3526            fn release(&mut self, _: &mut MutableAppContext) {
3527                *self.released.lock() = true;
3528            }
3529        }
3530
3531        impl super::View for View {
3532            fn ui_name() -> &'static str {
3533                "View"
3534            }
3535
3536            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3537                Empty::new().boxed()
3538            }
3539        }
3540
3541        let model_released = Arc::new(Mutex::new(false));
3542        let view_released = Arc::new(Mutex::new(false));
3543
3544        let model = cx.add_model(|_| Model {
3545            released: model_released.clone(),
3546        });
3547
3548        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3549            released: view_released.clone(),
3550        });
3551
3552        assert!(!*model_released.lock());
3553        assert!(!*view_released.lock());
3554
3555        cx.update(move || {
3556            drop(model);
3557        });
3558        assert!(*model_released.lock());
3559
3560        drop(cx.remove_window(window_id));
3561        assert!(*view_released.lock());
3562    }
3563
3564    #[crate::test(self)]
3565    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3566        #[derive(Default)]
3567        struct View {
3568            events: Vec<usize>,
3569        }
3570
3571        impl Entity for View {
3572            type Event = usize;
3573        }
3574
3575        impl super::View for View {
3576            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3577                Empty::new().boxed()
3578            }
3579
3580            fn ui_name() -> &'static str {
3581                "View"
3582            }
3583        }
3584
3585        struct Model;
3586
3587        impl Entity for Model {
3588            type Event = usize;
3589        }
3590
3591        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3592        let handle_2 = cx.add_view(window_id, |_| View::default());
3593        let handle_2b = handle_2.clone();
3594        let handle_3 = cx.add_model(|_| Model);
3595
3596        handle_1.update(cx, |_, c| {
3597            c.subscribe(&handle_2, move |me, _, event, c| {
3598                me.events.push(*event);
3599
3600                c.subscribe(&handle_2b, |me, _, event, _| {
3601                    me.events.push(*event * 2);
3602                })
3603                .detach();
3604            })
3605            .detach();
3606
3607            c.subscribe(&handle_3, |me, _, event, _| {
3608                me.events.push(*event);
3609            })
3610            .detach();
3611        });
3612
3613        handle_2.update(cx, |_, c| c.emit(7));
3614        assert_eq!(handle_1.read(cx).events, vec![7]);
3615
3616        handle_2.update(cx, |_, c| c.emit(5));
3617        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3618
3619        handle_3.update(cx, |_, c| c.emit(9));
3620        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
3621    }
3622
3623    #[crate::test(self)]
3624    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3625        struct View;
3626
3627        impl Entity for View {
3628            type Event = ();
3629        }
3630
3631        impl super::View for View {
3632            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3633                Empty::new().boxed()
3634            }
3635
3636            fn ui_name() -> &'static str {
3637                "View"
3638            }
3639        }
3640
3641        struct Model;
3642
3643        impl Entity for Model {
3644            type Event = ();
3645        }
3646
3647        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3648        let observing_view = cx.add_view(window_id, |_| View);
3649        let emitting_view = cx.add_view(window_id, |_| View);
3650        let observing_model = cx.add_model(|_| Model);
3651        let observed_model = cx.add_model(|_| Model);
3652
3653        observing_view.update(cx, |_, cx| {
3654            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
3655            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3656        });
3657        observing_model.update(cx, |_, cx| {
3658            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3659        });
3660
3661        cx.update(|| {
3662            drop(observing_view);
3663            drop(observing_model);
3664        });
3665
3666        emitting_view.update(cx, |_, cx| cx.emit(()));
3667        observed_model.update(cx, |_, cx| cx.emit(()));
3668    }
3669
3670    #[crate::test(self)]
3671    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3672        #[derive(Default)]
3673        struct View {
3674            events: Vec<usize>,
3675        }
3676
3677        impl Entity for View {
3678            type Event = usize;
3679        }
3680
3681        impl super::View for View {
3682            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3683                Empty::new().boxed()
3684            }
3685
3686            fn ui_name() -> &'static str {
3687                "View"
3688            }
3689        }
3690
3691        #[derive(Default)]
3692        struct Model {
3693            count: usize,
3694        }
3695
3696        impl Entity for Model {
3697            type Event = ();
3698        }
3699
3700        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3701        let model = cx.add_model(|_| Model::default());
3702
3703        view.update(cx, |_, c| {
3704            c.observe(&model, |me, observed, c| {
3705                me.events.push(observed.read(c).count)
3706            })
3707            .detach();
3708        });
3709
3710        model.update(cx, |model, c| {
3711            model.count = 11;
3712            c.notify();
3713        });
3714        assert_eq!(view.read(cx).events, vec![11]);
3715    }
3716
3717    #[crate::test(self)]
3718    fn test_dropping_observers(cx: &mut MutableAppContext) {
3719        struct View;
3720
3721        impl Entity for View {
3722            type Event = ();
3723        }
3724
3725        impl super::View for View {
3726            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3727                Empty::new().boxed()
3728            }
3729
3730            fn ui_name() -> &'static str {
3731                "View"
3732            }
3733        }
3734
3735        struct Model;
3736
3737        impl Entity for Model {
3738            type Event = ();
3739        }
3740
3741        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3742        let observing_view = cx.add_view(window_id, |_| View);
3743        let observing_model = cx.add_model(|_| Model);
3744        let observed_model = cx.add_model(|_| Model);
3745
3746        observing_view.update(cx, |_, cx| {
3747            cx.observe(&observed_model, |_, _, _| {}).detach();
3748        });
3749        observing_model.update(cx, |_, cx| {
3750            cx.observe(&observed_model, |_, _, _| {}).detach();
3751        });
3752
3753        cx.update(|| {
3754            drop(observing_view);
3755            drop(observing_model);
3756        });
3757
3758        observed_model.update(cx, |_, cx| cx.notify());
3759    }
3760
3761    #[crate::test(self)]
3762    fn test_focus(cx: &mut MutableAppContext) {
3763        struct View {
3764            name: String,
3765            events: Arc<Mutex<Vec<String>>>,
3766        }
3767
3768        impl Entity for View {
3769            type Event = ();
3770        }
3771
3772        impl super::View for View {
3773            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3774                Empty::new().boxed()
3775            }
3776
3777            fn ui_name() -> &'static str {
3778                "View"
3779            }
3780
3781            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3782                self.events.lock().push(format!("{} focused", &self.name));
3783            }
3784
3785            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3786                self.events.lock().push(format!("{} blurred", &self.name));
3787            }
3788        }
3789
3790        let events: Arc<Mutex<Vec<String>>> = Default::default();
3791        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3792            events: events.clone(),
3793            name: "view 1".to_string(),
3794        });
3795        let view_2 = cx.add_view(window_id, |_| View {
3796            events: events.clone(),
3797            name: "view 2".to_string(),
3798        });
3799
3800        view_1.update(cx, |_, cx| cx.focus(&view_2));
3801        view_1.update(cx, |_, cx| cx.focus(&view_1));
3802        view_1.update(cx, |_, cx| cx.focus(&view_2));
3803        view_1.update(cx, |_, _| drop(view_2));
3804
3805        assert_eq!(
3806            *events.lock(),
3807            [
3808                "view 1 focused".to_string(),
3809                "view 1 blurred".to_string(),
3810                "view 2 focused".to_string(),
3811                "view 2 blurred".to_string(),
3812                "view 1 focused".to_string(),
3813                "view 1 blurred".to_string(),
3814                "view 2 focused".to_string(),
3815                "view 1 focused".to_string(),
3816            ],
3817        );
3818    }
3819
3820    #[crate::test(self)]
3821    fn test_dispatch_action(cx: &mut MutableAppContext) {
3822        struct ViewA {
3823            id: usize,
3824        }
3825
3826        impl Entity for ViewA {
3827            type Event = ();
3828        }
3829
3830        impl View for ViewA {
3831            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3832                Empty::new().boxed()
3833            }
3834
3835            fn ui_name() -> &'static str {
3836                "View"
3837            }
3838        }
3839
3840        struct ViewB {
3841            id: usize,
3842        }
3843
3844        impl Entity for ViewB {
3845            type Event = ();
3846        }
3847
3848        impl View for ViewB {
3849            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3850                Empty::new().boxed()
3851            }
3852
3853            fn ui_name() -> &'static str {
3854                "View"
3855            }
3856        }
3857
3858        action!(Action, &'static str);
3859
3860        let actions = Rc::new(RefCell::new(Vec::new()));
3861
3862        let actions_clone = actions.clone();
3863        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3864            actions_clone.borrow_mut().push("global a".to_string());
3865        });
3866
3867        let actions_clone = actions.clone();
3868        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
3869            actions_clone.borrow_mut().push("global b".to_string());
3870        });
3871
3872        let actions_clone = actions.clone();
3873        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
3874            assert_eq!(action.0, "bar");
3875            cx.propagate_action();
3876            actions_clone.borrow_mut().push(format!("{} a", view.id));
3877        });
3878
3879        let actions_clone = actions.clone();
3880        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
3881            if view.id != 1 {
3882                cx.propagate_action();
3883            }
3884            actions_clone.borrow_mut().push(format!("{} b", view.id));
3885        });
3886
3887        let actions_clone = actions.clone();
3888        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3889            cx.propagate_action();
3890            actions_clone.borrow_mut().push(format!("{} c", view.id));
3891        });
3892
3893        let actions_clone = actions.clone();
3894        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
3895            cx.propagate_action();
3896            actions_clone.borrow_mut().push(format!("{} d", view.id));
3897        });
3898
3899        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3900        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3901        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3902        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3903
3904        cx.dispatch_action(
3905            window_id,
3906            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3907            &Action("bar"),
3908        );
3909
3910        assert_eq!(
3911            *actions.borrow(),
3912            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3913        );
3914
3915        // Remove view_1, which doesn't propagate the action
3916        actions.borrow_mut().clear();
3917        cx.dispatch_action(
3918            window_id,
3919            vec![view_2.id(), view_3.id(), view_4.id()],
3920            &Action("bar"),
3921        );
3922
3923        assert_eq!(
3924            *actions.borrow(),
3925            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3926        );
3927    }
3928
3929    #[crate::test(self)]
3930    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3931        use std::cell::Cell;
3932
3933        action!(Action, &'static str);
3934
3935        struct View {
3936            id: usize,
3937            keymap_context: keymap::Context,
3938        }
3939
3940        impl Entity for View {
3941            type Event = ();
3942        }
3943
3944        impl super::View for View {
3945            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3946                Empty::new().boxed()
3947            }
3948
3949            fn ui_name() -> &'static str {
3950                "View"
3951            }
3952
3953            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3954                self.keymap_context.clone()
3955            }
3956        }
3957
3958        impl View {
3959            fn new(id: usize) -> Self {
3960                View {
3961                    id,
3962                    keymap_context: keymap::Context::default(),
3963                }
3964            }
3965        }
3966
3967        let mut view_1 = View::new(1);
3968        let mut view_2 = View::new(2);
3969        let mut view_3 = View::new(3);
3970        view_1.keymap_context.set.insert("a".into());
3971        view_2.keymap_context.set.insert("b".into());
3972        view_3.keymap_context.set.insert("c".into());
3973
3974        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3975        let view_2 = cx.add_view(window_id, |_| view_2);
3976        let view_3 = cx.add_view(window_id, |_| view_3);
3977
3978        // This keymap's only binding dispatches an action on view 2 because that view will have
3979        // "a" and "b" in its context, but not "c".
3980        cx.add_bindings(vec![keymap::Binding::new(
3981            "a",
3982            Action("a"),
3983            Some("a && b && !c"),
3984        )]);
3985
3986        let handled_action = Rc::new(Cell::new(false));
3987        let handled_action_clone = handled_action.clone();
3988        cx.add_action(move |view: &mut View, action: &Action, _| {
3989            handled_action_clone.set(true);
3990            assert_eq!(view.id, 2);
3991            assert_eq!(action.0, "a");
3992        });
3993
3994        cx.dispatch_keystroke(
3995            window_id,
3996            vec![view_1.id(), view_2.id(), view_3.id()],
3997            &Keystroke::parse("a").unwrap(),
3998        )
3999        .unwrap();
4000
4001        assert!(handled_action.get());
4002    }
4003
4004    #[crate::test(self)]
4005    async fn test_model_condition(mut cx: TestAppContext) {
4006        struct Counter(usize);
4007
4008        impl super::Entity for Counter {
4009            type Event = ();
4010        }
4011
4012        impl Counter {
4013            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4014                self.0 += 1;
4015                cx.notify();
4016            }
4017        }
4018
4019        let model = cx.add_model(|_| Counter(0));
4020
4021        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4022        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4023        smol::pin!(condition1, condition2);
4024
4025        model.update(&mut cx, |model, cx| model.inc(cx));
4026        assert_eq!(poll_once(&mut condition1).await, None);
4027        assert_eq!(poll_once(&mut condition2).await, None);
4028
4029        model.update(&mut cx, |model, cx| model.inc(cx));
4030        assert_eq!(poll_once(&mut condition1).await, Some(()));
4031        assert_eq!(poll_once(&mut condition2).await, None);
4032
4033        model.update(&mut cx, |model, cx| model.inc(cx));
4034        assert_eq!(poll_once(&mut condition2).await, Some(()));
4035
4036        model.update(&mut cx, |_, cx| cx.notify());
4037    }
4038
4039    #[crate::test(self)]
4040    #[should_panic]
4041    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4042        struct Model;
4043
4044        impl super::Entity for Model {
4045            type Event = ();
4046        }
4047
4048        let model = cx.add_model(|_| Model);
4049        model.condition(&cx, |_, _| false).await;
4050    }
4051
4052    #[crate::test(self)]
4053    #[should_panic(expected = "model dropped with pending condition")]
4054    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4055        struct Model;
4056
4057        impl super::Entity for Model {
4058            type Event = ();
4059        }
4060
4061        let model = cx.add_model(|_| Model);
4062        let condition = model.condition(&cx, |_, _| false);
4063        cx.update(|_| drop(model));
4064        condition.await;
4065    }
4066
4067    #[crate::test(self)]
4068    async fn test_view_condition(mut cx: TestAppContext) {
4069        struct Counter(usize);
4070
4071        impl super::Entity for Counter {
4072            type Event = ();
4073        }
4074
4075        impl super::View for Counter {
4076            fn ui_name() -> &'static str {
4077                "test view"
4078            }
4079
4080            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4081                Empty::new().boxed()
4082            }
4083        }
4084
4085        impl Counter {
4086            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4087                self.0 += 1;
4088                cx.notify();
4089            }
4090        }
4091
4092        let (_, view) = cx.add_window(|_| Counter(0));
4093
4094        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4095        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4096        smol::pin!(condition1, condition2);
4097
4098        view.update(&mut cx, |view, cx| view.inc(cx));
4099        assert_eq!(poll_once(&mut condition1).await, None);
4100        assert_eq!(poll_once(&mut condition2).await, None);
4101
4102        view.update(&mut cx, |view, cx| view.inc(cx));
4103        assert_eq!(poll_once(&mut condition1).await, Some(()));
4104        assert_eq!(poll_once(&mut condition2).await, None);
4105
4106        view.update(&mut cx, |view, cx| view.inc(cx));
4107        assert_eq!(poll_once(&mut condition2).await, Some(()));
4108        view.update(&mut cx, |_, cx| cx.notify());
4109    }
4110
4111    #[crate::test(self)]
4112    #[should_panic]
4113    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4114        struct View;
4115
4116        impl super::Entity for View {
4117            type Event = ();
4118        }
4119
4120        impl super::View for View {
4121            fn ui_name() -> &'static str {
4122                "test view"
4123            }
4124
4125            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4126                Empty::new().boxed()
4127            }
4128        }
4129
4130        let (_, view) = cx.add_window(|_| View);
4131        view.condition(&cx, |_, _| false).await;
4132    }
4133
4134    #[crate::test(self)]
4135    #[should_panic(expected = "view dropped with pending condition")]
4136    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4137        struct View;
4138
4139        impl super::Entity for View {
4140            type Event = ();
4141        }
4142
4143        impl super::View for View {
4144            fn ui_name() -> &'static str {
4145                "test view"
4146            }
4147
4148            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4149                Empty::new().boxed()
4150            }
4151        }
4152
4153        let window_id = cx.add_window(|_| View).0;
4154        let view = cx.add_view(window_id, |_| View);
4155
4156        let condition = view.condition(&cx, |_, _| false);
4157        cx.update(|_| drop(view));
4158        condition.await;
4159    }
4160}