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