app.rs

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