app.rs

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