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