app.rs

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