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