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