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