app.rs

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